blob: 4bdacf66f2a92aa153b3fbca0b57fd853c65277e [file] [log] [blame]
Bram Moolenaar9b451252012-08-15 17:43:31 +02001*if_pyth.txt* For Vim version 7.3. Last change: 2012 Aug 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|
146. pyeval(), py3eval() Vim functions |python-pyeval|
157. Dynamic loading |python-dynamic|
168. Python 3 |python3|
Bram Moolenaar071d4272004-06-13 20:20:40 +000017
18{Vi does not have any of these commands}
19
Bram Moolenaar368373e2010-07-19 20:46:22 +020020The Python 2.x interface is available only when Vim was compiled with the
Bram Moolenaar071d4272004-06-13 20:20:40 +000021|+python| feature.
Bram Moolenaar368373e2010-07-19 20:46:22 +020022The Python 3 interface is available only when Vim was compiled with the
23|+python3| feature.
Bram Moolenaar071d4272004-06-13 20:20:40 +000024
25==============================================================================
261. Commands *python-commands*
27
28 *:python* *:py* *E205* *E263* *E264*
29:[range]py[thon] {stmt}
Bram Moolenaar9b451252012-08-15 17:43:31 +020030 Execute Python statement {stmt}. A simple check if
31 the `:python` command is working: >
32 :python print "Hello"
Bram Moolenaar071d4272004-06-13 20:20:40 +000033
34:[range]py[thon] << {endmarker}
35{script}
36{endmarker}
37 Execute Python script {script}.
38 Note: This command doesn't work when the Python
39 feature wasn't compiled in. To avoid errors, see
40 |script-here|.
41
42{endmarker} must NOT be preceded by any white space. If {endmarker} is
43omitted from after the "<<", a dot '.' must be used after {script}, like
44for the |:append| and |:insert| commands.
45This form of the |:python| command is mainly useful for including python code
46in Vim scripts.
47
48Example: >
49 function! IcecreamInitialize()
50 python << EOF
51 class StrawberryIcecream:
52 def __call__(self):
53 print 'EAT ME'
54 EOF
55 endfunction
56<
57Note: Python is very sensitive to the indenting. Also make sure the "class"
58line and "EOF" do not have any indent.
59
60 *:pyfile* *:pyf*
61:[range]pyf[ile] {file}
62 Execute the Python script in {file}. The whole
63 argument is used as a single file name. {not in Vi}
64
65Both of these commands do essentially the same thing - they execute a piece of
66Python code, with the "current range" |python-range| set to the given line
67range.
68
69In the case of :python, the code to execute is in the command-line.
70In the case of :pyfile, the code to execute is the contents of the given file.
71
72Python commands cannot be used in the |sandbox|.
73
74To pass arguments you need to set sys.argv[] explicitly. Example: >
75
76 :python import sys
77 :python sys.argv = ["foo", "bar"]
78 :pyfile myscript.py
79
80Here are some examples *python-examples* >
81
82 :python from vim import *
83 :python from string import upper
84 :python current.line = upper(current.line)
85 :python print "Hello"
86 :python str = current.buffer[42]
87
88(Note that changes - like the imports - persist from one command to the next,
89just like in the Python interpreter.)
90
91==============================================================================
922. The vim module *python-vim*
93
94Python code gets all of its access to vim (with one exception - see
Bram Moolenaar402d2fe2005-04-15 21:00:38 +000095|python-output| below) via the "vim" module. The vim module implements two
Bram Moolenaar071d4272004-06-13 20:20:40 +000096methods, three constants, and one error object. You need to import the vim
97module before using it: >
98 :python import vim
99
100Overview >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000101 :py print "Hello" # displays a message
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +0100102 :py vim.command(cmd) # execute an Ex command
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000103 :py w = vim.windows[n] # gets window "n"
104 :py cw = vim.current.window # gets the current window
105 :py b = vim.buffers[n] # gets buffer "n"
106 :py cb = vim.current.buffer # gets the current buffer
107 :py w.height = lines # sets the window height
108 :py w.cursor = (row, col) # sets the window cursor position
109 :py pos = w.cursor # gets a tuple (row, col)
110 :py name = b.name # gets the buffer file name
111 :py line = b[n] # gets a line from the buffer
112 :py lines = b[n:m] # gets a list of lines
113 :py num = len(b) # gets the number of lines
114 :py b[n] = str # sets a line in the buffer
115 :py b[n:m] = [str1, str2, str3] # sets a number of lines at once
116 :py del b[n] # deletes a line
117 :py del b[n:m] # deletes a number of lines
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118
119
120Methods of the "vim" module
121
122vim.command(str) *python-command*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000123 Executes the vim (ex-mode) command str. Returns None.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000125 :py vim.command("set tw=72")
126 :py vim.command("%s/aaa/bbb/g")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127< The following definition executes Normal mode commands: >
128 def normal(str):
129 vim.command("normal "+str)
130 # Note the use of single quotes to delimit a string containing
131 # double quotes
132 normal('"a2dd"aP')
133< *E659*
134 The ":python" command cannot be used recursively with Python 2.2 and
135 older. This only works with Python 2.3 and later: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000136 :py vim.command("python print 'Hello again Python'")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000137
138vim.eval(str) *python-eval*
139 Evaluates the expression str using the vim internal expression
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000140 evaluator (see |expression|). Returns the expression result as:
141 - a string if the Vim expression evaluates to a string or number
142 - a list if the Vim expression evaluates to a Vim list
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000143 - a dictionary if the Vim expression evaluates to a Vim dictionary
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000144 Dictionaries and lists are recursively expanded.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000146 :py text_width = vim.eval("&tw")
147 :py str = vim.eval("12+12") # NB result is a string! Use
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148 # string.atoi() to convert to
149 # a number.
150
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000151 :py tagList = vim.eval('taglist("eval_expr")')
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000152< The latter will return a python list of python dicts, for instance:
153 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name':
154 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}]
155
Bram Moolenaar30b65812012-07-12 22:01:11 +0200156vim.bindeval(str) *python-bindeval*
157 Like |python-eval|, but
158 1. if expression evaluates to |List| or |Dictionary| it is returned as
159 vimlist or vimdictionary python type that are connected to original
160 list or dictionary. Thus modifications to these objects imply
161 modifications of the original.
162 2. if expression evaluates to a function reference, then it returns
163 callable vimfunction object. Use self keyword argument to assign
164 |self| object for dictionary functions.
165
166 Note: this function has the same behavior as |lua-eval| (except that
167 lua does not support running vim functions), |python-eval| is
168 kept for backwards compatibility in order not to make scripts
169 relying on outputs of vim.eval() being a copy of original or
170 vim.eval("1") returning a string.
171
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000172
173
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174Error object of the "vim" module
175
176vim.error *python-error*
177 Upon encountering a Vim error, Python raises an exception of type
178 vim.error.
179 Example: >
180 try:
181 vim.command("put a")
182 except vim.error:
183 # nothing in register a
184
185Constants of the "vim" module
186
187 Note that these are not actually constants - you could reassign them.
188 But this is silly, as you would then lose access to the vim objects
189 to which the variables referred.
190
191vim.buffers *python-buffers*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000192 A sequence object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000194 :py b = vim.buffers[i] # Indexing (read-only)
195 :py b in vim.buffers # Membership test
196 :py n = len(vim.buffers) # Number of elements
197 :py for b in vim.buffers: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000198<
199vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000200 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000201 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000202 :py w = vim.windows[i] # Indexing (read-only)
203 :py w in vim.windows # Membership test
204 :py n = len(vim.windows) # Number of elements
205 :py for w in vim.windows: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000206<
207vim.current *python-current*
208 An object providing access (via specific attributes) to various
209 "current" objects available in vim:
210 vim.current.line The current line (RW) String
211 vim.current.buffer The current buffer (RO) Buffer
212 vim.current.window The current window (RO) Window
213 vim.current.range The current line range (RO) Range
214
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000215 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000217 "current range". A range is a bit like a buffer, but with all access
218 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219
220
221Output from Python *python-output*
222 Vim displays all Python code output in the Vim message area. Normal
223 output appears as information messages, and error output appears as
224 error messages.
225
226 In implementation terms, this means that all output to sys.stdout
227 (including the output from print statements) appears as information
228 messages, and all output to sys.stderr (including error tracebacks)
229 appears as error messages.
230
231 *python-input*
232 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000233 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 fixed.
235
236==============================================================================
2373. Buffer objects *python-buffer*
238
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000239Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240 - via vim.current.buffer (|python-current|)
241 - from indexing vim.buffers (|python-buffers|)
242 - from the "buffer" attribute of a window (|python-window|)
243
Bram Moolenaarb8ff1fb2012-02-04 21:59:01 +0100244Buffer objects have two read-only attributes - name - the full file name for
245the buffer, and number - the buffer number. They also have three methods
246(append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000248You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000250element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000252you would expect. Note that the result of indexing (slicing) a buffer is a
253string (list of strings). This has one unusual consequence - b[:] is different
254from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000255"b = None" merely updates the variable b, with no effect on the buffer.
256
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000257Buffer indexes start at zero, as is normal in Python. This differs from vim
258line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000259with marks (see below) which use vim line numbers.
260
261The buffer object methods are:
262 b.append(str) Append a line to the buffer
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200263 b.append(str, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000264 b.append(list) Append a list of lines to the buffer
265 Note that the option of supplying a list of strings to
266 the append method differs from the equivalent method
267 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200268 b.append(list, nr) Idem, below line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000269 b.mark(name) Return a tuple (row,col) representing the position
270 of the named mark (can also get the []"<> marks)
271 b.range(s,e) Return a range object (see |python-range|) which
272 represents the part of the given buffer between line
273 numbers s and e |inclusive|.
274
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000275Note that when adding a line it must not contain a line break character '\n'.
276A trailing '\n' is allowed and ignored, so that you can do: >
277 :py b.append(f.readlines())
278
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000280 :py print b.name # write the buffer file name
281 :py b[0] = "hello!!!" # replace the top line
282 :py b[:] = None # delete the whole buffer
283 :py del b[:] # delete the whole buffer
284 :py b[0:0] = [ "a line" ] # add a line at the top
285 :py del b[2] # delete a line (the third)
286 :py b.append("bottom") # add a line at the bottom
287 :py n = len(b) # number of lines
288 :py (row,col) = b.mark('a') # named mark
289 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290
291==============================================================================
2924. Range objects *python-range*
293
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000294Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000295number of ways:
296 - via vim.current.range (|python-current|)
297 - from a buffer's range() method (|python-buffer|)
298
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000299A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000300all operations are restricted to the lines within the range (this line range
301can, of course, change as a result of slice assignments, line deletions, or
302the range.append() method).
303
304The range object attributes are:
305 r.start Index of first line into the buffer
306 r.end Index of last line into the buffer
307
308The range object methods are:
309 r.append(str) Append a line to the range
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200310 r.append(str, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311 r.append(list) Append a list of lines to the range
312 Note that the option of supplying a list of strings to
313 the append method differs from the equivalent method
314 for Python's built-in list objects.
Bram Moolenaar2c3b1d92010-07-24 16:58:02 +0200315 r.append(list, nr) Idem, after line "nr"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316
317Example (assume r is the current range):
318 # Send all lines in a range to the default printer
319 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
320
321==============================================================================
3225. Window objects *python-window*
323
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000324Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 - via vim.current.window (|python-current|)
326 - from indexing vim.windows (|python-windows|)
327
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000328You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000329methods, and no sequence or other interface.
330
331Window attributes are:
332 buffer (read-only) The buffer displayed in this window
333 cursor (read-write) The current cursor position in the window
334 This is a tuple, (row,col).
335 height (read-write) The window height, in rows
336 width (read-write) The window width, in columns
337The height attribute is writable only if the screen is split horizontally.
338The width attribute is writable only if the screen is split vertically.
339
340==============================================================================
Bram Moolenaar30b65812012-07-12 22:01:11 +02003416. pyeval() and py3eval() Vim functions *python-pyeval*
342
343To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
344functions to evaluate Python expressions and pass their values to VimL.
345
346==============================================================================
3477. Dynamic loading *python-dynamic*
Bram Moolenaara5792f52005-11-23 21:25:05 +0000348
349On MS-Windows the Python library can be loaded dynamically. The |:version|
350output then includes |+python/dyn|.
351
352This means that Vim will search for the Python DLL file only when needed.
353When you don't use the Python interface you don't need it, thus you can use
354Vim without this DLL file.
355
356To use the Python interface the Python DLL must be in your search path. In a
357console window type "path" to see what directories are used.
358
359The name of the DLL must match the Python version Vim was compiled with.
360Currently the name is "python24.dll". That is for Python 2.4. To know for
361sure edit "gvim.exe" and search for "python\d*.dll\c".
362
363==============================================================================
Bram Moolenaar30b65812012-07-12 22:01:11 +02003648. Python 3 *python3*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200365
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200366 *:py3* *:python3*
Bram Moolenaar9b451252012-08-15 17:43:31 +0200367The |:py3| and |:python3| commands work similar to |:python|. A simple check
368if the `:py3` command is wrong: >
369 :py3 print("Hello")
370< *:py3file*
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200371The |:py3file| command works similar to |:pyfile|.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200372
Bram Moolenaar30b65812012-07-12 22:01:11 +0200373
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +0200374Vim can be built in four ways (:version output):
Bram Moolenaarbfc8b972010-08-13 22:05:54 +02003751. No Python support (-python, -python3)
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003762. Python 2 support only (+python or +python/dyn, -python3)
3773. Python 3 support only (-python, +python3 or +python3/dyn)
3784. Python 2 and 3 support (+python/dyn, +python3/dyn)
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200379
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200380Some more details on the special case 4:
Bram Moolenaarede981a2010-08-11 23:37:32 +0200381
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200382When Python 2 and Python 3 are both supported they must be loaded dynamically.
383
384When doing this on Linux/Unix systems and importing global symbols, this leads
385to a crash when the second Python version is used. So either global symbols
386are loaded but only one Python version is activated, or no global symbols are
Bram Moolenaar483c5d82010-10-20 18:45:33 +0200387loaded. The latter makes Python's "import" fail on libraries that expect the
Bram Moolenaarbfc8b972010-08-13 22:05:54 +0200388symbols to be provided by Vim.
389 *E836* *E837*
390Vim's configuration script makes a guess for all libraries based on one
391standard Python library (termios). If importing this library succeeds for
392both Python versions, then both will be made available in Vim at the same
393time. If not, only the version first used in a session will be enabled.
394When trying to use the other one you will get the E836 or E837 error message.
395
396Here Vim's behavior depends on the system in which it was configured. In a
397system where both versions of Python were configured with --enable-shared,
398both versions of Python will be activated at the same time. There will still
399be problems with other third party libraries that were not linked to
400libPython.
401
402To work around such problems there are these options:
4031. The problematic library is recompiled to link to the according
404 libpython.so.
4052. Vim is recompiled for only one Python version.
4063. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
407 may crash Vim though.
408
Bram Moolenaar446beb42011-05-10 17:18:44 +0200409 *has-python*
410You can test what Python version is available with: >
411 if has('python')
Bram Moolenaar5302d9e2011-09-14 17:55:08 +0200412 echo 'there is Python 2.x'
Bram Moolenaar446beb42011-05-10 17:18:44 +0200413 elseif has('python3')
414 echo 'there is Python 3.x'
415 endif
416
417Note however, that when Python 2 and 3 are both available and loaded
418dynamically, these has() calls will try to load them. If only one can be
419loaded at a time, just checking if Python 2 or 3 are available will prevent
420the other one from being available.
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200421
422==============================================================================
Bram Moolenaar071d4272004-06-13 20:20:40 +0000423 vim:tw=78:ts=8:ft=help:norl: