本文整理汇总了Python中vim.eval函数的典型用法代码示例。如果您正苦于以下问题:Python eval函数的具体用法?Python eval怎么用?Python eval使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了eval函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: tabnew
def tabnew(path):
"Open a file in a new tab or switch to an existing one"
path = os.path.abspath(path)
if vim.eval('has("gui")') == '1':
vim.command('tab drop %s' % path)
return
for tab_nr in range(int(vim.eval("tabpagenr('$')"))):
for buf_nr in vim.eval("tabpagebuflist(%i + 1)" % tab_nr):
buf_nr = int(buf_nr) - 1
try:
buf_path = vim.buffers[buf_nr].name
except IndexError:
# Just do good old asking for forgiveness.
# don't know why this happens :-)
pass
else:
if buf_path == path:
# tab exists, just switch to that tab
vim.command('tabfirst | tabnext %i' % (tab_nr + 1))
break
else:
continue
break
else:
# tab doesn't exist, add a new one.
vim.command('tabnew %s' % path)
开发者ID:Charlesdong,项目名称:my-vim,代码行数:27,代码来源:jedi_vim.py
示例2: tern_startServer
def tern_startServer(project):
if time.time() - project.last_failed < 30: return None
win = platform.system() == "Windows"
env = None
if platform.system() == "Darwin":
env = os.environ.copy()
env["PATH"] += ":/usr/local/bin"
command = vim.eval("g:tern#command") + vim.eval("g:tern#arguments")
try:
proc = subprocess.Popen(command,
cwd=project.dir, env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=win)
except Exception as e:
tern_displayError("Failed to start server: " + str(e))
return None
output = ""
while True:
line = proc.stdout.readline().decode('utf8')
if not line:
tern_displayError("Failed to start server" + (output and ":\n" + output))
project.last_failed = time.time()
return None
match = re.match("Listening on port (\\d+)", line)
if match:
port = int(match.group(1))
project.port = port
project.proc = proc
return port
else:
output += line
开发者ID:TDaglis,项目名称:tern_for_vim,代码行数:32,代码来源:tern.py
示例3: LoadDictIntoVimGlobals
def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
extend_option = '"force"' if overwrite else '"keep"'
# We need to use json.dumps because that won't use the 'u' prefix on strings
# which Vim would bork on.
vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
extend_option ) )
开发者ID:smartsystems4u,项目名称:YouCompleteMe,代码行数:7,代码来源:vimsupport.py
示例4: fold_text
def fold_text(allow_dirty=False):
u""" Set the fold text
:setlocal foldtext=Method-which-calls-foldtext
:allow_dirty: Perform a query without (re)building the DOM if True
:returns: None
"""
line = int(vim.eval(u_encode(u'v:foldstart')))
d = ORGMODE.get_document(allow_dirty=allow_dirty)
heading = None
if allow_dirty:
heading = d.find_current_heading(line - 1)
else:
heading = d.current_heading(line - 1)
if heading:
str_heading = unicode(heading)
# expand tabs
ts = int(vim.eval(u_encode(u'&ts')))
idx = str_heading.find(u'\t')
if idx != -1:
tabs, spaces = divmod(idx, ts)
str_heading = str_heading.replace(u'\t', u' ' * (ts - spaces), 1)
str_heading = str_heading.replace(u'\t', u' ' * ts)
# Workaround for vim.command seems to break the completion menu
vim.eval(u_encode(u'SetOrgFoldtext("%s...")' % (re.sub(r'\[\[([^[\]]*\]\[)?([^[\]]+)\]\]', r'\2',
str_heading).replace( u'\\', u'\\\\').replace(u'"', u'\\"'), )))
开发者ID:jqno,项目名称:vim-orgmode,代码行数:28,代码来源:_vim.py
示例5: main
def main():
binary = 'clang-rename'
if vim.eval('exists("g:clang_rename_path")') == "1":
binary = vim.eval('g:clang_rename')
# Get arguments for clang-rename binary.
offset = int(vim.eval('line2byte(line("."))+col(".")')) - 2
if offset < 0:
print >> sys.stderr, '''Couldn\'t determine cursor position.
Is your file empty?'''
return
filename = vim.current.buffer.name
new_name_request_message = 'type new name:'
new_name = vim.eval("input('{}\n')".format(new_name_request_message))
# Call clang-rename.
command = [binary,
filename,
'-i',
'-offset', str(offset),
'-new-name', str(new_name)]
# FIXME: make it possible to run the tool on unsaved file.
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if stderr:
print stderr
# Reload all buffers in Vim.
vim.command("bufdo edit")
开发者ID:bbannier,项目名称:clang-tools-extra-1,代码行数:33,代码来源:clang-rename.py
示例6: base_snippet_files_for
def base_snippet_files_for(self, ft, default=True):
""" Returns a list of snippet files matching the given filetype (ft).
If default is set to false, it doesn't include shipped files.
Searches through each path in 'runtimepath' in reverse order,
in each of these, it searches each directory name listed in
'g:UltiSnipsSnippetDirectories' in order, then looks for files in these
directories called 'ft.snippets' or '*_ft.snippets' replacing ft with
the filetype.
"""
snippet_dirs = vim.eval("g:UltiSnipsSnippetDirectories")
base_snippets = os.path.realpath(os.path.join(__file__, "../../../UltiSnips"))
ret = []
paths = vim.eval("&runtimepath").split(',')
if vim.eval("exists('g:UltiSnipsDontReverseSearchPath')") == "0" or \
vim.eval("g:UltiSnipsDontReverseSearchPath") == "0":
paths = paths[::-1]
for rtp in paths:
for snippet_dir in snippet_dirs:
pth = os.path.realpath(os.path.expanduser(os.path.join(rtp, snippet_dir)))
patterns = ["%s.snippets", "*_%s.snippets"]
if not default and pth == base_snippets:
patterns.remove("%s.snippets")
for pattern in patterns:
for fn in glob.glob(os.path.join(pth, pattern % ft)):
if fn not in ret:
ret.append(fn)
return ret
开发者ID:alexmorozov,项目名称:vim,代码行数:35,代码来源:__init__.py
示例7: create_new_note_from_current_buffer
def create_new_note_from_current_buffer(self):
""" get content of the current buffer and create new note """
content = "\n".join(str(line) for line in vim.current.buffer[:])
markdown = (vim.eval("&filetype") == "markdown")
if markdown:
note, status = self.simplenote.update_note({"content": content,
"systemtags": ["markdown"]})
else:
note, status = self.simplenote.update_note({"content": content})
if status == 0:
self.note_version[note["key"]] = note["version"]
self.transform_to_scratchbuffer()
# Replace any non alphanumeric characters to play safe with valid vim buffer names
# otherwise vim will happily add them, but will fail to switch to them
regex = re.compile("[^a-zA-Z0-9]")
firstline = regex.sub("_", vim.current.buffer[0])
buffertitle = "SN_%s" % firstline
self.set_current_note(buffertitle, note["key"])
self.bufnum_to_noteid[vim.current.buffer.number] = note["key"]
vim.command("doautocmd BufReadPost")
# BufReadPost can cause auto-selection of filetype based on file content so reset filetype after this
if int(vim.eval("exists('g:SimplenoteFiletype')")) == 1:
vim.command("setlocal filetype="+vim.eval("g:SimplenoteFiletype"))
# But let simplenote markdown flag override the above
if markdown:
vim.command("setlocal filetype=markdown")
print("New note created.")
else:
print("Update failed.: %s" % note["key"])
开发者ID:andrey-starodubtsev,项目名称:simplenote.vim,代码行数:29,代码来源:SimplenoteUtilities.py
示例8: _get_preview_url
def _get_preview_url(self):
wiki_repo_defined = int(vim.eval("exists('g:ghwiki_preview_repo')"))
if not wiki_repo_defined:
self._err = "please set ghwiki_preview_repo in your ~/.vimrc"
return
wiki_repo = vim.eval("g:ghwiki_preview_repo")
if len(wiki_repo.split('/')) != 2:
self._err = "invalid ghwiki_preview_repo set, "
self._err += "must have the form: 'user/repo'"
return
user, repo = wiki_repo.split('/')
gh = github.GitHub()
try:
repo_exists = gh.repos.show(user, repo)
if not repo_exists.has_wiki:
self._err = "repo %s does not have a git-backed wiki enabled"
self._err = self._err % repo
return
except urllib2.HTTPError:
self._err = "repo %s does not exist" % wiki_repo
return
except urllib2.URLError:
self._err = "no internet connection available"
return
return 'https://github.com/%s/%s/wiki/_preview' % (user, repo)
开发者ID:jtriley,项目名称:vim-ghwiki-preview,代码行数:25,代码来源:ghwiki.py
示例9: set_tags
def set_tags(cls):
u""" Set tags for current heading
"""
d = ORGMODE.get_document()
heading = d.current_heading()
if not heading:
return
# retrieve tags
res = None
if heading.tags:
res = vim.eval(u'input("Tags: ", ":%s:", "customlist,Org_complete_tags")' % u':'.join(heading.tags))
else:
res = vim.eval(u'input("Tags: ", "", "customlist,Org_complete_tags")')
if res is None:
# user pressed <Esc> abort any further processing
return
# remove empty tags
heading.tags = filter(lambda x: x.strip() != u'', res.decode(u'utf-8').strip().strip(u':').split(u':'))
d.write()
return u'OrgSetTags'
开发者ID:cowboy13,项目名称:vim-orgmode,代码行数:25,代码来源:TagsProperties.py
示例10: getCurrentCompletions
def getCurrentCompletions(base):
priority = vim.eval("g:clang_sort_algo") == "priority"
line = int(vim.eval("line('.')"))
column = int(vim.eval("b:col"))
t = CompleteThread(line, column, getCurrentFile(), vim.current.buffer.name)
t.start()
while t.isAlive():
t.join(0.01)
cancel = int(vim.eval("complete_check()"))
if cancel != 0:
return []
cr = t.result
if cr is None:
return []
regexp = re.compile("^" + base)
filteredResult = filter(lambda x: regexp.match(getAbbr(x.string)), cr.results)
getPriority = lambda x: x.string.priority
getAbbrevation = lambda x: getAbbr(x.string).lower()
if priority:
key = getPriority
else:
key = getAbbrevation
sortedResult = sorted(filteredResult, None, key)
return map(formatResult, sortedResult)
开发者ID:exclipy,项目名称:clang_complete,代码行数:27,代码来源:libclang.py
示例11: debugger_init
def debugger_init(debug=0):
global debugger
# get needed vim variables
# port that the engine will connect on
port = int(vim.eval("debuggerPort"))
if port == 0:
port = 9000
# the max_depth variable to set in the engine
max_children = vim.eval("debuggerMaxChildren")
if max_children == "":
max_children = "32"
max_data = vim.eval("debuggerMaxData")
if max_data == "":
max_data = "1024"
max_depth = vim.eval("debuggerMaxDepth")
if max_depth == "":
max_depth = "1"
minibufexpl = int(vim.eval("debuggerMiniBufExpl"))
if minibufexpl == 0:
minibufexpl = 0
debugger = Debugger(port, max_children, max_data, max_depth, minibufexpl, debug)
开发者ID:spigwitmer,项目名称:vim-dbgp,代码行数:28,代码来源:debugger.py
示例12: updateCurrentDiagnostics
def updateCurrentDiagnostics():
global debug
debug = int(vim.eval("g:clang_debug")) == 1
userOptionsGlobal = splitOptions(vim.eval("g:clang_user_options"))
userOptionsLocal = splitOptions(vim.eval("b:clang_user_options"))
args = userOptionsGlobal + userOptionsLocal
getCurrentTranslationUnit(args, getCurrentFile(), vim.current.buffer.name, update=True)
开发者ID:exclipy,项目名称:clang_complete,代码行数:7,代码来源:libclang.py
示例13: CandidatesForQueryAsyncInner
def CandidatesForQueryAsyncInner( self, query, unused_start_column ):
if not self.omnifunc:
self.stored_candidates = None
return
try:
return_value = int( vim.eval( self.omnifunc + '(1,"")' ) )
if return_value < 0:
self.stored_candidates = None
return
omnifunc_call = [ self.omnifunc,
"(0,'",
vimsupport.EscapeForVim( query ),
"')" ]
items = vim.eval( ''.join( omnifunc_call ) )
if 'words' in items:
items = items['words']
if not hasattr( items, '__iter__' ):
raise TypeError( OMNIFUNC_NOT_LIST )
self.stored_candidates = filter( bool, items )
except (TypeError, ValueError) as error:
vimsupport.PostVimMessage(
OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) )
self.stored_candidates = None
return
开发者ID:arcarson,项目名称:dotfiles,代码行数:29,代码来源:omni_completer.py
示例14: execute
def execute(self, should_open):
with open("pandoc.out", 'w') as tmp:
if vim.eval("has('clientserver')") == '1' and \
vim.eval("v:servername") != "" and \
vim.eval("executable('python')") == '1':
async_runner = '"' + os.path.join(os.path.dirname(__file__), "async.py") + '"'
servername_arg = "--servername=" + vim.eval("v:servername")
open_arg = "--open" if should_open else "--noopen"
async_command = " ".join(["python", async_runner, servername_arg, open_arg, self._run_command])
try:
Popen(shlex.split(async_command), stdout=tmp, stderr=tmp)
except:
vim.command('echoe "vim-pandoc: could not execute pandoc asynchronously"')
elif vim.eval("has('nvim')") == '1':
vim.command("call jobstart("+ \
str(['pandoc'] + shlex.split(self._run_command)[1:]) + \
", extend({'should_open': '" + str(int(should_open)) + \
"'}, {'on_exit': 'pandoc#command#JobHandler'}))")
#vim.command('call jobstart(["pandoc", ' + str(shlex.split(self._run_command)[1:]) + '])')
else:
try:
com = Popen(shlex.split(self._run_command), stdout=tmp, stderr=tmp)
com.wait()
except:
vim.command('echoe "vim-pandoc: could not execute pandoc"')
return
self.on_done(should_open, com.returncode)
开发者ID:kassick,项目名称:vim-pandoc,代码行数:28,代码来源:command.py
示例15: debugger_init
def debugger_init(debug = 0):
global debugger
# get needed vim variables
# port that the engine will connect on
port = int(vim.eval('debuggerPort'))
if port == 0:
port = 9000
# the max_depth variable to set in the engine
max_children = vim.eval('debuggerMaxChildren')
if max_children == '':
max_children = '32'
max_data = vim.eval('debuggerMaxData')
if max_data == '':
max_data = '1024'
max_depth = vim.eval('debuggerMaxDepth')
if max_depth == '':
max_depth = '1'
minibufexpl = int(vim.eval('debuggerMiniBufExpl'))
if minibufexpl == 0:
minibufexpl = 0
debugger = Debugger(port, max_children, max_data, max_depth, minibufexpl, debug)
开发者ID:charlielin,项目名称:vim_files,代码行数:28,代码来源:debugger-dbgp.py
示例16: bufvar_exists
def bufvar_exists(buffer, varname):
if not buffer or buffer.number == vim.current.buffer.number:
return int(vim.eval('exists("b:{0}")'.format(varname)))
else:
return int(vim.eval(
'has_key(getbufvar({0}, ""), {1})'.format(buffer.number, varname)
))
开发者ID:Tukeke,项目名称:powerline,代码行数:7,代码来源:__init__.py
示例17: set_srcview
def set_srcview(self, file, line):
""" set srcview windows to file:line and replace current sign """
if '0' != vim.eval('exists("g:debuggerPathMap")'):
import re
map_sep = re.compile(',\s*')
path_sep = re.compile('\s*:\s*')
mappings = map_sep.split(vim.eval('g:debuggerPathMap'))
#print mappings
if mappings:
for mapping in mappings:
(remote_path, local_path) = path_sep.split(mapping)
path_map = re.compile('(' + remote_path + ')')
file = path_map.sub(local_path, file)
if file == self.file and self.line == line:
return
nextsign = self.next_sign()
if file != self.file:
self.file = file
self.go_srcview()
vim.command('silent edit ' + file)
vim.command('sign place ' + nextsign + ' name=current line='+str(line)+' file='+file)
vim.command('sign unplace ' + self.cursign)
vim.command('sign jump ' + nextsign + ' file='+file)
#vim.command('normal z.')
self.line = line
self.cursign = nextsign
开发者ID:charlielin,项目名称:vim_files,代码行数:33,代码来源:debugger-dbgp.py
示例18: ub_get_meta
def ub_get_meta(item, buf=None):
'''Get value of the given item from meta data in the current buffer
'''
def __get_value(item, line):
tmp = line.split(':')
val = ':'.join(tmp[1:]).strip()
if item.endswith('id'):
if val.isdigit():
val = int(val)
if val<=0:
return None
else:
return None
return val
nr = ub_get_bufnr(buf)
if nr is None: nr = int(vim.eval("bufnr('%')"))
regex_meta_end = re.compile('^\s*-->')
regex_item = re.compile('^\$'+item+':\s*')
for line in vim.eval("getbufline(%d,0,'$')" % nr):
if regex_meta_end.match(line):
break
if regex_item.match(line):
return __get_value(item, line)
return None
开发者ID:bantana,项目名称:UltraBlog.vim,代码行数:25,代码来源:util.py
示例19: _handle_failure
def _handle_failure(self, trigger):
"""
Mainly make sure that we play well with SuperTab
"""
if trigger.lower() == "<tab>":
feedkey = "\\" + trigger
else:
feedkey = None
mode = "n"
if not self._supertab_keys:
if vim.eval("exists('g:SuperTabMappingForward')") != "0":
self._supertab_keys = (
vim.eval("g:SuperTabMappingForward"),
vim.eval("g:SuperTabMappingBackward"),
)
else:
self._supertab_keys = [ '', '' ]
for idx, sttrig in enumerate(self._supertab_keys):
if trigger.lower() == sttrig.lower():
if idx == 0:
feedkey= r"\<c-n>"
elif idx == 1:
feedkey = r"\<c-p>"
# Use remap mode so SuperTab mappings will be invoked.
mode = "m"
break
if feedkey:
feedkeys(feedkey, mode)
开发者ID:alexmorozov,项目名称:vim,代码行数:30,代码来源:__init__.py
示例20: ub_get_blog_settings
def ub_get_blog_settings():
'''Get the blog settings from vimrc and raise exception if none found
'''
class UBConfiguration:
homepage = 'http://0x3f.org/blog/ultrablog-as-an-ultimate-vim-blogging-plugin/'
def __init__(self, rawSettings):
self.loginName = rawSettings['login_name'].strip()
self.password = rawSettings['password'].strip()
self.dbf = rawSettings['db'].strip()
self.url = rawSettings['url'].strip()
self.url = self.url.endswith('/') and self.url or self.url+'/'
self.xmlrpc = self.url+'xmlrpc.php'
if vim.eval('exists("ub_blog")') == '0':
return None
settings = vim.eval('ub_blog')
cfg = UBConfiguration(settings)
# Manipulate db file path
editor_mode = ub_get_option('ub_editor_mode')
if editor_mode is not None and editor_mode.isdigit() and int(editor_mode) == 1:
cfg.dbf = ''
elif cfg.dbf is None or cfg.dbf=='':
cfg.dbf = os.path.normpath(os.path.expanduser('~')+'/.vim/UltraBlog.db')
else:
cfg.dbf = os.path.abspath(vim.eval("expand('%s')" % cfg.dbf))
return cfg
开发者ID:bantana,项目名称:UltraBlog.vim,代码行数:30,代码来源:util.py
注:本文中的vim.eval函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论