blob: 055a5372df1a6d6dedac4307151fd5bac8a25cbc [file] [log] [blame]
Bram Moolenaar14b69452013-06-29 23:05:20 +02001*if_pyth.txt* For Vim version 7.3. Last change: 2013 Jun 28
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
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200318Implementation is similar to the following, but written in C: >
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200319
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200320 from imp import find_module, load_module
321 import vim
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200322 import sys
323
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200324 class VimModuleLoader(object):
325 def __init__(self, module):
326 self.module = module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200327
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200328 def load_module(self, fullname, path=None):
329 return self.module
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200330
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200331 def _find_module(fullname, oldtail, path):
332 idx = oldtail.find('.')
333 if idx > 0:
334 name = oldtail[:idx]
335 tail = oldtail[idx+1:]
336 fmr = find_module(name, path)
337 module = load_module(fullname[:-len(oldtail)] + name, *fmr)
338 return _find_module(fullname, tail, module.__path__)
339 else:
340 fmr = find_module(fullname, path)
341 return load_module(fullname, *fmr)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200342
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200343 # It uses vim module itself in place of VimPathFinder class: it does not
344 # matter for python which object has find_module function attached to as
345 # an attribute.
346 class VimPathFinder(object):
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200347 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200348 def find_module(cls, fullname, path=None):
349 try:
350 return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
351 except ImportError:
352 return None
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200353
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200354 @classmethod
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200355 def load_module(cls, fullname, path=None):
356 return _find_module(fullname, fullname, path or vim._get_paths())
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200357
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200358 def hook(path):
359 if path == vim.VIM_SPECIAL_PATH:
360 return VimPathFinder
361 else:
362 raise ImportError
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200363
Bram Moolenaar9f3685a2013-06-12 14:20:36 +0200364 sys.path_hooks.append(hook)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200365
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200366vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
367 String constant used in conjunction with vim path hook. If path hook
368 installed by vim is requested to handle anything but path equal to
369 vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
370 case it uses special loader.
371
372 Note: you must not use value of this constant directly, always use
373 vim.VIM_SPECIAL_PATH object.
374
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200375vim.find_module(...) *python-find_module*
376vim.path_hook(path) *python-path_hook*
377 Methods or objects used to implement path loading as described above.
378 You should not be using any of these directly except for vim.path_hook
379 in case you need to do something with sys.meta_path. It is not
380 guaranteed that any of the objects will exist in the future vim
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200381 versions.
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200382
383vim._get_paths *python-_get_paths*
384 Methods returning a list of paths which will be searched for by path
385 hook. You should not rely on this method being present in future
386 versions, but can use it for debugging.
387
388 It returns a list of {rtp}/python2 (or {rtp}/python3) and
389 {rtp}/pythonx directories for each {rtp} in 'runtimepath'.
390
Bram Moolenaar071d4272004-06-13 20:20:40 +0000391==============================================================================
3923. Buffer objects *python-buffer*
393
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000394Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395 - via vim.current.buffer (|python-current|)
396 - from indexing vim.buffers (|python-buffers|)
397 - from the "buffer" attribute of a window (|python-window|)
398
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100399Buffer objects have two read-only attributes - name - the full file name for
400the buffer, and number - the buffer number. They also have three methods
401(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000403You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000405element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000407you would expect. Note that the result of indexing (slicing) a buffer is a
408string (list of strings). This has one unusual consequence - b[:] is different
409from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410"b = None" merely updates the variable b, with no effect on the buffer.
411
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000412Buffer indexes start at zero, as is normal in Python. This differs from vim
413line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414with marks (see below) which use vim line numbers.
415
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200416The buffer object attributes are:
417 b.vars Dictionary-like object used to access
418 |buffer-variable|s.
419 b.options Mapping object (supports item getting, setting and
420 deleting) that provides access to buffer-local options
421 and buffer-local values of |global-local| options. Use
422 |python-window|.options if option is window-local,
423 this object will raise KeyError. If option is
424 |global-local| and local value is missing getting it
425 will return None.
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200426 b.name String, RW. Contains buffer name (full path).
427 Note: when assigning to b.name |BufFilePre| and
428 |BufFilePost| autocommands are launched.
429 b.number Buffer number. Can be used as |python-buffers| key.
430 Read-only.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200431 b.valid True or False. Buffer object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200432 corresponding buffer is wiped out.
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200433
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434The buffer object methods are:
435 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200436 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 b.append(list) Append a list of lines to the buffer
438 Note that the option of supplying a list of strings to
439 the append method differs from the equivalent method
440 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200441 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 b.mark(name) Return a tuple (row,col) representing the position
443 of the named mark (can also get the []"<> marks)
444 b.range(s,e) Return a range object (see |python-range|) which
445 represents the part of the given buffer between line
446 numbers s and e |inclusive|.
447
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000448Note that when adding a line it must not contain a line break character '\n'.
449A trailing '\n' is allowed and ignored, so that you can do: >
450 :py b.append(f.readlines())
451
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200452Buffer object type is available using "Buffer" attribute of vim module.
453
Bram Moolenaar071d4272004-06-13 20:20:40 +0000454Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000455 :py print b.name # write the buffer file name
456 :py b[0] = "hello!!!" # replace the top line
457 :py b[:] = None # delete the whole buffer
458 :py del b[:] # delete the whole buffer
459 :py b[0:0] = [ "a line" ] # add a line at the top
460 :py del b[2] # delete a line (the third)
461 :py b.append("bottom") # add a line at the bottom
462 :py n = len(b) # number of lines
463 :py (row,col) = b.mark('a') # named mark
464 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200465 :py b.vars["foo"] = "bar" # assign b:foo variable
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200466 :py b.options["ff"] = "dos" # set fileformat
467 :py del b.options["ar"] # same as :set autoread<
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468
469==============================================================================
4704. Range objects *python-range*
471
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000472Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473number of ways:
474 - via vim.current.range (|python-current|)
475 - from a buffer's range() method (|python-buffer|)
476
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000477A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478all operations are restricted to the lines within the range (this line range
479can, of course, change as a result of slice assignments, line deletions, or
480the range.append() method).
481
482The range object attributes are:
483 r.start Index of first line into the buffer
484 r.end Index of last line into the buffer
485
486The range object methods are:
487 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200488 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489 r.append(list) Append a list of lines to the range
490 Note that the option of supplying a list of strings to
491 the append method differs from the equivalent method
492 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200493 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000494
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200495Range object type is available using "Range" attribute of vim module.
496
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497Example (assume r is the current range):
498 # Send all lines in a range to the default printer
499 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
500
501==============================================================================
5025. Window objects *python-window*
503
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000504Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 - via vim.current.window (|python-current|)
506 - from indexing vim.windows (|python-windows|)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200507 - from indexing "windows" attribute of a tab page (|python-tabpage|)
508 - from the "window" attribute of a tab page (|python-tabpage|)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000510You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511methods, and no sequence or other interface.
512
513Window attributes are:
514 buffer (read-only) The buffer displayed in this window
515 cursor (read-write) The current cursor position in the window
516 This is a tuple, (row,col).
517 height (read-write) The window height, in rows
518 width (read-write) The window width, in columns
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200519 vars (read-only) The window |w:| variables. Attribute is
520 unassignable, but you can change window
521 variables this way
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200522 options (read-only) The window-local options. Attribute is
523 unassignable, but you can change window
524 options this way. Provides access only to
525 window-local options, for buffer-local use
526 |python-buffer| and for global ones use
527 |python-options|. If option is |global-local|
528 and local value is missing getting it will
529 return None.
Bram Moolenaar6d216452013-05-12 19:00:41 +0200530 number (read-only) Window number. The first window has number 1.
531 This is zero in case it cannot be determined
532 (e.g. when the window object belongs to other
533 tab page).
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200534 row, col (read-only) On-screen window position in display cells.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200535 First position is zero.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200536 tabpage (read-only) Window tab page.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200537 valid (read-write) True or False. Window object becomes invalid
Bram Moolenaarbc411962013-06-02 17:46:40 +0200538 when corresponding window is closed.
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +0200539
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540The height attribute is writable only if the screen is split horizontally.
541The width attribute is writable only if the screen is split vertically.
542
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200543Window object type is available using "Window" attribute of vim module.
544
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545==============================================================================
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005466. Tab page objects *python-tabpage*
547
548Tab page objects represent vim tab pages. You can obtain them in a number of
549ways:
550 - via vim.current.tabpage (|python-current|)
551 - from indexing vim.tabpages (|python-tabpages|)
552
553You can use this object to access tab page windows. They have no methods and
554no sequence or other interfaces.
555
556Tab page attributes are:
557 number The tab page number like the one returned by
558 |tabpagenr()|.
559 windows Like |python-windows|, but for current tab page.
560 vars The tab page |t:| variables.
561 window Current tabpage window.
Bram Moolenaar203d04d2013-06-06 21:36:40 +0200562 valid True or False. Tab page object becomes invalid when
Bram Moolenaarbc411962013-06-02 17:46:40 +0200563 corresponding tab page is closed.
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200564
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200565TabPage object type is available using "TabPage" attribute of vim module.
566
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200567==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02005687. vim.bindeval objects *python-bindeval-objects*
569
570vim.Dictionary object *python-Dictionary*
571 Dictionary-like object providing access to vim |Dictionary| type.
572 Attributes:
573 Attribute Description ~
574 locked One of *python-.locked*
575 Value Description ~
576 zero Variable is not locked
577 vim.VAR_LOCKED Variable is locked, but can be unlocked
578 vim.VAR_FIXED Variable is locked and can't be unlocked
579 Read-write. You can unlock locked variable by assigning
580 `True` or `False` to this attribute. No recursive locking
581 is supported.
582 scope One of
583 Value Description ~
584 zero Dictionary is not a scope one
585 vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
586 vim.VAR_SCOPE Other scope dictionary,
587 see |internal-variables|
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200588 Methods (note: methods do not support keyword arguments):
Bram Moolenaara9922d62013-05-30 13:01:18 +0200589 Method Description ~
590 keys() Returns a list with dictionary keys.
591 values() Returns a list with dictionary values.
592 items() Returns a list of 2-tuples with dictionary contents.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200593 update(iterable), update(dictionary), update(**kwargs)
Bram Moolenaara9922d62013-05-30 13:01:18 +0200594 Adds keys to dictionary.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200595 get(key[, default=None])
596 Obtain key from dictionary, returning the default if it is
597 not present.
598 pop(key[, default])
599 Remove specified key from dictionary and return
600 corresponding value. If key is not found and default is
601 given returns the default, otherwise raises KeyError.
Bram Moolenaarde71b562013-06-02 17:41:54 +0200602 popitem()
603 Remove random key from dictionary and return (key, value)
604 pair.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200605 has_key(key)
606 Check whether dictionary contains specified key, similar
607 to `key in dict`.
608
609 __new__(), __new__(iterable), __new__(dictionary), __new__(update)
610 You can use `vim.Dictionary()` to create new vim
611 dictionaries. `d=vim.Dictionary(arg)` is the same as
612 `d=vim.bindeval('{}');d.update(arg)`. Without arguments
613 constructs empty dictionary.
614
Bram Moolenaara9922d62013-05-30 13:01:18 +0200615 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200616 d = vim.Dictionary(food="bar") # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200617 d['a'] = 'b' # Item assignment
618 print d['a'] # getting item
619 d.update({'c': 'd'}) # .update(dictionary)
620 d.update(e='f') # .update(**kwargs)
621 d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
622 for key in d.keys(): # .keys()
623 for val in d.values(): # .values()
624 for key, val in d.items(): # .items()
625 print isinstance(d, vim.Dictionary) # True
626 for key in d: # Iteration over keys
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200627 class Dict(vim.Dictionary): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200628<
629 Note: when iterating over keys you should not modify dictionary.
630
631vim.List object *python-List*
632 Sequence-like object providing access to vim |List| type.
633 Supports `.locked` attribute, see |python-.locked|. Also supports the
634 following methods:
635 Method Description ~
636 extend(item) Add items to the list.
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200637
638 __new__(), __new__(iterable)
639 You can use `vim.List()` to create new vim lists.
640 `l=vim.List(iterable)` is the same as
641 `l=vim.bindeval('[]');l.extend(iterable)`. Without
642 arguments constructs empty list.
Bram Moolenaara9922d62013-05-30 13:01:18 +0200643 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200644 l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
Bram Moolenaara9922d62013-05-30 13:01:18 +0200645 l.extend(['abc', 'def']) # .extend() method
646 print l[1:] # slicing
647 l[:0] = ['ghi', 'jkl'] # slice assignment
648 print l[0] # getting item
649 l[0] = 'mno' # assignment
650 for i in l: # iteration
651 print isinstance(l, vim.List) # True
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200652 class List(vim.List): # Subclassing
Bram Moolenaara9922d62013-05-30 13:01:18 +0200653
654vim.Function object *python-Function*
655 Function-like object, acting like vim |Funcref| object. Supports `.name`
656 attribute and is callable. Accepts special keyword argument `self`, see
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200657 |Dictionary-function|. You can also use `vim.Function(name)` constructor,
658 it is the same as `vim.bindeval('function(%s)'%json.dumps(name))`.
659
Bram Moolenaara9922d62013-05-30 13:01:18 +0200660 Examples: >
Bram Moolenaar305b2fd2013-05-30 13:32:30 +0200661 f = vim.Function('tr') # Constructor
Bram Moolenaara9922d62013-05-30 13:01:18 +0200662 print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
663 vim.command('''
664 function DictFun() dict
665 return self
666 endfunction
667 ''')
668 f = vim.bindeval('function("DictFun")')
669 print f(self={}) # Like call('DictFun', [], {})
670 print isinstance(f, vim.Function) # True
671
672==============================================================================
6738. pyeval() and py3eval() Vim functions *python-pyeval*
Bram Moolenaar30b65812012-07-12 22:01:11 +0200674
675To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
676functions to evaluate Python expressions and pass their values to VimL.
677
678==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +02006799. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000680
681On MS-Windows the Python library can be loaded dynamically. The |:version|
682output then includes |+python/dyn|.
683
684This means that Vim will search for the Python DLL file only when needed.
685When you don't use the Python interface you don't need it, thus you can use
686Vim without this DLL file.
687
688To use the Python interface the Python DLL must be in your search path. In a
689console window type "path" to see what directories are used.
690
691The name of the DLL must match the Python version Vim was compiled with.
692Currently the name is "python24.dll". That is for Python 2.4. To know for
693sure edit "gvim.exe" and search for "python\d*.dll\c".
694
695==============================================================================
Bram Moolenaara9922d62013-05-30 13:01:18 +020069610. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200697
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200698 *:py3* *:python3*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200699The `:py3` and `:python3` commands work similar to `:python`. A simple check
Bram Moolenaarfa13eef2013-02-06 17:34:04 +0100700if the `:py3` command is working: >
Bram Moolenaar9b451252012-08-15 17:43:31 +0200701 :py3 print("Hello")
702< *:py3file*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200703The `:py3file` command works similar to `:pyfile`.
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200704 *:py3do* *E863*
Bram Moolenaard620aa92013-05-17 16:40:06 +0200705The `:py3do` command works similar to `:pydo`.
Bram Moolenaar3dab2802013-05-15 18:28:13 +0200706
Bram Moolenaar30b65812012-07-12 22:01:11 +0200707
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200708Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02007091. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02007102. Python 2 support only (+python or +python/dyn, -python3)
7113. Python 3 support only (-python, +python3 or +python3/dyn)
7124. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200713
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200714Some more details on the special case 4:
Bram Moolenaarede981a2010-08-11 23:37:32 +0200715
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200716When Python 2 and Python 3 are both supported they must be loaded dynamically.
717
718When doing this on Linux/Unix systems and importing global symbols, this leads
719to a crash when the second Python version is used. So either global symbols
720are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200721loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200722symbols to be provided by Vim.
723 *E836* *E837*
724Vim's configuration script makes a guess for all libraries based on one
725standard Python library (termios). If importing this library succeeds for
726both Python versions, then both will be made available in Vim at the same
727time. If not, only the version first used in a session will be enabled.
728When trying to use the other one you will get the E836 or E837 error message.
729
730Here Vim's behavior depends on the system in which it was configured. In a
731system where both versions of Python were configured with --enable-shared,
732both versions of Python will be activated at the same time. There will still
733be problems with other third party libraries that were not linked to
734libPython.
735
736To work around such problems there are these options:
7371. The problematic library is recompiled to link to the according
738 libpython.so.
7392. Vim is recompiled for only one Python version.
7403. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
741 may crash Vim though.
742
Bram Moolenaar446beb42011-05-10 17:18:44 +0200743 *has-python*
744You can test what Python version is available with: >
745 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200746 echo 'there is Python 2.x'
Bram Moolenaar446beb42011-05-10 17:18:44 +0200747 elseif has('python3')
748 echo 'there is Python 3.x'
749 endif
750
751Note however, that when Python 2 and 3 are both available and loaded
752dynamically, these has() calls will try to load them. If only one can be
753loaded at a time, just checking if Python 2 or 3 are available will prevent
754the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200755
756==============================================================================
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 vim:tw=78:ts=8:ft=help:norl: