codekingpro/portable-devtools
114k
1*if_pyth.txt* For Vim version 9.2. Last change: 2026 Mar 182 3 4 VIM REFERENCE MANUAL by Paul Moore5 6 7The Python Interface to Vim *python* *Python*8 91. Commands |python-commands|102. The vim module |python-vim|113. Buffer objects |python-buffer|124. Range objects |python-range|135. Window objects |python-window|146. Tab page objects |python-tabpage|157. vim.bindeval objects |python-bindeval-objects|168. pyeval(), py3eval() Vim functions |python-pyeval|179. Dynamic loading |python-dynamic|1810. Python 3 |python3|1911. Python X |python_x|2012. Building with Python support |python-building|21 22The Python 2.x interface is available only when Vim was compiled with the23|+python| feature.24The Python 3 interface is available only when Vim was compiled with the25|+python3| feature.26Both can be available at the same time, but read |python-2-and-3|.27 28NOTE: Python 2 is old and no longer being developed. Using Python 3 is highly29recommended. Python 2 support will be dropped when it does not work properly30anymore.31 32==============================================================================331. Commands *python-commands*34 35 *:python* *:py* *E263* *E264* *E887*36:[range]py[thon] {stmt}37 Execute Python statement {stmt}. A simple check if38 the `:python` command is working: >39 :python print "Hello"40 41:[range]py[thon] << [trim] [{endmarker}]42{script}43{endmarker}44 Execute Python script {script}.45 Note: This command doesn't work when the Python46 feature wasn't compiled in. To avoid errors, see47 |script-here|.48 49If [endmarker] is omitted from after the "<<", a dot '.' must be used after50{script}, like for the |:append| and |:insert| commands. Refer to51|:let-heredoc| for more information.52 53This form of the |:python| command is mainly useful for including python code54in Vim scripts.55 56Example: >57 function! IcecreamInitialize()58 python << EOF59 class StrawberryIcecream:60 def __call__(self):61 print 'EAT ME'62 EOF63 endfunction64 65To see what version of Python you have: >66 :python print(sys.version)67 68There is no need to import sys, it's done by default.69 70 *python-environment*71Environment variables set in Vim are not always available in Python. This72depends on how Vim and Python were built. Also see73https://docs.python.org/3/library/os.html#os.environ74 75Note: Python is very sensitive to the indenting. Make sure the "class" line76and "EOF" do not have any indent.77 78 *:pydo*79:[range]pydo {body} Execute Python function "def _vim_pydo(line, linenr):80 {body}" for each line in the [range], with the81 function arguments being set to the text of each line82 in turn, without a trailing <EOL>, and the current83 line number. The function should return a string or84 None. If a string is returned, it becomes the text of85 the line in the current turn. The default for [range]86 is the whole file: "1,$".87 88Examples:89>90 :pydo return "%s\t%d" % (line[::-1], len(line))91 :pydo if line: return "%4d: %s" % (linenr, line)92<93One can use `:pydo` in possible conjunction with `:py` to filter a range using94python. For example: >95 96 :py3 << EOF97 needle = vim.eval('@a')98 replacement = vim.eval('@b')99 100 def py_vim_string_replace(str):101 return str.replace(needle, replacement)102 EOF103 :'<,'>py3do return py_vim_string_replace(line)104<105 *:pyfile* *:pyf*106:[range]pyf[ile] {file}107 Execute the Python script in {file}. The whole108 argument is used as a single file name.109 110Both of these commands do essentially the same thing - they execute a piece of111Python code, with the "current range" |python-range| set to the given line112range.113 114In the case of :python, the code to execute is in the command-line.115In the case of :pyfile, the code to execute is the contents of the given file.116 117Python commands cannot be used in the |sandbox|.118 119To pass arguments you need to set sys.argv[] explicitly. Example: >120 121 :python sys.argv = ["foo", "bar"]122 :pyfile myscript.py123 124Here are some examples *python-examples* >125 126 :python from vim import *127 :python from string import upper128 :python current.line = upper(current.line)129 :python print "Hello"130 :python str = current.buffer[42]131 132(Note that changes - like the imports - persist from one command to the next,133just like in the Python interpreter.)134 135==============================================================================1362. The vim module *python-vim*137 138Python code gets all of its access to vim (with one exception - see139|python-output| below) via the "vim" module. The vim module implements two140methods, three constants, and one error object. You need to import the vim141module before using it: >142 :python import vim143 144Overview >145 :py print "Hello" # displays a message146 :py vim.command(cmd) # execute an Ex command147 :py w = vim.windows[n] # gets window "n"148 :py cw = vim.current.window # gets the current window149 :py b = vim.buffers[n] # gets buffer "n"150 :py cb = vim.current.buffer # gets the current buffer151 :py w.height = lines # sets the window height152 :py w.cursor = (row, col) # sets the window cursor position153 :py pos = w.cursor # gets a tuple (row, col)154 :py name = b.name # gets the buffer file name155 :py line = b[n] # gets a line from the buffer156 :py lines = b[n:m] # gets a list of lines157 :py num = len(b) # gets the number of lines158 :py b[n] = str # sets a line in the buffer159 :py b[n:m] = [str1, str2, str3] # sets a number of lines at once160 :py del b[n] # deletes a line161 :py del b[n:m] # deletes a number of lines162 163 164Methods of the "vim" module165 166vim.command(str) *python-command*167 Executes the vim (ex-mode) command str. Returns None.168 Examples: >169 :py vim.command("set tw=72")170 :py vim.command("%s/aaa/bbb/g")171< The following definition executes Normal mode commands: >172 def normal(str):173 vim.command("normal "+str)174 # Note the use of single quotes to delimit a string containing175 # double quotes176 normal('"a2dd"aP')177< *E659*178 The ":python" command cannot be used recursively with Python 2.2 and179 older. This only works with Python 2.3 and later: >180 :py vim.command("python print 'Hello again Python'")181 182vim.eval(str) *python-eval*183 Evaluates the expression str using the vim internal expression184 evaluator (see |expression|). Returns the expression result as:185 - a string if the Vim expression evaluates to a string or number186 - a list if the Vim expression evaluates to a Vim |list|187 - a tuple if the Vim expression evaluates to a Vim |tuple|188 - a dictionary if the Vim expression evaluates to a Vim |dict|189 - a boolean if Vim expression evaluates to |v:true| or |v:false|190 - `None` if Vim expression evaluates to |v:null| or |v:none|191 Dictionaries, lists and tuples are recursively expanded.192 Examples: >193 :" value of the 'textwidth' option194 :py text_width = vim.eval("&tw")195 :196 :" contents of the 'a' register197 :py a_reg = vim.eval("@a")198 :199 :" Result is a string! Use string.atoi() to convert to a number.200 :py str = vim.eval("12+12")201 :202 :py tuple = vim.eval('(1, 2, 3)')203 :204 :py tagList = vim.eval('taglist("eval_expr")')205< The latter will return a python list of python dicts, for instance:206 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name': ~207 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}] ~208 209 NOTE: In Vim9 script, local variables in def functions are not visible210 to python evaluations. To pass local variables to python evaluations,211 use the {locals} dict when calling |py3eval()| and friends.212 213vim.bindeval(str) *python-bindeval*214 Like |python-eval|, but returns special objects described in215 |python-bindeval-objects|. These python objects let you modify216 (|List|, |Tuple| or |Dictionary|) or call (|Funcref|) vim objects.217 218vim.strwidth(str) *python-strwidth*219 Like |strwidth()|: returns number of display cells str occupies, tab220 is counted as one cell.221 222vim.foreach_rtp(callable) *python-foreach_rtp*223 Call the given callable for each path in 'runtimepath' until either224 callable returns something but None, the exception is raised or there225 are no longer paths. If stopped in case callable returned non-None,226 vim.foreach_rtp function returns the value returned by callable.227 228vim.chdir(*args, **kwargs) *python-chdir*229vim.fchdir(*args, **kwargs) *python-fchdir*230 Run os.chdir or os.fchdir, then all appropriate vim stuff.231 Note: you should not use these functions directly, use os.chdir and232 os.fchdir instead. Behavior of vim.fchdir is undefined in case233 os.fchdir does not exist.234 235Error object of the "vim" module236 237vim.error *python-error*238 Upon encountering a Vim error, Python raises an exception of type239 vim.error.240 Example: >241 try:242 vim.command("put a")243 except vim.error:244 # nothing in register a245 246Constants of the "vim" module247 248 Note that these are not actually constants - you could reassign them.249 But this is silly, as you would then lose access to the vim objects250 to which the variables referred.251 252vim.buffers *python-buffers*253 A mapping object providing access to the list of vim buffers. The254 object supports the following operations: >255 :py b = vim.buffers[i] # Indexing (read-only)256 :py b in vim.buffers # Membership test257 :py n = len(vim.buffers) # Number of elements258 :py for b in vim.buffers: # Iterating over buffer list259<260vim.windows *python-windows*261 A sequence object providing access to the list of vim windows. The262 object supports the following operations: >263 :py w = vim.windows[i] # Indexing (read-only)264 :py w in vim.windows # Membership test265 :py n = len(vim.windows) # Number of elements266 :py for w in vim.windows: # Sequential access267< Note: vim.windows object always accesses current tab page.268 |python-tabpage|.windows objects are bound to parent |python-tabpage|269 object and always use windows from that tab page (or throw vim.error270 in case tab page was deleted). You can keep a reference to both271 without keeping a reference to vim module object or |python-tabpage|,272 they will not lose their properties in this case.273 274vim.tabpages *python-tabpages*275 A sequence object providing access to the list of vim tab pages. The276 object supports the following operations: >277 :py t = vim.tabpages[i] # Indexing (read-only)278 :py t in vim.tabpages # Membership test279 :py n = len(vim.tabpages) # Number of elements280 :py for t in vim.tabpages: # Sequential access281<282vim.current *python-current*283 An object providing access (via specific attributes) to various284 "current" objects available in vim:285 vim.current.line The current line (RW) String286 vim.current.buffer The current buffer (RW) Buffer287 vim.current.window The current window (RW) Window288 vim.current.tabpage The current tab page (RW) TabPage289 vim.current.range The current line range (RO) Range290 291 The last case deserves a little explanation. When the :python or292 :pyfile command specifies a range, this range of lines becomes the293 "current range". A range is a bit like a buffer, but with all access294 restricted to a subset of lines. See |python-range| for more details.295 296 Note: When assigning to vim.current.{buffer,window,tabpage} it expects297 valid |python-buffer|, |python-window| or |python-tabpage| objects298 respectively. Assigning triggers normal (with |autocommand|s)299 switching to given buffer, window or tab page. It is the only way to300 switch UI objects in python: you can't assign to301 |python-tabpage|.window attribute. To switch without triggering302 autocommands use >303 py << EOF304 saved_eventignore = vim.options['eventignore']305 vim.options['eventignore'] = 'all'306 try:307 vim.current.buffer = vim.buffers[2] # Switch to buffer 2308 finally:309 vim.options['eventignore'] = saved_eventignore310 EOF311<312vim.vars *python-vars*313vim.vvars *python-vvars*314 Dictionary-like objects holding dictionaries with global (|g:|) and315 vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,316 but faster.317 318vim.options *python-options*319 Object partly supporting mapping protocol (supports setting and320 getting items) providing a read-write access to global options.321 Note: unlike |:set| this provides access only to global options. You322 cannot use this object to obtain or set local options' values or323 access local-only options in any fashion. Raises KeyError if no324 global option with such name exists (i.e. does not raise KeyError for325 |global-local| options and global only options, but does for window-326 and buffer-local ones). Use |python-buffer| objects to access to327 buffer-local options and |python-window| objects to access to328 window-local options.329 330 Type of this object is available via "Options" attribute of vim331 module.332 333Output from Python *python-output*334 Vim displays all Python code output in the Vim message area. Normal335 output appears as information messages, and error output appears as336 error messages.337 338 In implementation terms, this means that all output to sys.stdout339 (including the output from print statements) appears as information340 messages, and all output to sys.stderr (including error tracebacks)341 appears as error messages.342 343 *python-input*344 Input (via sys.stdin, including input() and raw_input()) is not345 supported, and may cause the program to crash. This should probably346 be fixed.347 348 *python2-directory* *python3-directory* *pythonx-directory*349Python 'runtimepath' handling *python-special-path*350 351In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for352the list of paths found in 'runtimepath': with this directory in sys.path and353vim.path_hooks in sys.path_hooks python will try to load module from354{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for355each {rtp} found in 'runtimepath' (Note: find_module() has been removed from356imp module around Python 3.12.0a7).357 358Implementation is similar to the following, but written in C: >359 360 from imp import find_module, load_module361 import vim362 import sys363 364 class VimModuleLoader(object):365 def __init__(self, module):366 self.module = module367 368 def load_module(self, fullname, path=None):369 return self.module370 371 def _find_module(fullname, oldtail, path):372 idx = oldtail.find('.')373 if idx > 0:374 name = oldtail[:idx]375 tail = oldtail[idx+1:]376 fmr = find_module(name, path)377 module = load_module(fullname[:-len(oldtail)] + name, *fmr)378 return _find_module(fullname, tail, module.__path__)379 else:380 fmr = find_module(fullname, path)381 return load_module(fullname, *fmr)382 383 # It uses vim module itself in place of VimPathFinder class: it does not384 # matter for python which object has find_module function attached to as385 # an attribute.386 class VimPathFinder(object):387 @classmethod388 def find_module(cls, fullname, path=None):389 try:390 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))391 except ImportError:392 return None393 394 @classmethod395 def load_module(cls, fullname, path=None):396 return _find_module(fullname, fullname, path or vim._get_paths())397 398 def hook(path):399 if path == vim.VIM_SPECIAL_PATH:400 return VimPathFinder401 else:402 raise ImportError403 404 sys.path_hooks.append(hook)405 406vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*407 String constant used in conjunction with vim path hook. If path hook408 installed by vim is requested to handle anything but path equal to409 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only410 other case it uses special loader.411 412 Note: you must not use value of this constant directly, always use413 vim.VIM_SPECIAL_PATH object.414 415vim.find_module(...) *python-find_module*416vim.path_hook(path) *python-path_hook*417vim.find_spec(...) *python-find_spec*418 Methods or objects used to implement path loading as described above.419 You should not be using any of these directly except for vim.path_hook420 in case you need to do something with sys.meta_path, vim.find_spec()421 is available starting with Python 3.7.422 It is not guaranteed that any of the objects will exist in future vim423 versions.424 425vim._get_paths *python-_get_paths*426 Methods returning a list of paths which will be searched for by path427 hook. You should not rely on this method being present in future428 versions, but can use it for debugging.429 430 It returns a list of {rtp}/python2 (or {rtp}/python3) and431 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.432 433==============================================================================4343. Buffer objects *python-buffer*435 436Buffer objects represent vim buffers. You can obtain them in a number of437ways:438 - via vim.current.buffer (|python-current|)439 - from indexing vim.buffers (|python-buffers|)440 - from the "buffer" attribute of a window (|python-window|)441 442Buffer objects have two read-only attributes - name - the full file name for443the buffer, and number - the buffer number. They also have three methods444(append, mark, and range; see below).445 446You can also treat buffer objects as sequence objects. In this context, they447act as if they were lists (yes, they are mutable) of strings, with each448element being a line of the buffer. All of the usual sequence operations,449including indexing, index assignment, slicing and slice assignment, work as450you would expect. Note that the result of indexing (slicing) a buffer is a451string (list of strings). This has one unusual consequence - b[:] is452different from b. In particular, "b[:] = None" deletes the whole of the453buffer, whereas "b = None" merely updates the variable b, with no effect on454the buffer.455 456Buffer indexes start at zero, as is normal in Python. This differs from vim457line numbers, which start from 1. This is particularly relevant when dealing458with marks (see below) which use vim line numbers.459 460The buffer object attributes are:461 b.vars Dictionary-like object used to access462 |buffer-variable|s.463 b.options Mapping object (supports item getting, setting and464 deleting) that provides access to buffer-local options465 and buffer-local values of |global-local| options. Use466 |python-window|.options if option is window-local,467 this object will raise KeyError. If option is468 |global-local| and local value is missing getting it469 will return None.470 b.name String, RW. Contains buffer name (full path).471 Note: when assigning to b.name |BufFilePre| and472 |BufFilePost| autocommands are launched.473 b.number Buffer number. Can be used as |python-buffers| key.474 Read-only.475 b.valid True or False. Buffer object becomes invalid when476 corresponding buffer is wiped out.477 478The buffer object methods are:479 b.append(str) Append a line to the buffer480 b.append(str, nr) Idem, below line "nr"481 b.append(list) Append a list of lines to the buffer482 Note that the option of supplying a list of strings to483 the append method differs from the equivalent method484 for Python's built-in list objects.485 b.append(list, nr) Idem, below line "nr"486 b.mark(name) Return a tuple (row,col) representing the position487 of the named mark (can also get the []"<> marks)488 b.range(s,e) Return a range object (see |python-range|) which489 represents the part of the given buffer between line490 numbers s and e |inclusive|.491 492Note that when adding a line it must not contain a line break character '\n'.493A trailing '\n' is allowed and ignored, so that you can do: >494 :py b.append(f.readlines())495 496Buffer object type is available using "Buffer" attribute of vim module.497 498Examples (assume b is the current buffer) >499 :py print b.name # write the buffer file name500 :py b[0] = "hello!!!" # replace the top line501 :py b[:] = None # delete the whole buffer502 :py del b[:] # delete the whole buffer503 :py b[0:0] = [ "a line" ] # add a line at the top504 :py del b[2] # delete a line (the third)505 :py b.append("bottom") # add a line at the bottom506 :py n = len(b) # number of lines507 :py (row,col) = b.mark('a') # named mark508 :py r = b.range(1,5) # a sub-range of the buffer509 :py b.vars["foo"] = "bar" # assign b:foo variable510 :py b.options["ff"] = "dos" # set fileformat511 :py del b.options["ar"] # same as :set autoread<512 513==============================================================================5144. Range objects *python-range*515 516Range objects represent a part of a vim buffer. You can obtain them in a517number of ways:518 - via vim.current.range (|python-current|)519 - from a buffer's range() method (|python-buffer|)520 521A range object is almost identical in operation to a buffer object. However,522all operations are restricted to the lines within the range (this line range523can, of course, change as a result of slice assignments, line deletions, or524the range.append() method).525 526The range object attributes are:527 r.start Index of first line into the buffer528 r.end Index of last line into the buffer529 530The range object methods are:531 r.append(str) Append a line to the range532 r.append(str, nr) Idem, after line "nr"533 r.append(list) Append a list of lines to the range534 Note that the option of supplying a list of strings to535 the append method differs from the equivalent method536 for Python's built-in list objects.537 r.append(list, nr) Idem, after line "nr"538 539Range object type is available using "Range" attribute of vim module.540 541Example (assume r is the current range): >542 # Send all lines in a range to the default printer543 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))544 545==============================================================================5465. Window objects *python-window*547 548Window objects represent vim windows. You can obtain them in a number of549ways:550 - via vim.current.window (|python-current|)551 - from indexing vim.windows (|python-windows|)552 - from indexing "windows" attribute of a tab page (|python-tabpage|)553 - from the "window" attribute of a tab page (|python-tabpage|)554 555You can manipulate window objects only through their attributes. They have no556methods, and no sequence or other interface.557 558Window attributes are:559 buffer (read-only) The buffer displayed in this window560 cursor (read-write) The current cursor position in the window561 This is a tuple, (row,col).562 height (read-write) The window height, in rows563 width (read-write) The window width, in columns564 vars (read-only) The window |w:| variables. Attribute is565 unassignable, but you can change window566 variables this way567 options (read-only) The window-local options. Attribute is568 unassignable, but you can change window569 options this way. Provides access only to570 window-local options, for buffer-local use571 |python-buffer| and for global ones use572 |python-options|. If option is |global-local|573 and local value is missing getting it will574 return None.575 number (read-only) Window number. The first window has number 1.576 This is zero in case it cannot be determined577 (e.g. when the window object belongs to other578 tab page).579 row, col (read-only) On-screen window position in display cells.580 First position is zero.581 tabpage (read-only) Window tab page.582 valid (read-write) True or False. Window object becomes invalid583 when corresponding window is closed.584 585The height attribute is writable only if the screen is split horizontally.586The width attribute is writable only if the screen is split vertically.587 588Window object type is available using "Window" attribute of vim module.589 590==============================================================================5916. Tab page objects *python-tabpage*592 593Tab page objects represent vim tab pages. You can obtain them in a number of594ways:595 - via vim.current.tabpage (|python-current|)596 - from indexing vim.tabpages (|python-tabpages|)597 598You can use this object to access tab page windows. They have no methods and599no sequence or other interfaces.600 601Tab page attributes are:602 number The tab page number like the one returned by603 |tabpagenr()|.604 windows Like |python-windows|, but for current tab page.605 vars The tab page |t:| variables.606 window Current tabpage window.607 valid True or False. Tab page object becomes invalid when608 corresponding tab page is closed.609 610TabPage object type is available using "TabPage" attribute of vim module.611 612==============================================================================6137. vim.bindeval objects *python-bindeval-objects*614 615vim.Dictionary object *python-Dictionary*616 Dictionary-like object providing access to vim |Dictionary| type.617 Attributes:618 Attribute Description ~619 locked One of *python-.locked*620 Value Description ~621 zero Variable is not locked622 vim.VAR_LOCKED Variable is locked, but can be unlocked623 vim.VAR_FIXED Variable is locked and can't be unlocked624 Read-write. You can unlock locked variable by assigning625 `True` or `False` to this attribute. No recursive locking626 is supported.627 scope One of628 Value Description ~629 zero Dictionary is not a scope one630 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary631 vim.VAR_SCOPE Other scope dictionary,632 see |internal-variables|633 Methods (note: methods do not support keyword arguments):634 Method Description ~635 keys() Returns a list with dictionary keys.636 values() Returns a list with dictionary values.637 items() Returns a list of 2-tuples with dictionary contents.638 update(iterable), update(dictionary), update(**kwargs)639 Adds keys to dictionary.640 get(key[, default=None])641 Obtain key from dictionary, returning the default if it is642 not present.643 pop(key[, default])644 Remove specified key from dictionary and return645 corresponding value. If key is not found and default is646 given returns the default, otherwise raises KeyError.647 popitem()648 Remove random key from dictionary and return (key, value)649 pair.650 has_key(key)651 Check whether dictionary contains specified key, similar652 to `key in dict`.653 654 __new__(), __new__(iterable), __new__(dictionary), __new__(update)655 You can use `vim.Dictionary()` to create new vim656 dictionaries. `d=vim.Dictionary(arg)` is the same as657 `d=vim.bindeval('{}');d.update(arg)`. Without arguments658 constructs empty dictionary.659 660 Examples: >661 d = vim.Dictionary(food="bar") # Constructor662 d['a'] = 'b' # Item assignment663 print d['a'] # getting item664 d.update({'c': 'd'}) # .update(dictionary)665 d.update(e='f') # .update(**kwargs)666 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)667 for key in d.keys(): # .keys()668 for val in d.values(): # .values()669 for key, val in d.items(): # .items()670 print isinstance(d, vim.Dictionary) # True671 for key in d: # Iteration over keys672 class Dict(vim.Dictionary): # Subclassing673<674 Note: when iterating over keys you should not modify dictionary.675 676vim.List object *python-List*677 Sequence-like object providing access to vim |List| type.678 Supports `.locked` attribute, see |python-.locked|. Also supports the679 following methods:680 Method Description ~681 extend(item) Add items to the list.682 683 __new__(), __new__(iterable)684 You can use `vim.List()` to create new vim lists.685 `l=vim.List(iterable)` is the same as686 `l=vim.bindeval('[]');l.extend(iterable)`. Without687 arguments constructs empty list.688 Examples: >689 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']690 l.extend(['abc', 'def']) # .extend() method691 print l[1:] # slicing692 l[:0] = ['ghi', 'jkl'] # slice assignment693 print l[0] # getting item694 l[0] = 'mno' # assignment695 for i in l: # iteration696 print isinstance(l, vim.List) # True697 class List(vim.List): # Subclassing698 699vim.Tuple object *python-Tuple*700 Sequence-like object providing access to vim |Tuple| type.701 Supports `.locked` attribute, see |python-.locked|. Also supports the702 following methods:703 Method Description ~704 __new__(), __new__(iterable)705 You can use `vim.Tuple()` to create new vim tuples.706 Without arguments constructs empty list.707 Examples: >708 t = vim.Tuple("abc") # Constructor, result: ('a', 'b', 'c')709 print t[1:] # slicing710 print t[0] # getting item711 for i in t: # iteration712 print isinstance(t, vim.Tuple) # True713 class Tuple(vim.Tuple): # Subclassing714 715vim.Function object *python-Function*716 Function-like object, acting like vim |Funcref| object. Accepts special717 keyword argument `self`, see |Dictionary-function|. You can also use718 `vim.Function(name)` constructor, it is the same as719 `vim.bindeval('function(%s)'%json.dumps(name))`.720 721 Attributes (read-only):722 Attribute Description ~723 name Function name.724 args `None` or a |python-List| object with arguments. Note725 that this is a copy of the arguments list, constructed726 each time you request this attribute. Modifications made727 to the list will be ignored (but not to the containers728 inside argument list: this is like |copy()| and not729 |deepcopy()|).730 self `None` or a |python-Dictionary| object with self731 dictionary. Note that explicit `self` keyword used when732 calling resulting object overrides this attribute.733 auto_rebind Boolean. True if partial created from this Python object734 and stored in the Vim script dictionary should be735 automatically rebound to the dictionary it is stored in736 when this dictionary is indexed. Exposes Vim internal737 difference between `dict.func` (auto_rebind=True) and738 `function(dict.func,dict)` (auto_rebind=False). This739 attribute makes no sense if `self` attribute is `None`.740 741 Constructor additionally accepts `args`, `self` and `auto_rebind`742 keywords. If `args` and/or `self` argument is given then it constructs743 a partial, see |function()|. `auto_rebind` is only used when `self`744 argument is given, otherwise it is assumed to be `True` regardless of745 whether it was given or not. If `self` is given then it defaults to746 `False`.747 748 Examples: >749 f = vim.Function('tr') # Constructor750 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')751 vim.command('''752 function DictFun() dict753 return self754 endfunction755 ''')756 f = vim.bindeval('function("DictFun")')757 print f(self={}) # Like call('DictFun', [], {})758 print isinstance(f, vim.Function) # True759 760 p = vim.Function('DictFun', self={})761 print f()762 p = vim.Function('tr', args=['abc', 'a'])763 print f('b')764 765==============================================================================7668. pyeval() and py3eval() Vim functions *python-pyeval*767 768To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|769functions to evaluate Python expressions and pass their values to Vim script.770|pyxeval()| is also available.771 772You can inject local variables into the evaluation using the optional {locals}773dict. This can be particularly useful in vim9script where vim.eval774|python-eval| will not find locals in a def func.775 776The Python value "None" is converted to v:none.777 778==============================================================================7799. Dynamic loading *python-dynamic*780 781On MS-Windows and Unix the Python library can be loaded dynamically. The782|:version| output then includes |+python/dyn| or |+python3/dyn|.783 784This means that Vim will search for the Python DLL or shared library file only785when needed. When you don't use the Python interface you don't need it, thus786you can use Vim without this file.787 788 789MS-Windows ~790 791To use the Python interface the Python DLL must be in your search path. In a792console window type "path" to see what directories are used. If the DLL is793not found in your search path, Vim will check the registry to find the path794where Python is installed. The 'pythondll' or 'pythonthreedll' option can be795also used to specify the Python DLL.796 797The name of the DLL should match the Python version Vim was compiled with.798Currently the name for Python 2 is "python27.dll", that is for Python 2.7.799That is the default value for 'pythondll'. For Python 3 it is python36.dll800(Python 3.6). To know for sure edit "gvim.exe" and search for801"python\d*.dll\c".802 803 804Unix ~805 806The 'pythondll' or 'pythonthreedll' option can be used to specify the Python807shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file808what were specified at compile time. The version of the shared library must809match the Python 2.x or Python 3 version (|v:python3_version|) Vim was810compiled with unless using |python3-stable-abi|.811 812 813Stable ABI and mixing Python versions ~814 *python-stable* *python-stable-abi* *python3-stable-abi*815If Vim was not compiled with Stable ABI (only available for Python 3), the816version of the Python shared library must match the version that Vim was817compiled with. Otherwise, mixing versions could result in unexpected crashes818and failures. With Stable ABI, this restriction is relaxed, and any Python 3819library with version of at least |v:python3_version| will work. See820|has-python| for how to check if Stable ABI is supported, or see if version821output includes |+python3/dyn-stable|.822On MS-Windows, 'pythonthreedll' will be set to "python3.dll". When searching823the DLL from the registry, Vim will search the latest version of Python.824 825==============================================================================82610. Python 3 *python3*827 828 *:py3* *:python3*829:[range]py3 {stmt}830:[range]py3 << [trim] [{endmarker}]831{script}832{endmarker}833 834:[range]python3 {stmt}835:[range]python3 << [trim] [{endmarker}]836{script}837{endmarker}838 The `:py3` and `:python3` commands work similar to `:python`. A839 simple check if the `:py3` command is working: >840 :py3 print("Hello")841<842 To see what version of Python you have: >843 :py3 import sys844 :py3 print(sys.version)845< *:py3file*846:[range]py3f[ile] {file}847 The `:py3file` command works similar to `:pyfile`.848 *:py3do*849:[range]py3do {body}850 The `:py3do` command works similar to `:pydo`.851 852 853Vim can be built in four ways (:version output):8541. No Python support (-python, -python3)8552. Python 2 support only (+python or +python/dyn, -python3)8563. Python 3 support only (-python, +python3 or +python3/dyn)8574. Python 2 and 3 support (+python/dyn, +python3/dyn)858 859Some more details on the special case 4: *python-2-and-3*860 861When Python 2 and Python 3 are both supported they must be loaded dynamically.862 863When doing this on Linux/Unix systems and importing global symbols, this leads864to a crash when the second Python version is used. So either global symbols865are loaded but only one Python version is activated, or no global symbols are866loaded. The latter makes Python's "import" fail on libraries that expect the867symbols to be provided by Vim.868 *E836* *E837*869Vim's configuration script makes a guess for all libraries based on one870standard Python library (termios). If importing this library succeeds for871both Python versions, then both will be made available in Vim at the same872time. If not, only the version first used in a session will be enabled.873When trying to use the other one you will get the E836 or E837 error message.874 875Here Vim's behavior depends on the system in which it was configured. In a876system where both versions of Python were configured with --enable-shared,877both versions of Python will be activated at the same time. There will still878be problems with other third party libraries that were not linked to879libPython.880 881To work around such problems there are these options:8821. The problematic library is recompiled to link to the according883 libpython.so.8842. Vim is recompiled for only one Python version.8853. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This886 may crash Vim though.887 888 *E880*889Raising SystemExit exception in python isn't endorsed way to quit vim, use: >890 :py vim.command("qall!")891<892 *E1266*893This error can occur when Python 3 cannot load the required modules. This894means that your Python 3 is not correctly installed or there are some mistakes895in your settings. Please check the following items:8961. Make sure that Python 3 is correctly installed. Also check the version of897 python.8982. Check the 'pythonthreedll' option.8993. Check the 'pythonthreehome' option.9004. Check the PATH environment variable if you don't set 'pythonthreedll'.901 On MS-Windows, you can use where.exe to check which dll will be loaded.902 E.g. >903 where.exe python310.dll9045. Check the PYTHONPATH and PYTHONHOME environment variables.905 906 *has-python*907You can test what Python version is available with: >908 if has('python')909 echo 'there is Python 2.x'910 endif911 if has('python3')912 echo 'there is Python 3.x'913 endif914 915Note however, that when Python 2 and 3 are both available and loaded916dynamically, these has() calls will try to load them. If only one can be917loaded at a time, just checking if Python 2 or 3 are available will prevent918the other one from being available.919 920To avoid loading the dynamic library, only check if Vim was compiled with921python support: >922 if has('python_compiled')923 echo 'compiled with Python 2.x support'924 if has('python_dynamic')925 echo 'Python 2.x dynamically loaded'926 endif927 endif928 if has('python3_compiled')929 echo 'compiled with Python 3.x support'930 if has('python3_dynamic')931 echo 'Python 3.x dynamically loaded'932 endif933 endif934 935When loading the library dynamically, Vim can be compiled to support Python 3936Stable ABI (|python3-stable-abi|) which allows you to load a different version937of Python 3 library than the one Vim was compiled with. To check it: >938 if has('python3_dynamic')939 if has('python3_stable')940 echo 'support Python 3 Stable ABI.'941 else942 echo 'does not support Python 3 Stable ABI.'943 echo 'only use Python 3 version ' .. v:python3_version944 endif945 endif946 947This also tells you whether Python is dynamically loaded, which will fail if948the runtime library cannot be found.949 950==============================================================================95111. Python X *python_x* *pythonx*952 953Because most python code can be written so that it works with Python 2.6+ and954Python 3 the pyx* functions and commands have been written. They work exactly955the same as the Python 2 and 3 variants, but select the Python version using956the 'pyxversion' setting.957 958You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3959for Python commands. If you change this setting at runtime you may risk that960state of plugins (such as initialization) may be lost.961 962If you want to use a module, you can put it in the {rtp}/pythonx directory.963See |pythonx-directory|.964 965 *:pyx* *:pythonx*966The `:pyx` and `:pythonx` commands work similar to `:python`. A simple check967if the `:pyx` command is working: >968 :pyx print("Hello")969 970To see what version of Python is being used: >971 :pyx import sys972 :pyx print(sys.version)973<974 *:pyxfile* *python_x-special-comments*975The `:pyxfile` command works similar to `:pyfile`. However you can add one of976these comments to force Vim using `:pyfile` or `:py3file`: >977 #!/any string/python2 " Shebang. Must be the first line of the file.978 #!/any string/python3 " Shebang. Must be the first line of the file.979 # requires python 2.x " Maximum lines depend on 'modelines'.980 # requires python 3.x " Maximum lines depend on 'modelines'.981Unlike normal modelines, the bottom of the file is not checked.982If none of them are found, the 'pyxversion' setting is used.983 *W20* *W21*984If Vim does not support the selected Python version a silent message will be985printed. Use `:messages` to read them.986 987 *:pyxdo*988The `:pyxdo` command works similar to `:pydo`.989 990 *has-pythonx*991You can test if pyx* commands are available with: >992 if has('pythonx')993 echo 'pyx* commands are available. (Python ' .. &pyx .. ')'994 endif995 996When compiled with only one of |+python| or |+python3|, the has() returns 1.997When compiled with both |+python| and |+python3|, the test depends on the998'pyxversion' setting. If 'pyxversion' is 0, it tests Python 3 first, and if999it is not available then Python 2. If 'pyxversion' is 2 or 3, it tests only1000Python 2 or 3 respectively.1001 1002Note that for `has('pythonx')` to work it may try to dynamically load Python 31003or 2. This may have side effects, especially when Vim can only load one of1004the two.1005 1006If a user prefers Python 2 and want to fallback to Python 3, he needs to set1007'pyxversion' explicitly in his |.vimrc|. E.g.: >1008 if has('python')1009 set pyx=21010 elseif has('python3')1011 set pyx=31012 endif1013 1014==============================================================================101512. Building with Python support *python-building*1016 1017A few hints for building with Python 2 or 3 support.1018 1019UNIX1020 1021See src/Makefile for how to enable including the Python interface.1022 1023On Ubuntu you will want to install these packages for Python 2:1024 python1025 python-dev1026For Python 3:1027 python31028 python3-dev1029For Python 3.6:1030 python3.61031 python3.6-dev1032 1033If you have more than one version of Python 3, you need to link python3 to the1034one you prefer, before running configure.1035 1036==============================================================================1037 vim:tw=78:ts=8:noet:ft=help:norl:1038 