vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

if_pyth.txt (42355B)


      1 *if_pyth.txt*	For Vim version 9.2.  Last change: 2026 Mar 18
      2 
      3 
      4 		  VIM REFERENCE MANUAL	  by Paul Moore
      5 
      6 
      7 The Python Interface to Vim				*python* *Python*
      8 
      9 1. Commands					|python-commands|
     10 2. The vim module				|python-vim|
     11 3. Buffer objects				|python-buffer|
     12 4. Range objects				|python-range|
     13 5. Window objects				|python-window|
     14 6. Tab page objects				|python-tabpage|
     15 7. vim.bindeval objects				|python-bindeval-objects|
     16 8. pyeval(), py3eval() Vim functions		|python-pyeval|
     17 9. Dynamic loading				|python-dynamic|
     18 10. Python 3					|python3|
     19 11. Python X					|python_x|
     20 12. Building with Python support		|python-building|
     21 
     22 The Python 2.x interface is available only when Vim was compiled with the
     23 |+python| feature.
     24 The Python 3 interface is available only when Vim was compiled with the
     25 |+python3| feature.
     26 Both can be available at the same time, but read |python-2-and-3|.
     27 
     28 NOTE: Python 2 is old and no longer being developed.  Using Python 3 is highly
     29 recommended.  Python 2 support will be dropped when it does not work properly
     30 anymore.
     31 
     32 ==============================================================================
     33 1. Commands						*python-commands*
     34 
     35 					*:python* *:py* *E263* *E264* *E887*
     36 :[range]py[thon] {stmt}
     37 			Execute Python statement {stmt}.  A simple check if
     38 			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 Python
     46 			feature wasn't compiled in.  To avoid errors, see
     47 			|script-here|.
     48 
     49 If [endmarker] is omitted from after the "<<", a dot '.' must be used after
     50 {script}, like for the |:append| and |:insert| commands.  Refer to
     51 |:let-heredoc| for more information.
     52 
     53 This form of the |:python| command is mainly useful for including python code
     54 in Vim scripts.
     55 
     56 Example: >
     57 	function! IcecreamInitialize()
     58 	python << EOF
     59 	class StrawberryIcecream:
     60 		def __call__(self):
     61 			print 'EAT ME'
     62 	EOF
     63 	endfunction
     64 
     65 To see what version of Python you have: >
     66 	:python print(sys.version)
     67 
     68 There is no need to import sys, it's done by default.
     69 
     70 							*python-environment*
     71 Environment variables set in Vim are not always available in Python.  This
     72 depends on how Vim and Python were built.  Also see
     73 https://docs.python.org/3/library/os.html#os.environ
     74 
     75 Note: Python is very sensitive to the indenting.  Make sure the "class" line
     76 and "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 the
     81 			function arguments being set to the text of each line
     82 			in turn, without a trailing <EOL>, and the current
     83 			line number.  The function should return a string or
     84 			None.  If a string is returned, it becomes the text of
     85 			the line in the current turn.  The default for [range]
     86 			is the whole file: "1,$".
     87 
     88 Examples:
     89 >
     90 	:pydo return "%s\t%d" % (line[::-1], len(line))
     91 	:pydo if line: return "%4d: %s" % (linenr, line)
     92 <
     93 One can use `:pydo` in possible conjunction with `:py` to filter a range using
     94 python.  For example: >
     95 
     96 	:py3 << EOF
     97 	needle = vim.eval('@a')
     98 	replacement = vim.eval('@b')
     99 
    100 	def py_vim_string_replace(str):
    101 		return str.replace(needle, replacement)
    102 	EOF
    103 	:'<,'>py3do return py_vim_string_replace(line)
    104 <
    105 							*:pyfile* *:pyf*
    106 :[range]pyf[ile] {file}
    107 			Execute the Python script in {file}.  The whole
    108 			argument is used as a single file name.
    109 
    110 Both of these commands do essentially the same thing - they execute a piece of
    111 Python code, with the "current range" |python-range| set to the given line
    112 range.
    113 
    114 In the case of :python, the code to execute is in the command-line.
    115 In the case of :pyfile, the code to execute is the contents of the given file.
    116 
    117 Python commands cannot be used in the |sandbox|.
    118 
    119 To pass arguments you need to set sys.argv[] explicitly.  Example: >
    120 
    121 	:python sys.argv = ["foo", "bar"]
    122 	:pyfile myscript.py
    123 
    124 Here are some examples					*python-examples*  >
    125 
    126 	:python from vim import *
    127 	:python from string import upper
    128 	: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,
    133 just like in the Python interpreter.)
    134 
    135 ==============================================================================
    136 2. The vim module					*python-vim*
    137 
    138 Python code gets all of its access to vim (with one exception - see
    139 |python-output| below) via the "vim" module.  The vim module implements two
    140 methods, three constants, and one error object.  You need to import the vim
    141 module before using it: >
    142 	:python import vim
    143 
    144 Overview >
    145 	:py print "Hello"		# displays a message
    146 	:py vim.command(cmd)		# execute an Ex command
    147 	:py w = vim.windows[n]		# gets window "n"
    148 	:py cw = vim.current.window	# gets the current window
    149 	:py b = vim.buffers[n]		# gets buffer "n"
    150 	:py cb = vim.current.buffer	# gets the current buffer
    151 	:py w.height = lines		# sets the window height
    152 	:py w.cursor = (row, col)	# sets the window cursor position
    153 	:py pos = w.cursor		# gets a tuple (row, col)
    154 	:py name = b.name		# gets the buffer file name
    155 	:py line = b[n]			# gets a line from the buffer
    156 	:py lines = b[n:m]		# gets a list of lines
    157 	:py num = len(b)		# gets the number of lines
    158 	:py b[n] = str			# sets a line in the buffer
    159 	:py b[n:m] = [str1, str2, str3]	# sets a number of lines at once
    160 	:py del b[n]			# deletes a line
    161 	:py del b[n:m]			# deletes a number of lines
    162 
    163 
    164 Methods of the "vim" module
    165 
    166 vim.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 containing
    175 		# double quotes
    176 		normal('"a2dd"aP')
    177 <								*E659*
    178 	The ":python" command cannot be used recursively with Python 2.2 and
    179 	older.  This only works with Python 2.3 and later: >
    180 	    :py vim.command("python print 'Hello again Python'")
    181 
    182 vim.eval(str)						*python-eval*
    183 	Evaluates the expression str using the vim internal expression
    184 	evaluator (see |expression|).  Returns the expression result as:
    185 	- a string if the Vim expression evaluates to a string or number
    186 	- 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' option
    194 	    :py text_width = vim.eval("&tw")
    195 	    :
    196 	    :" contents of the 'a' register
    197 	    :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 visible
    210 	to python evaluations.  To pass local variables to python evaluations,
    211 	use the {locals} dict when calling |py3eval()| and friends.
    212 
    213 vim.bindeval(str)					*python-bindeval*
    214 	Like |python-eval|, but returns special objects described in
    215 	|python-bindeval-objects|.  These python objects let you modify
    216 	(|List|, |Tuple| or |Dictionary|) or call (|Funcref|) vim objects.
    217 
    218 vim.strwidth(str)					*python-strwidth*
    219 	Like |strwidth()|: returns number of display cells str occupies, tab
    220 	is counted as one cell.
    221 
    222 vim.foreach_rtp(callable)				*python-foreach_rtp*
    223 	Call the given callable for each path in 'runtimepath' until either
    224 	callable returns something but None, the exception is raised or there
    225 	are no longer paths.  If stopped in case callable returned non-None,
    226 	vim.foreach_rtp function returns the value returned by callable.
    227 
    228 vim.chdir(*args, **kwargs)				*python-chdir*
    229 vim.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 and
    232 	      os.fchdir instead.  Behavior of vim.fchdir is undefined in case
    233 	      os.fchdir does not exist.
    234 
    235 Error object of the "vim" module
    236 
    237 vim.error						*python-error*
    238 	Upon encountering a Vim error, Python raises an exception of type
    239 	vim.error.
    240 	Example: >
    241 		try:
    242 			vim.command("put a")
    243 		except vim.error:
    244 			# nothing in register a
    245 
    246 Constants of the "vim" module
    247 
    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 objects
    250 	to which the variables referred.
    251 
    252 vim.buffers						*python-buffers*
    253 	A mapping object providing access to the list of vim buffers.  The
    254 	object supports the following operations: >
    255 	    :py b = vim.buffers[i]	# Indexing (read-only)
    256 	    :py b in vim.buffers	# Membership test
    257 	    :py n = len(vim.buffers)	# Number of elements
    258 	    :py for b in vim.buffers:	# Iterating over buffer list
    259 <
    260 vim.windows						*python-windows*
    261 	A sequence object providing access to the list of vim windows.  The
    262 	object supports the following operations: >
    263 	    :py w = vim.windows[i]	# Indexing (read-only)
    264 	    :py w in vim.windows	# Membership test
    265 	    :py n = len(vim.windows)	# Number of elements
    266 	    :py for w in vim.windows:	# Sequential access
    267 <	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.error
    270 	in case tab page was deleted).  You can keep a reference to both
    271 	without keeping a reference to vim module object or |python-tabpage|,
    272 	they will not lose their properties in this case.
    273 
    274 vim.tabpages						*python-tabpages*
    275 	A sequence object providing access to the list of vim tab pages.  The
    276 	object supports the following operations: >
    277 	    :py t = vim.tabpages[i]	# Indexing (read-only)
    278 	    :py t in vim.tabpages	# Membership test
    279 	    :py n = len(vim.tabpages)	# Number of elements
    280 	    :py for t in vim.tabpages:	# Sequential access
    281 <
    282 vim.current						*python-current*
    283 	An object providing access (via specific attributes) to various
    284 	"current" objects available in vim:
    285 		vim.current.line	The current line (RW)		String
    286 		vim.current.buffer	The current buffer (RW)		Buffer
    287 		vim.current.window	The current window (RW)		Window
    288 		vim.current.tabpage	The current tab page (RW)	TabPage
    289 		vim.current.range	The current line range (RO)	Range
    290 
    291 	The last case deserves a little explanation.  When the :python or
    292 	:pyfile command specifies a range, this range of lines becomes the
    293 	"current range".  A range is a bit like a buffer, but with all access
    294 	restricted to a subset of lines.  See |python-range| for more details.
    295 
    296 	Note: When assigning to vim.current.{buffer,window,tabpage} it expects
    297 	valid |python-buffer|, |python-window| or |python-tabpage| objects
    298 	respectively.  Assigning triggers normal (with |autocommand|s)
    299 	switching to given buffer, window or tab page.  It is the only way to
    300 	switch UI objects in python: you can't assign to
    301 	|python-tabpage|.window attribute.  To switch without triggering
    302 	autocommands use >
    303 	    py << EOF
    304 	    saved_eventignore = vim.options['eventignore']
    305 	    vim.options['eventignore'] = 'all'
    306 	    try:
    307 	        vim.current.buffer = vim.buffers[2] # Switch to buffer 2
    308 	    finally:
    309 	        vim.options['eventignore'] = saved_eventignore
    310 	    EOF
    311 <
    312 vim.vars						*python-vars*
    313 vim.vvars						*python-vvars*
    314 	Dictionary-like objects holding dictionaries with global (|g:|) and
    315 	vim (|v:|) variables respectively.  Identical to `vim.bindeval("g:")`,
    316 	but faster.
    317 
    318 vim.options						*python-options*
    319 	Object partly supporting mapping protocol (supports setting and
    320 	getting items) providing a read-write access to global options.
    321 	Note: unlike |:set| this provides access only to global options.  You
    322 	cannot use this object to obtain or set local options' values or
    323 	access local-only options in any fashion.  Raises KeyError if no
    324 	global option with such name exists (i.e. does not raise KeyError for
    325 	|global-local| options and global only options, but does for window-
    326 	and buffer-local ones).  Use |python-buffer| objects to access to
    327 	buffer-local options and |python-window| objects to access to
    328 	window-local options.
    329 
    330 	Type of this object is available via "Options" attribute of vim
    331 	module.
    332 
    333 Output from Python					*python-output*
    334 	Vim displays all Python code output in the Vim message area.  Normal
    335 	output appears as information messages, and error output appears as
    336 	error messages.
    337 
    338 	In implementation terms, this means that all output to sys.stdout
    339 	(including the output from print statements) appears as information
    340 	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 not
    345 	supported, and may cause the program to crash.  This should probably
    346 	be fixed.
    347 
    348 		    *python2-directory* *python3-directory* *pythonx-directory*
    349 Python 'runtimepath' handling				*python-special-path*
    350 
    351 In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
    352 the list of paths found in 'runtimepath': with this directory in sys.path and
    353 vim.path_hooks in sys.path_hooks python will try to load module from
    354 {rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
    355 each {rtp} found in 'runtimepath' (Note: find_module() has been removed from
    356 imp module around Python 3.12.0a7).
    357 
    358 Implementation is similar to the following, but written in C: >
    359 
    360     from imp import find_module, load_module
    361     import vim
    362     import sys
    363 
    364     class VimModuleLoader(object):
    365         def __init__(self, module):
    366             self.module = module
    367 
    368         def load_module(self, fullname, path=None):
    369             return self.module
    370 
    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 not
    384     # matter for python which object has find_module function attached to as
    385     # an attribute.
    386     class VimPathFinder(object):
    387         @classmethod
    388         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 None
    393 
    394         @classmethod
    395         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 VimPathFinder
    401         else:
    402             raise ImportError
    403 
    404     sys.path_hooks.append(hook)
    405 
    406 vim.VIM_SPECIAL_PATH				*python-VIM_SPECIAL_PATH*
    407 	String constant used in conjunction with vim path hook.  If path hook
    408 	installed by vim is requested to handle anything but path equal to
    409 	vim.VIM_SPECIAL_PATH constant it raises ImportError.  In the only
    410 	other case it uses special loader.
    411 
    412 	Note: you must not use value of this constant directly, always use
    413 	      vim.VIM_SPECIAL_PATH object.
    414 
    415 vim.find_module(...)					*python-find_module*
    416 vim.path_hook(path)					*python-path_hook*
    417 vim.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_hook
    420 	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 vim
    423 	versions.
    424 
    425 vim._get_paths						*python-_get_paths*
    426 	Methods returning a list of paths which will be searched for by path
    427 	hook.  You should not rely on this method being present in future
    428 	versions, but can use it for debugging.
    429 
    430 	It returns a list of {rtp}/python2 (or {rtp}/python3) and
    431 	{rtp}/pythonx directories for each {rtp} in 'runtimepath'.
    432 
    433 ==============================================================================
    434 3. Buffer objects					*python-buffer*
    435 
    436 Buffer objects represent vim buffers.  You can obtain them in a number of
    437 ways:
    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 
    442 Buffer objects have two read-only attributes - name - the full file name for
    443 the buffer, and number - the buffer number.  They also have three methods
    444 (append, mark, and range; see below).
    445 
    446 You can also treat buffer objects as sequence objects.  In this context, they
    447 act as if they were lists (yes, they are mutable) of strings, with each
    448 element being a line of the buffer.  All of the usual sequence operations,
    449 including indexing, index assignment, slicing and slice assignment, work as
    450 you would expect.  Note that the result of indexing (slicing) a buffer is a
    451 string (list of strings).  This has one unusual consequence - b[:] is
    452 different from b.  In particular, "b[:] = None" deletes the whole of the
    453 buffer, whereas "b = None" merely updates the variable b, with no effect on
    454 the buffer.
    455 
    456 Buffer indexes start at zero, as is normal in Python.  This differs from vim
    457 line numbers, which start from 1.  This is particularly relevant when dealing
    458 with marks (see below) which use vim line numbers.
    459 
    460 The buffer object attributes are:
    461 	b.vars		Dictionary-like object used to access
    462 			|buffer-variable|s.
    463 	b.options	Mapping object (supports item getting, setting and
    464 			deleting) that provides access to buffer-local options
    465 			and buffer-local values of |global-local| options.  Use
    466 			|python-window|.options if option is window-local,
    467 			this object will raise KeyError.  If option is
    468 			|global-local| and local value is missing getting it
    469 			will return None.
    470 	b.name		String, RW.  Contains buffer name (full path).
    471 			Note: when assigning to b.name |BufFilePre| and
    472 			|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 when
    476 			corresponding buffer is wiped out.
    477 
    478 The buffer object methods are:
    479 	b.append(str)	Append a line to the buffer
    480 	b.append(str, nr)  Idem, below line "nr"
    481 	b.append(list)	Append a list of lines to the buffer
    482 			Note that the option of supplying a list of strings to
    483 			the append method differs from the equivalent method
    484 			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 position
    487 			of the named mark (can also get the []"<> marks)
    488 	b.range(s,e)	Return a range object (see |python-range|) which
    489 			represents the part of the given buffer between line
    490 			numbers s and e |inclusive|.
    491 
    492 Note that when adding a line it must not contain a line break character '\n'.
    493 A trailing '\n' is allowed and ignored, so that you can do: >
    494 	:py b.append(f.readlines())
    495 
    496 Buffer object type is available using "Buffer" attribute of vim module.
    497 
    498 Examples (assume b is the current buffer) >
    499 	:py print b.name		# write the buffer file name
    500 	:py b[0] = "hello!!!"		# replace the top line
    501 	:py b[:] = None			# delete the whole buffer
    502 	:py del b[:]			# delete the whole buffer
    503 	:py b[0:0] = [ "a line" ]	# add a line at the top
    504 	:py del b[2]			# delete a line (the third)
    505 	:py b.append("bottom")		# add a line at the bottom
    506 	:py n = len(b)			# number of lines
    507 	:py (row,col) = b.mark('a')	# named mark
    508 	:py r = b.range(1,5)		# a sub-range of the buffer
    509 	:py b.vars["foo"] = "bar"	# assign b:foo variable
    510 	:py b.options["ff"] = "dos"	# set fileformat
    511 	:py del b.options["ar"]		# same as :set autoread<
    512 
    513 ==============================================================================
    514 4. Range objects					*python-range*
    515 
    516 Range objects represent a part of a vim buffer.  You can obtain them in a
    517 number of ways:
    518 	- via vim.current.range (|python-current|)
    519 	- from a buffer's range() method (|python-buffer|)
    520 
    521 A range object is almost identical in operation to a buffer object.  However,
    522 all operations are restricted to the lines within the range (this line range
    523 can, of course, change as a result of slice assignments, line deletions, or
    524 the range.append() method).
    525 
    526 The range object attributes are:
    527 	r.start		Index of first line into the buffer
    528 	r.end		Index of last line into the buffer
    529 
    530 The range object methods are:
    531 	r.append(str)	Append a line to the range
    532 	r.append(str, nr)  Idem, after line "nr"
    533 	r.append(list)	Append a list of lines to the range
    534 			Note that the option of supplying a list of strings to
    535 			the append method differs from the equivalent method
    536 			for Python's built-in list objects.
    537 	r.append(list, nr)  Idem, after line "nr"
    538 
    539 Range object type is available using "Range" attribute of vim module.
    540 
    541 Example (assume r is the current range): >
    542 	# Send all lines in a range to the default printer
    543 	vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
    544 
    545 ==============================================================================
    546 5. Window objects					*python-window*
    547 
    548 Window objects represent vim windows.  You can obtain them in a number of
    549 ways:
    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 
    555 You can manipulate window objects only through their attributes.  They have no
    556 methods, and no sequence or other interface.
    557 
    558 Window attributes are:
    559 	buffer (read-only)	The buffer displayed in this window
    560 	cursor (read-write)	The current cursor position in the window
    561 				This is a tuple, (row,col).
    562 	height (read-write)	The window height, in rows
    563 	width (read-write)	The window width, in columns
    564 	vars (read-only)	The window |w:| variables. Attribute is
    565 				unassignable, but you can change window
    566 				variables this way
    567 	options (read-only)	The window-local options. Attribute is
    568 				unassignable, but you can change window
    569 				options this way. Provides access only to
    570 				window-local options, for buffer-local use
    571 				|python-buffer| and for global ones use
    572 				|python-options|. If option is |global-local|
    573 				and local value is missing getting it will
    574 				return None.
    575 	number (read-only)	Window number.  The first window has number 1.
    576 				This is zero in case it cannot be determined
    577 				(e.g. when the window object belongs to other
    578 				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 invalid
    583 				when corresponding window is closed.
    584 
    585 The height attribute is writable only if the screen is split horizontally.
    586 The width attribute is writable only if the screen is split vertically.
    587 
    588 Window object type is available using "Window" attribute of vim module.
    589 
    590 ==============================================================================
    591 6. Tab page objects					*python-tabpage*
    592 
    593 Tab page objects represent vim tab pages. You can obtain them in a number of
    594 ways:
    595 	- via vim.current.tabpage (|python-current|)
    596 	- from indexing vim.tabpages (|python-tabpages|)
    597 
    598 You can use this object to access tab page windows. They have no methods and
    599 no sequence or other interfaces.
    600 
    601 Tab page attributes are:
    602 	number		The tab page number like the one returned by
    603 			|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 when
    608 			corresponding tab page is closed.
    609 
    610 TabPage object type is available using "TabPage" attribute of vim module.
    611 
    612 ==============================================================================
    613 7. vim.bindeval objects				*python-bindeval-objects*
    614 
    615 vim.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 locked
    622                     vim.VAR_LOCKED  Variable is locked, but can be unlocked
    623                     vim.VAR_FIXED   Variable is locked and can't be unlocked
    624                    Read-write. You can unlock locked variable by assigning
    625                    `True` or `False` to this attribute. No recursive locking
    626                    is supported.
    627         scope      One of
    628                     Value              Description ~
    629                     zero               Dictionary is not a scope one
    630                     vim.VAR_DEF_SCOPE  |g:| or |l:| dictionary
    631                     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 is
    642                     not present.
    643         pop(key[, default])
    644                     Remove specified key from dictionary and return
    645                     corresponding value. If key is not found and default is
    646                     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, similar
    652                     to `key in dict`.
    653 
    654         __new__(), __new__(iterable), __new__(dictionary), __new__(update)
    655                     You can use `vim.Dictionary()` to create new vim
    656                     dictionaries. `d=vim.Dictionary(arg)` is the same as
    657                     `d=vim.bindeval('{}');d.update(arg)`. Without arguments
    658                     constructs empty dictionary.
    659 
    660     Examples: >
    661         d = vim.Dictionary(food="bar")		# Constructor
    662         d['a'] = 'b'				# Item assignment
    663         print d['a']				# getting item
    664         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)	# True
    671         for key in d:				# Iteration over keys
    672         class Dict(vim.Dictionary):		# Subclassing
    673 <
    674     Note: when iterating over keys you should not modify dictionary.
    675 
    676 vim.List object					*python-List*
    677     Sequence-like object providing access to vim |List| type.
    678     Supports `.locked` attribute, see |python-.locked|. Also supports the
    679     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 as
    686                         `l=vim.bindeval('[]');l.extend(iterable)`. Without
    687                         arguments constructs empty list.
    688     Examples: >
    689         l = vim.List("abc")		# Constructor, result: ['a', 'b', 'c']
    690         l.extend(['abc', 'def'])	# .extend() method
    691         print l[1:]			# slicing
    692         l[:0] = ['ghi', 'jkl']		# slice assignment
    693         print l[0]			# getting item
    694         l[0] = 'mno'			# assignment
    695         for i in l:			# iteration
    696         print isinstance(l, vim.List)	# True
    697         class List(vim.List):		# Subclassing
    698 
    699 vim.Tuple object				*python-Tuple*
    700     Sequence-like object providing access to vim |Tuple| type.
    701     Supports `.locked` attribute, see |python-.locked|. Also supports the
    702     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:]			# slicing
    710         print t[0]			# getting item
    711         for i in t:			# iteration
    712         print isinstance(t, vim.Tuple)	# True
    713         class Tuple(vim.Tuple):		# Subclassing
    714 
    715 vim.Function object				*python-Function*
    716     Function-like object, acting like vim |Funcref| object. Accepts special
    717     keyword argument `self`, see |Dictionary-function|. You can also use
    718     `vim.Function(name)` constructor, it is the same as
    719     `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.  Note
    725                      that this is a copy of the arguments list, constructed
    726                      each time you request this attribute. Modifications made
    727                      to the list will be ignored (but not to the containers
    728                      inside argument list: this is like |copy()| and not
    729                      |deepcopy()|).
    730         self         `None` or a |python-Dictionary| object with self
    731                      dictionary. Note that explicit `self` keyword used when
    732                      calling resulting object overrides this attribute.
    733         auto_rebind  Boolean. True if partial created from this Python object
    734                      and stored in the Vim script dictionary should be
    735                      automatically rebound to the dictionary it is stored in
    736                      when this dictionary is indexed. Exposes Vim internal
    737                      difference between `dict.func` (auto_rebind=True) and
    738                      `function(dict.func,dict)` (auto_rebind=False). This
    739                      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 constructs
    743     a partial, see |function()|.  `auto_rebind` is only used when `self`
    744     argument is given, otherwise it is assumed to be `True` regardless of
    745     whether it was given or not.  If `self` is given then it defaults to
    746     `False`.
    747 
    748     Examples: >
    749         f = vim.Function('tr')			# Constructor
    750         print f('abc', 'a', 'b')		# Calls tr('abc', 'a', 'b')
    751         vim.command('''
    752             function DictFun() dict
    753                 return self
    754             endfunction
    755         ''')
    756         f = vim.bindeval('function("DictFun")')
    757         print f(self={})			# Like call('DictFun', [], {})
    758         print isinstance(f, vim.Function)	# True
    759 
    760         p = vim.Function('DictFun', self={})
    761         print f()
    762         p = vim.Function('tr', args=['abc', 'a'])
    763         print f('b')
    764 
    765 ==============================================================================
    766 8. pyeval() and py3eval() Vim functions			*python-pyeval*
    767 
    768 To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
    769 functions to evaluate Python expressions and pass their values to Vim script.
    770 |pyxeval()| is also available.
    771 
    772 You can inject local variables into the evaluation using the optional {locals}
    773 dict. This can be particularly useful in vim9script where vim.eval
    774 |python-eval| will not find locals in a def func.
    775 
    776 The Python value "None" is converted to v:none.
    777 
    778 ==============================================================================
    779 9. Dynamic loading					*python-dynamic*
    780 
    781 On MS-Windows and Unix the Python library can be loaded dynamically.  The
    782 |:version| output then includes |+python/dyn| or |+python3/dyn|.
    783 
    784 This means that Vim will search for the Python DLL or shared library file only
    785 when needed.  When you don't use the Python interface you don't need it, thus
    786 you can use Vim without this file.
    787 
    788 
    789 MS-Windows ~
    790 
    791 To use the Python interface the Python DLL must be in your search path.  In a
    792 console window type "path" to see what directories are used.  If the DLL is
    793 not found in your search path, Vim will check the registry to find the path
    794 where Python is installed.  The 'pythondll' or 'pythonthreedll' option can be
    795 also used to specify the Python DLL.
    796 
    797 The name of the DLL should match the Python version Vim was compiled with.
    798 Currently the name for Python 2 is "python27.dll", that is for Python 2.7.
    799 That is the default value for 'pythondll'.  For Python 3 it is python36.dll
    800 (Python 3.6).  To know for sure edit "gvim.exe" and search for
    801 "python\d*.dll\c".
    802 
    803 
    804 Unix ~
    805 
    806 The 'pythondll' or 'pythonthreedll' option can be used to specify the Python
    807 shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file
    808 what were specified at compile time.  The version of the shared library must
    809 match the Python 2.x or Python 3 version (|v:python3_version|) Vim was
    810 compiled with unless using |python3-stable-abi|.
    811 
    812 
    813 Stable ABI and mixing Python versions ~
    814 			*python-stable* *python-stable-abi* *python3-stable-abi*
    815 If Vim was not compiled with Stable ABI (only available for Python 3), the
    816 version of the Python shared library must match the version that Vim was
    817 compiled with.  Otherwise, mixing versions could result in unexpected crashes
    818 and failures.  With Stable ABI, this restriction is relaxed, and any Python 3
    819 library with version of at least |v:python3_version| will work.  See
    820 |has-python| for how to check if Stable ABI is supported, or see if version
    821 output includes |+python3/dyn-stable|.
    822 On MS-Windows, 'pythonthreedll' will be set to "python3.dll".  When searching
    823 the DLL from the registry, Vim will search the latest version of Python.
    824 
    825 ==============================================================================
    826 10. 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`.  A
    839 	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 sys
    844 		: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 
    853 Vim can be built in four ways (:version output):
    854 1. No Python support	    (-python, -python3)
    855 2. Python 2 support only    (+python or +python/dyn, -python3)
    856 3. Python 3 support only    (-python, +python3 or +python3/dyn)
    857 4. Python 2 and 3 support   (+python/dyn, +python3/dyn)
    858 
    859 Some more details on the special case 4:  *python-2-and-3*
    860 
    861 When Python 2 and Python 3 are both supported they must be loaded dynamically.
    862 
    863 When doing this on Linux/Unix systems and importing global symbols, this leads
    864 to a crash when the second Python version is used.  So either global symbols
    865 are loaded but only one Python version is activated, or no global symbols are
    866 loaded. The latter makes Python's "import" fail on libraries that expect the
    867 symbols to be provided by Vim.
    868 							*E836* *E837*
    869 Vim's configuration script makes a guess for all libraries based on one
    870 standard Python library (termios).  If importing this library succeeds for
    871 both Python versions, then both will be made available in Vim at the same
    872 time.  If not, only the version first used in a session will be enabled.
    873 When trying to use the other one you will get the E836 or E837 error message.
    874 
    875 Here Vim's behavior depends on the system in which it was configured.  In a
    876 system where both versions of Python were configured with --enable-shared,
    877 both versions of Python will be activated at the same time.  There will still
    878 be problems with other third party libraries that were not linked to
    879 libPython.
    880 
    881 To work around such problems there are these options:
    882 1. The problematic library is recompiled to link to the according
    883    libpython.so.
    884 2. Vim is recompiled for only one Python version.
    885 3. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration.  This
    886    may crash Vim though.
    887 
    888 							*E880*
    889 Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
    890 	:py vim.command("qall!")
    891 <
    892 							*E1266*
    893 This error can occur when Python 3 cannot load the required modules.  This
    894 means that your Python 3 is not correctly installed or there are some mistakes
    895 in your settings.  Please check the following items:
    896 1. Make sure that Python 3 is correctly installed.  Also check the version of
    897    python.
    898 2. Check the 'pythonthreedll' option.
    899 3. Check the 'pythonthreehome' option.
    900 4. 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.dll
    904 5. Check the PYTHONPATH and PYTHONHOME environment variables.
    905 
    906 							*has-python*
    907 You can test what Python version is available with: >
    908 	if has('python')
    909 	  echo 'there is Python 2.x'
    910 	endif
    911 	if has('python3')
    912 	  echo 'there is Python 3.x'
    913 	endif
    914 
    915 Note however, that when Python 2 and 3 are both available and loaded
    916 dynamically, these has() calls will try to load them.  If only one can be
    917 loaded at a time, just checking if Python 2 or 3 are available will prevent
    918 the other one from being available.
    919 
    920 To avoid loading the dynamic library, only check if Vim was compiled with
    921 python 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 	  endif
    927 	endif
    928 	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 	  endif
    933 	endif
    934 
    935 When loading the library dynamically, Vim can be compiled to support Python 3
    936 Stable ABI (|python3-stable-abi|) which allows you to load a different version
    937 of 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 	  else
    942 	    echo 'does not support Python 3 Stable ABI.'
    943 	    echo 'only use Python 3 version ' .. v:python3_version
    944 	  endif
    945 	endif
    946 
    947 This also tells you whether Python is dynamically loaded, which will fail if
    948 the runtime library cannot be found.
    949 
    950 ==============================================================================
    951 11. Python X						*python_x* *pythonx*
    952 
    953 Because most python code can be written so that it works with Python 2.6+ and
    954 Python 3 the pyx* functions and commands have been written.  They work exactly
    955 the same as the Python 2 and 3 variants, but select the Python version using
    956 the 'pyxversion' setting.
    957 
    958 You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3
    959 for Python commands. If you change this setting at runtime you may risk that
    960 state of plugins (such as initialization) may be lost.
    961 
    962 If you want to use a module, you can put it in the {rtp}/pythonx directory.
    963 See |pythonx-directory|.
    964 
    965 							*:pyx* *:pythonx*
    966 The `:pyx` and `:pythonx` commands work similar to `:python`.  A simple check
    967 if the `:pyx` command is working: >
    968 	:pyx print("Hello")
    969 
    970 To see what version of Python is being used: >
    971 	:pyx import sys
    972 	:pyx print(sys.version)
    973 <
    974 					*:pyxfile* *python_x-special-comments*
    975 The `:pyxfile` command works similar to `:pyfile`.  However you can add one of
    976 these 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'.
    981 Unlike normal modelines, the bottom of the file is not checked.
    982 If none of them are found, the 'pyxversion' setting is used.
    983 							*W20* *W21*
    984 If Vim does not support the selected Python version a silent message will be
    985 printed.  Use `:messages` to read them.
    986 
    987 							*:pyxdo*
    988 The `:pyxdo` command works similar to `:pydo`.
    989 
    990 							*has-pythonx*
    991 You can test if pyx* commands are available with: >
    992 	if has('pythonx')
    993 	  echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
    994 	endif
    995 
    996 When compiled with only one of |+python| or |+python3|, the has() returns 1.
    997 When compiled with both |+python| and |+python3|, the test depends on the
    998 'pyxversion' setting.  If 'pyxversion' is 0, it tests Python 3 first, and if
    999 it is not available then Python 2.  If 'pyxversion' is 2 or 3, it tests only
   1000 Python 2 or 3 respectively.
   1001 
   1002 Note that for `has('pythonx')` to work it may try to dynamically load Python 3
   1003 or 2.  This may have side effects, especially when Vim can only load one of
   1004 the two.
   1005 
   1006 If a user prefers Python 2 and want to fallback to Python 3, he needs to set
   1007 'pyxversion' explicitly in his |.vimrc|.  E.g.: >
   1008 	if has('python')
   1009 	  set pyx=2
   1010 	elseif has('python3')
   1011 	  set pyx=3
   1012 	endif
   1013 
   1014 ==============================================================================
   1015 12. Building with Python support			*python-building*
   1016 
   1017 A few hints for building with Python 2 or 3 support.
   1018 
   1019 UNIX
   1020 
   1021 See src/Makefile for how to enable including the Python interface.
   1022 
   1023 On Ubuntu you will want to install these packages for Python 2:
   1024 	python
   1025 	python-dev
   1026 For Python 3:
   1027 	python3
   1028 	python3-dev
   1029 For Python 3.6:
   1030 	python3.6
   1031 	python3.6-dev
   1032 
   1033 If you have more than one version of Python 3, you need to link python3 to the
   1034 one you prefer, before running configure.
   1035 
   1036 ==============================================================================
   1037  vim:tw=78:ts=8:noet:ft=help:norl: