Created
December 17, 2011 14:23
-
-
Save tsukkee/1490326 to your computer and use it in GitHub Desktop.
Vim Advent Calendar 18日目
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
python <<EOM | |
# coding=utf-8 | |
import vim | |
import re | |
# decorator for defining Vim script function | |
_functions_for_vim = {} | |
def vimfunc(name, *args): | |
def _(func): | |
_functions_for_vim[name] = func | |
args = func.func_code.co_varnames[:func.func_code.co_argcount] | |
vim.command(""" | |
function! {0}(...) | |
python <<END_OF_PYTHON | |
# coding=utf-8 | |
vim.command('return ' + vimliteral(_functions_for_vim['{0}']({2}))) | |
END_OF_PYTHON | |
endfunction | |
""".format(name, __name__, | |
", ".join(map(lambda x: "vim.eval('a:" + str(x) + "')", range(1, func.func_code.co_argcount + 1))))) | |
def __(*args, **keywords): | |
return func(*args, **keywords) | |
return __ | |
return _ | |
# convert python value to Vim script value | |
_none_type = type(None) | |
_bool_type = type(True) | |
_string_type = type('') | |
_unicode_type = type(u'') | |
_num_type = type(0) | |
_array_type = type([]) | |
_tuple_type = type(()) | |
_dict_type = type({}) | |
def vimliteral(obj): | |
kind = type(obj) | |
if kind == _none_type: | |
return '0' | |
elif kind == _bool_type: | |
return '1' if obj else '0' | |
elif kind == _num_type: | |
return str(obj) | |
elif kind == _unicode_type: | |
return vimliteral(encode(obj)) | |
elif kind == _string_type: | |
return '"' + escape(obj) + '"' | |
elif kind == _array_type: | |
return '[' + ','.join(map(vimliteral, obj)) + ']' | |
elif kind == _tuple_type: | |
return vimliteral(list(obj)) | |
elif kind == _dict_type: | |
result = [] | |
for k, v in obj.iteritems(): | |
result.append(vimliteral(k) + ':' + vimliteral(v)) | |
return '{' + ','.join(result) + '}' | |
else: | |
raise VimUtilError('vimliteral: can not convert') | |
# escape "(double quote) and \(backslash) | |
_quote_by_backslash = re.compile('(["\\\\])') | |
def escape(s): | |
return _quote_by_backslash.sub(r'\\\1', s) | |
# examples!! | |
@vimfunc('Hoge') | |
def hoge(a, b, c): | |
return ', '.join((a, b, c)) | |
@vimfunc('s:fuga') | |
def fuga(s, n): | |
return s * int(n) | |
EOM | |
# usage!! | |
echomsg Hoge(3, 4, 5) " => 3,4,5 | |
echomsg s:fuga('ふが', 5) " => ふがふがふがふがふが |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment