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" 屬性來取得 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}
:[範圍]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