blob: a6767925f84a37014d279af99754610fb9c0fd10 [file] [log] [blame]
Bram Moolenaarc51cf032022-02-26 12:25:45 +00001*if_pyth.txt* For Vim version 8.2. Last change: 2022 Feb 22
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
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200346each {rtp} found in 'runtimepath'.
347
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200348Implementation is similar to the following, but written in C: >
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200349
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200350 from imp import find_module, load_module
351 import vim
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200352 import sys
353
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200354 class VimModuleLoader(object):
355 def __init__(self, module):
356 self.module = module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200357
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200358 def load_module(self, fullname, path=None):
359 return self.module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200360
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200361 def _find_module(fullname, oldtail, path):
362 idx = oldtail.find('.')
363 if idx > 0:
364 name = oldtail[:idx]
365 tail = oldtail[idx+1:]
366 fmr = find_module(name, path)
367 module = load_module(fullname[:-len(oldtail)] + name, *fmr)
368 return _find_module(fullname, tail, module.__path__)
369 else:
370 fmr = find_module(fullname, path)
371 return load_module(fullname, *fmr)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200372
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100373 # It uses vim module itself in place of VimPathFinder class: it does not
374 # matter for python which object has find_module function attached to as
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200375 # an attribute.
376 class VimPathFinder(object):
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200377 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200378 def find_module(cls, fullname, path=None):
379 try:
380 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
381 except ImportError:
382 return None
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200383
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200384 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200385 def load_module(cls, fullname, path=None):
386 return _find_module(fullname, fullname, path or vim._get_paths())
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200387
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200388 def hook(path):
389 if path == vim.VIM_SPECIAL_PATH:
390 return VimPathFinder
391 else:
392 raise ImportError
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200393
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200394 sys.path_hooks.append(hook)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200395
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200396vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100397 String constant used in conjunction with vim path hook. If path hook
398 installed by vim is requested to handle anything but path equal to
399 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200400 case it uses special loader.
401
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100402 Note: you must not use value of this constant directly, always use
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200403 vim.VIM_SPECIAL_PATH object.
404
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200405vim.find_module(...) *python-find_module*
406vim.path_hook(path) *python-path_hook*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100407 Methods or objects used to implement path loading as described above.
408 You should not be using any of these directly except for vim.path_hook
409 in case you need to do something with sys.meta_path. It is not
410 guaranteed that any of the objects will exist in the future vim
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200411 versions.
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200412
413vim._get_paths *python-_get_paths*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100414 Methods returning a list of paths which will be searched for by path
415 hook. You should not rely on this method being present in future
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200416 versions, but can use it for debugging.
417
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100418 It returns a list of {rtp}/python2 (or {rtp}/python3) and
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200419 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
420
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421==============================================================================
4223. Buffer objects *python-buffer*
423
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000424Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 - via vim.current.buffer (|python-current|)
426 - from indexing vim.buffers (|python-buffers|)
427 - from the "buffer" attribute of a window (|python-window|)
428
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100429Buffer objects have two read-only attributes - name - the full file name for
430the buffer, and number - the buffer number. They also have three methods
431(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000433You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000435element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000437you would expect. Note that the result of indexing (slicing) a buffer is a
438string (list of strings). This has one unusual consequence - b[:] is different
439from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440"b = None" merely updates the variable b, with no effect on the buffer.
441
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000442Buffer indexes start at zero, as is normal in Python. This differs from vim
443line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444with marks (see below) which use vim line numbers.
445
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200446The buffer object attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100447 b.vars Dictionary-like object used to access
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200448 |buffer-variable|s.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100449 b.options Mapping object (supports item getting, setting and
450 deleting) that provides access to buffer-local options
451 and buffer-local values of |global-local| options. Use
452 |python-window|.options if option is window-local,
453 this object will raise KeyError. If option is
454 |global-local| and local value is missing getting it
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200455 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200456 b.name String, RW. Contains buffer name (full path).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100457 Note: when assigning to b.name |BufFilePre| and
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200458 |BufFilePost| autocommands are launched.
459 b.number Buffer number. Can be used as |python-buffers| key.
460 Read-only.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100461 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200462 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200463
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464The buffer object methods are:
465 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200466 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467 b.append(list) Append a list of lines to the buffer
468 Note that the option of supplying a list of strings to
469 the append method differs from the equivalent method
470 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200471 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472 b.mark(name) Return a tuple (row,col) representing the position
473 of the named mark (can also get the []"<> marks)
474 b.range(s,e) Return a range object (see |python-range|) which
475 represents the part of the given buffer between line
476 numbers s and e |inclusive|.
477
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000478Note that when adding a line it must not contain a line break character '\n'.
479A trailing '\n' is allowed and ignored, so that you can do: >
480 :py b.append(f.readlines())
481
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200482Buffer object type is available using "Buffer" attribute of vim module.
483
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000485 :py print b.name # write the buffer file name
486 :py b[0] = "hello!!!" # replace the top line
487 :py b[:] = None # delete the whole buffer
488 :py del b[:] # delete the whole buffer
489 :py b[0:0] = [ "a line" ] # add a line at the top
490 :py del b[2] # delete a line (the third)
491 :py b.append("bottom") # add a line at the bottom
492 :py n = len(b) # number of lines
493 :py (row,col) = b.mark('a') # named mark
494 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200495 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200496 :py b.options["ff"] = "dos" # set fileformat
497 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498
499==============================================================================
5004. Range objects *python-range*
501
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000502Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503number of ways:
504 - via vim.current.range (|python-current|)
505 - from a buffer's range() method (|python-buffer|)
506
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000507A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508all operations are restricted to the lines within the range (this line range
509can, of course, change as a result of slice assignments, line deletions, or
510the range.append() method).
511
512The range object attributes are:
513 r.start Index of first line into the buffer
514 r.end Index of last line into the buffer
515
516The range object methods are:
517 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200518 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 r.append(list) Append a list of lines to the range
520 Note that the option of supplying a list of strings to
521 the append method differs from the equivalent method
522 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200523 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200525Range object type is available using "Range" attribute of vim module.
526
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527Example (assume r is the current range):
528 # Send all lines in a range to the default printer
529 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
530
531==============================================================================
5325. Window objects *python-window*
533
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000534Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 - via vim.current.window (|python-current|)
536 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200537 - from indexing "windows" attribute of a tab page (|python-tabpage|)
538 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000540You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541methods, and no sequence or other interface.
542
543Window attributes are:
544 buffer (read-only) The buffer displayed in this window
545 cursor (read-write) The current cursor position in the window
546 This is a tuple, (row,col).
547 height (read-write) The window height, in rows
548 width (read-write) The window width, in columns
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100549 vars (read-only) The window |w:| variables. Attribute is
550 unassignable, but you can change window
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200551 variables this way
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100552 options (read-only) The window-local options. Attribute is
553 unassignable, but you can change window
554 options this way. Provides access only to
555 window-local options, for buffer-local use
556 |python-buffer| and for global ones use
557 |python-options|. If option is |global-local|
558 and local value is missing getting it will
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200559 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200560 number (read-only) Window number. The first window has number 1.
561 This is zero in case it cannot be determined
562 (e.g. when the window object belongs to other
563 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200564 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200565 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200566 tabpage (read-only) Window tab page.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100567 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200568 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200569
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570The height attribute is writable only if the screen is split horizontally.
571The width attribute is writable only if the screen is split vertically.
572
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200573Window object type is available using "Window" attribute of vim module.
574
Bram Moolenaar071d4272004-06-13 20:20:40 +0000575==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005766. Tab page objects *python-tabpage*
577
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100578Tab page objects represent vim tab pages. You can obtain them in a number of
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200579ways:
580 - via vim.current.tabpage (|python-current|)
581 - from indexing vim.tabpages (|python-tabpages|)
582
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100583You can use this object to access tab page windows. They have no methods and
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200584no sequence or other interfaces.
585
586Tab page attributes are:
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100587 number The tab page number like the one returned by
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200588 |tabpagenr()|.
589 windows Like |python-windows|, but for current tab page.
590 vars The tab page |t:| variables.
591 window Current tabpage window.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100592 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200593 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200594
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200595TabPage object type is available using "TabPage" attribute of vim module.
596
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200597==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02005987. vim.bindeval objects *python-bindeval-objects*
599
600vim.Dictionary object *python-Dictionary*
601 Dictionary-like object providing access to vim |Dictionary| type.
602 Attributes:
603 Attribute Description ~
604 locked One of *python-.locked*
605 Value Description ~
606 zero Variable is not locked
607 vim.VAR_LOCKED Variable is locked, but can be unlocked
608 vim.VAR_FIXED Variable is locked and can't be unlocked
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100609 Read-write. You can unlock locked variable by assigning
610 `True` or `False` to this attribute. No recursive locking
Bram Moolenaara9922d62013-05-30 13:01:18 +0200611 is supported.
612 scope One of
613 Value Description ~
614 zero Dictionary is not a scope one
615 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
616 vim.VAR_SCOPE Other scope dictionary,
617 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200618 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200619 Method Description ~
620 keys() Returns a list with dictionary keys.
621 values() Returns a list with dictionary values.
622 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200623 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200624 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200625 get(key[, default=None])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100626 Obtain key from dictionary, returning the default if it is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200627 not present.
628 pop(key[, default])
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100629 Remove specified key from dictionary and return
630 corresponding value. If key is not found and default is
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200631 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200632 popitem()
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100633 Remove random key from dictionary and return (key, value)
Bram Moolenaarde71b562013-06-02 17:41:54 +0200634 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200635 has_key(key)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100636 Check whether dictionary contains specified key, similar
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200637 to `key in dict`.
638
639 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100640 You can use `vim.Dictionary()` to create new vim
641 dictionaries. `d=vim.Dictionary(arg)` is the same as
642 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200643 constructs empty dictionary.
644
Bram Moolenaara9922d62013-05-30 13:01:18 +0200645 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200646 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200647 d['a'] = 'b' # Item assignment
648 print d['a'] # getting item
649 d.update({'c': 'd'}) # .update(dictionary)
650 d.update(e='f') # .update(**kwargs)
651 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
652 for key in d.keys(): # .keys()
653 for val in d.values(): # .values()
654 for key, val in d.items(): # .items()
655 print isinstance(d, vim.Dictionary) # True
656 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200657 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200658<
659 Note: when iterating over keys you should not modify dictionary.
660
661vim.List object *python-List*
662 Sequence-like object providing access to vim |List| type.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100663 Supports `.locked` attribute, see |python-.locked|. Also supports the
Bram Moolenaara9922d62013-05-30 13:01:18 +0200664 following methods:
665 Method Description ~
666 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200667
668 __new__(), __new__(iterable)
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100669 You can use `vim.List()` to create new vim lists.
670 `l=vim.List(iterable)` is the same as
671 `l=vim.bindeval('[]');l.extend(iterable)`. Without
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200672 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200673 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200674 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200675 l.extend(['abc', 'def']) # .extend() method
676 print l[1:] # slicing
677 l[:0] = ['ghi', 'jkl'] # slice assignment
678 print l[0] # getting item
679 l[0] = 'mno' # assignment
680 for i in l: # iteration
681 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200682 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200683
684vim.Function object *python-Function*
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100685 Function-like object, acting like vim |Funcref| object. Accepts special
686 keyword argument `self`, see |Dictionary-function|. You can also use
687 `vim.Function(name)` constructor, it is the same as
Bram Moolenaar8110a092016-04-14 15:56:09 +0200688 `vim.bindeval('function(%s)'%json.dumps(name))`.
689
690 Attributes (read-only):
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200691 Attribute Description ~
692 name Function name.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100693 args `None` or a |python-List| object with arguments. Note
694 that this is a copy of the arguments list, constructed
695 each time you request this attribute. Modifications made
696 to the list will be ignored (but not to the containers
697 inside argument list: this is like |copy()| and not
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200698 |deepcopy()|).
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100699 self `None` or a |python-Dictionary| object with self
700 dictionary. Note that explicit `self` keyword used when
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200701 calling resulting object overrides this attribute.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100702 auto_rebind Boolean. True if partial created from this Python object
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100703 and stored in the Vim script dictionary should be
704 automatically rebound to the dictionary it is stored in
705 when this dictionary is indexed. Exposes Vim internal
706 difference between `dict.func` (auto_rebind=True) and
707 `function(dict.func,dict)` (auto_rebind=False). This
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200708 attribute makes no sense if `self` attribute is `None`.
Bram Moolenaar8110a092016-04-14 15:56:09 +0200709
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100710 Constructor additionally accepts `args`, `self` and `auto_rebind`
711 keywords. If `args` and/or `self` argument is given then it constructs
712 a partial, see |function()|. `auto_rebind` is only used when `self`
713 argument is given, otherwise it is assumed to be `True` regardless of
714 whether it was given or not. If `self` is given then it defaults to
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200715 `False`.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200716
Bram Moolenaara9922d62013-05-30 13:01:18 +0200717 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200718 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200719 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
720 vim.command('''
721 function DictFun() dict
722 return self
723 endfunction
724 ''')
725 f = vim.bindeval('function("DictFun")')
726 print f(self={}) # Like call('DictFun', [], {})
727 print isinstance(f, vim.Function) # True
728
Bram Moolenaar8110a092016-04-14 15:56:09 +0200729 p = vim.Function('DictFun', self={})
730 print f()
731 p = vim.Function('tr', args=['abc', 'a'])
732 print f('b')
733
Bram Moolenaara9922d62013-05-30 13:01:18 +0200734==============================================================================
7358. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200736
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100737To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100738functions to evaluate Python expressions and pass their values to Vim script.
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100739|pyxeval()| is also available.
Bram Moolenaar30b65812012-07-12 22:01:11 +0200740
Bram Moolenaarde323092017-11-09 19:56:08 +0100741The Python value "None" is converted to v:none.
742
Bram Moolenaar30b65812012-07-12 22:01:11 +0200743==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02007449. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000745
Bram Moolenaard94464e2015-11-02 15:28:18 +0100746On MS-Windows and Unix the Python library can be loaded dynamically. The
747|:version| output then includes |+python/dyn| or |+python3/dyn|.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000748
Bram Moolenaard94464e2015-11-02 15:28:18 +0100749This means that Vim will search for the Python DLL or shared library file only
750when needed. When you don't use the Python interface you don't need it, thus
751you can use Vim without this file.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000752
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100753
754MS-Windows ~
755
756To use the Python interface the Python DLL must be in your search path. In a
757console window type "path" to see what directories are used. The 'pythondll'
758or 'pythonthreedll' option can be also used to specify the Python DLL.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000759
Bram Moolenaar3df01732017-02-17 22:47:16 +0100760The name of the DLL should match the Python version Vim was compiled with.
761Currently the name for Python 2 is "python27.dll", that is for Python 2.7.
Bram Moolenaar59eb0162017-12-10 18:17:44 +0100762That is the default value for 'pythondll'. For Python 3 it is python36.dll
763(Python 3.6). To know for sure edit "gvim.exe" and search for
Bram Moolenaar3df01732017-02-17 22:47:16 +0100764"python\d*.dll\c".
Bram Moolenaara5792f52005-11-23 21:25:05 +0000765
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100766
767Unix ~
768
769The 'pythondll' or 'pythonthreedll' option can be used to specify the Python
770shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file
771what were specified at compile time. The version of the shared library must
772match the Python 2.x or Python 3 version Vim was compiled with.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100773
Bram Moolenaara5792f52005-11-23 21:25:05 +0000774==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020077510. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200776
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200777 *:py3* *:python3*
Bram Moolenaar91359012019-11-30 17:57:03 +0100778:[range]py3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200779:[range]py3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100780{script}
781{endmarker}
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200782
Bram Moolenaar91359012019-11-30 17:57:03 +0100783:[range]python3 {stmt}
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200784:[range]python3 << [trim] [{endmarker}]
Bram Moolenaar91359012019-11-30 17:57:03 +0100785{script}
786{endmarker}
787 The `:py3` and `:python3` commands work similar to `:python`. A
788 simple check if the `:py3` command is working: >
789 :py3 print("Hello")
790<
791 To see what version of Python you have: >
792 :py3 import sys
793 :py3 print(sys.version)
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200794< *:py3file*
Bram Moolenaar91359012019-11-30 17:57:03 +0100795:[range]py3f[ile] {file}
796 The `:py3file` command works similar to `:pyfile`.
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +0200797 *:py3do*
Bram Moolenaar91359012019-11-30 17:57:03 +0100798:[range]py3do {body}
799 The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200800
Bram Moolenaar30b65812012-07-12 22:01:11 +0200801
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200802Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02008031. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02008042. Python 2 support only (+python or +python/dyn, -python3)
8053. Python 3 support only (-python, +python3 or +python3/dyn)
8064. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200807
Bram Moolenaar9ba7e172013-07-17 22:37:26 +0200808Some more details on the special case 4: *python-2-and-3*
Bram Moolenaarede981a2010-08-11 23:37:32 +0200809
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200810When Python 2 and Python 3 are both supported they must be loaded dynamically.
811
812When doing this on Linux/Unix systems and importing global symbols, this leads
813to a crash when the second Python version is used. So either global symbols
814are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200815loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200816symbols to be provided by Vim.
817 *E836* *E837*
818Vim's configuration script makes a guess for all libraries based on one
819standard Python library (termios). If importing this library succeeds for
820both Python versions, then both will be made available in Vim at the same
821time. If not, only the version first used in a session will be enabled.
822When trying to use the other one you will get the E836 or E837 error message.
823
824Here Vim's behavior depends on the system in which it was configured. In a
825system where both versions of Python were configured with --enable-shared,
826both versions of Python will be activated at the same time. There will still
827be problems with other third party libraries that were not linked to
828libPython.
829
830To work around such problems there are these options:
8311. The problematic library is recompiled to link to the according
832 libpython.so.
8332. Vim is recompiled for only one Python version.
8343. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
835 may crash Vim though.
836
Bram Moolenaar41009372013-07-01 22:03:04 +0200837 *E880*
838Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
839 :py vim.command("qall!")
840<
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000841 *E1266*
842This error can occur when python 3 cannot load the required modules. This
843means that your python 3 is not correctly installed or there are some mistakes
844in your settings. Please check the following items:
8451. Make sure that python 3 is correctly installed. Also check the version of
846 python.
8472. Check the 'pythonthreedll' option.
8483. Check the 'pythonthreehome' option.
8494. Check the PATH environment variable if you don't set 'pythonthreedll'.
850 On MS-Windows, you can use where.exe to check which dll will be loaded.
851 E.g. >
852 where.exe python310.dll
8535. Check the PYTHONPATH and PYTHONHOME environment variables.
Bram Moolenaar41009372013-07-01 22:03:04 +0200854
Bram Moolenaar446beb42011-05-10 17:18:44 +0200855 *has-python*
856You can test what Python version is available with: >
857 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200858 echo 'there is Python 2.x'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100859 endif
860 if has('python3')
Bram Moolenaar446beb42011-05-10 17:18:44 +0200861 echo 'there is Python 3.x'
862 endif
863
864Note however, that when Python 2 and 3 are both available and loaded
865dynamically, these has() calls will try to load them. If only one can be
866loaded at a time, just checking if Python 2 or 3 are available will prevent
867the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200868
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100869To avoid loading the dynamic library, only check if Vim was compiled with
870python support: >
871 if has('python_compiled')
872 echo 'compiled with Python 2.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100873 if has('python_dynamic')
874 echo 'Python 2.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100875 endif
876 endif
877 if has('python3_compiled')
878 echo 'compiled with Python 3.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100879 if has('python3_dynamic')
880 echo 'Python 3.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100881 endif
882 endif
883
884This also tells you whether Python is dynamically loaded, which will fail if
885the runtime library cannot be found.
886
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200887==============================================================================
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +010088811. Python X *python_x* *pythonx*
889
890Because most python code can be written so that it works with python 2.6+ and
Bram Moolenaar214641f2017-03-05 17:04:09 +0100891python 3 the pyx* functions and commands have been written. They work exactly
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100892the same as the Python 2 and 3 variants, but select the Python version using
893the 'pyxversion' setting.
894
895You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3
896for Python commands. If you change this setting at runtime you may risk that
897state of plugins (such as initialization) may be lost.
898
899If you want to use a module, you can put it in the {rtp}/pythonx directory.
900See |pythonx-directory|.
901
902 *:pyx* *:pythonx*
903The `:pyx` and `:pythonx` commands work similar to `:python`. A simple check
904if the `:pyx` command is working: >
905 :pyx print("Hello")
906
907To see what version of Python is being used: >
908 :pyx import sys
909 :pyx print(sys.version)
910<
911 *:pyxfile* *python_x-special-comments*
912The `:pyxfile` command works similar to `:pyfile`. However you can add one of
913these comments to force Vim using `:pyfile` or `:py3file`: >
914 #!/any string/python2 " Shebang. Must be the first line of the file.
915 #!/any string/python3 " Shebang. Must be the first line of the file.
916 # requires python 2.x " Maximum lines depend on 'modelines'.
917 # requires python 3.x " Maximum lines depend on 'modelines'.
918Unlike normal modelines, the bottom of the file is not checked.
919If none of them are found, the 'pyxversion' setting is used.
920 *W20* *W21*
921If Vim does not support the selected Python version a silent message will be
922printed. Use `:messages` to read them.
923
924 *:pyxdo*
925The `:pyxdo` command works similar to `:pydo`.
926
927 *has-pythonx*
928You can test if pyx* commands are available with: >
929 if has('pythonx')
Bram Moolenaarc51cf032022-02-26 12:25:45 +0000930 echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100931 endif
932
933When compiled with only one of |+python| or |+python3|, the has() returns 1.
934When compiled with both |+python| and |+python3|, the test depends on the
935'pyxversion' setting. If 'pyxversion' is 0, it tests Python 3 first, and if
936it is not available then Python 2. If 'pyxversion' is 2 or 3, it tests only
937Python 2 or 3 respectively.
938
Bram Moolenaar214641f2017-03-05 17:04:09 +0100939Note that for `has('pythonx')` to work it may try to dynamically load Python 3
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100940or 2. This may have side effects, especially when Vim can only load one of
941the two.
942
943If a user prefers Python 2 and want to fallback to Python 3, he needs to set
944'pyxversion' explicitly in his |.vimrc|. E.g.: >
945 if has('python')
946 set pyx=2
947 elseif has('python3')
948 set pyx=3
949 endif
950
951==============================================================================
Bram Moolenaar036986f2017-03-16 17:41:02 +010095212. Building with Python support *python-building*
953
954A few hints for building with Python 2 or 3 support.
955
956UNIX
957
958See src/Makefile for how to enable including the Python interface.
959
960On Ubuntu you will want to install these packages for Python 2:
961 python
962 python-dev
963For Python 3:
964 python3
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200965 python3-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +0100966For Python 3.6:
967 python3.6
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200968 python3.6-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +0100969
970If you have more than one version of Python 3, you need to link python3 to the
971one you prefer, before running configure.
972
973==============================================================================
Bram Moolenaar91f84f62018-07-29 15:07:52 +0200974 vim:tw=78:ts=8:noet:ft=help:norl: