blob: 86d9ac2615c8f94e220dff17e25e7aa1b93c7511 [file] [log] [blame]
Bram Moolenaarb1c91982018-05-17 17:04:55 +02001*if_pyth.txt* For Vim version 8.1. Last change: 2018 Jan 30
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
22{Vi does not have any of these commands}
23
Bram Moolenaar368373e2010-07-19 20:46:22 +020024The Python 2.x interface is available only when Vim was compiled with the
Bram Moolenaar071d4272004-06-13 20:20:40 +000025|+python| feature.
Bram Moolenaar368373e2010-07-19 20:46:22 +020026The Python 3 interface is available only when Vim was compiled with the
27|+python3| feature.
Bram Moolenaar9ba7e172013-07-17 22:37:26 +020028Both can be available at the same time, but read |python-2-and-3|.
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
30==============================================================================
311. Commands *python-commands*
32
Bram Moolenaardbc28022014-07-26 13:40:44 +020033 *:python* *:py* *E263* *E264* *E887*
Bram Moolenaar071d4272004-06-13 20:20:40 +000034:[range]py[thon] {stmt}
Bram Moolenaar9b451252012-08-15 17:43:31 +020035 Execute Python statement {stmt}. A simple check if
36 the `:python` command is working: >
37 :python print "Hello"
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39:[range]py[thon] << {endmarker}
40{script}
41{endmarker}
42 Execute Python script {script}.
43 Note: This command doesn't work when the Python
44 feature wasn't compiled in. To avoid errors, see
45 |script-here|.
46
47{endmarker} must NOT be preceded by any white space. If {endmarker} is
48omitted from after the "<<", a dot '.' must be used after {script}, like
49for the |:append| and |:insert| commands.
50This form of the |:python| command is mainly useful for including python code
51in Vim scripts.
52
53Example: >
54 function! IcecreamInitialize()
55 python << EOF
56 class StrawberryIcecream:
57 def __call__(self):
58 print 'EAT ME'
59 EOF
60 endfunction
Bram Moolenaar64d8e252016-09-06 22:12:34 +020061
62To see what version of Python you have: >
Bram Moolenaar64d8e252016-09-06 22:12:34 +020063 :python print(sys.version)
64
Bram Moolenaar95bafa22018-10-02 13:26:25 +020065There is no need to import sys, it's done by default.
66
Bram Moolenaara3e6bc92013-01-30 14:18:00 +010067Note: Python is very sensitive to the indenting. Make sure the "class" line
68and "EOF" do not have any indent.
Bram Moolenaar071d4272004-06-13 20:20:40 +000069
Bram Moolenaard620aa92013-05-17 16:40:06 +020070 *:pydo*
71:[range]pydo {body} Execute Python function "def _vim_pydo(line, linenr):
72 {body}" for each line in the [range], with the
73 function arguments being set to the text of each line
74 in turn, without a trailing <EOL>, and the current
75 line number. The function should return a string or
76 None. If a string is returned, it becomes the text of
77 the line in the current turn. The default for [range]
78 is the whole file: "1,$".
79 {not in Vi}
80
81Examples:
82>
83 :pydo return "%s\t%d" % (line[::-1], len(line))
84 :pydo if line: return "%4d: %s" % (linenr, line)
85<
Bram Moolenaar20aac6c2018-09-02 21:07:30 +020086One can use `:pydo` in possible conjunction with `:py` to filter a range using
87python. For example: >
88
89 :py3 << EOF
90 needle = vim.eval('@a')
91 replacement = vim.eval('@b')
92
93 def py_vim_string_replace(str):
94 return str.replace(needle, replacement)
95 EOF
96 :'<,'>py3do return py_vim_string_replace(line)
97<
Bram Moolenaar071d4272004-06-13 20:20:40 +000098 *:pyfile* *:pyf*
99:[range]pyf[ile] {file}
100 Execute the Python script in {file}. The whole
101 argument is used as a single file name. {not in Vi}
102
103Both of these commands do essentially the same thing - they execute a piece of
104Python code, with the "current range" |python-range| set to the given line
105range.
106
107In the case of :python, the code to execute is in the command-line.
108In the case of :pyfile, the code to execute is the contents of the given file.
109
110Python commands cannot be used in the |sandbox|.
111
112To pass arguments you need to set sys.argv[] explicitly. Example: >
113
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114 :python sys.argv = ["foo", "bar"]
115 :pyfile myscript.py
116
117Here are some examples *python-examples* >
118
119 :python from vim import *
120 :python from string import upper
121 :python current.line = upper(current.line)
122 :python print "Hello"
123 :python str = current.buffer[42]
124
125(Note that changes - like the imports - persist from one command to the next,
126just like in the Python interpreter.)
127
128==============================================================================
1292. The vim module *python-vim*
130
131Python code gets all of its access to vim (with one exception - see
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000132|python-output| below) via the "vim" module. The vim module implements two
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133methods, three constants, and one error object. You need to import the vim
134module before using it: >
135 :python import vim
136
137Overview >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000138 :py print "Hello" # displays a message
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +0100139 :py vim.command(cmd) # execute an Ex command
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000140 :py w = vim.windows[n] # gets window "n"
141 :py cw = vim.current.window # gets the current window
142 :py b = vim.buffers[n] # gets buffer "n"
143 :py cb = vim.current.buffer # gets the current buffer
144 :py w.height = lines # sets the window height
145 :py w.cursor = (row, col) # sets the window cursor position
146 :py pos = w.cursor # gets a tuple (row, col)
147 :py name = b.name # gets the buffer file name
148 :py line = b[n] # gets a line from the buffer
149 :py lines = b[n:m] # gets a list of lines
150 :py num = len(b) # gets the number of lines
151 :py b[n] = str # sets a line in the buffer
152 :py b[n:m] = [str1, str2, str3] # sets a number of lines at once
153 :py del b[n] # deletes a line
154 :py del b[n:m] # deletes a number of lines
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155
156
157Methods of the "vim" module
158
159vim.command(str) *python-command*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000160 Executes the vim (ex-mode) command str. Returns None.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000162 :py vim.command("set tw=72")
163 :py vim.command("%s/aaa/bbb/g")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164< The following definition executes Normal mode commands: >
165 def normal(str):
166 vim.command("normal "+str)
167 # Note the use of single quotes to delimit a string containing
168 # double quotes
169 normal('"a2dd"aP')
170< *E659*
171 The ":python" command cannot be used recursively with Python 2.2 and
172 older. This only works with Python 2.3 and later: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000173 :py vim.command("python print 'Hello again Python'")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174
175vim.eval(str) *python-eval*
176 Evaluates the expression str using the vim internal expression
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000177 evaluator (see |expression|). Returns the expression result as:
178 - a string if the Vim expression evaluates to a string or number
179 - a list if the Vim expression evaluates to a Vim list
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000180 - a dictionary if the Vim expression evaluates to a Vim dictionary
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000181 Dictionaries and lists are recursively expanded.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182 Examples: >
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200183 :" value of the 'textwidth' option
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000184 :py text_width = vim.eval("&tw")
Bram Moolenaarfc65cab2018-08-28 22:58:02 +0200185 :
186 :" contents of the 'a' register
187 :py a_reg = vim.eval("@a")
188 :
189 :" Result is a string! Use string.atoi() to convert to a number.
190 :py str = vim.eval("12+12")
191 :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000192 :py tagList = vim.eval('taglist("eval_expr")')
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000193< The latter will return a python list of python dicts, for instance:
Bram Moolenaar214641f2017-03-05 17:04:09 +0100194 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name': ~
195 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}] ~
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000196
Bram Moolenaar30b65812012-07-12 22:01:11 +0200197vim.bindeval(str) *python-bindeval*
Bram Moolenaara9922d62013-05-30 13:01:18 +0200198 Like |python-eval|, but returns special objects described in
199 |python-bindeval-objects|. These python objects let you modify (|List|
Bram Moolenaarde71b562013-06-02 17:41:54 +0200200 or |Dictionary|) or call (|Funcref|) vim objects.
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000201
Bram Moolenaarbc411962013-06-02 17:46:40 +0200202vim.strwidth(str) *python-strwidth*
203 Like |strwidth()|: returns number of display cells str occupies, tab
204 is counted as one cell.
205
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200206vim.foreach_rtp(callable) *python-foreach_rtp*
207 Call the given callable for each path in 'runtimepath' until either
208 callable returns something but None, the exception is raised or there
209 are no longer paths. If stopped in case callable returned non-None,
210 vim.foreach_rtp function returns the value returned by callable.
211
Bram Moolenaarf4258302013-06-02 18:20:17 +0200212vim.chdir(*args, **kwargs) *python-chdir*
213vim.fchdir(*args, **kwargs) *python-fchdir*
214 Run os.chdir or os.fchdir, then all appropriate vim stuff.
215 Note: you should not use these functions directly, use os.chdir and
216 os.fchdir instead. Behavior of vim.fchdir is undefined in case
217 os.fchdir does not exist.
218
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219Error object of the "vim" module
220
221vim.error *python-error*
222 Upon encountering a Vim error, Python raises an exception of type
223 vim.error.
224 Example: >
225 try:
226 vim.command("put a")
227 except vim.error:
228 # nothing in register a
229
230Constants of the "vim" module
231
232 Note that these are not actually constants - you could reassign them.
233 But this is silly, as you would then lose access to the vim objects
234 to which the variables referred.
235
236vim.buffers *python-buffers*
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200237 A mapping object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000239 :py b = vim.buffers[i] # Indexing (read-only)
240 :py b in vim.buffers # Membership test
241 :py n = len(vim.buffers) # Number of elements
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200242 :py for b in vim.buffers: # Iterating over buffer list
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243<
244vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000245 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000247 :py w = vim.windows[i] # Indexing (read-only)
248 :py w in vim.windows # Membership test
249 :py n = len(vim.windows) # Number of elements
250 :py for w in vim.windows: # Sequential access
Bram Moolenaarde71b562013-06-02 17:41:54 +0200251< Note: vim.windows object always accesses current tab page.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200252 |python-tabpage|.windows objects are bound to parent |python-tabpage|
253 object and always use windows from that tab page (or throw vim.error
254 in case tab page was deleted). You can keep a reference to both
255 without keeping a reference to vim module object or |python-tabpage|,
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200256 they will not lose their properties in this case.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200257
258vim.tabpages *python-tabpages*
259 A sequence object providing access to the list of vim tab pages. The
260 object supports the following operations: >
261 :py t = vim.tabpages[i] # Indexing (read-only)
262 :py t in vim.tabpages # Membership test
263 :py n = len(vim.tabpages) # Number of elements
264 :py for t in vim.tabpages: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265<
266vim.current *python-current*
267 An object providing access (via specific attributes) to various
268 "current" objects available in vim:
269 vim.current.line The current line (RW) String
Bram Moolenaare7614592013-05-15 15:51:08 +0200270 vim.current.buffer The current buffer (RW) Buffer
271 vim.current.window The current window (RW) Window
272 vim.current.tabpage The current tab page (RW) TabPage
Bram Moolenaar071d4272004-06-13 20:20:40 +0000273 vim.current.range The current line range (RO) Range
274
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000275 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000277 "current range". A range is a bit like a buffer, but with all access
278 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279
Bram Moolenaare7614592013-05-15 15:51:08 +0200280 Note: When assigning to vim.current.{buffer,window,tabpage} it expects
281 valid |python-buffer|, |python-window| or |python-tabpage| objects
282 respectively. Assigning triggers normal (with |autocommand|s)
283 switching to given buffer, window or tab page. It is the only way to
284 switch UI objects in python: you can't assign to
285 |python-tabpage|.window attribute. To switch without triggering
286 autocommands use >
287 py << EOF
288 saved_eventignore = vim.options['eventignore']
289 vim.options['eventignore'] = 'all'
290 try:
291 vim.current.buffer = vim.buffers[2] # Switch to buffer 2
292 finally:
293 vim.options['eventignore'] = saved_eventignore
294 EOF
295<
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200296vim.vars *python-vars*
297vim.vvars *python-vvars*
298 Dictionary-like objects holding dictionaries with global (|g:|) and
299 vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
300 but faster.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000301
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200302vim.options *python-options*
303 Object partly supporting mapping protocol (supports setting and
304 getting items) providing a read-write access to global options.
305 Note: unlike |:set| this provides access only to global options. You
306 cannot use this object to obtain or set local options' values or
307 access local-only options in any fashion. Raises KeyError if no global
308 option with such name exists (i.e. does not raise KeyError for
309 |global-local| options and global only options, but does for window-
310 and buffer-local ones). Use |python-buffer| objects to access to
311 buffer-local options and |python-window| objects to access to
312 window-local options.
313
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200314 Type of this object is available via "Options" attribute of vim
315 module.
316
Bram Moolenaar071d4272004-06-13 20:20:40 +0000317Output from Python *python-output*
318 Vim displays all Python code output in the Vim message area. Normal
319 output appears as information messages, and error output appears as
320 error messages.
321
322 In implementation terms, this means that all output to sys.stdout
323 (including the output from print statements) appears as information
324 messages, and all output to sys.stderr (including error tracebacks)
325 appears as error messages.
326
327 *python-input*
328 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000329 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000330 fixed.
331
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200332 *python2-directory* *python3-directory* *pythonx-directory*
333Python 'runtimepath' handling *python-special-path*
334
335In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
336the list of paths found in 'runtimepath': with this directory in sys.path and
337vim.path_hooks in sys.path_hooks python will try to load module from
338{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
339each {rtp} found in 'runtimepath'.
340
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200341Implementation is similar to the following, but written in C: >
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200342
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200343 from imp import find_module, load_module
344 import vim
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200345 import sys
346
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200347 class VimModuleLoader(object):
348 def __init__(self, module):
349 self.module = module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200350
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200351 def load_module(self, fullname, path=None):
352 return self.module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200353
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200354 def _find_module(fullname, oldtail, path):
355 idx = oldtail.find('.')
356 if idx > 0:
357 name = oldtail[:idx]
358 tail = oldtail[idx+1:]
359 fmr = find_module(name, path)
360 module = load_module(fullname[:-len(oldtail)] + name, *fmr)
361 return _find_module(fullname, tail, module.__path__)
362 else:
363 fmr = find_module(fullname, path)
364 return load_module(fullname, *fmr)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200365
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200366 # It uses vim module itself in place of VimPathFinder class: it does not
367 # matter for python which object has find_module function attached to as
368 # an attribute.
369 class VimPathFinder(object):
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200370 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200371 def find_module(cls, fullname, path=None):
372 try:
373 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
374 except ImportError:
375 return None
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200376
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200377 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200378 def load_module(cls, fullname, path=None):
379 return _find_module(fullname, fullname, path or vim._get_paths())
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200380
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200381 def hook(path):
382 if path == vim.VIM_SPECIAL_PATH:
383 return VimPathFinder
384 else:
385 raise ImportError
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200386
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200387 sys.path_hooks.append(hook)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200388
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200389vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
390 String constant used in conjunction with vim path hook. If path hook
391 installed by vim is requested to handle anything but path equal to
392 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
393 case it uses special loader.
394
395 Note: you must not use value of this constant directly, always use
396 vim.VIM_SPECIAL_PATH object.
397
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200398vim.find_module(...) *python-find_module*
399vim.path_hook(path) *python-path_hook*
400 Methods or objects used to implement path loading as described above.
401 You should not be using any of these directly except for vim.path_hook
402 in case you need to do something with sys.meta_path. It is not
403 guaranteed that any of the objects will exist in the future vim
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200404 versions.
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200405
406vim._get_paths *python-_get_paths*
407 Methods returning a list of paths which will be searched for by path
408 hook. You should not rely on this method being present in future
409 versions, but can use it for debugging.
410
411 It returns a list of {rtp}/python2 (or {rtp}/python3) and
412 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
413
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414==============================================================================
4153. Buffer objects *python-buffer*
416
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000417Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 - via vim.current.buffer (|python-current|)
419 - from indexing vim.buffers (|python-buffers|)
420 - from the "buffer" attribute of a window (|python-window|)
421
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100422Buffer objects have two read-only attributes - name - the full file name for
423the buffer, and number - the buffer number. They also have three methods
424(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000426You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000428element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000430you would expect. Note that the result of indexing (slicing) a buffer is a
431string (list of strings). This has one unusual consequence - b[:] is different
432from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433"b = None" merely updates the variable b, with no effect on the buffer.
434
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000435Buffer indexes start at zero, as is normal in Python. This differs from vim
436line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437with marks (see below) which use vim line numbers.
438
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200439The buffer object attributes are:
440 b.vars Dictionary-like object used to access
441 |buffer-variable|s.
442 b.options Mapping object (supports item getting, setting and
443 deleting) that provides access to buffer-local options
444 and buffer-local values of |global-local| options. Use
445 |python-window|.options if option is window-local,
446 this object will raise KeyError. If option is
447 |global-local| and local value is missing getting it
448 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200449 b.name String, RW. Contains buffer name (full path).
450 Note: when assigning to b.name |BufFilePre| and
451 |BufFilePost| autocommands are launched.
452 b.number Buffer number. Can be used as |python-buffers| key.
453 Read-only.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200454 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200455 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200456
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457The buffer object methods are:
458 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200459 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 b.append(list) Append a list of lines to the buffer
461 Note that the option of supplying a list of strings to
462 the append method differs from the equivalent method
463 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200464 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 b.mark(name) Return a tuple (row,col) representing the position
466 of the named mark (can also get the []"<> marks)
467 b.range(s,e) Return a range object (see |python-range|) which
468 represents the part of the given buffer between line
469 numbers s and e |inclusive|.
470
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000471Note that when adding a line it must not contain a line break character '\n'.
472A trailing '\n' is allowed and ignored, so that you can do: >
473 :py b.append(f.readlines())
474
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200475Buffer object type is available using "Buffer" attribute of vim module.
476
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000478 :py print b.name # write the buffer file name
479 :py b[0] = "hello!!!" # replace the top line
480 :py b[:] = None # delete the whole buffer
481 :py del b[:] # delete the whole buffer
482 :py b[0:0] = [ "a line" ] # add a line at the top
483 :py del b[2] # delete a line (the third)
484 :py b.append("bottom") # add a line at the bottom
485 :py n = len(b) # number of lines
486 :py (row,col) = b.mark('a') # named mark
487 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200488 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200489 :py b.options["ff"] = "dos" # set fileformat
490 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491
492==============================================================================
4934. Range objects *python-range*
494
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000495Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496number of ways:
497 - via vim.current.range (|python-current|)
498 - from a buffer's range() method (|python-buffer|)
499
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000500A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501all operations are restricted to the lines within the range (this line range
502can, of course, change as a result of slice assignments, line deletions, or
503the range.append() method).
504
505The range object attributes are:
506 r.start Index of first line into the buffer
507 r.end Index of last line into the buffer
508
509The range object methods are:
510 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200511 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512 r.append(list) Append a list of lines to the range
513 Note that the option of supplying a list of strings to
514 the append method differs from the equivalent method
515 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200516 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200518Range object type is available using "Range" attribute of vim module.
519
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520Example (assume r is the current range):
521 # Send all lines in a range to the default printer
522 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
523
524==============================================================================
5255. Window objects *python-window*
526
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000527Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528 - via vim.current.window (|python-current|)
529 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200530 - from indexing "windows" attribute of a tab page (|python-tabpage|)
531 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000533You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534methods, and no sequence or other interface.
535
536Window attributes are:
537 buffer (read-only) The buffer displayed in this window
538 cursor (read-write) The current cursor position in the window
539 This is a tuple, (row,col).
540 height (read-write) The window height, in rows
541 width (read-write) The window width, in columns
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200542 vars (read-only) The window |w:| variables. Attribute is
543 unassignable, but you can change window
544 variables this way
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200545 options (read-only) The window-local options. Attribute is
546 unassignable, but you can change window
547 options this way. Provides access only to
548 window-local options, for buffer-local use
549 |python-buffer| and for global ones use
550 |python-options|. If option is |global-local|
551 and local value is missing getting it will
552 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200553 number (read-only) Window number. The first window has number 1.
554 This is zero in case it cannot be determined
555 (e.g. when the window object belongs to other
556 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200557 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200558 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200559 tabpage (read-only) Window tab page.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200560 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200561 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200562
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563The height attribute is writable only if the screen is split horizontally.
564The width attribute is writable only if the screen is split vertically.
565
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200566Window object type is available using "Window" attribute of vim module.
567
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005696. Tab page objects *python-tabpage*
570
571Tab page objects represent vim tab pages. You can obtain them in a number of
572ways:
573 - via vim.current.tabpage (|python-current|)
574 - from indexing vim.tabpages (|python-tabpages|)
575
576You can use this object to access tab page windows. They have no methods and
577no sequence or other interfaces.
578
579Tab page attributes are:
580 number The tab page number like the one returned by
581 |tabpagenr()|.
582 windows Like |python-windows|, but for current tab page.
583 vars The tab page |t:| variables.
584 window Current tabpage window.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200585 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200586 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200587
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200588TabPage object type is available using "TabPage" attribute of vim module.
589
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200590==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02005917. vim.bindeval objects *python-bindeval-objects*
592
593vim.Dictionary object *python-Dictionary*
594 Dictionary-like object providing access to vim |Dictionary| type.
595 Attributes:
596 Attribute Description ~
597 locked One of *python-.locked*
598 Value Description ~
599 zero Variable is not locked
600 vim.VAR_LOCKED Variable is locked, but can be unlocked
601 vim.VAR_FIXED Variable is locked and can't be unlocked
602 Read-write. You can unlock locked variable by assigning
603 `True` or `False` to this attribute. No recursive locking
604 is supported.
605 scope One of
606 Value Description ~
607 zero Dictionary is not a scope one
608 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
609 vim.VAR_SCOPE Other scope dictionary,
610 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200611 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200612 Method Description ~
613 keys() Returns a list with dictionary keys.
614 values() Returns a list with dictionary values.
615 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200616 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200617 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200618 get(key[, default=None])
619 Obtain key from dictionary, returning the default if it is
620 not present.
621 pop(key[, default])
622 Remove specified key from dictionary and return
623 corresponding value. If key is not found and default is
624 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200625 popitem()
626 Remove random key from dictionary and return (key, value)
627 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200628 has_key(key)
629 Check whether dictionary contains specified key, similar
630 to `key in dict`.
631
632 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
633 You can use `vim.Dictionary()` to create new vim
634 dictionaries. `d=vim.Dictionary(arg)` is the same as
635 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
636 constructs empty dictionary.
637
Bram Moolenaara9922d62013-05-30 13:01:18 +0200638 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200639 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200640 d['a'] = 'b' # Item assignment
641 print d['a'] # getting item
642 d.update({'c': 'd'}) # .update(dictionary)
643 d.update(e='f') # .update(**kwargs)
644 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
645 for key in d.keys(): # .keys()
646 for val in d.values(): # .values()
647 for key, val in d.items(): # .items()
648 print isinstance(d, vim.Dictionary) # True
649 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200650 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200651<
652 Note: when iterating over keys you should not modify dictionary.
653
654vim.List object *python-List*
655 Sequence-like object providing access to vim |List| type.
656 Supports `.locked` attribute, see |python-.locked|. Also supports the
657 following methods:
658 Method Description ~
659 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200660
661 __new__(), __new__(iterable)
662 You can use `vim.List()` to create new vim lists.
663 `l=vim.List(iterable)` is the same as
664 `l=vim.bindeval('[]');l.extend(iterable)`. Without
665 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200666 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200667 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200668 l.extend(['abc', 'def']) # .extend() method
669 print l[1:] # slicing
670 l[:0] = ['ghi', 'jkl'] # slice assignment
671 print l[0] # getting item
672 l[0] = 'mno' # assignment
673 for i in l: # iteration
674 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200675 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200676
677vim.Function object *python-Function*
Bram Moolenaar8110a092016-04-14 15:56:09 +0200678 Function-like object, acting like vim |Funcref| object. Accepts special
679 keyword argument `self`, see |Dictionary-function|. You can also use
680 `vim.Function(name)` constructor, it is the same as
681 `vim.bindeval('function(%s)'%json.dumps(name))`.
682
683 Attributes (read-only):
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200684 Attribute Description ~
685 name Function name.
686 args `None` or a |python-List| object with arguments. Note
687 that this is a copy of the arguments list, constructed
688 each time you request this attribute. Modifications made
689 to the list will be ignored (but not to the containers
690 inside argument list: this is like |copy()| and not
691 |deepcopy()|).
692 self `None` or a |python-Dictionary| object with self
693 dictionary. Note that explicit `self` keyword used when
694 calling resulting object overrides this attribute.
695 auto_rebind Boolean. True if partial created from this Python object
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100696 and stored in the Vim script dictionary should be
697 automatically rebound to the dictionary it is stored in
698 when this dictionary is indexed. Exposes Vim internal
699 difference between `dict.func` (auto_rebind=True) and
700 `function(dict.func,dict)` (auto_rebind=False). This
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200701 attribute makes no sense if `self` attribute is `None`.
Bram Moolenaar8110a092016-04-14 15:56:09 +0200702
Bram Moolenaar2177f9f2016-05-25 20:39:09 +0200703 Constructor additionally accepts `args`, `self` and `auto_rebind`
704 keywords. If `args` and/or `self` argument is given then it constructs
705 a partial, see |function()|. `auto_rebind` is only used when `self`
706 argument is given, otherwise it is assumed to be `True` regardless of
707 whether it was given or not. If `self` is given then it defaults to
708 `False`.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200709
Bram Moolenaara9922d62013-05-30 13:01:18 +0200710 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200711 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200712 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
713 vim.command('''
714 function DictFun() dict
715 return self
716 endfunction
717 ''')
718 f = vim.bindeval('function("DictFun")')
719 print f(self={}) # Like call('DictFun', [], {})
720 print isinstance(f, vim.Function) # True
721
Bram Moolenaar8110a092016-04-14 15:56:09 +0200722 p = vim.Function('DictFun', self={})
723 print f()
724 p = vim.Function('tr', args=['abc', 'a'])
725 print f('b')
726
Bram Moolenaara9922d62013-05-30 13:01:18 +0200727==============================================================================
7288. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200729
730To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
Bram Moolenaarb544f3c2017-02-23 19:03:28 +0100731functions to evaluate Python expressions and pass their values to Vim script.
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100732|pyxeval()| is also available.
Bram Moolenaar30b65812012-07-12 22:01:11 +0200733
Bram Moolenaarde323092017-11-09 19:56:08 +0100734The Python value "None" is converted to v:none.
735
Bram Moolenaar30b65812012-07-12 22:01:11 +0200736==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02007379. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000738
Bram Moolenaard94464e2015-11-02 15:28:18 +0100739On MS-Windows and Unix the Python library can be loaded dynamically. The
740|:version| output then includes |+python/dyn| or |+python3/dyn|.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000741
Bram Moolenaard94464e2015-11-02 15:28:18 +0100742This means that Vim will search for the Python DLL or shared library file only
743when needed. When you don't use the Python interface you don't need it, thus
744you can use Vim without this file.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000745
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100746
747MS-Windows ~
748
749To use the Python interface the Python DLL must be in your search path. In a
750console window type "path" to see what directories are used. The 'pythondll'
751or 'pythonthreedll' option can be also used to specify the Python DLL.
Bram Moolenaara5792f52005-11-23 21:25:05 +0000752
Bram Moolenaar3df01732017-02-17 22:47:16 +0100753The name of the DLL should match the Python version Vim was compiled with.
754Currently the name for Python 2 is "python27.dll", that is for Python 2.7.
Bram Moolenaar59eb0162017-12-10 18:17:44 +0100755That is the default value for 'pythondll'. For Python 3 it is python36.dll
756(Python 3.6). To know for sure edit "gvim.exe" and search for
Bram Moolenaar3df01732017-02-17 22:47:16 +0100757"python\d*.dll\c".
Bram Moolenaara5792f52005-11-23 21:25:05 +0000758
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100759
760Unix ~
761
762The 'pythondll' or 'pythonthreedll' option can be used to specify the Python
763shared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL file
764what were specified at compile time. The version of the shared library must
765match the Python 2.x or Python 3 version Vim was compiled with.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100766
Bram Moolenaara5792f52005-11-23 21:25:05 +0000767==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020076810. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200769
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200770 *:py3* *:python3*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200771The `:py3` and `:python3` commands work similar to `:python`. A simple check
Bram Moolenaarfa13eef2013-02-06 17:34:04 +0100772if the `:py3` command is working: >
Bram Moolenaar9b451252012-08-15 17:43:31 +0200773 :py3 print("Hello")
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200774
Bram Moolenaar64d8e252016-09-06 22:12:34 +0200775To see what version of Python you have: >
776 :py3 import sys
777 :py3 print(sys.version)
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200778< *:py3file*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200779The `:py3file` command works similar to `:pyfile`.
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +0200780 *:py3do*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200781The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200782
Bram Moolenaar30b65812012-07-12 22:01:11 +0200783
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200784Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02007851. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02007862. Python 2 support only (+python or +python/dyn, -python3)
7873. Python 3 support only (-python, +python3 or +python3/dyn)
7884. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200789
Bram Moolenaar9ba7e172013-07-17 22:37:26 +0200790Some more details on the special case 4: *python-2-and-3*
Bram Moolenaarede981a2010-08-11 23:37:32 +0200791
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200792When Python 2 and Python 3 are both supported they must be loaded dynamically.
793
794When doing this on Linux/Unix systems and importing global symbols, this leads
795to a crash when the second Python version is used. So either global symbols
796are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200797loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200798symbols to be provided by Vim.
799 *E836* *E837*
800Vim's configuration script makes a guess for all libraries based on one
801standard Python library (termios). If importing this library succeeds for
802both Python versions, then both will be made available in Vim at the same
803time. If not, only the version first used in a session will be enabled.
804When trying to use the other one you will get the E836 or E837 error message.
805
806Here Vim's behavior depends on the system in which it was configured. In a
807system where both versions of Python were configured with --enable-shared,
808both versions of Python will be activated at the same time. There will still
809be problems with other third party libraries that were not linked to
810libPython.
811
812To work around such problems there are these options:
8131. The problematic library is recompiled to link to the according
814 libpython.so.
8152. Vim is recompiled for only one Python version.
8163. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
817 may crash Vim though.
818
Bram Moolenaar41009372013-07-01 22:03:04 +0200819 *E880*
820Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
821 :py vim.command("qall!")
822<
823
Bram Moolenaar446beb42011-05-10 17:18:44 +0200824 *has-python*
825You can test what Python version is available with: >
826 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200827 echo 'there is Python 2.x'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100828 endif
829 if has('python3')
Bram Moolenaar446beb42011-05-10 17:18:44 +0200830 echo 'there is Python 3.x'
831 endif
832
833Note however, that when Python 2 and 3 are both available and loaded
834dynamically, these has() calls will try to load them. If only one can be
835loaded at a time, just checking if Python 2 or 3 are available will prevent
836the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200837
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100838To avoid loading the dynamic library, only check if Vim was compiled with
839python support: >
840 if has('python_compiled')
841 echo 'compiled with Python 2.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100842 if has('python_dynamic')
843 echo 'Python 2.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100844 endif
845 endif
846 if has('python3_compiled')
847 echo 'compiled with Python 3.x support'
Bram Moolenaar72540672018-02-09 22:00:53 +0100848 if has('python3_dynamic')
849 echo 'Python 3.x dynamically loaded'
Bram Moolenaar40962ec2018-01-28 22:47:25 +0100850 endif
851 endif
852
853This also tells you whether Python is dynamically loaded, which will fail if
854the runtime library cannot be found.
855
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200856==============================================================================
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +010085711. Python X *python_x* *pythonx*
858
859Because most python code can be written so that it works with python 2.6+ and
Bram Moolenaar214641f2017-03-05 17:04:09 +0100860python 3 the pyx* functions and commands have been written. They work exactly
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100861the same as the Python 2 and 3 variants, but select the Python version using
862the 'pyxversion' setting.
863
864You should set 'pyxversion' in your |.vimrc| to prefer Python 2 or Python 3
865for Python commands. If you change this setting at runtime you may risk that
866state of plugins (such as initialization) may be lost.
867
868If you want to use a module, you can put it in the {rtp}/pythonx directory.
869See |pythonx-directory|.
870
871 *:pyx* *:pythonx*
872The `:pyx` and `:pythonx` commands work similar to `:python`. A simple check
873if the `:pyx` command is working: >
874 :pyx print("Hello")
875
876To see what version of Python is being used: >
877 :pyx import sys
878 :pyx print(sys.version)
879<
880 *:pyxfile* *python_x-special-comments*
881The `:pyxfile` command works similar to `:pyfile`. However you can add one of
882these comments to force Vim using `:pyfile` or `:py3file`: >
883 #!/any string/python2 " Shebang. Must be the first line of the file.
884 #!/any string/python3 " Shebang. Must be the first line of the file.
885 # requires python 2.x " Maximum lines depend on 'modelines'.
886 # requires python 3.x " Maximum lines depend on 'modelines'.
887Unlike normal modelines, the bottom of the file is not checked.
888If none of them are found, the 'pyxversion' setting is used.
889 *W20* *W21*
890If Vim does not support the selected Python version a silent message will be
891printed. Use `:messages` to read them.
892
893 *:pyxdo*
894The `:pyxdo` command works similar to `:pydo`.
895
896 *has-pythonx*
897You can test if pyx* commands are available with: >
898 if has('pythonx')
899 echo 'pyx* commands are available. (Python ' . &pyx . ')'
900 endif
901
902When compiled with only one of |+python| or |+python3|, the has() returns 1.
903When compiled with both |+python| and |+python3|, the test depends on the
904'pyxversion' setting. If 'pyxversion' is 0, it tests Python 3 first, and if
905it is not available then Python 2. If 'pyxversion' is 2 or 3, it tests only
906Python 2 or 3 respectively.
907
Bram Moolenaar214641f2017-03-05 17:04:09 +0100908Note that for `has('pythonx')` to work it may try to dynamically load Python 3
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +0100909or 2. This may have side effects, especially when Vim can only load one of
910the two.
911
912If a user prefers Python 2 and want to fallback to Python 3, he needs to set
913'pyxversion' explicitly in his |.vimrc|. E.g.: >
914 if has('python')
915 set pyx=2
916 elseif has('python3')
917 set pyx=3
918 endif
919
920==============================================================================
Bram Moolenaar036986f2017-03-16 17:41:02 +010092112. Building with Python support *python-building*
922
923A few hints for building with Python 2 or 3 support.
924
925UNIX
926
927See src/Makefile for how to enable including the Python interface.
928
929On Ubuntu you will want to install these packages for Python 2:
930 python
931 python-dev
932For Python 3:
933 python3
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200934 python3-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +0100935For Python 3.6:
936 python3.6
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200937 python3.6-dev
Bram Moolenaar036986f2017-03-16 17:41:02 +0100938
939If you have more than one version of Python 3, you need to link python3 to the
940one you prefer, before running configure.
941
942==============================================================================
Bram Moolenaar91f84f62018-07-29 15:07:52 +0200943 vim:tw=78:ts=8:noet:ft=help:norl: