blob: b17e1e762703f72f42a92affbd52a55f591b2a48 [file] [log] [blame]
Yegappan Lakshmanan038be272025-03-26 18:46:21 +01001*if_pyth.txt* For Vim version 9.1. Last change: 2025 Mar 26
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Paul Moore
5
6
7The Python Interface to Vim *python* *Python*
8
Bram Moolenaar30b65812012-07-12 22:01:11 +020091. Commands |python-commands|
102. The vim module |python-vim|
113. Buffer objects |python-buffer|
124. Range objects |python-range|
135. Window objects |python-window|
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200146. Tab page objects |python-tabpage|
Bram Moolenaara9922d62013-05-30 13:01:18 +0200157. vim.bindeval objects |python-bindeval-objects|
168. pyeval(), py3eval() Vim functions |python-pyeval|
179. Dynamic loading |python-dynamic|
1810. Python 3 |python3|
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +01001911. Python X |python_x|
Bram Moolenaar036986f2017-03-16 17:41:02 +01002012. Building with Python support |python-building|
Bram Moolenaar071d4272004-06-13 20:20:40 +000021
Bram Moolenaar368373e2010-07-19 20:46:22 +020022The Python 2.x interface is available only when Vim was compiled with the
Bram Moolenaar071d4272004-06-13 20:20:40 +000023|+python| feature.
Bram Moolenaar368373e2010-07-19 20:46:22 +020024The Python 3 interface is available only when Vim was compiled with the
25|+python3| feature.
Bram Moolenaar9ba7e172013-07-17 22:37:26 +020026Both can be available at the same time, but read |python-2-and-3|.
Bram Moolenaar071d4272004-06-13 20:20:40 +000027
Bram Moolenaarc51cf032022-02-26 12:25:45 +000028NOTE: Python 2 is old and no longer being developed. Using Python 3 is highly
29recommended. Python 2 support will be dropped when it does not work properly
30anymore.
31
Bram Moolenaar071d4272004-06-13 20:20:40 +000032==============================================================================
331. Commands *python-commands*
34
Bram Moolenaardbc28022014-07-26 13:40:44 +020035 *:python* *:py* *E263* *E264* *E887*
Bram Moolenaar071d4272004-06-13 20:20:40 +000036:[range]py[thon] {stmt}
Bram Moolenaar9b451252012-08-15 17:43:31 +020037 Execute Python statement {stmt}. A simple check if
38 the `:python` command is working: >
39 :python print "Hello"
Bram Moolenaar071d4272004-06-13 20:20:40 +000040
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +020041:[range]py[thon] << [trim] [{endmarker}]
Bram Moolenaar071d4272004-06-13 20:20:40 +000042{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
Bram Moolenaar54775062019-07-31 21:07:14 +020049If [endmarker] is omitted from after the "<<", a dot '.' must be used after
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +020050{script}, like for the |:append| and |:insert| commands. Refer to
51|:let-heredoc| for more information.
Bram Moolenaar54775062019-07-31 21:07:14 +020052
Bram Moolenaar071d4272004-06-13 20:20:40 +000053This form of the |:python| command is mainly useful for including python code
54in Vim scripts.
55
56Example: >
57 function! IcecreamInitialize()
58 python << EOF
59 class StrawberryIcecream:
60 def __call__(self):
61 print 'EAT ME'
62 EOF
63 endfunction
Bram Moolenaar64d8e252016-09-06 22:12:34 +020064
65To see what version of Python you have: >
Bram Moolenaar64d8e252016-09-06 22:12:34 +020066 :python print(sys.version)
67
Bram Moolenaar95bafa22018-10-02 13:26:25 +020068There is no need to import sys, it's done by default.
69
Bram Moolenaar519cc552021-11-16 19:18:26 +000070 *python-environment*
71Environment variables set in Vim are not always available in Python. This
Bram Moolenaar9da17d72022-02-09 21:50:44 +000072depends on how Vim and Python were built. Also see
Bram Moolenaar519cc552021-11-16 19:18:26 +000073https://docs.python.org/3/library/os.html#os.environ
74
Bram Moolenaara3e6bc92013-01-30 14:18:00 +010075Note: Python is very sensitive to the indenting. Make sure the "class" line
76and "EOF" do not have any indent.
Bram Moolenaar071d4272004-06-13 20:20:40 +000077
Bram Moolenaard620aa92013-05-17 16:40:06 +020078 *: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,$".
Bram Moolenaard620aa92013-05-17 16:40:06 +020087
88Examples:
89>
90 :pydo return "%s\t%d" % (line[::-1], len(line))
91 :pydo if line: return "%4d: %s" % (linenr, line)
92<
Bram Moolenaar20aac6c2018-09-02 21:07:30 +020093One can use `:pydo` in possible conjunction with `:py` to filter a range using
94python. 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<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105 *:pyfile* *:pyf*
106:[range]pyf[ile] {file}
107 Execute the Python script in {file}. The whole
Bram Moolenaar25c9c682019-05-05 18:13:34 +0200108 argument is used as a single file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109
110Both of these commands do essentially the same thing - they execute a piece of
111Python code, with the "current range" |python-range| set to the given line
112range.
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
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121 :python sys.argv = ["foo", "bar"]
122 :pyfile myscript.py
123
124Here 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,
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 - see
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000139|python-output| below) via the "vim" module. The vim module implements two
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140methods, three constants, and one error object. You need to import the vim
141module before using it: >
142 :python import vim
143
144Overview >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000145 :py print "Hello" # displays a message
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +0100146 :py vim.command(cmd) # execute an Ex command
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000147 :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
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162
163
164Methods of the "vim" module
165
166vim.command(str) *python-command*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000167 Executes the vim (ex-mode) command str. Returns None.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000169 :py vim.command("set tw=72")
170 :py vim.command("%s/aaa/bbb/g")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171< 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: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000180 :py vim.command("python print 'Hello again Python'")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181
182vim.eval(str) *python-eval*
183 Evaluates the expression str using the vim internal expression
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000184 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
Yegappan Lakshmanan038be272025-03-26 18:46:21 +0100187 - a tuple if the Vim expression evaluates to a Vim tuple
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000188 - a dictionary if the Vim expression evaluates to a Vim dictionary
Yegappan Lakshmanan038be272025-03-26 18:46:21 +0100189 Dictionaries, lists and tuples are recursively expanded.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000190 Examples: >
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200191 :" value of the 'textwidth' option
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000192 :py text_width = vim.eval("&tw")
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200193 :
194 :" contents of the 'a' register
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100195 :py a_reg = vim.eval("@a")
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200196 :
197 :" Result is a string! Use string.atoi() to convert to a number.
198 :py str = vim.eval("12+12")
199 :
Yegappan Lakshmanan038be272025-03-26 18:46:21 +0100200 :py tuple = vim.eval('(1, 2, 3)')
201 :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000202 :py tagList = vim.eval('taglist("eval_expr")')
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000203< The latter will return a python list of python dicts, for instance:
Bram Moolenaar214641f2017-03-05 17:04:09 +0100204 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name': ~
205 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}] ~
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000206
h-east624bb832024-11-09 18:37:32 +0100207 NOTE: In Vim9 script, local variables in def functions are not visible
208 to python evaluations. To pass local variables to python evaluations,
Ben Jacksonea19e782024-11-06 21:50:05 +0100209 use the {locals} dict when calling |py3eval()| and friends.
210
Bram Moolenaar30b65812012-07-12 22:01:11 +0200211vim.bindeval(str) *python-bindeval*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100212 Like |python-eval|, but returns special objects described in
Yegappan Lakshmanan038be272025-03-26 18:46:21 +0100213 |python-bindeval-objects|. These python objects let you modify
214 (|List|, |Tuple| or |Dictionary|) or call (|Funcref|) vim objects.
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000215
Bram Moolenaarbc411962013-06-02 17:46:40 +0200216vim.strwidth(str) *python-strwidth*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100217 Like |strwidth()|: returns number of display cells str occupies, tab
Bram Moolenaarbc411962013-06-02 17:46:40 +0200218 is counted as one cell.
219
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200220vim.foreach_rtp(callable) *python-foreach_rtp*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100221 Call the given callable for each path in 'runtimepath' until either
222 callable returns something but None, the exception is raised or there
223 are no longer paths. If stopped in case callable returned non-None,
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200224 vim.foreach_rtp function returns the value returned by callable.
225
Bram Moolenaarf4258302013-06-02 18:20:17 +0200226vim.chdir(*args, **kwargs) *python-chdir*
227vim.fchdir(*args, **kwargs) *python-fchdir*
228 Run os.chdir or os.fchdir, then all appropriate vim stuff.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100229 Note: you should not use these functions directly, use os.chdir and
230 os.fchdir instead. Behavior of vim.fchdir is undefined in case
Bram Moolenaarf4258302013-06-02 18:20:17 +0200231 os.fchdir does not exist.
232
Bram Moolenaar071d4272004-06-13 20:20:40 +0000233Error object of the "vim" module
234
235vim.error *python-error*
236 Upon encountering a Vim error, Python raises an exception of type
237 vim.error.
238 Example: >
239 try:
240 vim.command("put a")
241 except vim.error:
242 # nothing in register a
243
244Constants of the "vim" module
245
246 Note that these are not actually constants - you could reassign them.
247 But this is silly, as you would then lose access to the vim objects
248 to which the variables referred.
249
250vim.buffers *python-buffers*
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200251 A mapping object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000252 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000253 :py b = vim.buffers[i] # Indexing (read-only)
254 :py b in vim.buffers # Membership test
255 :py n = len(vim.buffers) # Number of elements
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200256 :py for b in vim.buffers: # Iterating over buffer list
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257<
258vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000259 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000261 :py w = vim.windows[i] # Indexing (read-only)
262 :py w in vim.windows # Membership test
263 :py n = len(vim.windows) # Number of elements
264 :py for w in vim.windows: # Sequential access
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100265< Note: vim.windows object always accesses current tab page.
266 |python-tabpage|.windows objects are bound to parent |python-tabpage|
267 object and always use windows from that tab page (or throw vim.error
268 in case tab page was deleted). You can keep a reference to both
269 without keeping a reference to vim module object or |python-tabpage|,
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200270 they will not lose their properties in this case.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200271
272vim.tabpages *python-tabpages*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100273 A sequence object providing access to the list of vim tab pages. The
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200274 object supports the following operations: >
275 :py t = vim.tabpages[i] # Indexing (read-only)
276 :py t in vim.tabpages # Membership test
277 :py n = len(vim.tabpages) # Number of elements
278 :py for t in vim.tabpages: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279<
280vim.current *python-current*
281 An object providing access (via specific attributes) to various
282 "current" objects available in vim:
283 vim.current.line The current line (RW) String
Bram Moolenaare7614592013-05-15 15:51:08 +0200284 vim.current.buffer The current buffer (RW) Buffer
285 vim.current.window The current window (RW) Window
286 vim.current.tabpage The current tab page (RW) TabPage
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 vim.current.range The current line range (RO) Range
288
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000289 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000291 "current range". A range is a bit like a buffer, but with all access
292 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100294 Note: When assigning to vim.current.{buffer,window,tabpage} it expects
295 valid |python-buffer|, |python-window| or |python-tabpage| objects
296 respectively. Assigning triggers normal (with |autocommand|s)
297 switching to given buffer, window or tab page. It is the only way to
298 switch UI objects in python: you can't assign to
299 |python-tabpage|.window attribute. To switch without triggering
Bram Moolenaare7614592013-05-15 15:51:08 +0200300 autocommands use >
301 py << EOF
302 saved_eventignore = vim.options['eventignore']
303 vim.options['eventignore'] = 'all'
304 try:
305 vim.current.buffer = vim.buffers[2] # Switch to buffer 2
306 finally:
307 vim.options['eventignore'] = saved_eventignore
308 EOF
309<
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200310vim.vars *python-vars*
311vim.vvars *python-vvars*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100312 Dictionary-like objects holding dictionaries with global (|g:|) and
313 vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200314 but faster.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200316vim.options *python-options*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100317 Object partly supporting mapping protocol (supports setting and
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200318 getting items) providing a read-write access to global options.
319 Note: unlike |:set| this provides access only to global options. You
320 cannot use this object to obtain or set local options' values or
321 access local-only options in any fashion. Raises KeyError if no global
322 option with such name exists (i.e. does not raise KeyError for
323 |global-local| options and global only options, but does for window-
324 and buffer-local ones). Use |python-buffer| objects to access to
325 buffer-local options and |python-window| objects to access to
326 window-local options.
327
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100328 Type of this object is available via "Options" attribute of vim
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200329 module.
330
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331Output from Python *python-output*
332 Vim displays all Python code output in the Vim message area. Normal
333 output appears as information messages, and error output appears as
334 error messages.
335
336 In implementation terms, this means that all output to sys.stdout
337 (including the output from print statements) appears as information
338 messages, and all output to sys.stderr (including error tracebacks)
339 appears as error messages.
340
341 *python-input*
342 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000343 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 fixed.
345
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200346 *python2-directory* *python3-directory* *pythonx-directory*
347Python 'runtimepath' handling *python-special-path*
348
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100349In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
350the list of paths found in 'runtimepath': with this directory in sys.path and
351vim.path_hooks in sys.path_hooks python will try to load module from
352{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
Christian Brabandtf0905a82024-05-17 18:30:01 +0200353each {rtp} found in 'runtimepath' (Note: find_module() has been removed from
354imp module around Python 3.12.0a7).
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200355
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200356Implementation is similar to the following, but written in C: >
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200357
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200358 from imp import find_module, load_module
359 import vim
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200360 import sys
361
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200362 class VimModuleLoader(object):
363 def __init__(self, module):
364 self.module = module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200365
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200366 def load_module(self, fullname, path=None):
367 return self.module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200368
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200369 def _find_module(fullname, oldtail, path):
370 idx = oldtail.find('.')
371 if idx > 0:
372 name = oldtail[:idx]
373 tail = oldtail[idx+1:]
374 fmr = find_module(name, path)
375 module = load_module(fullname[:-len(oldtail)] + name, *fmr)
376 return _find_module(fullname, tail, module.__path__)
377 else:
378 fmr = find_module(fullname, path)
379 return load_module(fullname, *fmr)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200380
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100381 # It uses vim module itself in place of VimPathFinder class: it does not
382 # matter for python which object has find_module function attached to as
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200383 # an attribute.
384 class VimPathFinder(object):
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200385 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200386 def find_module(cls, fullname, path=None):
387 try:
388 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
389 except ImportError:
390 return None
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200391
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200392 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200393 def load_module(cls, fullname, path=None):
394 return _find_module(fullname, fullname, path or vim._get_paths())
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200395
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200396 def hook(path):
397 if path == vim.VIM_SPECIAL_PATH:
398 return VimPathFinder
399 else:
400 raise ImportError
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200401
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200402 sys.path_hooks.append(hook)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200403
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200404vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100405 String constant used in conjunction with vim path hook. If path hook
406 installed by vim is requested to handle anything but path equal to
407 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200408 case it uses special loader.
409
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100410 Note: you must not use value of this constant directly, always use
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200411 vim.VIM_SPECIAL_PATH object.
412
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200413vim.find_module(...) *python-find_module*
414vim.path_hook(path) *python-path_hook*
Christian Brabandtf0905a82024-05-17 18:30:01 +0200415vim.find_spec(...) *python-find_spec*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100416 Methods or objects used to implement path loading as described above.
417 You should not be using any of these directly except for vim.path_hook
Christian Brabandtf0905a82024-05-17 18:30:01 +0200418 in case you need to do something with sys.meta_path, vim.find_spec()
419 is available starting with Python 3.7.
420 It is not guaranteed that any of the objects will exist in future vim
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200421 versions.
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200422
423vim._get_paths *python-_get_paths*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100424 Methods returning a list of paths which will be searched for by path
425 hook. You should not rely on this method being present in future
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200426 versions, but can use it for debugging.
427
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100428 It returns a list of {rtp}/python2 (or {rtp}/python3) and
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200429 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
430
Bram Moolenaar071d4272004-06-13 20:20:40 +0000431==============================================================================
4323. Buffer objects *python-buffer*
433
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000434Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 - via vim.current.buffer (|python-current|)
436 - from indexing vim.buffers (|python-buffers|)
437 - from the "buffer" attribute of a window (|python-window|)
438
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100439Buffer objects have two read-only attributes - name - the full file name for
440the buffer, and number - the buffer number. They also have three methods
441(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000443You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000445element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000447you would expect. Note that the result of indexing (slicing) a buffer is a
448string (list of strings). This has one unusual consequence - b[:] is different
449from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450"b = None" merely updates the variable b, with no effect on the buffer.
451
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000452Buffer indexes start at zero, as is normal in Python. This differs from vim
453line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000454with marks (see below) which use vim line numbers.
455
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200456The buffer object attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100457 b.vars Dictionary-like object used to access
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200458 |buffer-variable|s.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100459 b.options Mapping object (supports item getting, setting and
460 deleting) that provides access to buffer-local options
461 and buffer-local values of |global-local| options. Use
462 |python-window|.options if option is window-local,
463 this object will raise KeyError. If option is
464 |global-local| and local value is missing getting it
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200465 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200466 b.name String, RW. Contains buffer name (full path).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100467 Note: when assigning to b.name |BufFilePre| and
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200468 |BufFilePost| autocommands are launched.
469 b.number Buffer number. Can be used as |python-buffers| key.
470 Read-only.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100471 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200472 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200473
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474The buffer object methods are:
475 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200476 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 b.append(list) Append a list of lines to the buffer
478 Note that the option of supplying a list of strings to
479 the append method differs from the equivalent method
480 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200481 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 b.mark(name) Return a tuple (row,col) representing the position
483 of the named mark (can also get the []"<> marks)
484 b.range(s,e) Return a range object (see |python-range|) which
485 represents the part of the given buffer between line
486 numbers s and e |inclusive|.
487
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000488Note that when adding a line it must not contain a line break character '\n'.
489A trailing '\n' is allowed and ignored, so that you can do: >
490 :py b.append(f.readlines())
491
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200492Buffer object type is available using "Buffer" attribute of vim module.
493
Bram Moolenaar071d4272004-06-13 20:20:40 +0000494Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000495 :py print b.name # write the buffer file name
496 :py b[0] = "hello!!!" # replace the top line
497 :py b[:] = None # delete the whole buffer
498 :py del b[:] # delete the whole buffer
499 :py b[0:0] = [ "a line" ] # add a line at the top
500 :py del b[2] # delete a line (the third)
501 :py b.append("bottom") # add a line at the bottom
502 :py n = len(b) # number of lines
503 :py (row,col) = b.mark('a') # named mark
504 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200505 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200506 :py b.options["ff"] = "dos" # set fileformat
507 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508
509==============================================================================
5104. Range objects *python-range*
511
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000512Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513number of ways:
514 - via vim.current.range (|python-current|)
515 - from a buffer's range() method (|python-buffer|)
516
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000517A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518all operations are restricted to the lines within the range (this line range
519can, of course, change as a result of slice assignments, line deletions, or
520the range.append() method).
521
522The range object attributes are:
523 r.start Index of first line into the buffer
524 r.end Index of last line into the buffer
525
526The range object methods are:
527 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200528 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529 r.append(list) Append a list of lines to the range
530 Note that the option of supplying a list of strings to
531 the append method differs from the equivalent method
532 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200533 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200535Range object type is available using "Range" attribute of vim module.
536
Christian Brabandta56f02d2023-10-25 21:21:56 +0200537Example (assume r is the current range): >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538 # Send all lines in a range to the default printer
539 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
540
541==============================================================================
5425. Window objects *python-window*
543
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000544Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545 - via vim.current.window (|python-current|)
546 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200547 - from indexing "windows" attribute of a tab page (|python-tabpage|)
548 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000550You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551methods, and no sequence or other interface.
552
553Window attributes are:
554 buffer (read-only) The buffer displayed in this window
555 cursor (read-write) The current cursor position in the window
556 This is a tuple, (row,col).
557 height (read-write) The window height, in rows
558 width (read-write) The window width, in columns
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100559 vars (read-only) The window |w:| variables. Attribute is
560 unassignable, but you can change window
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200561 variables this way
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100562 options (read-only) The window-local options. Attribute is
563 unassignable, but you can change window
564 options this way. Provides access only to
565 window-local options, for buffer-local use
566 |python-buffer| and for global ones use
567 |python-options|. If option is |global-local|
568 and local value is missing getting it will
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200569 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200570 number (read-only) Window number. The first window has number 1.
571 This is zero in case it cannot be determined
572 (e.g. when the window object belongs to other
573 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200574 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200575 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200576 tabpage (read-only) Window tab page.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100577 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200578 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200579
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580The height attribute is writable only if the screen is split horizontally.
581The width attribute is writable only if the screen is split vertically.
582
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200583Window object type is available using "Window" attribute of vim module.
584
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005866. Tab page objects *python-tabpage*
587
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100588Tab page objects represent vim tab pages. You can obtain them in a number of
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200589ways:
590 - via vim.current.tabpage (|python-current|)
591 - from indexing vim.tabpages (|python-tabpages|)
592
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100593You can use this object to access tab page windows. They have no methods and
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200594no sequence or other interfaces.
595
596Tab page attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100597 number The tab page number like the one returned by
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200598 |tabpagenr()|.
599 windows Like |python-windows|, but for current tab page.
600 vars The tab page |t:| variables.
601 window Current tabpage window.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100602 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200603 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200604
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200605TabPage object type is available using "TabPage" attribute of vim module.
606
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200607==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02006087. vim.bindeval objects *python-bindeval-objects*
609
610vim.Dictionary object *python-Dictionary*
611 Dictionary-like object providing access to vim |Dictionary| type.
612 Attributes:
613 Attribute Description ~
614 locked One of *python-.locked*
615 Value Description ~
616 zero Variable is not locked
617 vim.VAR_LOCKED Variable is locked, but can be unlocked
618 vim.VAR_FIXED Variable is locked and can't be unlocked
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100619 Read-write. You can unlock locked variable by assigning
620 `True` or `False` to this attribute. No recursive locking
Bram Moolenaara9922d62013-05-30 13:01:18 +0200621 is supported.
622 scope One of
623 Value Description ~
624 zero Dictionary is not a scope one
625 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
626 vim.VAR_SCOPE Other scope dictionary,
627 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200628 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200629 Method Description ~
630 keys() Returns a list with dictionary keys.
631 values() Returns a list with dictionary values.
632 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200633 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200634 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200635 get(key[, default=None])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100636 Obtain key from dictionary, returning the default if it is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200637 not present.
638 pop(key[, default])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100639 Remove specified key from dictionary and return
640 corresponding value. If key is not found and default is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200641 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200642 popitem()
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100643 Remove random key from dictionary and return (key, value)
Bram Moolenaarde71b562013-06-02 17:41:54 +0200644 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200645 has_key(key)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100646 Check whether dictionary contains specified key, similar
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200647 to `key in dict`.
648
649 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100650 You can use `vim.Dictionary()` to create new vim
651 dictionaries. `d=vim.Dictionary(arg)` is the same as
652 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200653 constructs empty dictionary.
654
Bram Moolenaara9922d62013-05-30 13:01:18 +0200655 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200656 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200657 d['a'] = 'b' # Item assignment
658 print d['a'] # getting item
659 d.update({'c': 'd'}) # .update(dictionary)
660 d.update(e='f') # .update(**kwargs)
661 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
662 for key in d.keys(): # .keys()
663 for val in d.values(): # .values()
664 for key, val in d.items(): # .items()
665 print isinstance(d, vim.Dictionary) # True
666 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200667 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200668<
669 Note: when iterating over keys you should not modify dictionary.
670
671vim.List object *python-List*
672 Sequence-like object providing access to vim |List| type.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100673 Supports `.locked` attribute, see |python-.locked|. Also supports the
Bram Moolenaara9922d62013-05-30 13:01:18 +0200674 following methods:
675 Method Description ~
676 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200677
678 __new__(), __new__(iterable)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100679 You can use `vim.List()` to create new vim lists.
680 `l=vim.List(iterable)` is the same as
681 `l=vim.bindeval('[]');l.extend(iterable)`. Without
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200682 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200683 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200684 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200685 l.extend(['abc', 'def']) # .extend() method
686 print l[1:] # slicing
687 l[:0] = ['ghi', 'jkl'] # slice assignment
688 print l[0] # getting item
689 l[0] = 'mno' # assignment
690 for i in l: # iteration
691 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200692 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200693
Yegappan Lakshmanan038be272025-03-26 18:46:21 +0100694vim.Tuple object *python-Tuple*
695 Sequence-like object providing access to vim |Tuple| type.
696 Supports `.locked` attribute, see |python-.locked|. Also supports the
697 following methods:
698 Method Description ~
699 __new__(), __new__(iterable)
700 You can use `vim.Tuple()` to create new vim tuples.
701 Without arguments constructs empty list.
702 Examples: >
703 t = vim.Tuple("abc") # Constructor, result: ('a', 'b', 'c')
704 print t[1:] # slicing
705 print t[0] # getting item
706 for i in t: # iteration
707 print isinstance(t, vim.Tuple) # True
708 class Tuple(vim.Tuple): # Subclassing
709
Bram Moolenaara9922d62013-05-30 13:01:18 +0200710vim.Function object *python-Function*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100711 Function-like object, acting like vim |Funcref| object. Accepts special
712 keyword argument `self`, see |Dictionary-function|. You can also use
713 `vim.Function(name)` constructor, it is the same as
Bram Moolenaar8110a092016-04-14 15:56:09 +0200714 `vim.bindeval('function(%s)'%json.dumps(name))`.
715
716 Attributes (read-only):
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200717 Attribute Description ~
718 name Function name.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100719 args `None` or a |python-List| object with arguments. Note
720 that this is a copy of the arguments list, constructed
721 each time you request this attribute. Modifications made
722 to the list will be ignored (but not to the containers
723 inside argument list: this is like |copy()| and not
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200724 |deepcopy()|).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100725 self `None` or a |python-Dictionary| object with self
726 dictionary. Note that explicit `self` keyword used when
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200727 calling resulting object overrides this attribute.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100728 auto_rebind Boolean. True if partial created from this Python object
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100729 and stored in the Vim script dictionary should be
730 automatically rebound to the dictionary it is stored in
731 when this dictionary is indexed. Exposes Vim internal
732 difference between `dict.func` (auto_rebind=True) and
733 `function(dict.func,dict)` (auto_rebind=False). This
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200734 attribute makes no sense if `self` attribute is `None`.
Bram Moolenaar8110a092016-04-14 15:56:09 +0200735
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100736 Constructor additionally accepts `args`, `self` and `auto_rebind`
737 keywords. If `args` and/or `self` argument is given then it constructs
738 a partial, see |function()|. `auto_rebind` is only used when `self`
739 argument is given, otherwise it is assumed to be `True` regardless of
740 whether it was given or not. If `self` is given then it defaults to
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200741 `False`.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200742
Bram Moolenaara9922d62013-05-30 13:01:18 +0200743 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200744 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200745 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
746 vim.command('''
747 function DictFun() dict
748 return self
749 endfunction
750 ''')
751 f = vim.bindeval('function("DictFun")')
752 print f(self={}) # Like call('DictFun', [], {})
753 print isinstance(f, vim.Function) # True
754
Bram Moolenaar8110a092016-04-14 15:56:09 +0200755 p = vim.Function('DictFun', self={})
756 print f()
757 p = vim.Function('tr', args=['abc', 'a'])
758 print f('b')
759
Bram Moolenaara9922d62013-05-30 13:01:18 +0200760==============================================================================
7618. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200762
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100763To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100764functions to evaluate Python expressions and pass their values to Vim script.
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100765|pyxeval()| is also available.
Bram Moolenaar30b65812012-07-12 22:01:11 +0200766
Ben Jacksonea19e782024-11-06 21:50:05 +0100767You can inject local variables into the evaluation using the optional {locals}
768dict. This can be particularly useful in vim9script where vim.eval
769|python-eval| will not find locals in a def func.
770
Bram Moolenaarde323092017-11-09 19:56:08 +0100771The Python value "None" is converted to v:none.
772
Bram Moolenaar30b65812012-07-12 22:01:11 +0200773==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02007749. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000775
Bram Moolenaard94464e2015-11-02 15:28:18 +0100776On MS-Windows and Unix the Python library can be loaded dynamically. The
777|:version| output then includes |+python/dyn| or |+python3/dyn|.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000778
Bram Moolenaard94464e2015-11-02 15:28:18 +0100779This means that Vim will search for the Python DLL or shared library file only
780when needed. When you don't use the Python interface you don't need it, thus
781you can use Vim without this file.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000782
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100783
784MS-Windows ~
785
786To use the Python interface the Python DLL must be in your search path. In a
Ken Takataae3cfa42023-10-14 11:49:09 +0200787console window type "path" to see what directories are used. If the DLL is
788not found in your search path, Vim will check the registry to find the path
789where Python is installed. The 'pythondll' or 'pythonthreedll' option can be
790also used to specify the Python DLL.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000791
Bram Moolenaar3df01732017-02-17 22:47:16 +0100792The name of the DLL should match the Python version Vim was compiled with.
793Currently the name for Python 2 is "python27.dll", that is for Python 2.7.
Bram Moolenaar59eb0162017-12-10 18:17:44 +0100794That is the default value for 'pythondll'. For Python 3 it is python36.dll
795(Python 3.6). To know for sure edit "gvim.exe" and search for
Bram Moolenaar3df01732017-02-17 22:47:16 +0100796"python\d*.dll\c".
Bram Moolenaara5792f52005-11-23 21:25:05 +0000797
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100798
799Unix ~
800
801The 'pythondll' or 'pythonthreedll' option can be used to specify the Python
802shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file
803what were specified at compile time. The version of the shared library must
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200804match the Python 2.x or Python 3 version (|v:python3_version|) Vim was
805compiled with unless using |python3-stable-abi|.
806
807
808Stable ABI and mixing Python versions ~
809 *python-stable* *python-stable-abi* *python3-stable-abi*
810If Vim was not compiled with Stable ABI (only available for Python 3), the
811version of the Python shared library must match the version that Vim was
812compiled with. Otherwise, mixing versions could result in unexpected crashes
813and failures. With Stable ABI, this restriction is relaxed, and any Python 3
814library with version of at least |v:python3_version| will work. See
815|has-python| for how to check if Stable ABI is supported, or see if version
816output includes |+python3/dyn-stable|.
Ken Takataae3cfa42023-10-14 11:49:09 +0200817On MS-Windows, 'pythonthreedll' will be set to "python3.dll". When searching
818the DLL from the registry, Vim will search the latest version of Python.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100819
Bram Moolenaara5792f52005-11-23 21:25:05 +0000820==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020082110. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200822
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200823 *:py3* *:python3*
Bram Moolenaar91359012019-11-30 17:57:03 +0100824:[range]py3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200825:[range]py3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100826{script}
827{endmarker}
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200828
Bram Moolenaar91359012019-11-30 17:57:03 +0100829:[range]python3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200830:[range]python3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100831{script}
832{endmarker}
833 The `:py3` and `:python3` commands work similar to `:python`. A
834 simple check if the `:py3` command is working: >
835 :py3 print("Hello")
836<
837 To see what version of Python you have: >
838 :py3 import sys
839 :py3 print(sys.version)
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200840< *:py3file*
Bram Moolenaar91359012019-11-30 17:57:03 +0100841:[range]py3f[ile] {file}
842 The `:py3file` command works similar to `:pyfile`.
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +0200843 *:py3do*
Bram Moolenaar91359012019-11-30 17:57:03 +0100844:[range]py3do {body}
845 The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200846
Bram Moolenaar30b65812012-07-12 22:01:11 +0200847
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200848Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02008491. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02008502. Python 2 support only (+python or +python/dyn, -python3)
8513. Python 3 support only (-python, +python3 or +python3/dyn)
8524. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200853
Bram Moolenaar9ba7e172013-07-17 22:37:26 +0200854Some more details on the special case 4: *python-2-and-3*
Bram Moolenaarede981a2010-08-11 23:37:32 +0200855
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200856When Python 2 and Python 3 are both supported they must be loaded dynamically.
857
858When doing this on Linux/Unix systems and importing global symbols, this leads
859to a crash when the second Python version is used. So either global symbols
860are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200861loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200862symbols to be provided by Vim.
863 *E836* *E837*
864Vim's configuration script makes a guess for all libraries based on one
865standard Python library (termios). If importing this library succeeds for
866both Python versions, then both will be made available in Vim at the same
867time. If not, only the version first used in a session will be enabled.
868When trying to use the other one you will get the E836 or E837 error message.
869
870Here Vim's behavior depends on the system in which it was configured. In a
871system where both versions of Python were configured with --enable-shared,
872both versions of Python will be activated at the same time. There will still
873be problems with other third party libraries that were not linked to
874libPython.
875
876To work around such problems there are these options:
8771. The problematic library is recompiled to link to the according
878 libpython.so.
8792. Vim is recompiled for only one Python version.
8803. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
881 may crash Vim though.
882
Bram Moolenaar41009372013-07-01 22:03:04 +0200883 *E880*
884Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
885 :py vim.command("qall!")
886<
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000887 *E1266*
Bram Moolenaar8a3b8052022-06-26 12:21:15 +0100888This error can occur when Python 3 cannot load the required modules. This
889means that your Python 3 is not correctly installed or there are some mistakes
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000890in your settings. Please check the following items:
Bram Moolenaar8a3b8052022-06-26 12:21:15 +01008911. Make sure that Python 3 is correctly installed. Also check the version of
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000892 python.
8932. Check the 'pythonthreedll' option.
8943. Check the 'pythonthreehome' option.
8954. Check the PATH environment variable if you don't set 'pythonthreedll'.
896 On MS-Windows, you can use where.exe to check which dll will be loaded.
897 E.g. >
898 where.exe python310.dll
8995. Check the PYTHONPATH and PYTHONHOME environment variables.
Bram Moolenaar41009372013-07-01 22:03:04 +0200900
Bram Moolenaar446beb42011-05-10 17:18:44 +0200901 *has-python*
902You can test what Python version is available with: >
903 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200904 echo 'there is Python 2.x'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100905 endif
Bram Moolenaar938ae282023-02-20 20:44:55 +0000906 if has('python3')
Bram Moolenaar446beb42011-05-10 17:18:44 +0200907 echo 'there is Python 3.x'
908 endif
909
910Note however, that when Python 2 and 3 are both available and loaded
911dynamically, these has() calls will try to load them. If only one can be
912loaded at a time, just checking if Python 2 or 3 are available will prevent
913the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200914
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100915To avoid loading the dynamic library, only check if Vim was compiled with
916python support: >
917 if has('python_compiled')
918 echo 'compiled with Python 2.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100919 if has('python_dynamic')
920 echo 'Python 2.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100921 endif
922 endif
Bram Moolenaar938ae282023-02-20 20:44:55 +0000923 if has('python3_compiled')
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100924 echo 'compiled with Python 3.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100925 if has('python3_dynamic')
926 echo 'Python 3.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100927 endif
928 endif
929
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200930When loading the library dynamically, Vim can be compiled to support Python 3
931Stable ABI (|python3-stable-abi|) which allows you to load a different version
932of Python 3 library than the one Vim was compiled with. To check it: >
933 if has('python3_dynamic')
934 if has('python3_stable')
935 echo 'support Python 3 Stable ABI.'
936 else
937 echo 'does not support Python 3 Stable ABI.'
938 echo 'only use Python 3 version ' .. v:python3_version
939 endif
940 endif
941
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100942This also tells you whether Python is dynamically loaded, which will fail if
943the runtime library cannot be found.
944
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200945==============================================================================
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +010094611. Python X *python_x* *pythonx*
947
Bram Moolenaar8a3b8052022-06-26 12:21:15 +0100948Because most python code can be written so that it works with Python 2.6+ and
949Python 3 the pyx* functions and commands have been written. They work exactly
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100950the same as the Python 2 and 3 variants, but select the Python version using
951the 'pyxversion' setting.
952
953You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3
954for Python commands. If you change this setting at runtime you may risk that
955state of plugins (such as initialization) may be lost.
956
957If you want to use a module, you can put it in the {rtp}/pythonx directory.
958See |pythonx-directory|.
959
960 *:pyx* *:pythonx*
961The `:pyx` and `:pythonx` commands work similar to `:python`. A simple check
962if the `:pyx` command is working: >
963 :pyx print("Hello")
964
965To see what version of Python is being used: >
966 :pyx import sys
967 :pyx print(sys.version)
968<
969 *:pyxfile* *python_x-special-comments*
970The `:pyxfile` command works similar to `:pyfile`. However you can add one of
971these comments to force Vim using `:pyfile` or `:py3file`: >
972 #!/any string/python2 " Shebang. Must be the first line of the file.
973 #!/any string/python3 " Shebang. Must be the first line of the file.
974 # requires python 2.x " Maximum lines depend on 'modelines'.
975 # requires python 3.x " Maximum lines depend on 'modelines'.
976Unlike normal modelines, the bottom of the file is not checked.
977If none of them are found, the 'pyxversion' setting is used.
978 *W20* *W21*
979If Vim does not support the selected Python version a silent message will be
980printed. Use `:messages` to read them.
981
982 *:pyxdo*
983The `:pyxdo` command works similar to `:pydo`.
984
985 *has-pythonx*
986You can test if pyx* commands are available with: >
987 if has('pythonx')
Bram Moolenaarc51cf032022-02-26 12:25:45 +0000988 echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100989 endif
990
991When compiled with only one of |+python| or |+python3|, the has() returns 1.
992When compiled with both |+python| and |+python3|, the test depends on the
993'pyxversion' setting. If 'pyxversion' is 0, it tests Python 3 first, and if
994it is not available then Python 2. If 'pyxversion' is 2 or 3, it tests only
995Python 2 or 3 respectively.
996
Bram Moolenaar214641f2017-03-05 17:04:09 +0100997Note that for `has('pythonx')` to work it may try to dynamically load Python 3
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100998or 2. This may have side effects, especially when Vim can only load one of
999the two.
1000
1001If a user prefers Python 2 and want to fallback to Python 3, he needs to set
1002'pyxversion' explicitly in his |.vimrc|. E.g.: >
1003 if has('python')
1004 set pyx=2
1005 elseif has('python3')
1006 set pyx=3
1007 endif
1008
1009==============================================================================
Bram Moolenaar036986f2017-03-16 17:41:02 +0100101012. Building with Python support *python-building*
1011
1012A few hints for building with Python 2 or 3 support.
1013
1014UNIX
1015
1016See src/Makefile for how to enable including the Python interface.
1017
1018On Ubuntu you will want to install these packages for Python 2:
1019 python
1020 python-dev
1021For Python 3:
1022 python3
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +02001023 python3-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +01001024For Python 3.6:
1025 python3.6
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +02001026 python3.6-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +01001027
1028If you have more than one version of Python 3, you need to link python3 to the
1029one you prefer, before running configure.
1030
1031==============================================================================
Bram Moolenaar91f84f62018-07-29 15:07:52 +02001032 vim:tw=78:ts=8:noet:ft=help:norl: