blob: 623684152b7459fc000eb2a9bb6294a68a127504 [file] [log] [blame]
Christian Brabandtf0905a82024-05-17 18:30:01 +02001*if_pyth.txt* For Vim version 9.1. Last change: 2024 May 16
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
Bram Moolenaar30b65812012-07-12 22:01:11 +0200204vim.bindeval(str) *python-bindeval*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100205 Like |python-eval|, but returns special objects described in
206 |python-bindeval-objects|. These python objects let you modify (|List|
Bram Moolenaarde71b562013-06-02 17:41:54 +0200207 or |Dictionary|) or call (|Funcref|) vim objects.
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000208
Bram Moolenaarbc411962013-06-02 17:46:40 +0200209vim.strwidth(str) *python-strwidth*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100210 Like |strwidth()|: returns number of display cells str occupies, tab
Bram Moolenaarbc411962013-06-02 17:46:40 +0200211 is counted as one cell.
212
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200213vim.foreach_rtp(callable) *python-foreach_rtp*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100214 Call the given callable for each path in 'runtimepath' until either
215 callable returns something but None, the exception is raised or there
216 are no longer paths. If stopped in case callable returned non-None,
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200217 vim.foreach_rtp function returns the value returned by callable.
218
Bram Moolenaarf4258302013-06-02 18:20:17 +0200219vim.chdir(*args, **kwargs) *python-chdir*
220vim.fchdir(*args, **kwargs) *python-fchdir*
221 Run os.chdir or os.fchdir, then all appropriate vim stuff.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100222 Note: you should not use these functions directly, use os.chdir and
223 os.fchdir instead. Behavior of vim.fchdir is undefined in case
Bram Moolenaarf4258302013-06-02 18:20:17 +0200224 os.fchdir does not exist.
225
Bram Moolenaar071d4272004-06-13 20:20:40 +0000226Error object of the "vim" module
227
228vim.error *python-error*
229 Upon encountering a Vim error, Python raises an exception of type
230 vim.error.
231 Example: >
232 try:
233 vim.command("put a")
234 except vim.error:
235 # nothing in register a
236
237Constants of the "vim" module
238
239 Note that these are not actually constants - you could reassign them.
240 But this is silly, as you would then lose access to the vim objects
241 to which the variables referred.
242
243vim.buffers *python-buffers*
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200244 A mapping object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000246 :py b = vim.buffers[i] # Indexing (read-only)
247 :py b in vim.buffers # Membership test
248 :py n = len(vim.buffers) # Number of elements
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200249 :py for b in vim.buffers: # Iterating over buffer list
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250<
251vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000252 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000254 :py w = vim.windows[i] # Indexing (read-only)
255 :py w in vim.windows # Membership test
256 :py n = len(vim.windows) # Number of elements
257 :py for w in vim.windows: # Sequential access
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100258< Note: vim.windows object always accesses current tab page.
259 |python-tabpage|.windows objects are bound to parent |python-tabpage|
260 object and always use windows from that tab page (or throw vim.error
261 in case tab page was deleted). You can keep a reference to both
262 without keeping a reference to vim module object or |python-tabpage|,
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200263 they will not lose their properties in this case.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200264
265vim.tabpages *python-tabpages*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100266 A sequence object providing access to the list of vim tab pages. The
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200267 object supports the following operations: >
268 :py t = vim.tabpages[i] # Indexing (read-only)
269 :py t in vim.tabpages # Membership test
270 :py n = len(vim.tabpages) # Number of elements
271 :py for t in vim.tabpages: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000272<
273vim.current *python-current*
274 An object providing access (via specific attributes) to various
275 "current" objects available in vim:
276 vim.current.line The current line (RW) String
Bram Moolenaare7614592013-05-15 15:51:08 +0200277 vim.current.buffer The current buffer (RW) Buffer
278 vim.current.window The current window (RW) Window
279 vim.current.tabpage The current tab page (RW) TabPage
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280 vim.current.range The current line range (RO) Range
281
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000282 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000283 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000284 "current range". A range is a bit like a buffer, but with all access
285 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000286
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100287 Note: When assigning to vim.current.{buffer,window,tabpage} it expects
288 valid |python-buffer|, |python-window| or |python-tabpage| objects
289 respectively. Assigning triggers normal (with |autocommand|s)
290 switching to given buffer, window or tab page. It is the only way to
291 switch UI objects in python: you can't assign to
292 |python-tabpage|.window attribute. To switch without triggering
Bram Moolenaare7614592013-05-15 15:51:08 +0200293 autocommands use >
294 py << EOF
295 saved_eventignore = vim.options['eventignore']
296 vim.options['eventignore'] = 'all'
297 try:
298 vim.current.buffer = vim.buffers[2] # Switch to buffer 2
299 finally:
300 vim.options['eventignore'] = saved_eventignore
301 EOF
302<
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200303vim.vars *python-vars*
304vim.vvars *python-vvars*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100305 Dictionary-like objects holding dictionaries with global (|g:|) and
306 vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200307 but faster.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000308
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200309vim.options *python-options*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100310 Object partly supporting mapping protocol (supports setting and
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200311 getting items) providing a read-write access to global options.
312 Note: unlike |:set| this provides access only to global options. You
313 cannot use this object to obtain or set local options' values or
314 access local-only options in any fashion. Raises KeyError if no global
315 option with such name exists (i.e. does not raise KeyError for
316 |global-local| options and global only options, but does for window-
317 and buffer-local ones). Use |python-buffer| objects to access to
318 buffer-local options and |python-window| objects to access to
319 window-local options.
320
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100321 Type of this object is available via "Options" attribute of vim
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200322 module.
323
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324Output from Python *python-output*
325 Vim displays all Python code output in the Vim message area. Normal
326 output appears as information messages, and error output appears as
327 error messages.
328
329 In implementation terms, this means that all output to sys.stdout
330 (including the output from print statements) appears as information
331 messages, and all output to sys.stderr (including error tracebacks)
332 appears as error messages.
333
334 *python-input*
335 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000336 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000337 fixed.
338
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200339 *python2-directory* *python3-directory* *pythonx-directory*
340Python 'runtimepath' handling *python-special-path*
341
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100342In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
343the list of paths found in 'runtimepath': with this directory in sys.path and
344vim.path_hooks in sys.path_hooks python will try to load module from
345{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
Christian Brabandtf0905a82024-05-17 18:30:01 +0200346each {rtp} found in 'runtimepath' (Note: find_module() has been removed from
347imp module around Python 3.12.0a7).
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200348
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200349Implementation is similar to the following, but written in C: >
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200350
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200351 from imp import find_module, load_module
352 import vim
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200353 import sys
354
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200355 class VimModuleLoader(object):
356 def __init__(self, module):
357 self.module = module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200358
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200359 def load_module(self, fullname, path=None):
360 return self.module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200361
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200362 def _find_module(fullname, oldtail, path):
363 idx = oldtail.find('.')
364 if idx > 0:
365 name = oldtail[:idx]
366 tail = oldtail[idx+1:]
367 fmr = find_module(name, path)
368 module = load_module(fullname[:-len(oldtail)] + name, *fmr)
369 return _find_module(fullname, tail, module.__path__)
370 else:
371 fmr = find_module(fullname, path)
372 return load_module(fullname, *fmr)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200373
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100374 # It uses vim module itself in place of VimPathFinder class: it does not
375 # matter for python which object has find_module function attached to as
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200376 # an attribute.
377 class VimPathFinder(object):
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200378 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200379 def find_module(cls, fullname, path=None):
380 try:
381 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
382 except ImportError:
383 return None
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200384
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200385 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200386 def load_module(cls, fullname, path=None):
387 return _find_module(fullname, fullname, path or vim._get_paths())
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200388
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200389 def hook(path):
390 if path == vim.VIM_SPECIAL_PATH:
391 return VimPathFinder
392 else:
393 raise ImportError
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200394
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200395 sys.path_hooks.append(hook)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200396
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200397vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100398 String constant used in conjunction with vim path hook. If path hook
399 installed by vim is requested to handle anything but path equal to
400 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200401 case it uses special loader.
402
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100403 Note: you must not use value of this constant directly, always use
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200404 vim.VIM_SPECIAL_PATH object.
405
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200406vim.find_module(...) *python-find_module*
407vim.path_hook(path) *python-path_hook*
Christian Brabandtf0905a82024-05-17 18:30:01 +0200408vim.find_spec(...) *python-find_spec*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100409 Methods or objects used to implement path loading as described above.
410 You should not be using any of these directly except for vim.path_hook
Christian Brabandtf0905a82024-05-17 18:30:01 +0200411 in case you need to do something with sys.meta_path, vim.find_spec()
412 is available starting with Python 3.7.
413 It is not guaranteed that any of the objects will exist in future vim
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200414 versions.
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200415
416vim._get_paths *python-_get_paths*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100417 Methods returning a list of paths which will be searched for by path
418 hook. You should not rely on this method being present in future
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200419 versions, but can use it for debugging.
420
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100421 It returns a list of {rtp}/python2 (or {rtp}/python3) and
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200422 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
423
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424==============================================================================
4253. Buffer objects *python-buffer*
426
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000427Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 - via vim.current.buffer (|python-current|)
429 - from indexing vim.buffers (|python-buffers|)
430 - from the "buffer" attribute of a window (|python-window|)
431
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100432Buffer objects have two read-only attributes - name - the full file name for
433the buffer, and number - the buffer number. They also have three methods
434(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000436You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000438element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000440you would expect. Note that the result of indexing (slicing) a buffer is a
441string (list of strings). This has one unusual consequence - b[:] is different
442from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443"b = None" merely updates the variable b, with no effect on the buffer.
444
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000445Buffer indexes start at zero, as is normal in Python. This differs from vim
446line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447with marks (see below) which use vim line numbers.
448
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200449The buffer object attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100450 b.vars Dictionary-like object used to access
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200451 |buffer-variable|s.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100452 b.options Mapping object (supports item getting, setting and
453 deleting) that provides access to buffer-local options
454 and buffer-local values of |global-local| options. Use
455 |python-window|.options if option is window-local,
456 this object will raise KeyError. If option is
457 |global-local| and local value is missing getting it
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200458 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200459 b.name String, RW. Contains buffer name (full path).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100460 Note: when assigning to b.name |BufFilePre| and
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200461 |BufFilePost| autocommands are launched.
462 b.number Buffer number. Can be used as |python-buffers| key.
463 Read-only.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100464 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200465 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200466
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467The buffer object methods are:
468 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200469 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 b.append(list) Append a list of lines to the buffer
471 Note that the option of supplying a list of strings to
472 the append method differs from the equivalent method
473 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200474 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 b.mark(name) Return a tuple (row,col) representing the position
476 of the named mark (can also get the []"<> marks)
477 b.range(s,e) Return a range object (see |python-range|) which
478 represents the part of the given buffer between line
479 numbers s and e |inclusive|.
480
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000481Note that when adding a line it must not contain a line break character '\n'.
482A trailing '\n' is allowed and ignored, so that you can do: >
483 :py b.append(f.readlines())
484
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200485Buffer object type is available using "Buffer" attribute of vim module.
486
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000488 :py print b.name # write the buffer file name
489 :py b[0] = "hello!!!" # replace the top line
490 :py b[:] = None # delete the whole buffer
491 :py del b[:] # delete the whole buffer
492 :py b[0:0] = [ "a line" ] # add a line at the top
493 :py del b[2] # delete a line (the third)
494 :py b.append("bottom") # add a line at the bottom
495 :py n = len(b) # number of lines
496 :py (row,col) = b.mark('a') # named mark
497 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200498 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200499 :py b.options["ff"] = "dos" # set fileformat
500 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501
502==============================================================================
5034. Range objects *python-range*
504
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000505Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506number of ways:
507 - via vim.current.range (|python-current|)
508 - from a buffer's range() method (|python-buffer|)
509
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000510A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511all operations are restricted to the lines within the range (this line range
512can, of course, change as a result of slice assignments, line deletions, or
513the range.append() method).
514
515The range object attributes are:
516 r.start Index of first line into the buffer
517 r.end Index of last line into the buffer
518
519The range object methods are:
520 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200521 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 r.append(list) Append a list of lines to the range
523 Note that the option of supplying a list of strings to
524 the append method differs from the equivalent method
525 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200526 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200528Range object type is available using "Range" attribute of vim module.
529
Christian Brabandta56f02d2023-10-25 21:21:56 +0200530Example (assume r is the current range): >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531 # Send all lines in a range to the default printer
532 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
533
534==============================================================================
5355. Window objects *python-window*
536
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000537Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538 - via vim.current.window (|python-current|)
539 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200540 - from indexing "windows" attribute of a tab page (|python-tabpage|)
541 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000543You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544methods, and no sequence or other interface.
545
546Window attributes are:
547 buffer (read-only) The buffer displayed in this window
548 cursor (read-write) The current cursor position in the window
549 This is a tuple, (row,col).
550 height (read-write) The window height, in rows
551 width (read-write) The window width, in columns
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100552 vars (read-only) The window |w:| variables. Attribute is
553 unassignable, but you can change window
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200554 variables this way
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100555 options (read-only) The window-local options. Attribute is
556 unassignable, but you can change window
557 options this way. Provides access only to
558 window-local options, for buffer-local use
559 |python-buffer| and for global ones use
560 |python-options|. If option is |global-local|
561 and local value is missing getting it will
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200562 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200563 number (read-only) Window number. The first window has number 1.
564 This is zero in case it cannot be determined
565 (e.g. when the window object belongs to other
566 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200567 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200568 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200569 tabpage (read-only) Window tab page.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100570 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200571 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573The height attribute is writable only if the screen is split horizontally.
574The width attribute is writable only if the screen is split vertically.
575
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200576Window object type is available using "Window" attribute of vim module.
577
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005796. Tab page objects *python-tabpage*
580
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100581Tab page objects represent vim tab pages. You can obtain them in a number of
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200582ways:
583 - via vim.current.tabpage (|python-current|)
584 - from indexing vim.tabpages (|python-tabpages|)
585
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100586You can use this object to access tab page windows. They have no methods and
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200587no sequence or other interfaces.
588
589Tab page attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100590 number The tab page number like the one returned by
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200591 |tabpagenr()|.
592 windows Like |python-windows|, but for current tab page.
593 vars The tab page |t:| variables.
594 window Current tabpage window.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100595 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200596 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200597
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200598TabPage object type is available using "TabPage" attribute of vim module.
599
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200600==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02006017. vim.bindeval objects *python-bindeval-objects*
602
603vim.Dictionary object *python-Dictionary*
604 Dictionary-like object providing access to vim |Dictionary| type.
605 Attributes:
606 Attribute Description ~
607 locked One of *python-.locked*
608 Value Description ~
609 zero Variable is not locked
610 vim.VAR_LOCKED Variable is locked, but can be unlocked
611 vim.VAR_FIXED Variable is locked and can't be unlocked
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100612 Read-write. You can unlock locked variable by assigning
613 `True` or `False` to this attribute. No recursive locking
Bram Moolenaara9922d62013-05-30 13:01:18 +0200614 is supported.
615 scope One of
616 Value Description ~
617 zero Dictionary is not a scope one
618 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
619 vim.VAR_SCOPE Other scope dictionary,
620 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200621 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200622 Method Description ~
623 keys() Returns a list with dictionary keys.
624 values() Returns a list with dictionary values.
625 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200626 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200627 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200628 get(key[, default=None])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100629 Obtain key from dictionary, returning the default if it is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200630 not present.
631 pop(key[, default])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100632 Remove specified key from dictionary and return
633 corresponding value. If key is not found and default is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200634 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200635 popitem()
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100636 Remove random key from dictionary and return (key, value)
Bram Moolenaarde71b562013-06-02 17:41:54 +0200637 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200638 has_key(key)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100639 Check whether dictionary contains specified key, similar
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200640 to `key in dict`.
641
642 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100643 You can use `vim.Dictionary()` to create new vim
644 dictionaries. `d=vim.Dictionary(arg)` is the same as
645 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200646 constructs empty dictionary.
647
Bram Moolenaara9922d62013-05-30 13:01:18 +0200648 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200649 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200650 d['a'] = 'b' # Item assignment
651 print d['a'] # getting item
652 d.update({'c': 'd'}) # .update(dictionary)
653 d.update(e='f') # .update(**kwargs)
654 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
655 for key in d.keys(): # .keys()
656 for val in d.values(): # .values()
657 for key, val in d.items(): # .items()
658 print isinstance(d, vim.Dictionary) # True
659 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200660 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200661<
662 Note: when iterating over keys you should not modify dictionary.
663
664vim.List object *python-List*
665 Sequence-like object providing access to vim |List| type.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100666 Supports `.locked` attribute, see |python-.locked|. Also supports the
Bram Moolenaara9922d62013-05-30 13:01:18 +0200667 following methods:
668 Method Description ~
669 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200670
671 __new__(), __new__(iterable)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100672 You can use `vim.List()` to create new vim lists.
673 `l=vim.List(iterable)` is the same as
674 `l=vim.bindeval('[]');l.extend(iterable)`. Without
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200675 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200676 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200677 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200678 l.extend(['abc', 'def']) # .extend() method
679 print l[1:] # slicing
680 l[:0] = ['ghi', 'jkl'] # slice assignment
681 print l[0] # getting item
682 l[0] = 'mno' # assignment
683 for i in l: # iteration
684 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200685 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200686
687vim.Function object *python-Function*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100688 Function-like object, acting like vim |Funcref| object. Accepts special
689 keyword argument `self`, see |Dictionary-function|. You can also use
690 `vim.Function(name)` constructor, it is the same as
Bram Moolenaar8110a092016-04-14 15:56:09 +0200691 `vim.bindeval('function(%s)'%json.dumps(name))`.
692
693 Attributes (read-only):
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200694 Attribute Description ~
695 name Function name.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100696 args `None` or a |python-List| object with arguments. Note
697 that this is a copy of the arguments list, constructed
698 each time you request this attribute. Modifications made
699 to the list will be ignored (but not to the containers
700 inside argument list: this is like |copy()| and not
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200701 |deepcopy()|).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100702 self `None` or a |python-Dictionary| object with self
703 dictionary. Note that explicit `self` keyword used when
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200704 calling resulting object overrides this attribute.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100705 auto_rebind Boolean. True if partial created from this Python object
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100706 and stored in the Vim script dictionary should be
707 automatically rebound to the dictionary it is stored in
708 when this dictionary is indexed. Exposes Vim internal
709 difference between `dict.func` (auto_rebind=True) and
710 `function(dict.func,dict)` (auto_rebind=False). This
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200711 attribute makes no sense if `self` attribute is `None`.
Bram Moolenaar8110a092016-04-14 15:56:09 +0200712
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100713 Constructor additionally accepts `args`, `self` and `auto_rebind`
714 keywords. If `args` and/or `self` argument is given then it constructs
715 a partial, see |function()|. `auto_rebind` is only used when `self`
716 argument is given, otherwise it is assumed to be `True` regardless of
717 whether it was given or not. If `self` is given then it defaults to
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200718 `False`.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200719
Bram Moolenaara9922d62013-05-30 13:01:18 +0200720 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200721 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200722 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
723 vim.command('''
724 function DictFun() dict
725 return self
726 endfunction
727 ''')
728 f = vim.bindeval('function("DictFun")')
729 print f(self={}) # Like call('DictFun', [], {})
730 print isinstance(f, vim.Function) # True
731
Bram Moolenaar8110a092016-04-14 15:56:09 +0200732 p = vim.Function('DictFun', self={})
733 print f()
734 p = vim.Function('tr', args=['abc', 'a'])
735 print f('b')
736
Bram Moolenaara9922d62013-05-30 13:01:18 +0200737==============================================================================
7388. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200739
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100740To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100741functions to evaluate Python expressions and pass their values to Vim script.
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100742|pyxeval()| is also available.
Bram Moolenaar30b65812012-07-12 22:01:11 +0200743
Bram Moolenaarde323092017-11-09 19:56:08 +0100744The Python value "None" is converted to v:none.
745
Bram Moolenaar30b65812012-07-12 22:01:11 +0200746==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02007479. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000748
Bram Moolenaard94464e2015-11-02 15:28:18 +0100749On MS-Windows and Unix the Python library can be loaded dynamically. The
750|:version| output then includes |+python/dyn| or |+python3/dyn|.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000751
Bram Moolenaard94464e2015-11-02 15:28:18 +0100752This means that Vim will search for the Python DLL or shared library file only
753when needed. When you don't use the Python interface you don't need it, thus
754you can use Vim without this file.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000755
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100756
757MS-Windows ~
758
759To use the Python interface the Python DLL must be in your search path. In a
Ken Takataae3cfa42023-10-14 11:49:09 +0200760console window type "path" to see what directories are used. If the DLL is
761not found in your search path, Vim will check the registry to find the path
762where Python is installed. The 'pythondll' or 'pythonthreedll' option can be
763also used to specify the Python DLL.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000764
Bram Moolenaar3df01732017-02-17 22:47:16 +0100765The name of the DLL should match the Python version Vim was compiled with.
766Currently the name for Python 2 is "python27.dll", that is for Python 2.7.
Bram Moolenaar59eb0162017-12-10 18:17:44 +0100767That is the default value for 'pythondll'. For Python 3 it is python36.dll
768(Python 3.6). To know for sure edit "gvim.exe" and search for
Bram Moolenaar3df01732017-02-17 22:47:16 +0100769"python\d*.dll\c".
Bram Moolenaara5792f52005-11-23 21:25:05 +0000770
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100771
772Unix ~
773
774The 'pythondll' or 'pythonthreedll' option can be used to specify the Python
775shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file
776what were specified at compile time. The version of the shared library must
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200777match the Python 2.x or Python 3 version (|v:python3_version|) Vim was
778compiled with unless using |python3-stable-abi|.
779
780
781Stable ABI and mixing Python versions ~
782 *python-stable* *python-stable-abi* *python3-stable-abi*
783If Vim was not compiled with Stable ABI (only available for Python 3), the
784version of the Python shared library must match the version that Vim was
785compiled with. Otherwise, mixing versions could result in unexpected crashes
786and failures. With Stable ABI, this restriction is relaxed, and any Python 3
787library with version of at least |v:python3_version| will work. See
788|has-python| for how to check if Stable ABI is supported, or see if version
789output includes |+python3/dyn-stable|.
Ken Takataae3cfa42023-10-14 11:49:09 +0200790On MS-Windows, 'pythonthreedll' will be set to "python3.dll". When searching
791the DLL from the registry, Vim will search the latest version of Python.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100792
Bram Moolenaara5792f52005-11-23 21:25:05 +0000793==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020079410. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200795
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200796 *:py3* *:python3*
Bram Moolenaar91359012019-11-30 17:57:03 +0100797:[range]py3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200798:[range]py3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100799{script}
800{endmarker}
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200801
Bram Moolenaar91359012019-11-30 17:57:03 +0100802:[range]python3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200803:[range]python3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100804{script}
805{endmarker}
806 The `:py3` and `:python3` commands work similar to `:python`. A
807 simple check if the `:py3` command is working: >
808 :py3 print("Hello")
809<
810 To see what version of Python you have: >
811 :py3 import sys
812 :py3 print(sys.version)
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200813< *:py3file*
Bram Moolenaar91359012019-11-30 17:57:03 +0100814:[range]py3f[ile] {file}
815 The `:py3file` command works similar to `:pyfile`.
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +0200816 *:py3do*
Bram Moolenaar91359012019-11-30 17:57:03 +0100817:[range]py3do {body}
818 The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200819
Bram Moolenaar30b65812012-07-12 22:01:11 +0200820
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200821Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02008221. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02008232. Python 2 support only (+python or +python/dyn, -python3)
8243. Python 3 support only (-python, +python3 or +python3/dyn)
8254. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200826
Bram Moolenaar9ba7e172013-07-17 22:37:26 +0200827Some more details on the special case 4: *python-2-and-3*
Bram Moolenaarede981a2010-08-11 23:37:32 +0200828
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200829When Python 2 and Python 3 are both supported they must be loaded dynamically.
830
831When doing this on Linux/Unix systems and importing global symbols, this leads
832to a crash when the second Python version is used. So either global symbols
833are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200834loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200835symbols to be provided by Vim.
836 *E836* *E837*
837Vim's configuration script makes a guess for all libraries based on one
838standard Python library (termios). If importing this library succeeds for
839both Python versions, then both will be made available in Vim at the same
840time. If not, only the version first used in a session will be enabled.
841When trying to use the other one you will get the E836 or E837 error message.
842
843Here Vim's behavior depends on the system in which it was configured. In a
844system where both versions of Python were configured with --enable-shared,
845both versions of Python will be activated at the same time. There will still
846be problems with other third party libraries that were not linked to
847libPython.
848
849To work around such problems there are these options:
8501. The problematic library is recompiled to link to the according
851 libpython.so.
8522. Vim is recompiled for only one Python version.
8533. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
854 may crash Vim though.
855
Bram Moolenaar41009372013-07-01 22:03:04 +0200856 *E880*
857Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
858 :py vim.command("qall!")
859<
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000860 *E1266*
Bram Moolenaar8a3b8052022-06-26 12:21:15 +0100861This error can occur when Python 3 cannot load the required modules. This
862means that your Python 3 is not correctly installed or there are some mistakes
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000863in your settings. Please check the following items:
Bram Moolenaar8a3b8052022-06-26 12:21:15 +01008641. Make sure that Python 3 is correctly installed. Also check the version of
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000865 python.
8662. Check the 'pythonthreedll' option.
8673. Check the 'pythonthreehome' option.
8684. Check the PATH environment variable if you don't set 'pythonthreedll'.
869 On MS-Windows, you can use where.exe to check which dll will be loaded.
870 E.g. >
871 where.exe python310.dll
8725. Check the PYTHONPATH and PYTHONHOME environment variables.
Bram Moolenaar41009372013-07-01 22:03:04 +0200873
Bram Moolenaar446beb42011-05-10 17:18:44 +0200874 *has-python*
875You can test what Python version is available with: >
876 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200877 echo 'there is Python 2.x'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100878 endif
Bram Moolenaar938ae282023-02-20 20:44:55 +0000879 if has('python3')
Bram Moolenaar446beb42011-05-10 17:18:44 +0200880 echo 'there is Python 3.x'
881 endif
882
883Note however, that when Python 2 and 3 are both available and loaded
884dynamically, these has() calls will try to load them. If only one can be
885loaded at a time, just checking if Python 2 or 3 are available will prevent
886the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200887
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100888To avoid loading the dynamic library, only check if Vim was compiled with
889python support: >
890 if has('python_compiled')
891 echo 'compiled with Python 2.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100892 if has('python_dynamic')
893 echo 'Python 2.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100894 endif
895 endif
Bram Moolenaar938ae282023-02-20 20:44:55 +0000896 if has('python3_compiled')
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100897 echo 'compiled with Python 3.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100898 if has('python3_dynamic')
899 echo 'Python 3.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100900 endif
901 endif
902
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200903When loading the library dynamically, Vim can be compiled to support Python 3
904Stable ABI (|python3-stable-abi|) which allows you to load a different version
905of Python 3 library than the one Vim was compiled with. To check it: >
906 if has('python3_dynamic')
907 if has('python3_stable')
908 echo 'support Python 3 Stable ABI.'
909 else
910 echo 'does not support Python 3 Stable ABI.'
911 echo 'only use Python 3 version ' .. v:python3_version
912 endif
913 endif
914
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100915This also tells you whether Python is dynamically loaded, which will fail if
916the runtime library cannot be found.
917
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200918==============================================================================
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +010091911. Python X *python_x* *pythonx*
920
Bram Moolenaar8a3b8052022-06-26 12:21:15 +0100921Because most python code can be written so that it works with Python 2.6+ and
922Python 3 the pyx* functions and commands have been written. They work exactly
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100923the same as the Python 2 and 3 variants, but select the Python version using
924the 'pyxversion' setting.
925
926You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3
927for Python commands. If you change this setting at runtime you may risk that
928state of plugins (such as initialization) may be lost.
929
930If you want to use a module, you can put it in the {rtp}/pythonx directory.
931See |pythonx-directory|.
932
933 *:pyx* *:pythonx*
934The `:pyx` and `:pythonx` commands work similar to `:python`. A simple check
935if the `:pyx` command is working: >
936 :pyx print("Hello")
937
938To see what version of Python is being used: >
939 :pyx import sys
940 :pyx print(sys.version)
941<
942 *:pyxfile* *python_x-special-comments*
943The `:pyxfile` command works similar to `:pyfile`. However you can add one of
944these comments to force Vim using `:pyfile` or `:py3file`: >
945 #!/any string/python2 " Shebang. Must be the first line of the file.
946 #!/any string/python3 " Shebang. Must be the first line of the file.
947 # requires python 2.x " Maximum lines depend on 'modelines'.
948 # requires python 3.x " Maximum lines depend on 'modelines'.
949Unlike normal modelines, the bottom of the file is not checked.
950If none of them are found, the 'pyxversion' setting is used.
951 *W20* *W21*
952If Vim does not support the selected Python version a silent message will be
953printed. Use `:messages` to read them.
954
955 *:pyxdo*
956The `:pyxdo` command works similar to `:pydo`.
957
958 *has-pythonx*
959You can test if pyx* commands are available with: >
960 if has('pythonx')
Bram Moolenaarc51cf032022-02-26 12:25:45 +0000961 echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100962 endif
963
964When compiled with only one of |+python| or |+python3|, the has() returns 1.
965When compiled with both |+python| and |+python3|, the test depends on the
966'pyxversion' setting. If 'pyxversion' is 0, it tests Python 3 first, and if
967it is not available then Python 2. If 'pyxversion' is 2 or 3, it tests only
968Python 2 or 3 respectively.
969
Bram Moolenaar214641f2017-03-05 17:04:09 +0100970Note that for `has('pythonx')` to work it may try to dynamically load Python 3
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100971or 2. This may have side effects, especially when Vim can only load one of
972the two.
973
974If a user prefers Python 2 and want to fallback to Python 3, he needs to set
975'pyxversion' explicitly in his |.vimrc|. E.g.: >
976 if has('python')
977 set pyx=2
978 elseif has('python3')
979 set pyx=3
980 endif
981
982==============================================================================
Bram Moolenaar036986f2017-03-16 17:41:02 +010098312. Building with Python support *python-building*
984
985A few hints for building with Python 2 or 3 support.
986
987UNIX
988
989See src/Makefile for how to enable including the Python interface.
990
991On Ubuntu you will want to install these packages for Python 2:
992 python
993 python-dev
994For Python 3:
995 python3
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200996 python3-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +0100997For Python 3.6:
998 python3.6
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200999 python3.6-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +01001000
1001If you have more than one version of Python 3, you need to link python3 to the
1002one you prefer, before running configure.
1003
1004==============================================================================
Bram Moolenaar91f84f62018-07-29 15:07:52 +02001005 vim:tw=78:ts=8:noet:ft=help:norl: