Skip to content
Snippets Groups Projects
Commit af7a6adb authored by Taddeüs Kroes's avatar Taddeüs Kroes
Browse files

First version

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 2185 additions and 0 deletions
# Copyright 2013-2014 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'rbconfig'
module CommandT
module Util
class << self
def processor_count
@processor_count ||= begin
count = processor_count!
count = 1 if count < 1 # sanity check
count = 32 if count > 32 # sanity check
count
end
end
private
# This method derived from:
#
# https://github.com/grosser/parallel/blob/d11e4a3c8c1a/lib/parallel.rb
#
# Number of processors seen by the OS and used for process scheduling.
#
# * AIX: /usr/sbin/pmcycles (AIX 5+), /usr/sbin/lsdev
# * BSD: /sbin/sysctl
# * Cygwin: /proc/cpuinfo
# * Darwin: /usr/bin/hwprefs, /usr/sbin/sysctl
# * HP-UX: /usr/sbin/ioscan
# * IRIX: /usr/sbin/sysconf
# * Linux: /proc/cpuinfo
# * Minix 3+: /proc/cpuinfo
# * Solaris: /usr/sbin/psrinfo
# * Tru64 UNIX: /usr/sbin/psrinfo
# * UnixWare: /usr/sbin/psrinfo
#
# Copyright (C) 2013 Michael Grosser <michael@grosser.it>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
def processor_count!
os_name = RbConfig::CONFIG['target_os']
if os_name =~ /mingw|mswin/
require 'win32ole'
result = WIN32OLE.connect('winmgmts://').ExecQuery(
'select NumberOfLogicalProcessors from Win32_Processor')
result.to_enum.collect(&:NumberOfLogicalProcessors).reduce(:+)
elsif File.readable?('/proc/cpuinfo')
IO.read('/proc/cpuinfo').scan(/^processor/).size
elsif File.executable?('/usr/bin/hwprefs')
IO.popen(%w[/usr/bin/hwprefs thread_count]).read.to_i
elsif File.executable?('/usr/sbin/psrinfo')
IO.popen('/usr/sbin/psrinfo').read.scan(/^.*on-*line/).size
elsif File.executable?('/usr/sbin/ioscan')
IO.popen(%w[/usr/sbin/ioscan -kC processor]) do |out|
out.read.scan(/^.*processor/).size
end
elsif File.executable?('/usr/sbin/pmcycles')
IO.popen(%w[/usr/sbin/pmcycles -m]).read.count("\n")
elsif File.executable?('/usr/sbin/lsdev')
IO.popen(%w[/usr/sbin/lsdev -Cc processor -S 1]).read.count("\n")
elsif File.executable?('/usr/sbin/sysconf') and os_name =~ /irix/i
IO.popen(%w[/usr/sbin/sysconf NPROC_ONLN]).read.to_i
elsif File.executable?('/usr/sbin/sysctl')
IO.popen(%w[/usr/sbin/sysctl -n hw.ncpu]).read.to_i
elsif File.executable?('/sbin/sysctl')
IO.popen(%w[/sbin/sysctl -n hw.ncpu]).read.to_i
else # unknown platform
1
end
rescue
1
end
end
end # module Util
end # module commandT
# Copyright 2010-2013 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim/screen'
require 'command-t/vim/window'
module CommandT
module VIM
def self.has_syntax?
::VIM::evaluate('has("syntax")').to_i != 0
end
def self.exists? str
::VIM::evaluate(%{exists("#{str}")}).to_i != 0
end
def self.has_conceal?
::VIM::evaluate('has("conceal")').to_i != 0
end
def self.pwd
::VIM::evaluate 'getcwd()'
end
def self.wild_ignore
exists?('&wildignore') && ::VIM::evaluate('&wildignore').to_s
end
# Execute cmd, capturing the output into a variable and returning it.
def self.capture cmd
::VIM::command 'silent redir => g:command_t_captured_output'
::VIM::command cmd
::VIM::command 'silent redir END'
::VIM::evaluate 'g:command_t_captured_output'
end
# Escape a string for safe inclusion in a Vim single-quoted string
# (single quotes escaped by doubling, everything else is literal)
def self.escape_for_single_quotes str
str.gsub "'", "''"
end
end # module VIM
end # module CommandT
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
module CommandT
module VIM
module PathUtilities
private
def relative_path_under_working_directory path
# any path under the working directory will be specified as a relative
# path to improve the readability of the buffer list etc
pwd = File.expand_path(VIM::pwd) + '/'
path.index(pwd) == 0 ? path[pwd.length..-1] : path
end
end # module PathUtilities
end # module VIM
end # module CommandT
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
module VIM
module Screen
def self.lines
::VIM::evaluate('&lines').to_i
end
end # module Screen
end # module VIM
end # module CommandT
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
module VIM
class Window
def self.select window
return true if $curwin == window
initial = $curwin
while true do
::VIM::command 'wincmd w' # cycle through windows
return true if $curwin == window # have selected desired window
return false if $curwin == initial # have already looped through all
end
end
end # class Window
end # module VIM
end # module CommandT
// Copyright 2014 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "watchman.h"
#ifdef WATCHMAN_BUILD
#if defined(HAVE_RUBY_ST_H)
#include <ruby/st.h>
#elif defined(HAVE_ST_H)
#include <st.h>
#else
#error no st.h header found
#endif
#include <fcntl.h> /* for fcntl() */
#include <sys/errno.h> /* for errno */
#include <sys/socket.h> /* for recv(), MSG_PEEK */
typedef struct {
uint8_t *data; // payload
size_t cap; // total capacity
size_t len; // current length
} watchman_t;
// Forward declarations:
VALUE watchman_load(char **ptr, char *end);
void watchman_dump(watchman_t *w, VALUE serializable);
/**
* Inspect a ruby object (debugging aid)
*/
#define ruby_inspect(obj) rb_funcall(rb_mKernel, rb_intern("p"), 1, obj)
/**
* Print `count` bytes of memory at `address` (debugging aid)
*/
#define dump(address, count) \
do { \
for (int i = 0; i < count; i++) { \
printf("%02x ", ((unsigned char *)address)[i]); printf("\n"); \
} \
} while(0)
#define WATCHMAN_DEFAULT_STORAGE 4096
#define WATCHMAN_BINARY_MARKER "\x00\x01"
#define WATCHMAN_ARRAY_MARKER 0x00
#define WATCHMAN_HASH_MARKER 0x01
#define WATCHMAN_STRING_MARKER 0x02
#define WATCHMAN_INT8_MARKER 0x03
#define WATCHMAN_INT16_MARKER 0x04
#define WATCHMAN_INT32_MARKER 0x05
#define WATCHMAN_INT64_MARKER 0x06
#define WATCHMAN_FLOAT_MARKER 0x07
#define WATCHMAN_TRUE 0x08
#define WATCHMAN_FALSE 0x09
#define WATCHMAN_NIL 0x0a
#define WATCHMAN_TEMPLATE_MARKER 0x0b
#define WATCHMAN_SKIP_MARKER 0x0c
#define WATCHMAN_HEADER \
WATCHMAN_BINARY_MARKER \
"\x06" \
"\x00\x00\x00\x00\x00\x00\x00\x00"
static const char watchman_array_marker = WATCHMAN_ARRAY_MARKER;
static const char watchman_hash_marker = WATCHMAN_HASH_MARKER;
static const char watchman_string_marker = WATCHMAN_STRING_MARKER;
static const char watchman_true = WATCHMAN_TRUE;
static const char watchman_false = WATCHMAN_FALSE;
static const char watchman_nil = WATCHMAN_NIL;
/**
* Appends `len` bytes, starting at `data`, to the watchman_t struct `w`
*
* Will attempt to reallocate the underlying storage if it is not sufficient.
*/
void watchman_append(watchman_t *w, const char *data, size_t len) {
if (w->len + len > w->cap) {
w->cap += w->len + WATCHMAN_DEFAULT_STORAGE;
REALLOC_N(w->data, uint8_t, w->cap);
}
memcpy(w->data + w->len, data, len);
w->len += len;
}
/**
* Allocate a new watchman_t struct
*
* The struct has a small amount of extra capacity preallocated, and a blank
* header that can be filled in later to describe the PDU.
*/
watchman_t *watchman_init() {
watchman_t *w = ALLOC(watchman_t);
w->cap = WATCHMAN_DEFAULT_STORAGE;
w->len = 0;
w->data = ALLOC_N(uint8_t, WATCHMAN_DEFAULT_STORAGE);
watchman_append(w, WATCHMAN_HEADER, sizeof(WATCHMAN_HEADER) - 1);
return w;
}
/**
* Free a watchman_t struct `w` that was previously allocated with
* `watchman_init`
*/
void watchman_free(watchman_t *w) {
xfree(w->data);
xfree(w);
}
/**
* Encodes and appends the integer `num` to `w`
*/
void watchman_dump_int(watchman_t *w, int64_t num) {
char encoded[1 + sizeof(int64_t)];
if (num == (int8_t)num) {
encoded[0] = WATCHMAN_INT8_MARKER;
encoded[1] = (int8_t)num;
watchman_append(w, encoded, 1 + sizeof(int8_t));
} else if (num == (int16_t)num) {
encoded[0] = WATCHMAN_INT16_MARKER;
*(int16_t *)(encoded + 1) = (int16_t)num;
watchman_append(w, encoded, 1 + sizeof(int16_t));
} else if (num == (int32_t)num) {
encoded[0] = WATCHMAN_INT32_MARKER;
*(int32_t *)(encoded + 1) = (int32_t)num;
watchman_append(w, encoded, 1 + sizeof(int32_t));
} else {
encoded[0] = WATCHMAN_INT64_MARKER;
*(int64_t *)(encoded + 1) = (int64_t)num;
watchman_append(w, encoded, 1 + sizeof(int64_t));
}
}
/**
* Encodes and appends the string `string` to `w`
*/
void watchman_dump_string(watchman_t *w, VALUE string) {
watchman_append(w, &watchman_string_marker, sizeof(watchman_string_marker));
watchman_dump_int(w, RSTRING_LEN(string));
watchman_append(w, RSTRING_PTR(string), RSTRING_LEN(string));
}
/**
* Encodes and appends the double `num` to `w`
*/
void watchman_dump_double(watchman_t *w, double num) {
char encoded[1 + sizeof(double)];
encoded[0] = WATCHMAN_FLOAT_MARKER;
*(double *)(encoded + 1) = num;
watchman_append(w, encoded, sizeof(encoded));
}
/**
* Encodes and appends the array `array` to `w`
*/
void watchman_dump_array(watchman_t *w, VALUE array) {
long i;
watchman_append(w, &watchman_array_marker, sizeof(watchman_array_marker));
watchman_dump_int(w, RARRAY_LEN(array));
for (i = 0; i < RARRAY_LEN(array); i++) {
watchman_dump(w, rb_ary_entry(array, i));
}
}
/**
* Helper method that encodes and appends a key/value pair (`key`, `value`) from
* a hash to the watchman_t struct passed in via `data`
*/
int watchman_dump_hash_iterator(VALUE key, VALUE value, VALUE data) {
watchman_t *w = (watchman_t *)data;
watchman_dump_string(w, StringValue(key));
watchman_dump(w, value);
return ST_CONTINUE;
}
/**
* Encodes and appends the hash `hash` to `w`
*/
void watchman_dump_hash(watchman_t *w, VALUE hash) {
watchman_append(w, &watchman_hash_marker, sizeof(watchman_hash_marker));
watchman_dump_int(w, RHASH_SIZE(hash));
rb_hash_foreach(hash, watchman_dump_hash_iterator, (VALUE)w);
}
/**
* Encodes and appends the serialized Ruby object `serializable` to `w`
*
* Examples of serializable objects include arrays, hashes, strings, numbers
* (integers, floats), booleans, and nil.
*/
void watchman_dump(watchman_t *w, VALUE serializable) {
switch (TYPE(serializable)) {
case T_ARRAY:
return watchman_dump_array(w, serializable);
case T_HASH:
return watchman_dump_hash(w, serializable);
case T_STRING:
return watchman_dump_string(w, serializable);
case T_FIXNUM: // up to 63 bits
return watchman_dump_int(w, FIX2LONG(serializable));
case T_BIGNUM:
return watchman_dump_int(w, NUM2LL(serializable));
case T_FLOAT:
return watchman_dump_double(w, NUM2DBL(serializable));
case T_TRUE:
return watchman_append(w, &watchman_true, sizeof(watchman_true));
case T_FALSE:
return watchman_append(w, &watchman_false, sizeof(watchman_false));
case T_NIL:
return watchman_append(w, &watchman_nil, sizeof(watchman_nil));
default:
rb_raise(rb_eTypeError, "unsupported type");
}
}
/**
* Extract and return the int encoded at `ptr`
*
* Moves `ptr` past the extracted int.
*
* Will raise an ArgumentError if extracting the int would take us beyond the
* end of the buffer indicated by `end`, or if there is no int encoded at `ptr`.
*
* @returns The extracted int
*/
int64_t watchman_load_int(char **ptr, char *end) {
char *val_ptr = *ptr + sizeof(int8_t);
int64_t val = 0;
if (val_ptr >= end) {
rb_raise(rb_eArgError, "insufficient int storage");
}
switch (*ptr[0]) {
case WATCHMAN_INT8_MARKER:
if (val_ptr + sizeof(int8_t) > end) {
rb_raise(rb_eArgError, "overrun extracting int8_t");
}
val = *(int8_t *)val_ptr;
*ptr = val_ptr + sizeof(int8_t);
break;
case WATCHMAN_INT16_MARKER:
if (val_ptr + sizeof(int16_t) > end) {
rb_raise(rb_eArgError, "overrun extracting int16_t");
}
val = *(int16_t *)val_ptr;
*ptr = val_ptr + sizeof(int16_t);
break;
case WATCHMAN_INT32_MARKER:
if (val_ptr + sizeof(int32_t) > end) {
rb_raise(rb_eArgError, "overrun extracting int32_t");
}
val = *(int32_t *)val_ptr;
*ptr = val_ptr + sizeof(int32_t);
break;
case WATCHMAN_INT64_MARKER:
if (val_ptr + sizeof(int64_t) > end) {
rb_raise(rb_eArgError, "overrun extracting int64_t");
}
val = *(int64_t *)val_ptr;
*ptr = val_ptr + sizeof(int64_t);
break;
default:
rb_raise(rb_eArgError, "bad integer marker 0x%02x", (unsigned int)*ptr[0]);
break;
}
return val;
}
/**
* Reads and returns a string encoded in the Watchman binary protocol format,
* starting at `ptr` and finishing at or before `end`
*/
VALUE watchman_load_string(char **ptr, char *end) {
if (*ptr >= end) {
rb_raise(rb_eArgError, "unexpected end of input");
}
if (*ptr[0] != WATCHMAN_STRING_MARKER) {
rb_raise(rb_eArgError, "not a number");
}
*ptr += sizeof(int8_t);
if (*ptr >= end) {
rb_raise(rb_eArgError, "invalid string header");
}
int64_t len = watchman_load_int(ptr, end);
if (len == 0) { // special case for zero-length strings
return rb_str_new2("");
} else if (*ptr + len > end) {
rb_raise(rb_eArgError, "insufficient string storage");
}
VALUE string = rb_str_new(*ptr, len);
*ptr += len;
return string;
}
/**
* Reads and returns a double encoded in the Watchman binary protocol format,
* starting at `ptr` and finishing at or before `end`
*/
double watchman_load_double(char **ptr, char *end) {
*ptr += sizeof(int8_t); // caller has already verified the marker
if (*ptr + sizeof(double) > end) {
rb_raise(rb_eArgError, "insufficient double storage");
}
double val = *(double *)*ptr;
*ptr += sizeof(double);
return val;
}
/**
* Helper method which returns length of the array encoded in the Watchman
* binary protocol format, starting at `ptr` and finishing at or before `end`
*/
int64_t watchman_load_array_header(char **ptr, char *end) {
if (*ptr >= end) {
rb_raise(rb_eArgError, "unexpected end of input");
}
// verify and consume marker
if (*ptr[0] != WATCHMAN_ARRAY_MARKER) {
rb_raise(rb_eArgError, "not an array");
}
*ptr += sizeof(int8_t);
// expect a count
if (*ptr + sizeof(int8_t) * 2 > end) {
rb_raise(rb_eArgError, "incomplete array header");
}
return watchman_load_int(ptr, end);
}
/**
* Reads and returns an array encoded in the Watchman binary protocol format,
* starting at `ptr` and finishing at or before `end`
*/
VALUE watchman_load_array(char **ptr, char *end) {
int64_t count, i;
VALUE array;
count = watchman_load_array_header(ptr, end);
array = rb_ary_new2(count);
for (i = 0; i < count; i++) {
rb_ary_push(array, watchman_load(ptr, end));
}
return array;
}
/**
* Reads and returns a hash encoded in the Watchman binary protocol format,
* starting at `ptr` and finishing at or before `end`
*/
VALUE watchman_load_hash(char **ptr, char *end) {
int64_t count, i;
VALUE hash, key, value;
*ptr += sizeof(int8_t); // caller has already verified the marker
// expect a count
if (*ptr + sizeof(int8_t) * 2 > end) {
rb_raise(rb_eArgError, "incomplete hash header");
}
count = watchman_load_int(ptr, end);
hash = rb_hash_new();
for (i = 0; i < count; i++) {
key = watchman_load_string(ptr, end);
value = watchman_load(ptr, end);
rb_hash_aset(hash, key, value);
}
return hash;
}
/**
* Reads and returns a templated array encoded in the Watchman binary protocol
* format, starting at `ptr` and finishing at or before `end`
*
* Templated arrays are arrays of hashes which have repetitive key information
* pulled out into a separate "headers" prefix.
*
* @see https://github.com/facebook/watchman/blob/master/BSER.markdown
*/
VALUE watchman_load_template(char **ptr, char *end) {
int64_t header_items_count, i, row_count;
VALUE array, hash, header, key, value;
*ptr += sizeof(int8_t); // caller has already verified the marker
// process template header array
header_items_count = watchman_load_array_header(ptr, end);
header = rb_ary_new2(header_items_count);
for (i = 0; i < header_items_count; i++) {
rb_ary_push(header, watchman_load_string(ptr, end));
}
// process row items
row_count = watchman_load_int(ptr, end);
array = rb_ary_new2(header_items_count);
while (row_count--) {
hash = rb_hash_new();
for (i = 0; i < header_items_count; i++) {
if (*ptr >= end) {
rb_raise(rb_eArgError, "unexpected end of input");
}
if (*ptr[0] == WATCHMAN_SKIP_MARKER) {
*ptr += sizeof(uint8_t);
} else {
value = watchman_load(ptr, end);
key = rb_ary_entry(header, i);
rb_hash_aset(hash, key, value);
}
}
rb_ary_push(array, hash);
}
return array;
}
/**
* Reads and returns an object encoded in the Watchman binary protocol format,
* starting at `ptr` and finishing at or before `end`
*/
VALUE watchman_load(char **ptr, char *end) {
if (*ptr >= end) {
rb_raise(rb_eArgError, "unexpected end of input");
}
switch (*ptr[0]) {
case WATCHMAN_ARRAY_MARKER:
return watchman_load_array(ptr, end);
case WATCHMAN_HASH_MARKER:
return watchman_load_hash(ptr, end);
case WATCHMAN_STRING_MARKER:
return watchman_load_string(ptr, end);
case WATCHMAN_INT8_MARKER:
case WATCHMAN_INT16_MARKER:
case WATCHMAN_INT32_MARKER:
case WATCHMAN_INT64_MARKER:
return LL2NUM(watchman_load_int(ptr, end));
case WATCHMAN_FLOAT_MARKER:
return rb_float_new(watchman_load_double(ptr, end));
case WATCHMAN_TRUE:
*ptr += 1;
return Qtrue;
case WATCHMAN_FALSE:
*ptr += 1;
return Qfalse;
case WATCHMAN_NIL:
*ptr += 1;
return Qnil;
case WATCHMAN_TEMPLATE_MARKER:
return watchman_load_template(ptr, end);
default:
rb_raise(rb_eTypeError, "unsupported type");
}
return Qnil; // keep the compiler happy
}
/**
* CommandT::Watchman::Utils.load(serialized)
*
* Converts the binary object, `serialized`, from the Watchman binary protocol
* format into a normal Ruby object.
*/
VALUE CommandTWatchmanUtils_load(VALUE self, VALUE serialized) {
serialized = StringValue(serialized);
long len = RSTRING_LEN(serialized);
char *ptr = RSTRING_PTR(serialized);
char *end = ptr + len;
// expect at least the binary marker and a int8_t length counter
if ((size_t)len < sizeof(WATCHMAN_BINARY_MARKER) - 1 + sizeof(int8_t) * 2) {
rb_raise(rb_eArgError, "undersized header");
}
if (memcmp(ptr, WATCHMAN_BINARY_MARKER, sizeof(WATCHMAN_BINARY_MARKER) - 1)) {
rb_raise(rb_eArgError, "missing binary marker");
}
// get size marker
ptr += sizeof(WATCHMAN_BINARY_MARKER) - 1;
uint64_t payload_size = watchman_load_int(&ptr, end);
if (!payload_size) {
rb_raise(rb_eArgError, "empty payload");
}
// sanity check length
if (ptr + payload_size != end) {
rb_raise(rb_eArgError, "payload size mismatch (%lu)", end - (ptr + payload_size));
}
VALUE loaded = watchman_load(&ptr, end);
// one more sanity check
if (ptr != end) {
rb_raise(rb_eArgError, "payload termination mismatch (%lu)", end - ptr);
}
return loaded;
}
/**
* CommandT::Watchman::Utils.dump(serializable)
*
* Converts the Ruby object, `serializable`, into a binary string in the
* Watchman binary protocol format.
*
* Examples of serializable objects include arrays, hashes, strings, numbers
* (integers, floats), booleans, and nil.
*/
VALUE CommandTWatchmanUtils_dump(VALUE self, VALUE serializable) {
watchman_t *w = watchman_init();
watchman_dump(w, serializable);
// update header with final length information
uint64_t *len = (uint64_t *)(w->data + sizeof(WATCHMAN_HEADER) - sizeof(uint64_t) - 1);
*len = w->len - sizeof(WATCHMAN_HEADER) + 1;
// prepare final return value
VALUE serialized = rb_str_buf_new(w->len);
rb_str_buf_cat(serialized, (const char*)w->data, w->len);
watchman_free(w);
return serialized;
}
/**
* Helper method for raising a SystemCallError wrapping a lower-level error code
* coming from the `errno` global variable.
*/
void watchman_raise_system_call_error(int number) {
VALUE error = INT2FIX(number);
rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError));
}
// How far we have to look to figure out the size of the PDU header
#define WATCHMAN_SNIFF_BUFFER_SIZE sizeof(WATCHMAN_BINARY_MARKER) - 1 + sizeof(int8_t)
// How far we have to peek, at most, to figure out the size of the PDU itself
#define WATCHMAN_PEEK_BUFFER_SIZE \
sizeof(WATCHMAN_BINARY_MARKER) - 1 + \
sizeof(WATCHMAN_INT64_MARKER) + \
sizeof(int64_t)
/**
* CommandT::Watchman::Utils.query(query, socket)
*
* Converts `query`, a Watchman query comprising Ruby objects, into the Watchman
* binary protocol format, transmits it over socket, and unserializes and
* returns the result.
*/
VALUE CommandTWatchmanUtils_query(VALUE self, VALUE query, VALUE socket) {
int fileno = NUM2INT(rb_funcall(socket, rb_intern("fileno"), 0));
// do blocking I/O to simplify the following logic
int flags = fcntl(fileno, F_GETFL);
if (fcntl(fileno, F_SETFL, flags & ~O_NONBLOCK) == -1) {
rb_raise(rb_eRuntimeError, "unable to clear O_NONBLOCK flag");
}
// send the message
VALUE serialized = CommandTWatchmanUtils_dump(self, query);
long query_len = RSTRING_LEN(serialized);
ssize_t sent = send(fileno, RSTRING_PTR(serialized), query_len, 0);
if (sent == -1) {
watchman_raise_system_call_error(errno);
} else if (sent != query_len) {
rb_raise(rb_eRuntimeError, "expected to send %ld bytes but sent %ld",
query_len, sent);
}
// sniff to see how large the header is
int8_t peek[WATCHMAN_PEEK_BUFFER_SIZE];
ssize_t received = recv(fileno, peek, WATCHMAN_SNIFF_BUFFER_SIZE, MSG_PEEK | MSG_WAITALL);
if (received == -1) {
watchman_raise_system_call_error(errno);
} else if (received != WATCHMAN_SNIFF_BUFFER_SIZE) {
rb_raise(rb_eRuntimeError, "failed to sniff PDU header");
}
// peek at size of PDU
int8_t sizes[] = { 0, 0, 0, 1, 2, 4, 8 };
ssize_t peek_size = sizeof(WATCHMAN_BINARY_MARKER) - 1 + sizeof(int8_t) +
sizes[peek[sizeof(WATCHMAN_BINARY_MARKER) - 1]];
received = recv(fileno, peek, peek_size, MSG_PEEK);
if (received == -1) {
watchman_raise_system_call_error(errno);
} else if (received != peek_size) {
rb_raise(rb_eRuntimeError, "failed to peek at PDU header");
}
int8_t *pdu_size_ptr = peek + sizeof(WATCHMAN_BINARY_MARKER) - sizeof(int8_t);
int64_t payload_size =
peek_size +
watchman_load_int((char **)&pdu_size_ptr, (char *)peek + peek_size);
// actually read the PDU
void *buffer = xmalloc(payload_size);
if (!buffer) {
rb_raise(rb_eNoMemError, "failed to allocate %lld bytes", payload_size);
}
received = recv(fileno, buffer, payload_size, MSG_WAITALL);
if (received == -1) {
watchman_raise_system_call_error(errno);
} else if (received != payload_size) {
rb_raise(rb_eRuntimeError, "failed to load PDU");
}
char *payload = buffer + peek_size;
VALUE loaded = watchman_load(&payload, payload + payload_size);
free(buffer);
return loaded;
}
#else /* don't build Watchman utils; supply stubs only*/
VALUE CommandTWatchmanUtils_load(VALUE self, VALUE serialized) {
rb_raise(rb_eRuntimeError, "unsupported operation");
}
VALUE CommandTWatchmanUtils_dump(VALUE self, VALUE serializable) {
rb_raise(rb_eRuntimeError, "unsupported operation");
}
VALUE CommandTWatchmanUtils_query(VALUE self, VALUE query, VALUE socket) {
rb_raise(rb_eRuntimeError, "unsupported operation");
}
#endif
// Copyright 2014 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <ruby.h>
/**
* @module CommandT::Watchman::Utils
*
* Methods for working with the Watchman binary protocol
*
* @see https://github.com/facebook/watchman/blob/master/BSER.markdown
*/
/**
* Convert an object serialized using the Watchman binary protocol[0] into an
* unpacked Ruby object
*/
extern VALUE CommandTWatchmanUtils_load(VALUE self, VALUE serialized);
/**
* Serialize a Ruby object into the Watchman binary protocol format
*/
extern VALUE CommandTWatchmanUtils_dump(VALUE self, VALUE serializable);
/**
* Issue `query` to the Watchman instance listening on `socket` (a `UNIXSocket`
* instance) and return the result
*
* The query is serialized following the Watchman binary protocol and the
* result is converted to native Ruby objects before returning to the caller.
*/
extern VALUE CommandTWatchmanUtils_query(VALUE self, VALUE query, VALUE socket);
File added
# Global snippets
# (c) holds no legal value ;)
snippet c)
`&enc[:2] == "utf" ? "©" : "(c)"` Copyright `strftime("%Y")` ${1:`g:snips_author`}. All Rights Reserved.${2}
snippet date
`strftime("%Y-%m-%d")`
snippet if
If ${1:condition} Then
${2:; True code}
EndIf
snippet el
Else
${1}
snippet elif
ElseIf ${1:condition} Then
${2:; True code}
# If/Else block
snippet ifel
If ${1:condition} Then
${2:; True code}
Else
${3:; Else code}
EndIf
# If/ElseIf/Else block
snippet ifelif
If ${1:condition 1} Then
${2:; True code}
ElseIf ${3:condition 2} Then
${4:; True code}
Else
${5:; Else code}
EndIf
# Switch block
snippet switch
Switch (${1:condition})
Case {$2:case1}:
{$3:; Case 1 code}
Case Else:
{$4:; Else code}
EndSwitch
# Select block
snippet select
Select (${1:condition})
Case {$2:case1}:
{$3:; Case 1 code}
Case Else:
{$4:; Else code}
EndSelect
# While loop
snippet while
While (${1:condition})
${2:; code...}
WEnd
# For loop
snippet for
For ${1:n} = ${3:1} to ${2:count}
${4:; code...}
Next
# New Function
snippet func
Func ${1:fname}(${2:`indent('.') ? 'self' : ''`}):
${4:Return}
EndFunc
# Message box
snippet msg
MsgBox(${3:MsgType}, ${1:"Title"}, ${2:"Message Text"})
# Debug Message
snippet debug
MsgBox(0, "Debug", ${1:"Debug Message"})
# Show Variable Debug Message
snippet showvar
MsgBox(0, "${1:VarName}", $1)
# main()
snippet main
int main(int argc, const char *argv[])
{
${1}
return 0;
}
# #include <...>
snippet inc
#include <${1:stdio}.h>${2}
# #include "..."
snippet Inc
#include "${1:`Filename("$1.h")`}"${2}
# #ifndef ... #define ... #endif
snippet Def
#ifndef $1
#define ${1:SYMBOL} ${2:value}
#endif${3}
snippet def
#define
snippet ifdef
#ifdef ${1:FOO}
${2:#define }
#endif
snippet #if
#if ${1:FOO}
${2}
#endif
# Header Include-Guard
# (the randomizer code is taken directly from TextMate; it could probably be
# cleaner, I don't know how to do it in vim script)
snippet once
#ifndef ${1:`toupper(Filename('', 'UNTITLED').'_'.system("/usr/bin/ruby -e 'print (rand * 2821109907455).round.to_s(36)'"))`}
#define $1
${2}
#endif /* end of include guard: $1 */
# If Condition
snippet if
if (${1:/* condition */}) {
${2:/* code */}
}
snippet el
else {
${1}
}
# Tertiary conditional
snippet t
${1:/* condition */} ? ${2:a} : ${3:b}
# Do While Loop
snippet do
do {
${2:/* code */}
} while (${1:/* condition */});
# While Loop
snippet wh
while (${1:/* condition */}) {
${2:/* code */}
}
# For Loop
snippet for
for (${2:i} = 0; $2 < ${1:count}; $2${3:++}) {
${4:/* code */}
}
# Custom For Loop
snippet forr
for (${1:i} = ${2:0}; ${3:$1 < 10}; $1${4:++}) {
${5:/* code */}
}
# Function
snippet fun
${1:void} ${2:function_name}(${3})
{
${4:/* code */}
}
# Function Declaration
snippet fund
${1:void} ${2:function_name}(${3});${4}
# Typedef
snippet td
typedef ${1:int} ${2:MyCustomType};${3}
# Struct
snippet st
struct ${1:`Filename('$1_t', 'name')`} {
${2:/* data */}
}${3: /* optional variable list */};${4}
# Typedef struct
snippet tds
typedef struct ${2:_$1 }{
${3:/* data */}
} ${1:`Filename('$1_t', 'name')`};
# Typdef enum
snippet tde
typedef enum {
${1:/* data */}
} ${2:foo};
# printf
# unfortunately version this isn't as nice as TextMates's, given the lack of a
# dynamic `...`
snippet pr
printf("${1:%s}\n"${2});${3}
# fprintf (again, this isn't as nice as TextMate's version, but it works)
snippet fpr
fprintf(${1:stderr}, "${2:%s}\n"${3});${4}
snippet .
[${1}]${2}
snippet un
unsigned
# Read File Into Vector
snippet readfile
std::vector<char> v;
if (FILE *${2:fp} = fopen(${1:"filename"}, "r")) {
char buf[1024];
while (size_t len = fread(buf, 1, sizeof(buf), $2))
v.insert(v.end(), buf, buf + len);
fclose($2);
}${3}
# std::map
snippet map
std::map<${1:key}, ${2:value}> map${3};
# std::vector
snippet vector
std::vector<${1:char}> v${2};
# Namespace
snippet ns
namespace ${1:`Filename('', 'my')`} {
${2}
} /* $1 */
# Class
snippet cl
class ${1:`Filename('$1_t', 'name')`} {
public:
$1 (${2:arguments});
virtual ~$1 ();
private:
${3:/* data */}
};
# Some useful Unicode entities
# Non-Breaking Space
snippet nbs
&nbsp;
# ←
snippet left
&#x2190;
# →
snippet right
&#x2192;
# ↑
snippet up
&#x2191;
# ↓
snippet down
&#x2193;
# ↩
snippet return
&#x21A9;
# ⇤
snippet backtab
&#x21E4;
# ⇥
snippet tab
&#x21E5;
# ⇧
snippet shift
&#x21E7;
# ⌃
snippet control
&#x2303;
# ⌅
snippet enter
&#x2305;
# ⌘
snippet command
&#x2318;
# ⌥
snippet option
&#x2325;
# ⌦
snippet delete
&#x2326;
# ⌫
snippet backspace
&#x232B;
# ⎋
snippet escape
&#x238B;
# Generic Doctype
snippet doctype HTML 4.01 Strict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""
"http://www.w3.org/TR/html4/strict.dtd">
snippet doctype HTML 4.01 Transitional
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""
"http://www.w3.org/TR/html4/loose.dtd">
snippet doctype HTML 5
<!DOCTYPE HTML>
snippet doctype XHTML 1.0 Frameset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
snippet doctype XHTML 1.0 Strict
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
snippet doctype XHTML 1.0 Transitional
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
snippet doctype XHTML 1.1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
# HTML Doctype 4.01 Strict
snippet docts
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""
"http://www.w3.org/TR/html4/strict.dtd">
# HTML Doctype 4.01 Transitional
snippet doct
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""
"http://www.w3.org/TR/html4/loose.dtd">
# HTML Doctype 5
snippet doct5
<!DOCTYPE HTML>
# XHTML Doctype 1.0 Frameset
snippet docxf
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
# XHTML Doctype 1.0 Strict
snippet docxs
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
# XHTML Doctype 1.0 Transitional
snippet docxt
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
# XHTML Doctype 1.1
snippet docx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
snippet html
<html>
${1}
</html>
snippet xhtml
<html xmlns="http://www.w3.org/1999/xhtml">
${1}
</html>
snippet body
<body>
${1}
</body>
snippet head
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"`Close()`>
<title>${1:`substitute(Filename('', 'Page Title'), '^.', '\u&', '')`}</title>
${2}
</head>
snippet title
<title>${1:`substitute(Filename('', 'Page Title'), '^.', '\u&', '')`}</title>${2}
snippet script
<script type="text/javascript" charset="utf-8">
${1}
</script>${2}
snippet scriptsrc
<script src="${1}.js" type="text/javascript" charset="utf-8"></script>${2}
snippet style
<style type="text/css" media="${1:screen}">
${2}
</style>${3}
snippet base
<base href="${1}" target="${2}"`Close()`>
snippet r
<br`Close()[1:]`>
snippet div
<div id="${1:name}">
${2}
</div>
# Embed QT Movie
snippet movie
<object width="$2" height="$3" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="$1"`Close()`>
<param name="controller" value="$4"`Close()`>
<param name="autoplay" value="$5"`Close()`>
<embed src="${1:movie.mov}"
width="${2:320}" height="${3:240}"
controller="${4:true}" autoplay="${5:true}"
scale="tofit" cache="true"
pluginspage="http://www.apple.com/quicktime/download/"
`Close()[1:]`>
</object>${6}
snippet fieldset
<fieldset id="$1">
<legend>${1:name}</legend>
${3}
</fieldset>
snippet form
<form action="${1:`Filename('$1_submit')`}" method="${2:get}" accept-charset="utf-8">
${3}
<p><input type="submit" value="Continue &rarr;"`Close()`></p>
</form>
snippet h1
<h1 id="${1:heading}">${2:$1}</h1>
snippet input
<input type="${1:text/submit/hidden/button}" name="${2:some_name}" value="${3}"`Close()`>${4}
snippet label
<label for="${2:$1}">${1:name}</label><input type="${3:text/submit/hidden/button}" name="${4:$2}" value="${5}" id="${6:$2}"`Close()`>${7}
snippet link
<link rel="${1:stylesheet}" href="${2:/css/master.css}" type="text/css" media="${3:screen}" charset="utf-8"`Close()`>${4}
snippet mailto
<a href="mailto:${1:joe@example.com}?subject=${2:feedback}">${3:email me}</a>
snippet meta
<meta name="${1:name}" content="${2:content}"`Close()`>${3}
snippet opt
<option value="${1:option}">${2:$1}</option>${3}
snippet optt
<option>${1:option}</option>${2}
snippet select
<select name="${1:some_name}" id="${2:$1}">
<option value="${3:option}">${4:$3}</option>
</select>${5}
snippet table
<table border="${1:0}">
<tr><th>${2:Header}</th></tr>
<tr><th>${3:Data}</th></tr>
</table>${4}
snippet textarea
<textarea name="${1:Name}" rows="${2:8}" cols="${3:40}">${4}</textarea>${5}
snippet main
public static void main (String [] args)
{
${1:/* code */}
}
snippet pu
public
snippet po
protected
snippet pr
private
snippet st
static
snippet fi
final
snippet ab
abstract
snippet re
return
snippet br
break;
snippet de
default:
${1}
snippet ca
catch(${1:Exception} ${2:e}) ${3}
snippet th
throw
snippet sy
synchronized
snippet im
import
snippet j.u
java.util
snippet j.i
java.io.
snippet j.b
java.beans.
snippet j.n
java.net.
snippet j.m
java.math.
snippet if
if (${1}) ${2}
snippet el
else
snippet elif
else if (${1}) ${2}
snippet wh
while (${1}) ${2}
snippet for
for (${1}; ${2}; ${3}) ${4}
snippet fore
for (${1} : ${2}) ${3}
snippet sw
switch (${1}) ${2}
snippet cs
case ${1}:
${2}
${3}
snippet tc
public class ${1:`Filename()`} extends ${2:TestCase}
snippet t
public void test${1:Name}() throws Exception ${2}
snippet cl
class ${1:`Filename("", "untitled")`} ${2}
snippet in
interface ${1:`Filename("", "untitled")`} ${2:extends Parent}${3}
snippet m
${1:void} ${2:method}(${3}) ${4:throws }${5}
snippet v
${1:String} ${2:var}${3: = null}${4};${5}
snippet co
static public final ${1:String} ${2:var} = ${3};${4}
snippet cos
static public final String ${1:var} = "${2}";${3}
snippet as
assert ${1:test} : "${2:Failure message}";${3}
# Prototype
snippet proto
${1:class_name}.prototype.${2:method_name} =
function(${3:first_argument}) {
${4:// body...}
};
# Function
snippet fun
function ${1:function_name} (${2:argument}) {
${3:// body...}
}
# Anonymous Function
snippet f
function(${1}) {${2}};
# if
snippet if
if (${1:true}) {${2}};
# if ... else
snippet ife
if (${1:true}) {${2}}
else{${3}};
# tertiary conditional
snippet t
${1:/* condition */} ? ${2:a} : ${3:b}
# switch
snippet switch
switch(${1:expression}) {
case '${3:case}':
${4:// code}
break;
${5}
default:
${2:// code}
}
# case
snippet case
case '${1:case}':
${2:// code}
break;
${3}
# for (...) {...}
snippet for
for (var ${2:i} = 0; $2 < ${1:Things}.length; $2${3:++}) {
${4:$1[$2]}
};
# for (...) {...} (Improved Native For-Loop)
snippet forr
for (var ${2:i} = ${1:Things}.length - 1; $2 >= 0; $2${3:--}) {
${4:$1[$2]}
};
# while (...) {...}
snippet wh
while (${1:/* condition */}) {
${2:/* code */}
}
# do...while
snippet do
do {
${2:/* code */}
} while (${1:/* condition */});
# Object Method
snippet :f
${1:method_name}: function(${2:attribute}) {
${4}
}${3:,}
# setTimeout function
snippet timeout
setTimeout(function() {${3}}${2}, ${1:10};
# Get Elements
snippet get
getElementsBy${1:TagName}('${2}')${3}
# Get Element
snippet gett
getElementBy${1:Id}('${2}')${3}
snippet def
<%def name="${1:name}">
${2:}
</%def>
snippet call
<%call expr="${1:name}">
${2:}
</%call>
snippet doc
<%doc>
${1:}
</%doc>
snippet text
<%text>
${1:}
</%text>
snippet for
% for ${1:i} in ${2:iter}:
${3:}
% endfor
snippet if if
% if ${1:condition}:
${2:}
% endif
snippet if if/else
% if ${1:condition}:
${2:}
% else:
${3:}
% endif
snippet try
% try:
${1:}
% except${2:}:
${3:pass}
% endtry
snippet wh
% while ${1:}:
${2:}
% endwhile
snippet $
${ ${1:} }
snippet <%
<% ${1:} %>
snippet <!%
<!% ${1:} %>
snippet inherit
<%inherit file="${1:filename}" />
snippet include
<%include file="${1:filename}" />
snippet namespace
<%namespace file="${1:name}" />
snippet page
<%page args="${1:}" />
# #import <...>
snippet Imp
#import <${1:Cocoa/Cocoa.h}>${2}
# #import "..."
snippet imp
#import "${1:`Filename()`.h}"${2}
# @selector(...)
snippet sel
@selector(${1:method}:)${3}
# @"..." string
snippet s
@"${1}"${2}
# Object
snippet o
${1:NSObject} *${2:foo} = [${3:$1 alloc}]${4};${5}
# NSLog(...)
snippet log
NSLog(@"${1:%@}"${2});${3}
# Class
snippet objc
@interface ${1:`Filename('', 'someClass')`} : ${2:NSObject}
{
}
@end
@implementation $1
${3}
@end
# Class Interface
snippet int
@interface ${1:`Filename('', 'someClass')`} : ${2:NSObject}
{${3}
}
${4}
@end
# Class Implementation
snippet impl
@implementation ${1:`Filename('', 'someClass')`}
${2}
@end
snippet init
- (id)init
{
[super init];
return self;
}
snippet ifself
if (self = [super init]) {
${1:/* code */}
}
return self;
snippet ibo
IBOutlet ${1:NSSomeClass} *${2:$1};${3}
# Category
snippet cat
@interface ${1:NSObject} (${2:Category})
@end
@implementation $1 ($2)
${3}
@end
# Category Interface
snippet cath
@interface ${1:NSObject} (${2:Category})
${3}
@end
# NSArray
snippet array
NSMutableArray *${1:array} = [NSMutable array];${2}
# NSDictionary
snippet dict
NSMutableDictionary *${1:dict} = [NSMutableDictionary dictionary];${2}
# NSBezierPath
snippet bez
NSBezierPath *${1:path} = [NSBezierPath bezierPath];${2}
# Method
snippet m
- (${1:id})${2:method}
{
${3}
}
# Method declaration
snippet md
- (${1:id})${2:method};${3}
# IBAction declaration
snippet ibad
- (IBAction)${1:method}:(${2:id})sender;${3}
# IBAction method
snippet iba
- (IBAction)${1:method}:(${2:id})sender
{
${3}
}
# awakeFromNib method
snippet wake
- (void)awakeFromNib
{
${1}
}
# Class Method
snippet M
+ (${1:id})${2:method}
{${3}
return nil;
}
# Sub-method (Call super)
snippet sm
- (${1:id})${2:method}
{
[super $2];${3}
return self;
}
# Method: Initialize
snippet I
+ (void) initialize
{
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWIthObjectsAndKeys:
${1}@"value", @"key",
nil]];
}
# Accessor Methods For:
# Object
snippet objacc
- (${1:id})${2:thing}
{
return $2;
}
- (void)set$2:($1)${3:new$2}
{
[$3 retain];
[$2 release];
$2 = $3;
}${4}
# for (object in array)
snippet forin
for (${1:Class} *${2:some$1} in ${3:array}) {
${4}
}
snippet forarray
unsigned int ${1:object}Count = [${2:array} count];
for (unsigned int index = 0; index < $1Count; index++) {
${3:id} $1 = [$2 $1AtIndex:index];
${4}
}
# IBOutlet
# @property (Objective-C 2.0)
snippet prop
@property (${1:retain}) ${2:NSSomeClass} ${3:*$2};${4}
# @synthesize (Objective-C 2.0)
snippet syn
@synthesize ${1:property};${2}
# [[ alloc] init]
snippet alloc
[[${1:foo} alloc] init${2}];${3}
# retain
snippet ret
[${1:foo} retain];${2}
# release
snippet rel
[${1:foo} release];
${2:$1 = nil;}
# autorelease
snippet arel
[${1:foo} autorelease];
# autorelease pool
snippet pool
NSAutoreleasePool *${1:pool} = [[NSAutoreleasePool alloc] init];
${2:/* code */}
[$1 drain];
# Throw an exception
snippet except
NSException *${1:badness};
$1 = [NSException exceptionWithName:@"${2:$1Name}"
reason:@"${3}"
userInfo:nil];
[$1 raise];
snippet prag
#pragma mark ${1:foo}
snippet cl
@class ${1:Foo};${2}
snippet color
[[NSColor ${1:blackColor}] set];
# #!/usr/bin/perl
snippet #!
#!/usr/bin/perl
# Hash Pointer
snippet .
=>
# Function
snippet sub
sub ${1:function_name} {
${2:#body ...}
}
# Conditional
snippet if
if (${1}) {
${2:# body...}
}
# Conditional if..else
snippet ife
if (${1}) {
${2:# body...}
} else {
${3:# else...}
}
# Conditional if..elsif..else
snippet ifee
if (${1}) {
${2:# body...}
} elsif (${3}) {
${4:# elsif...}
} else {
${5:# else...}
}
# Conditional One-line
snippet xif
${1:expression} if ${2:condition};${3}
# Unless conditional
snippet unless
unless (${1}) {
${2:# body...}
}
# Unless conditional One-line
snippet xunless
${1:expression} unless ${2:condition};${3}
# Try/Except
snippet eval
eval {
${1:# do something risky...}
};
if ($@) {
${2:# handle failure...}
}
# While Loop
snippet wh
while (${1}) {
${2:# body...}
}
# While Loop One-line
snippet xwh
${1:expression} while ${2:condition};${3}
# For Loop
snippet for
for (my $${2:var} = 0; $$2 < ${1:count}; $$2${3:++}) {
${4:# body...}
}
# Foreach Loop
snippet fore
foreach my $${1:x} (@${2:array}) {
${3:# body...}
}
# Foreach Loop One-line
snippet xfore
${1:expression} foreach @${2:array};${3}
# Package
snippet cl
package ${1:ClassName};
use base qw(${2:ParentClass});
sub new {
my $class = shift;
$class = ref $class if ref $class;
my $self = bless {}, $class;
$self;
}
1;${3}
# Read File
snippet slurp
my $${1:var};
{ local $/ = undef; local *FILE; open FILE, "<${2:file}"; $$1 = <FILE>; close FILE }${3}
snippet php
<?php
${1}
?>
snippet ec
echo "${1:string}"${2};
snippet inc
include '${1:file}';${2}
snippet inc1
include_once '${1:file}';${2}
snippet req
require '${1:file}';${2}
snippet req1
require_once '${1:file}';${2}
# $GLOBALS['...']
snippet globals
$GLOBALS['${1:variable}']${2: = }${3:something}${4:;}${5}
snippet $_ COOKIE['...']
$_COOKIE['${1:variable}']${2}
snippet $_ ENV['...']
$_ENV['${1:variable}']${2}
snippet $_ FILES['...']
$_FILES['${1:variable}']${2}
snippet $_ Get['...']
$_GET['${1:variable}']${2}
snippet $_ POST['...']
$_POST['${1:variable}']${2}
snippet $_ REQUEST['...']
$_REQUEST['${1:variable}']${2}
snippet $_ SERVER['...']
$_SERVER['${1:variable}']${2}
snippet $_ SESSION['...']
$_SESSION['${1:variable}']${2}
# Start Docblock
snippet /*
/**
* ${1}
**/
# Class - post doc
snippet doc_cp
/**
* ${1:undocumented class}
*
* @package ${2:default}
* @author ${3:`g:snips_author`}
**/${4}
# Class Variable - post doc
snippet doc_vp
/**
* ${1:undocumented class variable}
*
* @var ${2:string}
**/${3}
# Class Variable
snippet doc_v
/**
* ${3:undocumented class variable}
*
* @var ${4:string}
**/
${1:var} $${2};${5}
# Class
snippet doc_c
/**
* ${3:undocumented class}
*
* @packaged ${4:default}
* @author ${5:`g:snips_author`}
**/
${1:}class ${2:}
{${6}
} // END $1class $2
# Constant Definition - post doc
snippet doc_dp
/**
* ${1:undocumented constant}
**/${2}
# Constant Definition
snippet doc_d
/**
* ${3:undocumented constant}
**/
define(${1}, ${2});${4}
# Function - post doc
snippet doc_fp
/**
* ${1:undocumented function}
*
* @return ${2:void}
* @author ${3:`g:snips_author`}
**/${4}
# Function signature
snippet doc_s
/**
* ${4:undocumented function}
*
* @return ${5:void}
* @author ${6:`g:snips_author`}
**/
${1}function ${2}(${3});${7}
# Function
snippet doc_f
/**
* ${4:undocumented function}
*
* @return ${5:void}
* @author ${6:`g:snips_author`}
**/
${1}function ${2}(${3})
{${7}
}
# Header
snippet doc_h
/**
* ${1}
*
* @author ${2:`g:snips_author`}
* @version ${3:$Id$}
* @copyright ${4:$2}, `strftime('%d %B, %Y')`
* @package ${5:default}
**/
/**
* Define DocBlock
*//
# Interface
snippet doc_i
/**
* ${2:undocumented class}
*
* @package ${3:default}
* @author ${4:`g:snips_author`}
**/
interface ${1:}
{${5}
} // END interface $1
# class ...
snippet class
/**
* ${1}
**/
class ${2:ClassName}
{
${3}
function ${4:__construct}(${5:argument})
{
${6:// code...}
}
}
# define(...)
snippet def
define('${1}'${2});${3}
# defined(...)
snippet def?
${1}defined('${2}')${3}
snippet wh
while (${1:/* condition */}) {
${2:// code...}
}
# do ... while
snippet do
do {
${2:// code... }
} while (${1:/* condition */});
snippet if
if (${1:/* condition */}) {
${2:// code...}
}
snippet ife
if (${1:/* condition */}) {
${2:// code...}
} else {
${3:// code...}
}
${4}
snippet else
else {
${1:// code...}
}
snippet elseif
elseif (${1:/* condition */}) {
${2:// code...}
}
# Tertiary conditional
snippet t
$${1:retVal} = (${2:condition}) ? ${3:a} : ${4:b};${5}
snippet switch
switch ($${1:variable}) {
case '${2:value}':
${3:// code...}
break;
${5}
default:
${4:// code...}
break;
}
snippet case
case '${1:value}':
${2:// code...}
break;${3}
snippet for
for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) {
${4: // code...}
}
snippet foreach
foreach ($${1:variable} as $${2:key}) {
${3:// code...}
}
snippet fun
${1:public }function ${2:FunctionName}(${3})
{
${4:// code...}
}
# $... = array (...)
snippet array
$${1:arrayName} = array('${2}' => ${3});${4}
snippet #!
#!/usr/bin/python
snippet imp
import ${1:module}
# Module Docstring
snippet docs
'''
File: ${1:`Filename('$1.py', 'foo.py')`}
Author: ${2:`g:snips_author`}
Description: ${3}
'''
snippet wh
while ${1:condition}:
${2:# code...}
snippet for
for ${1:needle} in ${2:haystack}:
${3:# code...}
# New Class
snippet cl
class ${1:ClassName}(${2:object}):
"""${3:docstring for $1}"""
def __init__(self, ${4:arg}):
${5:super($1, self).__init__()}
self.$4 = $4
${6}
# New Function
snippet def
def ${1:fname}(${2:`indent('.') ? 'self' : ''`}):
"""${3:docstring for $1}"""
${4:pass}
snippet deff
def ${1:fname}(${2:`indent('.') ? 'self' : ''`}):
${3}
# New Method
snippet defs
def ${1:mname}(self, ${2:arg}):
${3:pass}
# New Property
snippet property
def ${1:foo}():
doc = "${2:The $1 property.}"
def fget(self):
${3:return self._$1}
def fset(self, value):
${4:self._$1 = value}
# Lambda
snippet ld
${1:var} = lambda ${2:vars} : ${3:action}
snippet .
self.
snippet try Try/Except
try:
${1:pass}
except ${2:Exception}, ${3:e}:
${4:raise $3}
snippet try Try/Except/Else
try:
${1:pass}
except ${2:Exception}, ${3:e}:
${4:raise $3}
else:
${5:pass}
snippet try Try/Except/Finally
try:
${1:pass}
except ${2:Exception}, ${3:e}:
${4:raise $3}
finally:
${5:pass}
snippet try Try/Except/Else/Finally
try:
${1:pass}
except ${2:Exception}, ${3:e}:
${4:raise $3}
else:
${5:pass}
finally:
${6:pass}
# if __name__ == '__main__':
snippet ifmain
if __name__ == '__main__':
${1:main()}
# __magic__
snippet _
__${1:init}__${2}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment