blob: c54f564209d2a71db3515119c98d44769ce78e4e [file] [log] [blame]
Bram Moolenaar203d04d2013-06-06 21:36:40 +02001*if_pyth.txt* For Vim version 7.3. Last change: 2013 Jun 02
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 Moolenaar071d4272004-06-13 20:20:40 +000019
20{Vi does not have any of these commands}
21
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 Moolenaar071d4272004-06-13 20:20:40 +000026
27==============================================================================
281. Commands *python-commands*
29
30 *:python* *:py* *E205* *E263* *E264*
31:[range]py[thon] {stmt}
Bram Moolenaar9b451252012-08-15 17:43:31 +020032 Execute Python statement {stmt}. A simple check if
33 the `:python` command is working: >
34 :python print "Hello"
Bram Moolenaar071d4272004-06-13 20:20:40 +000035
36:[range]py[thon] << {endmarker}
37{script}
38{endmarker}
39 Execute Python script {script}.
40 Note: This command doesn't work when the Python
41 feature wasn't compiled in. To avoid errors, see
42 |script-here|.
43
44{endmarker} must NOT be preceded by any white space. If {endmarker} is
45omitted from after the "<<", a dot '.' must be used after {script}, like
46for the |:append| and |:insert| commands.
47This form of the |:python| command is mainly useful for including python code
48in Vim scripts.
49
50Example: >
51 function! IcecreamInitialize()
52 python << EOF
53 class StrawberryIcecream:
54 def __call__(self):
55 print 'EAT ME'
56 EOF
57 endfunction
58<
Bram Moolenaara3e6bc92013-01-30 14:18:00 +010059Note: Python is very sensitive to the indenting. Make sure the "class" line
60and "EOF" do not have any indent.
Bram Moolenaar071d4272004-06-13 20:20:40 +000061
Bram Moolenaard620aa92013-05-17 16:40:06 +020062 *:pydo*
63:[range]pydo {body} Execute Python function "def _vim_pydo(line, linenr):
64 {body}" for each line in the [range], with the
65 function arguments being set to the text of each line
66 in turn, without a trailing <EOL>, and the current
67 line number. The function should return a string or
68 None. If a string is returned, it becomes the text of
69 the line in the current turn. The default for [range]
70 is the whole file: "1,$".
71 {not in Vi}
72
73Examples:
74>
75 :pydo return "%s\t%d" % (line[::-1], len(line))
76 :pydo if line: return "%4d: %s" % (linenr, line)
77<
Bram Moolenaar071d4272004-06-13 20:20:40 +000078 *:pyfile* *:pyf*
79:[range]pyf[ile] {file}
80 Execute the Python script in {file}. The whole
81 argument is used as a single file name. {not in Vi}
82
83Both of these commands do essentially the same thing - they execute a piece of
84Python code, with the "current range" |python-range| set to the given line
85range.
86
87In the case of :python, the code to execute is in the command-line.
88In the case of :pyfile, the code to execute is the contents of the given file.
89
90Python commands cannot be used in the |sandbox|.
91
92To pass arguments you need to set sys.argv[] explicitly. Example: >
93
94 :python import sys
95 :python sys.argv = ["foo", "bar"]
96 :pyfile myscript.py
97
98Here are some examples *python-examples* >
99
100 :python from vim import *
101 :python from string import upper
102 :python current.line = upper(current.line)
103 :python print "Hello"
104 :python str = current.buffer[42]
105
106(Note that changes - like the imports - persist from one command to the next,
107just like in the Python interpreter.)
108
109==============================================================================
1102. The vim module *python-vim*
111
112Python code gets all of its access to vim (with one exception - see
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000113|python-output| below) via the "vim" module. The vim module implements two
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114methods, three constants, and one error object. You need to import the vim
115module before using it: >
116 :python import vim
117
118Overview >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000119 :py print "Hello" # displays a message
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +0100120 :py vim.command(cmd) # execute an Ex command
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000121 :py w = vim.windows[n] # gets window "n"
122 :py cw = vim.current.window # gets the current window
123 :py b = vim.buffers[n] # gets buffer "n"
124 :py cb = vim.current.buffer # gets the current buffer
125 :py w.height = lines # sets the window height
126 :py w.cursor = (row, col) # sets the window cursor position
127 :py pos = w.cursor # gets a tuple (row, col)
128 :py name = b.name # gets the buffer file name
129 :py line = b[n] # gets a line from the buffer
130 :py lines = b[n:m] # gets a list of lines
131 :py num = len(b) # gets the number of lines
132 :py b[n] = str # sets a line in the buffer
133 :py b[n:m] = [str1, str2, str3] # sets a number of lines at once
134 :py del b[n] # deletes a line
135 :py del b[n:m] # deletes a number of lines
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136
137
138Methods of the "vim" module
139
140vim.command(str) *python-command*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000141 Executes the vim (ex-mode) command str. Returns None.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000143 :py vim.command("set tw=72")
144 :py vim.command("%s/aaa/bbb/g")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145< The following definition executes Normal mode commands: >
146 def normal(str):
147 vim.command("normal "+str)
148 # Note the use of single quotes to delimit a string containing
149 # double quotes
150 normal('"a2dd"aP')
151< *E659*
152 The ":python" command cannot be used recursively with Python 2.2 and
153 older. This only works with Python 2.3 and later: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000154 :py vim.command("python print 'Hello again Python'")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155
156vim.eval(str) *python-eval*
157 Evaluates the expression str using the vim internal expression
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000158 evaluator (see |expression|). Returns the expression result as:
159 - a string if the Vim expression evaluates to a string or number
160 - a list if the Vim expression evaluates to a Vim list
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000161 - a dictionary if the Vim expression evaluates to a Vim dictionary
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000162 Dictionaries and lists are recursively expanded.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000164 :py text_width = vim.eval("&tw")
165 :py str = vim.eval("12+12") # NB result is a string! Use
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166 # string.atoi() to convert to
167 # a number.
168
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000169 :py tagList = vim.eval('taglist("eval_expr")')
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000170< The latter will return a python list of python dicts, for instance:
171 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name':
172 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}]
173
Bram Moolenaar30b65812012-07-12 22:01:11 +0200174vim.bindeval(str) *python-bindeval*
Bram Moolenaara9922d62013-05-30 13:01:18 +0200175 Like |python-eval|, but returns special objects described in
176 |python-bindeval-objects|. These python objects let you modify (|List|
Bram Moolenaarde71b562013-06-02 17:41:54 +0200177 or |Dictionary|) or call (|Funcref|) vim objects.
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000178
Bram Moolenaarbc411962013-06-02 17:46:40 +0200179vim.strwidth(str) *python-strwidth*
180 Like |strwidth()|: returns number of display cells str occupies, tab
181 is counted as one cell.
182
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200183vim.foreach_rtp(callable) *python-foreach_rtp*
184 Call the given callable for each path in 'runtimepath' until either
185 callable returns something but None, the exception is raised or there
186 are no longer paths. If stopped in case callable returned non-None,
187 vim.foreach_rtp function returns the value returned by callable.
188
Bram Moolenaarf4258302013-06-02 18:20:17 +0200189vim.chdir(*args, **kwargs) *python-chdir*
190vim.fchdir(*args, **kwargs) *python-fchdir*
191 Run os.chdir or os.fchdir, then all appropriate vim stuff.
192 Note: you should not use these functions directly, use os.chdir and
193 os.fchdir instead. Behavior of vim.fchdir is undefined in case
194 os.fchdir does not exist.
195
Bram Moolenaar071d4272004-06-13 20:20:40 +0000196Error object of the "vim" module
197
198vim.error *python-error*
199 Upon encountering a Vim error, Python raises an exception of type
200 vim.error.
201 Example: >
202 try:
203 vim.command("put a")
204 except vim.error:
205 # nothing in register a
206
207Constants of the "vim" module
208
209 Note that these are not actually constants - you could reassign them.
210 But this is silly, as you would then lose access to the vim objects
211 to which the variables referred.
212
213vim.buffers *python-buffers*
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200214 A mapping object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000216 :py b = vim.buffers[i] # Indexing (read-only)
217 :py b in vim.buffers # Membership test
218 :py n = len(vim.buffers) # Number of elements
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200219 :py for b in vim.buffers: # Iterating over buffer list
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220<
221vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000222 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000223 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000224 :py w = vim.windows[i] # Indexing (read-only)
225 :py w in vim.windows # Membership test
226 :py n = len(vim.windows) # Number of elements
227 :py for w in vim.windows: # Sequential access
Bram Moolenaarde71b562013-06-02 17:41:54 +0200228< Note: vim.windows object always accesses current tab page.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200229 |python-tabpage|.windows objects are bound to parent |python-tabpage|
230 object and always use windows from that tab page (or throw vim.error
231 in case tab page was deleted). You can keep a reference to both
232 without keeping a reference to vim module object or |python-tabpage|,
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200233 they will not lose their properties in this case.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200234
235vim.tabpages *python-tabpages*
236 A sequence object providing access to the list of vim tab pages. The
237 object supports the following operations: >
238 :py t = vim.tabpages[i] # Indexing (read-only)
239 :py t in vim.tabpages # Membership test
240 :py n = len(vim.tabpages) # Number of elements
241 :py for t in vim.tabpages: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000242<
243vim.current *python-current*
244 An object providing access (via specific attributes) to various
245 "current" objects available in vim:
246 vim.current.line The current line (RW) String
Bram Moolenaare7614592013-05-15 15:51:08 +0200247 vim.current.buffer The current buffer (RW) Buffer
248 vim.current.window The current window (RW) Window
249 vim.current.tabpage The current tab page (RW) TabPage
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250 vim.current.range The current line range (RO) Range
251
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000252 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000254 "current range". A range is a bit like a buffer, but with all access
255 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256
Bram Moolenaare7614592013-05-15 15:51:08 +0200257 Note: When assigning to vim.current.{buffer,window,tabpage} it expects
258 valid |python-buffer|, |python-window| or |python-tabpage| objects
259 respectively. Assigning triggers normal (with |autocommand|s)
260 switching to given buffer, window or tab page. It is the only way to
261 switch UI objects in python: you can't assign to
262 |python-tabpage|.window attribute. To switch without triggering
263 autocommands use >
264 py << EOF
265 saved_eventignore = vim.options['eventignore']
266 vim.options['eventignore'] = 'all'
267 try:
268 vim.current.buffer = vim.buffers[2] # Switch to buffer 2
269 finally:
270 vim.options['eventignore'] = saved_eventignore
271 EOF
272<
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200273vim.vars *python-vars*
274vim.vvars *python-vvars*
275 Dictionary-like objects holding dictionaries with global (|g:|) and
276 vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
277 but faster.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000278
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200279vim.options *python-options*
280 Object partly supporting mapping protocol (supports setting and
281 getting items) providing a read-write access to global options.
282 Note: unlike |:set| this provides access only to global options. You
283 cannot use this object to obtain or set local options' values or
284 access local-only options in any fashion. Raises KeyError if no global
285 option with such name exists (i.e. does not raise KeyError for
286 |global-local| options and global only options, but does for window-
287 and buffer-local ones). Use |python-buffer| objects to access to
288 buffer-local options and |python-window| objects to access to
289 window-local options.
290
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200291 Type of this object is available via "Options" attribute of vim
292 module.
293
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294Output from Python *python-output*
295 Vim displays all Python code output in the Vim message area. Normal
296 output appears as information messages, and error output appears as
297 error messages.
298
299 In implementation terms, this means that all output to sys.stdout
300 (including the output from print statements) appears as information
301 messages, and all output to sys.stderr (including error tracebacks)
302 appears as error messages.
303
304 *python-input*
305 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000306 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307 fixed.
308
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200309 *python2-directory* *python3-directory* *pythonx-directory*
310Python 'runtimepath' handling *python-special-path*
311
312In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
313the list of paths found in 'runtimepath': with this directory in sys.path and
314vim.path_hooks in sys.path_hooks python will try to load module from
315{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
316each {rtp} found in 'runtimepath'.
317
318Implementation for python 2 is the following: usual importing code with empty
319lists in place of sys.path_hooks and sys.meta_path. Code is similar to the
320below, but written in C: >
321
322 # Assuming vim variable is already accessible and is set to the current
323 # module
324 import sys
325
326 def find_module(fullname):
327 return vim
328
329 def load_module(fullname):
330 # see vim._get_paths below
331 new_path = _get_paths()
332
333 try: old_path = sys.path
334 except: pass
335 try: old_meta_path = sys.meta_path
336 except: pass
337 try: old_path_hooks = sys.path_hooks
338 except: pass
339
340 sys.meta_path = []
341 sys.path_hooks = sys.meta_path
342 sys.path = new_path
343
344 try:
345 exec ('import ' + fullname + ' as m') # No actual exec in C code
346 return m
347 finally:
348 e = None
349 try: sys.path = old_path
350 except Exception as e: pass
351 try: sys.meta_path = old_meta_path
352 except Exception as e: pass
353 try: sys.path_hooks = old_path_hooks
354 except Exception as e: pass
355 if e:
356 raise e
357
358 def path_hook(d):
359 if d == VIM_SPECIAL_PATH:
360 return vim
361 raise ImportError
362
363 sys.path_hooks.append(path_hook)
364
365Implementation for python 3 is cleaner: code is similar to the following, but,
366again, written in C: >
367
368 from importlib.machinery import PathFinder
369 import sys
370
371 class Finder(PathFinder):
372 @classmethod
373 def find_module(cls, fullname):
374 # see vim._get_paths below
375 new_path = _get_paths()
376
377 # super().find_module is also a class method
378 # super() is not used because this variant is easier to implement
379 # in C
380 return PathFinder.find_module(fullname, new_path)
381
382 def path_hook(path):
383 if path == VIM_SPECIAL_PATH:
384 return Finder
385 raise ImportError
386
387 sys.path_hooks.append(path_hook)
388
389vim.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
398vim.load_module(name) *python-load_module*
399vim.find_module(...) *python-find_module*
400vim.path_hook(path) *python-path_hook*
401 Methods or objects used to implement path loading as described above.
402 You should not be using any of these directly except for vim.path_hook
403 in case you need to do something with sys.meta_path. It is not
404 guaranteed that any of the objects will exist in the future vim
405 versions. In fact, load_module and find_module methods do not exists
406 in python3.
407
408vim._get_paths *python-_get_paths*
409 Methods returning a list of paths which will be searched for by path
410 hook. You should not rely on this method being present in future
411 versions, but can use it for debugging.
412
413 It returns a list of {rtp}/python2 (or {rtp}/python3) and
414 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
415
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416==============================================================================
4173. Buffer objects *python-buffer*
418
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000419Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 - via vim.current.buffer (|python-current|)
421 - from indexing vim.buffers (|python-buffers|)
422 - from the "buffer" attribute of a window (|python-window|)
423
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100424Buffer objects have two read-only attributes - name - the full file name for
425the buffer, and number - the buffer number. They also have three methods
426(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000428You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000430element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000431including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000432you would expect. Note that the result of indexing (slicing) a buffer is a
433string (list of strings). This has one unusual consequence - b[:] is different
434from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435"b = None" merely updates the variable b, with no effect on the buffer.
436
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000437Buffer indexes start at zero, as is normal in Python. This differs from vim
438line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439with marks (see below) which use vim line numbers.
440
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200441The buffer object attributes are:
442 b.vars Dictionary-like object used to access
443 |buffer-variable|s.
444 b.options Mapping object (supports item getting, setting and
445 deleting) that provides access to buffer-local options
446 and buffer-local values of |global-local| options. Use
447 |python-window|.options if option is window-local,
448 this object will raise KeyError. If option is
449 |global-local| and local value is missing getting it
450 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200451 b.name String, RW. Contains buffer name (full path).
452 Note: when assigning to b.name |BufFilePre| and
453 |BufFilePost| autocommands are launched.
454 b.number Buffer number. Can be used as |python-buffers| key.
455 Read-only.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200456 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200457 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200458
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459The buffer object methods are:
460 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200461 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 b.append(list) Append a list of lines to the buffer
463 Note that the option of supplying a list of strings to
464 the append method differs from the equivalent method
465 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200466 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467 b.mark(name) Return a tuple (row,col) representing the position
468 of the named mark (can also get the []"<> marks)
469 b.range(s,e) Return a range object (see |python-range|) which
470 represents the part of the given buffer between line
471 numbers s and e |inclusive|.
472
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000473Note that when adding a line it must not contain a line break character '\n'.
474A trailing '\n' is allowed and ignored, so that you can do: >
475 :py b.append(f.readlines())
476
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200477Buffer object type is available using "Buffer" attribute of vim module.
478
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000480 :py print b.name # write the buffer file name
481 :py b[0] = "hello!!!" # replace the top line
482 :py b[:] = None # delete the whole buffer
483 :py del b[:] # delete the whole buffer
484 :py b[0:0] = [ "a line" ] # add a line at the top
485 :py del b[2] # delete a line (the third)
486 :py b.append("bottom") # add a line at the bottom
487 :py n = len(b) # number of lines
488 :py (row,col) = b.mark('a') # named mark
489 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200490 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200491 :py b.options["ff"] = "dos" # set fileformat
492 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493
494==============================================================================
4954. Range objects *python-range*
496
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000497Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498number of ways:
499 - via vim.current.range (|python-current|)
500 - from a buffer's range() method (|python-buffer|)
501
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000502A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503all operations are restricted to the lines within the range (this line range
504can, of course, change as a result of slice assignments, line deletions, or
505the range.append() method).
506
507The range object attributes are:
508 r.start Index of first line into the buffer
509 r.end Index of last line into the buffer
510
511The range object methods are:
512 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200513 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 r.append(list) Append a list of lines to the range
515 Note that the option of supplying a list of strings to
516 the append method differs from the equivalent method
517 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200518 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200520Range object type is available using "Range" attribute of vim module.
521
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522Example (assume r is the current range):
523 # Send all lines in a range to the default printer
524 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
525
526==============================================================================
5275. Window objects *python-window*
528
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000529Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 - via vim.current.window (|python-current|)
531 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200532 - from indexing "windows" attribute of a tab page (|python-tabpage|)
533 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000535You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536methods, and no sequence or other interface.
537
538Window attributes are:
539 buffer (read-only) The buffer displayed in this window
540 cursor (read-write) The current cursor position in the window
541 This is a tuple, (row,col).
542 height (read-write) The window height, in rows
543 width (read-write) The window width, in columns
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200544 vars (read-only) The window |w:| variables. Attribute is
545 unassignable, but you can change window
546 variables this way
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200547 options (read-only) The window-local options. Attribute is
548 unassignable, but you can change window
549 options this way. Provides access only to
550 window-local options, for buffer-local use
551 |python-buffer| and for global ones use
552 |python-options|. If option is |global-local|
553 and local value is missing getting it will
554 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200555 number (read-only) Window number. The first window has number 1.
556 This is zero in case it cannot be determined
557 (e.g. when the window object belongs to other
558 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200559 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200560 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200561 tabpage (read-only) Window tab page.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200562 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200563 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200564
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565The height attribute is writable only if the screen is split horizontally.
566The width attribute is writable only if the screen is split vertically.
567
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200568Window object type is available using "Window" attribute of vim module.
569
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005716. Tab page objects *python-tabpage*
572
573Tab page objects represent vim tab pages. You can obtain them in a number of
574ways:
575 - via vim.current.tabpage (|python-current|)
576 - from indexing vim.tabpages (|python-tabpages|)
577
578You can use this object to access tab page windows. They have no methods and
579no sequence or other interfaces.
580
581Tab page attributes are:
582 number The tab page number like the one returned by
583 |tabpagenr()|.
584 windows Like |python-windows|, but for current tab page.
585 vars The tab page |t:| variables.
586 window Current tabpage window.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200587 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200588 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200589
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200590TabPage object type is available using "TabPage" attribute of vim module.
591
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200592==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02005937. vim.bindeval objects *python-bindeval-objects*
594
595vim.Dictionary object *python-Dictionary*
596 Dictionary-like object providing access to vim |Dictionary| type.
597 Attributes:
598 Attribute Description ~
599 locked One of *python-.locked*
600 Value Description ~
601 zero Variable is not locked
602 vim.VAR_LOCKED Variable is locked, but can be unlocked
603 vim.VAR_FIXED Variable is locked and can't be unlocked
604 Read-write. You can unlock locked variable by assigning
605 `True` or `False` to this attribute. No recursive locking
606 is supported.
607 scope One of
608 Value Description ~
609 zero Dictionary is not a scope one
610 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
611 vim.VAR_SCOPE Other scope dictionary,
612 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200613 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200614 Method Description ~
615 keys() Returns a list with dictionary keys.
616 values() Returns a list with dictionary values.
617 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200618 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200619 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200620 get(key[, default=None])
621 Obtain key from dictionary, returning the default if it is
622 not present.
623 pop(key[, default])
624 Remove specified key from dictionary and return
625 corresponding value. If key is not found and default is
626 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200627 popitem()
628 Remove random key from dictionary and return (key, value)
629 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200630 has_key(key)
631 Check whether dictionary contains specified key, similar
632 to `key in dict`.
633
634 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
635 You can use `vim.Dictionary()` to create new vim
636 dictionaries. `d=vim.Dictionary(arg)` is the same as
637 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
638 constructs empty dictionary.
639
Bram Moolenaara9922d62013-05-30 13:01:18 +0200640 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200641 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200642 d['a'] = 'b' # Item assignment
643 print d['a'] # getting item
644 d.update({'c': 'd'}) # .update(dictionary)
645 d.update(e='f') # .update(**kwargs)
646 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
647 for key in d.keys(): # .keys()
648 for val in d.values(): # .values()
649 for key, val in d.items(): # .items()
650 print isinstance(d, vim.Dictionary) # True
651 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200652 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200653<
654 Note: when iterating over keys you should not modify dictionary.
655
656vim.List object *python-List*
657 Sequence-like object providing access to vim |List| type.
658 Supports `.locked` attribute, see |python-.locked|. Also supports the
659 following methods:
660 Method Description ~
661 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200662
663 __new__(), __new__(iterable)
664 You can use `vim.List()` to create new vim lists.
665 `l=vim.List(iterable)` is the same as
666 `l=vim.bindeval('[]');l.extend(iterable)`. Without
667 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200668 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200669 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200670 l.extend(['abc', 'def']) # .extend() method
671 print l[1:] # slicing
672 l[:0] = ['ghi', 'jkl'] # slice assignment
673 print l[0] # getting item
674 l[0] = 'mno' # assignment
675 for i in l: # iteration
676 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200677 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200678
679vim.Function object *python-Function*
680 Function-like object, acting like vim |Funcref| object. Supports `.name`
681 attribute and is callable. Accepts special keyword argument `self`, see
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200682 |Dictionary-function|. You can also use `vim.Function(name)` constructor,
683 it is the same as `vim.bindeval('function(%s)'%json.dumps(name))`.
684
Bram Moolenaara9922d62013-05-30 13:01:18 +0200685 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200686 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200687 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
688 vim.command('''
689 function DictFun() dict
690 return self
691 endfunction
692 ''')
693 f = vim.bindeval('function("DictFun")')
694 print f(self={}) # Like call('DictFun', [], {})
695 print isinstance(f, vim.Function) # True
696
697==============================================================================
6988. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200699
700To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
701functions to evaluate Python expressions and pass their values to VimL.
702
703==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02007049. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000705
706On MS-Windows the Python library can be loaded dynamically. The |:version|
707output then includes |+python/dyn|.
708
709This means that Vim will search for the Python DLL file only when needed.
710When you don't use the Python interface you don't need it, thus you can use
711Vim without this DLL file.
712
713To use the Python interface the Python DLL must be in your search path. In a
714console window type "path" to see what directories are used.
715
716The name of the DLL must match the Python version Vim was compiled with.
717Currently the name is "python24.dll". That is for Python 2.4. To know for
718sure edit "gvim.exe" and search for "python\d*.dll\c".
719
720==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020072110. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200722
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200723 *:py3* *:python3*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200724The `:py3` and `:python3` commands work similar to `:python`. A simple check
Bram Moolenaarfa13eef2013-02-06 17:34:04 +0100725if the `:py3` command is working: >
Bram Moolenaar9b451252012-08-15 17:43:31 +0200726 :py3 print("Hello")
727< *:py3file*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200728The `:py3file` command works similar to `:pyfile`.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200729 *:py3do* *E863*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200730The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200731
Bram Moolenaar30b65812012-07-12 22:01:11 +0200732
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200733Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02007341. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02007352. Python 2 support only (+python or +python/dyn, -python3)
7363. Python 3 support only (-python, +python3 or +python3/dyn)
7374. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200738
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200739Some more details on the special case 4:
Bram Moolenaarede981a2010-08-11 23:37:32 +0200740
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200741When Python 2 and Python 3 are both supported they must be loaded dynamically.
742
743When doing this on Linux/Unix systems and importing global symbols, this leads
744to a crash when the second Python version is used. So either global symbols
745are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200746loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200747symbols to be provided by Vim.
748 *E836* *E837*
749Vim's configuration script makes a guess for all libraries based on one
750standard Python library (termios). If importing this library succeeds for
751both Python versions, then both will be made available in Vim at the same
752time. If not, only the version first used in a session will be enabled.
753When trying to use the other one you will get the E836 or E837 error message.
754
755Here Vim's behavior depends on the system in which it was configured. In a
756system where both versions of Python were configured with --enable-shared,
757both versions of Python will be activated at the same time. There will still
758be problems with other third party libraries that were not linked to
759libPython.
760
761To work around such problems there are these options:
7621. The problematic library is recompiled to link to the according
763 libpython.so.
7642. Vim is recompiled for only one Python version.
7653. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
766 may crash Vim though.
767
Bram Moolenaar446beb42011-05-10 17:18:44 +0200768 *has-python*
769You can test what Python version is available with: >
770 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200771 echo 'there is Python 2.x'
Bram Moolenaar446beb42011-05-10 17:18:44 +0200772 elseif has('python3')
773 echo 'there is Python 3.x'
774 endif
775
776Note however, that when Python 2 and 3 are both available and loaded
777dynamically, these has() calls will try to load them. If only one can be
778loaded at a time, just checking if Python 2 or 3 are available will prevent
779the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200780
781==============================================================================
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 vim:tw=78:ts=8:ft=help:norl: