If_pyth
Nvim:help
pages,generated fromsource using thetree-sitter-vimdoc parser.
:python:pyE263E264E887:[range]py[thon]
{stmt}
Execute Python statement
{stmt}
. A simple check ifthe
:python
command is working:
:python print("Hello")
:[range]py[thon] << [trim] [
{endmarker}
]
{script}
{endmarker}
Execute Python script
{script}
. Useful for includingpython code in Vim scripts. Requires Python, see
script-here.
If [endmarker] is omitted from after the "<<", a dot '.' must be used after
{script}
, like for the
:append and
:insert commands. Refer to
:let-heredoc for more information.
Example:
function! IcecreamInitialize()python << EOFclass StrawberryIcecream: def __call__(self): print('EAT ME')EOFendfunction
To see what version of Python you have:
:python print(sys.version)
There is no need to "import sys", it's done by default.
Note: Python is very sensitive to indenting. Make sure the "class" line and"EOF" do not have any indent.
:pydo:[range]pydo
{body}
Execute Python function "def _vim_pydo(line, linenr):
{body}
" for each line in the [range], with thefunction arguments being set to the text of each linein turn, without a trailing
<EOL>
, and the currentline number. The function should return a string orNone. If a string is returned, it becomes the text ofthe line in the current turn. The default for [range]is the whole file: "1,$".
Examples:
:pydo return "%s\t%d" % (line[::-1], len(line)):pydo if line: return "%4d: %s" % (linenr, line)
One can use
:pydo
in possible conjunction with
:py
to filter a range usingpython. For example:
:py3 << EOFneedle = 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 wholeargument is used as a single file name.
Both of these commands do essentially the same thing - they execute a piece ofPython code, with the "current range"
python-range set to the given linerange.
In the case of :python, the code to execute is in the command-line.In the case of :pyfile, the code to execute is the contents of the given file.
Python commands cannot be used in the
sandbox.
To pass arguments you need to set sys.argv[] explicitly. Example:
: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 commandto the next, just like the Python REPL.
script-hereWhen using a script language in-line, you might want to skip this when thelanguage isn't supported.
if has('python') python << EOF print("python works")EOFendif
Note that "EOF" must be at the start of the line without preceding whitespace.
Python code gets all of its access to vim (with one exception - see
python-output below) via the "vim" module. The vim module implements twomethods, three constants, and one error object. You need to import the vimmodule before using it:
: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" module
vim.command(str)
python-commandExecutes the vim (ex-mode) command str. Returns None.Examples:
:py vim.command("set tw=72"):py vim.command("%s/aaa/bbb/g")
The following definition executes Normal mode commands:
def normal(str): vim.command("normal "+str)# Note the use of single quotes to delimit a string containing# double quotesnormal('"a2dd"aP')
vim.eval(str)
python-evalEvaluates the expression str using the vim internal expressionevaluator (see
expression). Returns the expression result as:
a string if the Vim expression evaluates to a string or number
a list if the Vim expression evaluates to a Vim list
a dictionary if the Vim expression evaluates to a Vim dictionaryDictionaries and lists are recursively expanded.Examples:
: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-strwidthLike
strwidth(): returns number of display cells str occupies, tabis counted as one cell.
vim.foreach_rtp(callable)
python-foreach_rtpCall the given callable for each path in
'runtimepath' until eithercallable returns something but None, the exception is raised or thereare 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-chdirvim.fchdir(*args, **kwargs)
python-fchdirRun 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.
Error object of the "vim" module
vim.error
python-errorUpon encountering a Vim error, Python raises an exception of typevim.error.Example:
try: vim.command("put a")except vim.error: # nothing in register a
Constants of the "vim" module
Note that these are not actually constants - you could reassign them.But this is silly, as you would then lose access to the vim objectsto which the variables referred.
vim.buffers
python-buffersA mapping object providing access to the list of vim buffers. Theobject 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
vim.windows
python-windowsA sequence object providing access to the list of vim windows. Theobject 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
Note: vim.windows object always accesses current tab page.
python-tabpage.windows objects are bound to parent
python-tabpageobject and always use windows from that tab page (or throw vim.errorin case tab page was deleted). You can keep a reference to bothwithout keeping a reference to vim module object or
python-tabpage,they will not lose their properties in this case.
vim.tabpages
python-tabpagesA sequence object providing access to the list of vim tab pages. Theobject 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
vim.current
python-currentAn object providing access (via specific attributes) to various"current" objects available in vim:vim.current.lineThe current line (RW)Stringvim.current.bufferThe current buffer (RW)Buffervim.current.windowThe current window (RW)Windowvim.current.tabpageThe current tab page (RW)TabPagevim.current.rangeThe current line range (RO)Range
The last case deserves a little explanation. When the :python or:pyfile command specifies a range, this range of lines becomes the"current range". A range is a bit like a buffer, but with all accessrestricted to a subset of lines. See
python-range for more details.
Note: When assigning to vim.current.{buffer,window,tabpage} it expectsvalid
python-buffer,
python-window or
python-tabpage objectsrespectively. Assigning triggers normal (with
autocommands)switching to given buffer, window or tab page. It is the only way toswitch UI objects in python: you can't assign to
python-tabpage.window attribute. To switch without triggeringautocommands use
py << EOFsaved_eventignore = vim.options['eventignore']vim.options['eventignore'] = 'all'try: vim.current.buffer = vim.buffers[2] # Switch to buffer 2finally: vim.options['eventignore'] = saved_eventignoreEOF
vim.vars
python-varsvim.vvars
python-vvarsDictionary-like objects holding dictionaries with global (
g:) andvim (
v:) variables respectively.
vim.options
python-optionsObject partly supporting mapping protocol (supports setting andgetting items) providing a read-write access to global options.
Note: unlike
:set this provides access only to global options. Youcannot use this object to obtain or set local options' values oraccess local-only options in any fashion. Raises KeyError if no globaloption 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 tobuffer-local options and
python-window objects to access towindow-local options.
Type of this object is available via "Options" attribute of vimmodule.
Output from Python
python-outputVim displays all Python code output in the Vim message area. Normaloutput appears as information messages, and error output appears aserror messages.
In implementation terms, this means that all output to sys.stdout(including the output from print statements) appears as informationmessages, and all output to sys.stderr (including error tracebacks)appears as error messages.
python-inputInput (via sys.stdin, including input() and raw_input()) is notsupported, and may cause the program to crash. This should probably befixed.
In python vim.VIM_SPECIAL_PATH special directory is used as a replacement forthe list of paths found in
'runtimepath': with this directory in sys.path andvim.path_hooks in sys.path_hooks python will try to load module from
{rtp}
/python3 and
{rtp}
/pythonx for each
{rtp}
found in
'runtimepath'.
Implementation is similar to the following, but written in C:
from imp import find_module, load_moduleimport vimimport sysclass VimModuleLoader(object): def __init__(self, module): self.module = module def load_module(self, fullname, path=None): return self.moduledef _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 ImportErrorsys.path_hooks.append(hook)
vim.VIM_SPECIAL_PATH
python-VIM_SPECIAL_PATHString constant used in conjunction with vim path hook. If path hookinstalled by vim is requested to handle anything but path equal tovim.VIM_SPECIAL_PATH constant it raises ImportError. In the only othercase it uses special loader.
Note: you must not use value of this constant directly, always use vim.VIM_SPECIAL_PATH object.
vim.find_module(...)
python-find_modulevim.path_hook(path)
python-path_hookMethods or objects used to implement path loading as described above.You should not be using any of these directly except for vim.path_hookin case you need to do something with sys.meta_path. It is notguaranteed that any of the objects will exist in the future vimversions.
vim._get_paths
python-_get_pathsMethods returning a list of paths which will be searched for by pathhook. You should not rely on this method being present in futureversions, but can use it for debugging.
It returns a list of
{rtp}
/python3 and
{rtp}
/pythonxdirectories for each
{rtp}
in
'runtimepath'.
Buffer objects represent vim buffers. You can obtain them in a number of ways:
Buffer objects have two read-only attributes - name - the full file name forthe buffer, and number - the buffer number. They also have three methods(append, mark, and range; see below).
You can also treat buffer objects as sequence objects. In this context, theyact as if they were lists (yes, they are mutable) of strings, with eachelement being a line of the buffer. All of the usual sequence operations,including indexing, index assignment, slicing and slice assignment, work asyou would expect. Note that the result of indexing (slicing) a buffer is astring (list of strings). This has one unusual consequence - b[:] is differentfrom b. In particular, "b[:] = None" deletes the whole of the buffer, whereas"b = None" merely updates the variable b, with no effect on the buffer.
Buffer indexes start at zero, as is normal in Python. This differs from vimline numbers, which start from 1. This is particularly relevant when dealingwith marks (see below) which use vim line numbers.
The buffer object attributes are:b.varsDictionary-like object used to access
buffer-variables.b.optionsMapping object (supports item getting, setting anddeleting) that provides access to buffer-local optionsand buffer-local values of
global-local options. Use
python-window.options if option is window-local,this object will raise KeyError. If option is
global-local and local value is missing getting itwill return None.b.nameString, RW. Contains buffer name (full path).
Note: when assigning to b.name
BufFilePre and
BufFilePost autocommands are launched.b.numberBuffer number. Can be used as
python-buffers key.Read-only.b.validTrue or False. Buffer object becomes invalid whencorresponding buffer is wiped out.
The buffer object methods are:b.append(str)Append a line to the bufferb.append(str, nr) Idem, below line "nr"b.append(list)Append a list of lines to the bufferNote that the option of supplying a list of strings tothe append method differs from the equivalent methodfor Python's built-in list objects.b.append(list, nr) Idem, below line "nr"b.mark(name)Return a tuple (row,col) representing the positionof the named mark (can also get the []"<> marks)b.range(s,e)Return a range object (see
python-range) whichrepresents the part of the given buffer between linenumbers s and e
inclusive.
Note that when adding a line it must not contain a line break character '\n'.A trailing '\n' is allowed and ignored, so that you can do:
:py b.append(f.readlines())
Buffer object type is available using "Buffer" attribute of vim module.
Examples (assume b is the current 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<
Range objects represent a part of a vim buffer. You can obtain them in anumber of ways:
A range object is almost identical in operation to a buffer object. However,all operations are restricted to the lines within the range (this line rangecan, of course, change as a result of slice assignments, line deletions, orthe range.append() method).
The range object attributes are:r.startIndex of first line into the bufferr.endIndex of last line into the buffer
The range object methods are:r.append(str)Append a line to the ranger.append(str, nr) Idem, after line "nr"r.append(list)Append a list of lines to the rangeNote that the option of supplying a list of strings tothe append method differs from the equivalent methodfor Python's built-in list objects.r.append(list, nr) Idem, after line "nr"
Range object type is available using "Range" attribute of vim module.
Example (assume r is the current range):# Send all lines in a range to the default printervim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
Window objects represent vim windows. You can obtain them in a number of ways:
You can manipulate window objects only through their attributes. They have nomethods, and no sequence or other interface.
Window attributes are:buffer (read-only)The buffer displayed in this windowcursor (read-write)The current cursor position in the windowThis is a tuple, (row,col).height (read-write)The window height, in rowswidth (read-write)The window width, in columnsvars (read-only)The window
w: variables. Attribute isunassignable, but you can change windowvariables this wayoptions (read-only)The window-local options. Attribute isunassignable, but you can change windowoptions this way. Provides access only towindow-local options, for buffer-local use
python-buffer and for global ones use
python-options. If option is
global-localand local value is missing getting it willreturn None.number (read-only)Window number. The first window has number 1.This is zero in case it cannot be determined(e.g. when the window object belongs to othertab page).row, col (read-only)On-screen window position in display cells.First position is zero.tabpage (read-only)Window tab page.valid (read-write)True or False. Window object becomes invalidwhen corresponding window is closed.
The height attribute is writable only if the screen is split horizontally.The width attribute is writable only if the screen is split vertically.
Window object type is available using "Window" attribute of vim module.
Tab page objects represent vim tab pages. You can obtain them in a number ofways:
You can use this object to access tab page windows. They have no methods andno sequence or other interfaces.
Tab page attributes are:numberThe tab page number like the one returned by
tabpagenr().windowsLike
python-windows, but for current tab page.varsThe tab page
t: variables.windowCurrent tabpage window.validTrue or False. Tab page object becomes invalid whencorresponding tab page is closed.
TabPage object type is available using "TabPage" attribute of vim module.
To facilitate bi-directional interface, you can use
pyeval() and
py3eval()functions to evaluate Python expressions and pass their values to Vim script.
pyxeval() is also available.
As Python 3 is the only supported version in Nvim, "python" is synonymouswith "python3" in the current version. However, code that aims to support olderversions of Nvim, as well as Vim, should prefer to use "python3" variantsexplicitly if Python 3 is required.
:py3:python3:[range]py3
{stmt}
:[range]py3 << [trim] [
{endmarker}
]
{script}
{endmarker}
:[range]python3
{stmt}
:[range]python3 << [trim] [
{endmarker}
]
{script}
{endmarker}
The
:py3
and
:python3
commands work similar to
:python
. Asimple check if the
:py3
command is working:
:py3 print("Hello")
To see what version of Python you have:
: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
.
E880Raising SystemExit exception in python isn't endorsed way to quit vim, use:
:py vim.command("qall!")
has-pythonYou can test if Python is available with:
if has('pythonx') echo 'there is Python'endifif has('python3') echo 'there is Python 3.x'endif
Python 2 is no longer supported. Thus
has('python')
always returnszero for backwards compatibility reasons.
The "pythonx" and "pyx" prefixes were introduced for python code whichworks with Python 2.6+ and Python 3. As Nvim only supports Python 3,all these commands are now synonymous to their "python3" equivalents.
: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)
:pyxdo:pyxdo
works the same as
:py3do
.
has-pythonxTo check if
pyx*
functions and commands are available:
if has('pythonx') echo 'pyx* commands are available. (Python ' .. &pyx .. ')'endif