blob: 480ff02c2765a2057b2ef6289575f3e1c3cd7467 [file] [log] [blame]
h-east624bb832024-11-09 18:37:32 +01001*if_pyth.txt* For Vim version 9.1. Last change: 2024 Nov 09
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
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000187 - a dictionary if the Vim expression evaluates to a Vim dictionary
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000188 Dictionaries and lists are recursively expanded.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189 Examples: >
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200190 :" value of the 'textwidth' option
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000191 :py text_width = vim.eval("&tw")
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200192 :
193 :" contents of the 'a' register
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100194 :py a_reg = vim.eval("@a")
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200195 :
196 :" Result is a string! Use string.atoi() to convert to a number.
197 :py str = vim.eval("12+12")
198 :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000199 :py tagList = vim.eval('taglist("eval_expr")')
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000200< The latter will return a python list of python dicts, for instance:
Bram Moolenaar214641f2017-03-05 17:04:09 +0100201 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name': ~
202 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}] ~
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000203
h-east624bb832024-11-09 18:37:32 +0100204 NOTE: In Vim9 script, local variables in def functions are not visible
205 to python evaluations. To pass local variables to python evaluations,
Ben Jacksonea19e782024-11-06 21:50:05 +0100206 use the {locals} dict when calling |py3eval()| and friends.
207
Bram Moolenaar30b65812012-07-12 22:01:11 +0200208vim.bindeval(str) *python-bindeval*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100209 Like |python-eval|, but returns special objects described in
210 |python-bindeval-objects|. These python objects let you modify (|List|
Bram Moolenaarde71b562013-06-02 17:41:54 +0200211 or |Dictionary|) or call (|Funcref|) vim objects.
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000212
Bram Moolenaarbc411962013-06-02 17:46:40 +0200213vim.strwidth(str) *python-strwidth*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100214 Like |strwidth()|: returns number of display cells str occupies, tab
Bram Moolenaarbc411962013-06-02 17:46:40 +0200215 is counted as one cell.
216
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200217vim.foreach_rtp(callable) *python-foreach_rtp*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100218 Call the given callable for each path in 'runtimepath' until either
219 callable returns something but None, the exception is raised or there
220 are no longer paths. If stopped in case callable returned non-None,
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200221 vim.foreach_rtp function returns the value returned by callable.
222
Bram Moolenaarf4258302013-06-02 18:20:17 +0200223vim.chdir(*args, **kwargs) *python-chdir*
224vim.fchdir(*args, **kwargs) *python-fchdir*
225 Run os.chdir or os.fchdir, then all appropriate vim stuff.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100226 Note: you should not use these functions directly, use os.chdir and
227 os.fchdir instead. Behavior of vim.fchdir is undefined in case
Bram Moolenaarf4258302013-06-02 18:20:17 +0200228 os.fchdir does not exist.
229
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230Error object of the "vim" module
231
232vim.error *python-error*
233 Upon encountering a Vim error, Python raises an exception of type
234 vim.error.
235 Example: >
236 try:
237 vim.command("put a")
238 except vim.error:
239 # nothing in register a
240
241Constants of the "vim" module
242
243 Note that these are not actually constants - you could reassign them.
244 But this is silly, as you would then lose access to the vim objects
245 to which the variables referred.
246
247vim.buffers *python-buffers*
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200248 A mapping object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000250 :py b = vim.buffers[i] # Indexing (read-only)
251 :py b in vim.buffers # Membership test
252 :py n = len(vim.buffers) # Number of elements
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200253 :py for b in vim.buffers: # Iterating over buffer list
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254<
255vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000256 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000258 :py w = vim.windows[i] # Indexing (read-only)
259 :py w in vim.windows # Membership test
260 :py n = len(vim.windows) # Number of elements
261 :py for w in vim.windows: # Sequential access
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100262< Note: vim.windows object always accesses current tab page.
263 |python-tabpage|.windows objects are bound to parent |python-tabpage|
264 object and always use windows from that tab page (or throw vim.error
265 in case tab page was deleted). You can keep a reference to both
266 without keeping a reference to vim module object or |python-tabpage|,
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200267 they will not lose their properties in this case.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200268
269vim.tabpages *python-tabpages*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100270 A sequence object providing access to the list of vim tab pages. The
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200271 object supports the following operations: >
272 :py t = vim.tabpages[i] # Indexing (read-only)
273 :py t in vim.tabpages # Membership test
274 :py n = len(vim.tabpages) # Number of elements
275 :py for t in vim.tabpages: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276<
277vim.current *python-current*
278 An object providing access (via specific attributes) to various
279 "current" objects available in vim:
280 vim.current.line The current line (RW) String
Bram Moolenaare7614592013-05-15 15:51:08 +0200281 vim.current.buffer The current buffer (RW) Buffer
282 vim.current.window The current window (RW) Window
283 vim.current.tabpage The current tab page (RW) TabPage
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284 vim.current.range The current line range (RO) Range
285
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000286 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000288 "current range". A range is a bit like a buffer, but with all access
289 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100291 Note: When assigning to vim.current.{buffer,window,tabpage} it expects
292 valid |python-buffer|, |python-window| or |python-tabpage| objects
293 respectively. Assigning triggers normal (with |autocommand|s)
294 switching to given buffer, window or tab page. It is the only way to
295 switch UI objects in python: you can't assign to
296 |python-tabpage|.window attribute. To switch without triggering
Bram Moolenaare7614592013-05-15 15:51:08 +0200297 autocommands use >
298 py << EOF
299 saved_eventignore = vim.options['eventignore']
300 vim.options['eventignore'] = 'all'
301 try:
302 vim.current.buffer = vim.buffers[2] # Switch to buffer 2
303 finally:
304 vim.options['eventignore'] = saved_eventignore
305 EOF
306<
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200307vim.vars *python-vars*
308vim.vvars *python-vvars*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100309 Dictionary-like objects holding dictionaries with global (|g:|) and
310 vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200311 but faster.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000312
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200313vim.options *python-options*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100314 Object partly supporting mapping protocol (supports setting and
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200315 getting items) providing a read-write access to global options.
316 Note: unlike |:set| this provides access only to global options. You
317 cannot use this object to obtain or set local options' values or
318 access local-only options in any fashion. Raises KeyError if no global
319 option with such name exists (i.e. does not raise KeyError for
320 |global-local| options and global only options, but does for window-
321 and buffer-local ones). Use |python-buffer| objects to access to
322 buffer-local options and |python-window| objects to access to
323 window-local options.
324
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100325 Type of this object is available via "Options" attribute of vim
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200326 module.
327
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328Output from Python *python-output*
329 Vim displays all Python code output in the Vim message area. Normal
330 output appears as information messages, and error output appears as
331 error messages.
332
333 In implementation terms, this means that all output to sys.stdout
334 (including the output from print statements) appears as information
335 messages, and all output to sys.stderr (including error tracebacks)
336 appears as error messages.
337
338 *python-input*
339 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000340 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000341 fixed.
342
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200343 *python2-directory* *python3-directory* *pythonx-directory*
344Python 'runtimepath' handling *python-special-path*
345
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100346In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
347the list of paths found in 'runtimepath': with this directory in sys.path and
348vim.path_hooks in sys.path_hooks python will try to load module from
349{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
Christian Brabandtf0905a82024-05-17 18:30:01 +0200350each {rtp} found in 'runtimepath' (Note: find_module() has been removed from
351imp module around Python 3.12.0a7).
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200352
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200353Implementation is similar to the following, but written in C: >
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200354
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200355 from imp import find_module, load_module
356 import vim
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200357 import sys
358
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200359 class VimModuleLoader(object):
360 def __init__(self, module):
361 self.module = module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200362
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200363 def load_module(self, fullname, path=None):
364 return self.module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200365
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200366 def _find_module(fullname, oldtail, path):
367 idx = oldtail.find('.')
368 if idx > 0:
369 name = oldtail[:idx]
370 tail = oldtail[idx+1:]
371 fmr = find_module(name, path)
372 module = load_module(fullname[:-len(oldtail)] + name, *fmr)
373 return _find_module(fullname, tail, module.__path__)
374 else:
375 fmr = find_module(fullname, path)
376 return load_module(fullname, *fmr)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200377
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100378 # It uses vim module itself in place of VimPathFinder class: it does not
379 # matter for python which object has find_module function attached to as
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200380 # an attribute.
381 class VimPathFinder(object):
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200382 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200383 def find_module(cls, fullname, path=None):
384 try:
385 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
386 except ImportError:
387 return None
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200388
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200389 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200390 def load_module(cls, fullname, path=None):
391 return _find_module(fullname, fullname, path or vim._get_paths())
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200392
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200393 def hook(path):
394 if path == vim.VIM_SPECIAL_PATH:
395 return VimPathFinder
396 else:
397 raise ImportError
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200398
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200399 sys.path_hooks.append(hook)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200400
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200401vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100402 String constant used in conjunction with vim path hook. If path hook
403 installed by vim is requested to handle anything but path equal to
404 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200405 case it uses special loader.
406
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100407 Note: you must not use value of this constant directly, always use
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200408 vim.VIM_SPECIAL_PATH object.
409
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200410vim.find_module(...) *python-find_module*
411vim.path_hook(path) *python-path_hook*
Christian Brabandtf0905a82024-05-17 18:30:01 +0200412vim.find_spec(...) *python-find_spec*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100413 Methods or objects used to implement path loading as described above.
414 You should not be using any of these directly except for vim.path_hook
Christian Brabandtf0905a82024-05-17 18:30:01 +0200415 in case you need to do something with sys.meta_path, vim.find_spec()
416 is available starting with Python 3.7.
417 It is not guaranteed that any of the objects will exist in future vim
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200418 versions.
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200419
420vim._get_paths *python-_get_paths*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100421 Methods returning a list of paths which will be searched for by path
422 hook. You should not rely on this method being present in future
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200423 versions, but can use it for debugging.
424
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100425 It returns a list of {rtp}/python2 (or {rtp}/python3) and
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200426 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
427
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428==============================================================================
4293. Buffer objects *python-buffer*
430
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000431Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 - via vim.current.buffer (|python-current|)
433 - from indexing vim.buffers (|python-buffers|)
434 - from the "buffer" attribute of a window (|python-window|)
435
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100436Buffer objects have two read-only attributes - name - the full file name for
437the buffer, and number - the buffer number. They also have three methods
438(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000440You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000442element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000444you would expect. Note that the result of indexing (slicing) a buffer is a
445string (list of strings). This has one unusual consequence - b[:] is different
446from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447"b = None" merely updates the variable b, with no effect on the buffer.
448
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000449Buffer indexes start at zero, as is normal in Python. This differs from vim
450line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451with marks (see below) which use vim line numbers.
452
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200453The buffer object attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100454 b.vars Dictionary-like object used to access
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200455 |buffer-variable|s.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100456 b.options Mapping object (supports item getting, setting and
457 deleting) that provides access to buffer-local options
458 and buffer-local values of |global-local| options. Use
459 |python-window|.options if option is window-local,
460 this object will raise KeyError. If option is
461 |global-local| and local value is missing getting it
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200462 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200463 b.name String, RW. Contains buffer name (full path).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100464 Note: when assigning to b.name |BufFilePre| and
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200465 |BufFilePost| autocommands are launched.
466 b.number Buffer number. Can be used as |python-buffers| key.
467 Read-only.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100468 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200469 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200470
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471The buffer object methods are:
472 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200473 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 b.append(list) Append a list of lines to the buffer
475 Note that the option of supplying a list of strings to
476 the append method differs from the equivalent method
477 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200478 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 b.mark(name) Return a tuple (row,col) representing the position
480 of the named mark (can also get the []"<> marks)
481 b.range(s,e) Return a range object (see |python-range|) which
482 represents the part of the given buffer between line
483 numbers s and e |inclusive|.
484
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000485Note that when adding a line it must not contain a line break character '\n'.
486A trailing '\n' is allowed and ignored, so that you can do: >
487 :py b.append(f.readlines())
488
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200489Buffer object type is available using "Buffer" attribute of vim module.
490
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000492 :py print b.name # write the buffer file name
493 :py b[0] = "hello!!!" # replace the top line
494 :py b[:] = None # delete the whole buffer
495 :py del b[:] # delete the whole buffer
496 :py b[0:0] = [ "a line" ] # add a line at the top
497 :py del b[2] # delete a line (the third)
498 :py b.append("bottom") # add a line at the bottom
499 :py n = len(b) # number of lines
500 :py (row,col) = b.mark('a') # named mark
501 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200502 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200503 :py b.options["ff"] = "dos" # set fileformat
504 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505
506==============================================================================
5074. Range objects *python-range*
508
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000509Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510number of ways:
511 - via vim.current.range (|python-current|)
512 - from a buffer's range() method (|python-buffer|)
513
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000514A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515all operations are restricted to the lines within the range (this line range
516can, of course, change as a result of slice assignments, line deletions, or
517the range.append() method).
518
519The range object attributes are:
520 r.start Index of first line into the buffer
521 r.end Index of last line into the buffer
522
523The range object methods are:
524 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200525 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526 r.append(list) Append a list of lines to the range
527 Note that the option of supplying a list of strings to
528 the append method differs from the equivalent method
529 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200530 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200532Range object type is available using "Range" attribute of vim module.
533
Christian Brabandta56f02d2023-10-25 21:21:56 +0200534Example (assume r is the current range): >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 # Send all lines in a range to the default printer
536 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
537
538==============================================================================
5395. Window objects *python-window*
540
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000541Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542 - via vim.current.window (|python-current|)
543 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200544 - from indexing "windows" attribute of a tab page (|python-tabpage|)
545 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000547You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000548methods, and no sequence or other interface.
549
550Window attributes are:
551 buffer (read-only) The buffer displayed in this window
552 cursor (read-write) The current cursor position in the window
553 This is a tuple, (row,col).
554 height (read-write) The window height, in rows
555 width (read-write) The window width, in columns
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100556 vars (read-only) The window |w:| variables. Attribute is
557 unassignable, but you can change window
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200558 variables this way
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100559 options (read-only) The window-local options. Attribute is
560 unassignable, but you can change window
561 options this way. Provides access only to
562 window-local options, for buffer-local use
563 |python-buffer| and for global ones use
564 |python-options|. If option is |global-local|
565 and local value is missing getting it will
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200566 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200567 number (read-only) Window number. The first window has number 1.
568 This is zero in case it cannot be determined
569 (e.g. when the window object belongs to other
570 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200571 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200572 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200573 tabpage (read-only) Window tab page.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100574 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200575 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200576
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577The height attribute is writable only if the screen is split horizontally.
578The width attribute is writable only if the screen is split vertically.
579
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200580Window object type is available using "Window" attribute of vim module.
581
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005836. Tab page objects *python-tabpage*
584
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100585Tab page objects represent vim tab pages. You can obtain them in a number of
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200586ways:
587 - via vim.current.tabpage (|python-current|)
588 - from indexing vim.tabpages (|python-tabpages|)
589
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100590You can use this object to access tab page windows. They have no methods and
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200591no sequence or other interfaces.
592
593Tab page attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100594 number The tab page number like the one returned by
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200595 |tabpagenr()|.
596 windows Like |python-windows|, but for current tab page.
597 vars The tab page |t:| variables.
598 window Current tabpage window.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100599 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200600 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200601
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200602TabPage object type is available using "TabPage" attribute of vim module.
603
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200604==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02006057. vim.bindeval objects *python-bindeval-objects*
606
607vim.Dictionary object *python-Dictionary*
608 Dictionary-like object providing access to vim |Dictionary| type.
609 Attributes:
610 Attribute Description ~
611 locked One of *python-.locked*
612 Value Description ~
613 zero Variable is not locked
614 vim.VAR_LOCKED Variable is locked, but can be unlocked
615 vim.VAR_FIXED Variable is locked and can't be unlocked
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100616 Read-write. You can unlock locked variable by assigning
617 `True` or `False` to this attribute. No recursive locking
Bram Moolenaara9922d62013-05-30 13:01:18 +0200618 is supported.
619 scope One of
620 Value Description ~
621 zero Dictionary is not a scope one
622 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
623 vim.VAR_SCOPE Other scope dictionary,
624 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200625 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200626 Method Description ~
627 keys() Returns a list with dictionary keys.
628 values() Returns a list with dictionary values.
629 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200630 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200631 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200632 get(key[, default=None])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100633 Obtain key from dictionary, returning the default if it is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200634 not present.
635 pop(key[, default])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100636 Remove specified key from dictionary and return
637 corresponding value. If key is not found and default is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200638 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200639 popitem()
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100640 Remove random key from dictionary and return (key, value)
Bram Moolenaarde71b562013-06-02 17:41:54 +0200641 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200642 has_key(key)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100643 Check whether dictionary contains specified key, similar
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200644 to `key in dict`.
645
646 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100647 You can use `vim.Dictionary()` to create new vim
648 dictionaries. `d=vim.Dictionary(arg)` is the same as
649 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200650 constructs empty dictionary.
651
Bram Moolenaara9922d62013-05-30 13:01:18 +0200652 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200653 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200654 d['a'] = 'b' # Item assignment
655 print d['a'] # getting item
656 d.update({'c': 'd'}) # .update(dictionary)
657 d.update(e='f') # .update(**kwargs)
658 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
659 for key in d.keys(): # .keys()
660 for val in d.values(): # .values()
661 for key, val in d.items(): # .items()
662 print isinstance(d, vim.Dictionary) # True
663 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200664 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200665<
666 Note: when iterating over keys you should not modify dictionary.
667
668vim.List object *python-List*
669 Sequence-like object providing access to vim |List| type.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100670 Supports `.locked` attribute, see |python-.locked|. Also supports the
Bram Moolenaara9922d62013-05-30 13:01:18 +0200671 following methods:
672 Method Description ~
673 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200674
675 __new__(), __new__(iterable)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100676 You can use `vim.List()` to create new vim lists.
677 `l=vim.List(iterable)` is the same as
678 `l=vim.bindeval('[]');l.extend(iterable)`. Without
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200679 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200680 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200681 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200682 l.extend(['abc', 'def']) # .extend() method
683 print l[1:] # slicing
684 l[:0] = ['ghi', 'jkl'] # slice assignment
685 print l[0] # getting item
686 l[0] = 'mno' # assignment
687 for i in l: # iteration
688 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200689 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200690
691vim.Function object *python-Function*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100692 Function-like object, acting like vim |Funcref| object. Accepts special
693 keyword argument `self`, see |Dictionary-function|. You can also use
694 `vim.Function(name)` constructor, it is the same as
Bram Moolenaar8110a092016-04-14 15:56:09 +0200695 `vim.bindeval('function(%s)'%json.dumps(name))`.
696
697 Attributes (read-only):
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200698 Attribute Description ~
699 name Function name.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100700 args `None` or a |python-List| object with arguments. Note
701 that this is a copy of the arguments list, constructed
702 each time you request this attribute. Modifications made
703 to the list will be ignored (but not to the containers
704 inside argument list: this is like |copy()| and not
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200705 |deepcopy()|).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100706 self `None` or a |python-Dictionary| object with self
707 dictionary. Note that explicit `self` keyword used when
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200708 calling resulting object overrides this attribute.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100709 auto_rebind Boolean. True if partial created from this Python object
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100710 and stored in the Vim script dictionary should be
711 automatically rebound to the dictionary it is stored in
712 when this dictionary is indexed. Exposes Vim internal
713 difference between `dict.func` (auto_rebind=True) and
714 `function(dict.func,dict)` (auto_rebind=False). This
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200715 attribute makes no sense if `self` attribute is `None`.
Bram Moolenaar8110a092016-04-14 15:56:09 +0200716
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100717 Constructor additionally accepts `args`, `self` and `auto_rebind`
718 keywords. If `args` and/or `self` argument is given then it constructs
719 a partial, see |function()|. `auto_rebind` is only used when `self`
720 argument is given, otherwise it is assumed to be `True` regardless of
721 whether it was given or not. If `self` is given then it defaults to
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200722 `False`.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200723
Bram Moolenaara9922d62013-05-30 13:01:18 +0200724 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200725 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200726 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
727 vim.command('''
728 function DictFun() dict
729 return self
730 endfunction
731 ''')
732 f = vim.bindeval('function("DictFun")')
733 print f(self={}) # Like call('DictFun', [], {})
734 print isinstance(f, vim.Function) # True
735
Bram Moolenaar8110a092016-04-14 15:56:09 +0200736 p = vim.Function('DictFun', self={})
737 print f()
738 p = vim.Function('tr', args=['abc', 'a'])
739 print f('b')
740
Bram Moolenaara9922d62013-05-30 13:01:18 +0200741==============================================================================
7428. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200743
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100744To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100745functions to evaluate Python expressions and pass their values to Vim script.
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100746|pyxeval()| is also available.
Bram Moolenaar30b65812012-07-12 22:01:11 +0200747
Ben Jacksonea19e782024-11-06 21:50:05 +0100748You can inject local variables into the evaluation using the optional {locals}
749dict. This can be particularly useful in vim9script where vim.eval
750|python-eval| will not find locals in a def func.
751
Bram Moolenaarde323092017-11-09 19:56:08 +0100752The Python value "None" is converted to v:none.
753
Bram Moolenaar30b65812012-07-12 22:01:11 +0200754==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02007559. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000756
Bram Moolenaard94464e2015-11-02 15:28:18 +0100757On MS-Windows and Unix the Python library can be loaded dynamically. The
758|:version| output then includes |+python/dyn| or |+python3/dyn|.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000759
Bram Moolenaard94464e2015-11-02 15:28:18 +0100760This means that Vim will search for the Python DLL or shared library file only
761when needed. When you don't use the Python interface you don't need it, thus
762you can use Vim without this file.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000763
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100764
765MS-Windows ~
766
767To use the Python interface the Python DLL must be in your search path. In a
Ken Takataae3cfa42023-10-14 11:49:09 +0200768console window type "path" to see what directories are used. If the DLL is
769not found in your search path, Vim will check the registry to find the path
770where Python is installed. The 'pythondll' or 'pythonthreedll' option can be
771also used to specify the Python DLL.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000772
Bram Moolenaar3df01732017-02-17 22:47:16 +0100773The name of the DLL should match the Python version Vim was compiled with.
774Currently the name for Python 2 is "python27.dll", that is for Python 2.7.
Bram Moolenaar59eb0162017-12-10 18:17:44 +0100775That is the default value for 'pythondll'. For Python 3 it is python36.dll
776(Python 3.6). To know for sure edit "gvim.exe" and search for
Bram Moolenaar3df01732017-02-17 22:47:16 +0100777"python\d*.dll\c".
Bram Moolenaara5792f52005-11-23 21:25:05 +0000778
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100779
780Unix ~
781
782The 'pythondll' or 'pythonthreedll' option can be used to specify the Python
783shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file
784what were specified at compile time. The version of the shared library must
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200785match the Python 2.x or Python 3 version (|v:python3_version|) Vim was
786compiled with unless using |python3-stable-abi|.
787
788
789Stable ABI and mixing Python versions ~
790 *python-stable* *python-stable-abi* *python3-stable-abi*
791If Vim was not compiled with Stable ABI (only available for Python 3), the
792version of the Python shared library must match the version that Vim was
793compiled with. Otherwise, mixing versions could result in unexpected crashes
794and failures. With Stable ABI, this restriction is relaxed, and any Python 3
795library with version of at least |v:python3_version| will work. See
796|has-python| for how to check if Stable ABI is supported, or see if version
797output includes |+python3/dyn-stable|.
Ken Takataae3cfa42023-10-14 11:49:09 +0200798On MS-Windows, 'pythonthreedll' will be set to "python3.dll". When searching
799the DLL from the registry, Vim will search the latest version of Python.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100800
Bram Moolenaara5792f52005-11-23 21:25:05 +0000801==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020080210. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200803
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200804 *:py3* *:python3*
Bram Moolenaar91359012019-11-30 17:57:03 +0100805:[range]py3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200806:[range]py3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100807{script}
808{endmarker}
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200809
Bram Moolenaar91359012019-11-30 17:57:03 +0100810:[range]python3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200811:[range]python3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100812{script}
813{endmarker}
814 The `:py3` and `:python3` commands work similar to `:python`. A
815 simple check if the `:py3` command is working: >
816 :py3 print("Hello")
817<
818 To see what version of Python you have: >
819 :py3 import sys
820 :py3 print(sys.version)
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200821< *:py3file*
Bram Moolenaar91359012019-11-30 17:57:03 +0100822:[range]py3f[ile] {file}
823 The `:py3file` command works similar to `:pyfile`.
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +0200824 *:py3do*
Bram Moolenaar91359012019-11-30 17:57:03 +0100825:[range]py3do {body}
826 The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200827
Bram Moolenaar30b65812012-07-12 22:01:11 +0200828
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200829Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02008301. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02008312. Python 2 support only (+python or +python/dyn, -python3)
8323. Python 3 support only (-python, +python3 or +python3/dyn)
8334. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200834
Bram Moolenaar9ba7e172013-07-17 22:37:26 +0200835Some more details on the special case 4: *python-2-and-3*
Bram Moolenaarede981a2010-08-11 23:37:32 +0200836
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200837When Python 2 and Python 3 are both supported they must be loaded dynamically.
838
839When doing this on Linux/Unix systems and importing global symbols, this leads
840to a crash when the second Python version is used. So either global symbols
841are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200842loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200843symbols to be provided by Vim.
844 *E836* *E837*
845Vim's configuration script makes a guess for all libraries based on one
846standard Python library (termios). If importing this library succeeds for
847both Python versions, then both will be made available in Vim at the same
848time. If not, only the version first used in a session will be enabled.
849When trying to use the other one you will get the E836 or E837 error message.
850
851Here Vim's behavior depends on the system in which it was configured. In a
852system where both versions of Python were configured with --enable-shared,
853both versions of Python will be activated at the same time. There will still
854be problems with other third party libraries that were not linked to
855libPython.
856
857To work around such problems there are these options:
8581. The problematic library is recompiled to link to the according
859 libpython.so.
8602. Vim is recompiled for only one Python version.
8613. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
862 may crash Vim though.
863
Bram Moolenaar41009372013-07-01 22:03:04 +0200864 *E880*
865Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
866 :py vim.command("qall!")
867<
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000868 *E1266*
Bram Moolenaar8a3b8052022-06-26 12:21:15 +0100869This error can occur when Python 3 cannot load the required modules. This
870means that your Python 3 is not correctly installed or there are some mistakes
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000871in your settings. Please check the following items:
Bram Moolenaar8a3b8052022-06-26 12:21:15 +01008721. Make sure that Python 3 is correctly installed. Also check the version of
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000873 python.
8742. Check the 'pythonthreedll' option.
8753. Check the 'pythonthreehome' option.
8764. Check the PATH environment variable if you don't set 'pythonthreedll'.
877 On MS-Windows, you can use where.exe to check which dll will be loaded.
878 E.g. >
879 where.exe python310.dll
8805. Check the PYTHONPATH and PYTHONHOME environment variables.
Bram Moolenaar41009372013-07-01 22:03:04 +0200881
Bram Moolenaar446beb42011-05-10 17:18:44 +0200882 *has-python*
883You can test what Python version is available with: >
884 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200885 echo 'there is Python 2.x'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100886 endif
Bram Moolenaar938ae282023-02-20 20:44:55 +0000887 if has('python3')
Bram Moolenaar446beb42011-05-10 17:18:44 +0200888 echo 'there is Python 3.x'
889 endif
890
891Note however, that when Python 2 and 3 are both available and loaded
892dynamically, these has() calls will try to load them. If only one can be
893loaded at a time, just checking if Python 2 or 3 are available will prevent
894the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200895
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100896To avoid loading the dynamic library, only check if Vim was compiled with
897python support: >
898 if has('python_compiled')
899 echo 'compiled with Python 2.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100900 if has('python_dynamic')
901 echo 'Python 2.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100902 endif
903 endif
Bram Moolenaar938ae282023-02-20 20:44:55 +0000904 if has('python3_compiled')
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100905 echo 'compiled with Python 3.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100906 if has('python3_dynamic')
907 echo 'Python 3.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100908 endif
909 endif
910
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200911When loading the library dynamically, Vim can be compiled to support Python 3
912Stable ABI (|python3-stable-abi|) which allows you to load a different version
913of Python 3 library than the one Vim was compiled with. To check it: >
914 if has('python3_dynamic')
915 if has('python3_stable')
916 echo 'support Python 3 Stable ABI.'
917 else
918 echo 'does not support Python 3 Stable ABI.'
919 echo 'only use Python 3 version ' .. v:python3_version
920 endif
921 endif
922
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100923This also tells you whether Python is dynamically loaded, which will fail if
924the runtime library cannot be found.
925
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200926==============================================================================
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +010092711. Python X *python_x* *pythonx*
928
Bram Moolenaar8a3b8052022-06-26 12:21:15 +0100929Because most python code can be written so that it works with Python 2.6+ and
930Python 3 the pyx* functions and commands have been written. They work exactly
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100931the same as the Python 2 and 3 variants, but select the Python version using
932the 'pyxversion' setting.
933
934You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3
935for Python commands. If you change this setting at runtime you may risk that
936state of plugins (such as initialization) may be lost.
937
938If you want to use a module, you can put it in the {rtp}/pythonx directory.
939See |pythonx-directory|.
940
941 *:pyx* *:pythonx*
942The `:pyx` and `:pythonx` commands work similar to `:python`. A simple check
943if the `:pyx` command is working: >
944 :pyx print("Hello")
945
946To see what version of Python is being used: >
947 :pyx import sys
948 :pyx print(sys.version)
949<
950 *:pyxfile* *python_x-special-comments*
951The `:pyxfile` command works similar to `:pyfile`. However you can add one of
952these comments to force Vim using `:pyfile` or `:py3file`: >
953 #!/any string/python2 " Shebang. Must be the first line of the file.
954 #!/any string/python3 " Shebang. Must be the first line of the file.
955 # requires python 2.x " Maximum lines depend on 'modelines'.
956 # requires python 3.x " Maximum lines depend on 'modelines'.
957Unlike normal modelines, the bottom of the file is not checked.
958If none of them are found, the 'pyxversion' setting is used.
959 *W20* *W21*
960If Vim does not support the selected Python version a silent message will be
961printed. Use `:messages` to read them.
962
963 *:pyxdo*
964The `:pyxdo` command works similar to `:pydo`.
965
966 *has-pythonx*
967You can test if pyx* commands are available with: >
968 if has('pythonx')
Bram Moolenaarc51cf032022-02-26 12:25:45 +0000969 echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100970 endif
971
972When compiled with only one of |+python| or |+python3|, the has() returns 1.
973When compiled with both |+python| and |+python3|, the test depends on the
974'pyxversion' setting. If 'pyxversion' is 0, it tests Python 3 first, and if
975it is not available then Python 2. If 'pyxversion' is 2 or 3, it tests only
976Python 2 or 3 respectively.
977
Bram Moolenaar214641f2017-03-05 17:04:09 +0100978Note that for `has('pythonx')` to work it may try to dynamically load Python 3
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100979or 2. This may have side effects, especially when Vim can only load one of
980the two.
981
982If a user prefers Python 2 and want to fallback to Python 3, he needs to set
983'pyxversion' explicitly in his |.vimrc|. E.g.: >
984 if has('python')
985 set pyx=2
986 elseif has('python3')
987 set pyx=3
988 endif
989
990==============================================================================
Bram Moolenaar036986f2017-03-16 17:41:02 +010099112. Building with Python support *python-building*
992
993A few hints for building with Python 2 or 3 support.
994
995UNIX
996
997See src/Makefile for how to enable including the Python interface.
998
999On Ubuntu you will want to install these packages for Python 2:
1000 python
1001 python-dev
1002For Python 3:
1003 python3
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +02001004 python3-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +01001005For Python 3.6:
1006 python3.6
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +02001007 python3.6-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +01001008
1009If you have more than one version of Python 3, you need to link python3 to the
1010one you prefer, before running configure.
1011
1012==============================================================================
Bram Moolenaar91f84f62018-07-29 15:07:52 +02001013 vim:tw=78:ts=8:noet:ft=help:norl: