Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
:python
:py
E263
E264
E887
:[range]py[thon] {stmt}
Execute Python statement {stmt}
. A simple check if
the :python
command is working::python print("Hello")
:[range]py[thon] << [trim] [{endmarker}
]
{script}
{endmarker}
Execute Python script {script}
. Useful for including
python code in Vim scripts. Requires Python, see
script-here.{script}
, like for the :append and :insert commands. Refer to
:let-heredoc for more information.function! IcecreamInitialize()
python << EOF
class StrawberryIcecream:
def __call__(self):
print('EAT ME')
EOF
endfunction
To see what version of Python you have::python print(sys.version)
There is no need to "import sys", it's done by default.python-environment
Environment variables set in Vim are not always available in Python. This
depends on how Vim and Python were build. Also see
https://docs.python.org/3/library/os.html#os.environ:pydo
:[range]pydo {body}
Execute Python function "def _vim_pydo(line, linenr):
{body}
" for each line in the [range], with the
function arguments being set to the text of each line
in turn, without a trailing <EOL>
, and the current
line number. The function should return a string or
None. If a string is returned, it becomes the text of
the line in the current turn. The default for [range]
is the whole file: "1,$".:pydo return "%s\t%d" % (line[::-1], len(line))
:pydo if line: return "%4d: %s" % (linenr, line)
:pydo
in possible conjunction with :py
to filter a range using
python. For example::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)
:pyfile
:pyf
:[range]pyf[ile] {file}
Execute the Python script in {file}
. The whole
argument is used as a single file name.:python sys.argv = ["foo", "bar"]
:pyfile myscript.py
Here are some examples python-examples
:python from vim import *
:python current.line = str.upper(current.line)
:python print("Hello")
:python str = current.buffer[42]
Note that changes (such as the "import" statements) persist from one command
to the next, just like the Python REPL.script-here
When using a script language in-line, you might want to skip this when the
language isn't supported.
if has('python')
python << EOF
print("python works")
EOF
endif
:python import vim
Overview: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
Methods of the "vim" modulepython-command
Executes the vim (ex-mode) command str. Returns None.
Examples::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
Evaluates the expression str using the vim internal expression
evaluator (see expression). Returns the expression result as:
: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-strwidth
Like strwidth(): returns number of display cells str occupies, tab
is counted as one cell.
python-foreach_rtp
Call the given callable for each path in 'runtimepath' until either
callable returns something but None, the exception is raised or there
are no longer paths. If stopped in case callable returned non-None,
vim.foreach_rtp function returns the value returned by callable.vim.chdir(*args, **kwargs)
python-chdir
vim.fchdir(*args, **kwargs)
python-fchdir
Run os.chdir or os.fchdir, then all appropriate vim stuff.
Note: you should not use these functions directly, use os.chdir and
os.fchdir instead. Behavior of vim.fchdir is undefined in case
os.fchdir does not exist.python-error
Upon encountering a Vim error, Python raises an exception of type
vim.error.
Example:try:
vim.command("put a")
except vim.error:
# nothing in register a
Constants of the "vim" modulepython-buffers
A mapping object providing access to the list of vim buffers. The
object supports the following operations::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
python-windows
A sequence object providing access to the list of vim windows. The
object supports the following operations::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
python-tabpages
A sequence object providing access to the list of vim tab pages. The
object supports the following operations::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
python-current
An object providing access (via specific attributes) to various
"current" objects available in vim:
vim.current.line The current line (RW) String
vim.current.buffer The current buffer (RW) Buffer
vim.current.window The current window (RW) Window
vim.current.tabpage The current tab page (RW) TabPage
vim.current.range The current line range (RO) Rangepy << 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
python-vars
vim.vvars python-vvars
Dictionary-like objects holding dictionaries with global (g:) and
vim (v:) variables respectively.python-options
Object partly supporting mapping protocol (supports setting and
getting items) providing a read-write access to global options.
Note: unlike :set this provides access only to global options. You
cannot use this object to obtain or set local options' values or
access local-only options in any fashion. Raises KeyError if no global
option with such name exists (i.e. does not raise KeyError for
global-local options and global only options, but does for window-
and buffer-local ones). Use python-buffer objects to access to
buffer-local options and python-window objects to access to
window-local options.python-output
Vim displays all Python code output in the Vim message area. Normal
output appears as information messages, and error output appears as
error messages.python-input
Input (via sys.stdin, including input() and raw_input()) is not
supported, and may cause the program to crash. This should probably be
fixed.{rtp}
/python3 and {rtp}
/pythonx for each {rtp}
found in 'runtimepath'.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
String constant used in conjunction with vim path hook. If path hook
installed by vim is requested to handle anything but path equal to
vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
case it uses special loader.python-find_module
vim.path_hook(path) python-path_hook
Methods or objects used to implement path loading as described above.
You should not be using any of these directly except for vim.path_hook
in case you need to do something with sys.meta_path. It is not
guaranteed that any of the objects will exist in the future vim
versions.python-_get_paths
Methods returning a list of paths which will be searched for by path
hook. You should not rely on this method being present in future
versions, but can use it for debugging.:py b.append(f.readlines())
Buffer object type is available using "Buffer" attribute of vim module.: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}
The :py3
and :python3
commands work similar to :python
. A
simple check if the :py3
command is working::py3 print("Hello")
:py3 import sys
:py3 print(sys.version)
:py3file
:[range]py3f[ile] {file}
The :py3file
command works similar to :pyfile
.
:py3do
:[range]py3do {body}
The :py3do
command works similar to :pydo
.E880
Raising SystemExit exception in python isn't endorsed way to quit vim, use:
:py vim.command("qall!")
has-python
You can test if Python is available with:if has('pythonx')
echo 'there is Python'
endif
if has('python3')
echo 'there is Python 3.x'
endif
Python 2 is no longer supported. Thus has('python')
always returns
zero for backwards compatibility reasons.:pyx
:pythonx
:pyx
and :pythonx
work the same as :python3
. To check if :pyx
works::pyx print("Hello")
To see what version of Python is being used::pyx import sys
:pyx print(sys.version)
has-pythonx
To check if pyx*
functions and commands are available:if has('pythonx')
echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
endif