Nvim :help
页面,生成 自 源 使用 tree-sitter-vimdoc 解析器。
{stmt}
执行 Python 语句 {stmt}
。一个简单的检查 :python
命令是否工作的测试。:python print("Hello")
:[range]py[thon] << [trim] [{endmarker}
] {script}
{endmarker}
执行 Python 脚本 {script}
。在 Vim 脚本中包含 python 代码很有用。需要 Python,参见 script-here。{script}
之后必须使用一个点 '.',就像 :append 和 :insert 命令一样。有关更多信息,请参阅 :let-heredoc。function! IcecreamInitialize()
python << EOF
class StrawberryIcecream:
def __call__(self):
print('EAT ME')
EOF
endfunction
要查看你的 Python 版本:python print(sys.version)
不需要 "import sys",它默认情况下是完成的。{body}
对 [range] 中的每一行执行 Python 函数 "def _vim_pydo(line, linenr): {body}
",将函数参数分别设置为每一行的文本,不带尾部的 <EOL>
,以及当前行号。函数应返回一个字符串或 None。如果返回一个字符串,它将成为当前轮次的行的文本。[range] 的默认值为整个文件:"1,$"。:pydo return "%s\t%d" % (line[::-1], len(line))
:pydo if line: return "%4d: %s" % (linenr, line)
:pydo
与 :py
结合使用,以使用 python 过滤一个范围。例如:py3 << EOF
needle = vim.eval('@a')
replacement = vim.eval('@b')
def py_vim_string_replace(str):
return str.replace(needle, replacement)
EOF
:'<,'>py3do return py_vim_string_replace(line)
:python sys.argv = ["foo", "bar"]
:pyfile myscript.py
以下是一些示例 python-examples:python from vim import *
:python current.line = str.upper(current.line)
:python print("Hello")
:python str = current.buffer[42]
请注意,更改(例如 "import" 语句)从一个命令持续到下一个命令,就像 Python REPL 一样。if has('python')
python << EOF
print("python works")
EOF
endif
:python import vim
概述:py print("Hello") # displays a message
:py vim.command(cmd) # execute an Ex command
:py w = vim.windows[n] # gets window "n"
:py cw = vim.current.window # gets the current window
:py b = vim.buffers[n] # gets buffer "n"
:py cb = vim.current.buffer # gets the current buffer
:py w.height = lines # sets the window height
:py w.cursor = (row, col) # sets the window cursor position
:py pos = w.cursor # gets a tuple (row, col)
:py name = b.name # gets the buffer file name
:py line = b[n] # gets a line from the buffer
:py lines = b[n:m] # gets a list of lines
:py num = len(b) # gets the number of lines
:py b[n] = str # sets a line in the buffer
:py b[n:m] = [str1, str2, str3] # sets a number of lines at once
:py del b[n] # deletes a line
:py del b[n:m] # deletes a number of lines
"vim" 模块的方法:py vim.command("set tw=72")
:py vim.command("%s/aaa/bbb/g")
def normal(str):
vim.command("normal "+str)
# Note the use of single quotes to delimit a string containing
# double quotes
normal('"a2dd"aP')
vim.eval(str) python-eval:py text_width = vim.eval("&tw")
:py str = vim.eval("12+12") # NB result is a string! Use
# int() to convert to a
# number.
vim.strwidth(str) python-strwidthvim.chdir(*args, **kwargs)
python-chdirvim.fchdir(*args, **kwargs)
python-fchdirtry:
vim.command("put a")
except vim.error:
# nothing in register a
"vim" 模块的常量:py b = vim.buffers[i] # Indexing (read-only)
:py b in vim.buffers # Membership test
:py n = len(vim.buffers) # Number of elements
:py for b in vim.buffers: # Iterating over buffer list
:py w = vim.windows[i] # Indexing (read-only)
:py w in vim.windows # Membership test
:py n = len(vim.windows) # Number of elements
:py for w in vim.windows: # Sequential access
:py t = vim.tabpages[i] # Indexing (read-only)
:py t in vim.tabpages # Membership test
:py n = len(vim.tabpages) # Number of elements
:py for t in vim.tabpages: # Sequential access
py << EOF
saved_eventignore = vim.options['eventignore']
vim.options['eventignore'] = 'all'
try:
vim.current.buffer = vim.buffers[2] # Switch to buffer 2
finally:
vim.options['eventignore'] = saved_eventignore
EOF
{rtp}
/python3 和 {rtp}
/pythonx 中加载模块,对于 'runtimepath' 中找到的每个 {rtp}
。from imp import find_module, load_module
import vim
import sys
class VimModuleLoader(object):
def __init__(self, module):
self.module = module
def load_module(self, fullname, path=None):
return self.module
def _find_module(fullname, oldtail, path):
idx = oldtail.find('.')
if idx > 0:
name = oldtail[:idx]
tail = oldtail[idx+1:]
fmr = find_module(name, path)
module = load_module(fullname[:-len(oldtail)] + name, *fmr)
return _find_module(fullname, tail, module.__path__)
else:
fmr = find_module(fullname, path)
return load_module(fullname, *fmr)
# It uses vim module itself in place of VimPathFinder class: it does not
# matter for python which object has find_module function attached to as
# an attribute.
class VimPathFinder(object):
@classmethod
def find_module(cls, fullname, path=None):
try:
return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
except ImportError:
return None
@classmethod
def load_module(cls, fullname, path=None):
return _find_module(fullname, fullname, path or vim._get_paths())
def hook(path):
if path == vim.VIM_SPECIAL_PATH:
return VimPathFinder
else:
raise ImportError
sys.path_hooks.append(hook)
vim.VIM_SPECIAL_PATH python-VIM_SPECIAL_PATH:py b.append(f.readlines())
缓冲区对象类型可以使用 vim 模块的 "Buffer" 属性获得。:py print(b.name) # write the buffer file name
:py b[0] = "hello!!!" # replace the top line
:py b[:] = None # delete the whole buffer
:py del b[:] # delete the whole buffer
:py b[0:0] = [ "a line" ] # add a line at the top
:py del b[2] # delete a line (the third)
:py b.append("bottom") # add a line at the bottom
:py n = len(b) # number of lines
:py (row,col) = b.mark('a') # named mark
:py r = b.range(1,5) # a sub-range of the buffer
:py b.vars["foo"] = "bar" # assign b:foo variable
:py b.options["ff"] = "dos" # set fileformat
:py del b.options["ar"] # same as :set autoread<
{stmt}
:[range]python3 << [trim] [{endmarker}
] {script}
{endmarker}
:py3
和 :python3
命令的工作原理与 :python
相似。一个简单的检查 :py3
命令是否正常工作的例子:py3 print("Hello")
:py3 import sys
:py3 print(sys.version)
{file}
:py3file
命令的工作原理与 :pyfile
相似。 :py3do{body}
:py3do
命令的工作原理与 :pydo
相似。if has('pythonx')
echo 'there is Python'
endif
if has('python3')
echo 'there is Python 3.x'
endif
Python 2 已不再受支持。因此,出于向后兼容性的原因,has('python')
始终返回零。:pyx
和 :pythonx
的工作方式与 :python3
相同。要检查 :pyx
是否正常工作:pyx print("Hello")
要查看正在使用哪个版本的 Python:pyx import sys
:pyx print(sys.version)
pyx*
函数和命令是否可用if has('pythonx')
echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
endif