blob: 42e6478c0291d0c9254305656f35b2ce10346bab [file] [log] [blame]
Bram Moolenaard28478b2010-07-18 23:29:58 +02001*if_pyth.txt* For Vim version 7.3b. Last change: 2008 Aug 16
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
91. 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 Moolenaara5792f52005-11-23 21:25:05 +0000146. Dynamic loading |python-dynamic|
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200157. Python 3 |python3|
Bram Moolenaar071d4272004-06-13 20:20:40 +000016
17{Vi does not have any of these commands}
18
19The Python interface is available only when Vim was compiled with the
20|+python| feature.
21
22==============================================================================
231. Commands *python-commands*
24
25 *:python* *:py* *E205* *E263* *E264*
26:[range]py[thon] {stmt}
27 Execute Python statement {stmt}.
28
29:[range]py[thon] << {endmarker}
30{script}
31{endmarker}
32 Execute Python script {script}.
33 Note: This command doesn't work when the Python
34 feature wasn't compiled in. To avoid errors, see
35 |script-here|.
36
37{endmarker} must NOT be preceded by any white space. If {endmarker} is
38omitted from after the "<<", a dot '.' must be used after {script}, like
39for the |:append| and |:insert| commands.
40This form of the |:python| command is mainly useful for including python code
41in Vim scripts.
42
43Example: >
44 function! IcecreamInitialize()
45 python << EOF
46 class StrawberryIcecream:
47 def __call__(self):
48 print 'EAT ME'
49 EOF
50 endfunction
51<
52Note: Python is very sensitive to the indenting. Also make sure the "class"
53line and "EOF" do not have any indent.
54
55 *:pyfile* *:pyf*
56:[range]pyf[ile] {file}
57 Execute the Python script in {file}. The whole
58 argument is used as a single file name. {not in Vi}
59
60Both of these commands do essentially the same thing - they execute a piece of
61Python code, with the "current range" |python-range| set to the given line
62range.
63
64In the case of :python, the code to execute is in the command-line.
65In the case of :pyfile, the code to execute is the contents of the given file.
66
67Python commands cannot be used in the |sandbox|.
68
69To pass arguments you need to set sys.argv[] explicitly. Example: >
70
71 :python import sys
72 :python sys.argv = ["foo", "bar"]
73 :pyfile myscript.py
74
75Here are some examples *python-examples* >
76
77 :python from vim import *
78 :python from string import upper
79 :python current.line = upper(current.line)
80 :python print "Hello"
81 :python str = current.buffer[42]
82
83(Note that changes - like the imports - persist from one command to the next,
84just like in the Python interpreter.)
85
86==============================================================================
872. The vim module *python-vim*
88
89Python code gets all of its access to vim (with one exception - see
Bram Moolenaar402d2fe2005-04-15 21:00:38 +000090|python-output| below) via the "vim" module. The vim module implements two
Bram Moolenaar071d4272004-06-13 20:20:40 +000091methods, three constants, and one error object. You need to import the vim
92module before using it: >
93 :python import vim
94
95Overview >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +000096 :py print "Hello" # displays a message
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +010097 :py vim.command(cmd) # execute an Ex command
Bram Moolenaar5eb86f92004-07-26 12:53:41 +000098 :py w = vim.windows[n] # gets window "n"
99 :py cw = vim.current.window # gets the current window
100 :py b = vim.buffers[n] # gets buffer "n"
101 :py cb = vim.current.buffer # gets the current buffer
102 :py w.height = lines # sets the window height
103 :py w.cursor = (row, col) # sets the window cursor position
104 :py pos = w.cursor # gets a tuple (row, col)
105 :py name = b.name # gets the buffer file name
106 :py line = b[n] # gets a line from the buffer
107 :py lines = b[n:m] # gets a list of lines
108 :py num = len(b) # gets the number of lines
109 :py b[n] = str # sets a line in the buffer
110 :py b[n:m] = [str1, str2, str3] # sets a number of lines at once
111 :py del b[n] # deletes a line
112 :py del b[n:m] # deletes a number of lines
Bram Moolenaar071d4272004-06-13 20:20:40 +0000113
114
115Methods of the "vim" module
116
117vim.command(str) *python-command*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000118 Executes the vim (ex-mode) command str. Returns None.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000119 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000120 :py vim.command("set tw=72")
121 :py vim.command("%s/aaa/bbb/g")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000122< The following definition executes Normal mode commands: >
123 def normal(str):
124 vim.command("normal "+str)
125 # Note the use of single quotes to delimit a string containing
126 # double quotes
127 normal('"a2dd"aP')
128< *E659*
129 The ":python" command cannot be used recursively with Python 2.2 and
130 older. This only works with Python 2.3 and later: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000131 :py vim.command("python print 'Hello again Python'")
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132
133vim.eval(str) *python-eval*
134 Evaluates the expression str using the vim internal expression
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000135 evaluator (see |expression|). Returns the expression result as:
136 - a string if the Vim expression evaluates to a string or number
137 - a list if the Vim expression evaluates to a Vim list
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000138 - a dictionary if the Vim expression evaluates to a Vim dictionary
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000139 Dictionaries and lists are recursively expanded.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140 Examples: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000141 :py text_width = vim.eval("&tw")
142 :py str = vim.eval("12+12") # NB result is a string! Use
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143 # string.atoi() to convert to
144 # a number.
145
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000146 :py tagList = vim.eval('taglist("eval_expr")')
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000147< The latter will return a python list of python dicts, for instance:
148 [{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name':
149 'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}]
150
151
152
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153Error object of the "vim" module
154
155vim.error *python-error*
156 Upon encountering a Vim error, Python raises an exception of type
157 vim.error.
158 Example: >
159 try:
160 vim.command("put a")
161 except vim.error:
162 # nothing in register a
163
164Constants of the "vim" module
165
166 Note that these are not actually constants - you could reassign them.
167 But this is silly, as you would then lose access to the vim objects
168 to which the variables referred.
169
170vim.buffers *python-buffers*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000171 A sequence object providing access to the list of vim buffers. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000173 :py b = vim.buffers[i] # Indexing (read-only)
174 :py b in vim.buffers # Membership test
175 :py n = len(vim.buffers) # Number of elements
176 :py for b in vim.buffers: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177<
178vim.windows *python-windows*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000179 A sequence object providing access to the list of vim windows. The
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180 object supports the following operations: >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000181 :py w = vim.windows[i] # Indexing (read-only)
182 :py w in vim.windows # Membership test
183 :py n = len(vim.windows) # Number of elements
184 :py for w in vim.windows: # Sequential access
Bram Moolenaar071d4272004-06-13 20:20:40 +0000185<
186vim.current *python-current*
187 An object providing access (via specific attributes) to various
188 "current" objects available in vim:
189 vim.current.line The current line (RW) String
190 vim.current.buffer The current buffer (RO) Buffer
191 vim.current.window The current window (RO) Window
192 vim.current.range The current line range (RO) Range
193
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000194 The last case deserves a little explanation. When the :python or
Bram Moolenaar071d4272004-06-13 20:20:40 +0000195 :pyfile command specifies a range, this range of lines becomes the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000196 "current range". A range is a bit like a buffer, but with all access
197 restricted to a subset of lines. See |python-range| for more details.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000198
199
200Output from Python *python-output*
201 Vim displays all Python code output in the Vim message area. Normal
202 output appears as information messages, and error output appears as
203 error messages.
204
205 In implementation terms, this means that all output to sys.stdout
206 (including the output from print statements) appears as information
207 messages, and all output to sys.stderr (including error tracebacks)
208 appears as error messages.
209
210 *python-input*
211 Input (via sys.stdin, including input() and raw_input()) is not
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000212 supported, and may cause the program to crash. This should probably be
Bram Moolenaar071d4272004-06-13 20:20:40 +0000213 fixed.
214
215==============================================================================
2163. Buffer objects *python-buffer*
217
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000218Buffer objects represent vim buffers. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219 - via vim.current.buffer (|python-current|)
220 - from indexing vim.buffers (|python-buffers|)
221 - from the "buffer" attribute of a window (|python-window|)
222
223Buffer objects have one read-only attribute - name - the full file name for
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000224the buffer. They also have three methods (append, mark, and range; see below).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000226You can also treat buffer objects as sequence objects. In this context, they
Bram Moolenaar071d4272004-06-13 20:20:40 +0000227act as if they were lists (yes, they are mutable) of strings, with each
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000228element being a line of the buffer. All of the usual sequence operations,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229including indexing, index assignment, slicing and slice assignment, work as
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000230you would expect. Note that the result of indexing (slicing) a buffer is a
231string (list of strings). This has one unusual consequence - b[:] is different
232from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
Bram Moolenaar071d4272004-06-13 20:20:40 +0000233"b = None" merely updates the variable b, with no effect on the buffer.
234
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000235Buffer indexes start at zero, as is normal in Python. This differs from vim
236line numbers, which start from 1. This is particularly relevant when dealing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237with marks (see below) which use vim line numbers.
238
239The buffer object methods are:
240 b.append(str) Append a line to the buffer
241 b.append(list) Append a list of lines to the buffer
242 Note that the option of supplying a list of strings to
243 the append method differs from the equivalent method
244 for Python's built-in list objects.
245 b.mark(name) Return a tuple (row,col) representing the position
246 of the named mark (can also get the []"<> marks)
247 b.range(s,e) Return a range object (see |python-range|) which
248 represents the part of the given buffer between line
249 numbers s and e |inclusive|.
250
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000251Note that when adding a line it must not contain a line break character '\n'.
252A trailing '\n' is allowed and ignored, so that you can do: >
253 :py b.append(f.readlines())
254
Bram Moolenaar071d4272004-06-13 20:20:40 +0000255Examples (assume b is the current buffer) >
Bram Moolenaar5eb86f92004-07-26 12:53:41 +0000256 :py print b.name # write the buffer file name
257 :py b[0] = "hello!!!" # replace the top line
258 :py b[:] = None # delete the whole buffer
259 :py del b[:] # delete the whole buffer
260 :py b[0:0] = [ "a line" ] # add a line at the top
261 :py del b[2] # delete a line (the third)
262 :py b.append("bottom") # add a line at the bottom
263 :py n = len(b) # number of lines
264 :py (row,col) = b.mark('a') # named mark
265 :py r = b.range(1,5) # a sub-range of the buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +0000266
267==============================================================================
2684. Range objects *python-range*
269
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000270Range objects represent a part of a vim buffer. You can obtain them in a
Bram Moolenaar071d4272004-06-13 20:20:40 +0000271number of ways:
272 - via vim.current.range (|python-current|)
273 - from a buffer's range() method (|python-buffer|)
274
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000275A range object is almost identical in operation to a buffer object. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276all operations are restricted to the lines within the range (this line range
277can, of course, change as a result of slice assignments, line deletions, or
278the range.append() method).
279
280The range object attributes are:
281 r.start Index of first line into the buffer
282 r.end Index of last line into the buffer
283
284The range object methods are:
285 r.append(str) Append a line to the range
286 r.append(list) Append a list of lines to the range
287 Note that the option of supplying a list of strings to
288 the append method differs from the equivalent method
289 for Python's built-in list objects.
290
291Example (assume r is the current range):
292 # Send all lines in a range to the default printer
293 vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
294
295==============================================================================
2965. Window objects *python-window*
297
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000298Window objects represent vim windows. You can obtain them in a number of ways:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000299 - via vim.current.window (|python-current|)
300 - from indexing vim.windows (|python-windows|)
301
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000302You can manipulate window objects only through their attributes. They have no
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303methods, and no sequence or other interface.
304
305Window attributes are:
306 buffer (read-only) The buffer displayed in this window
307 cursor (read-write) The current cursor position in the window
308 This is a tuple, (row,col).
309 height (read-write) The window height, in rows
310 width (read-write) The window width, in columns
311The height attribute is writable only if the screen is split horizontally.
312The width attribute is writable only if the screen is split vertically.
313
314==============================================================================
Bram Moolenaara5792f52005-11-23 21:25:05 +00003156. Dynamic loading *python-dynamic*
316
317On MS-Windows the Python library can be loaded dynamically. The |:version|
318output then includes |+python/dyn|.
319
320This means that Vim will search for the Python DLL file only when needed.
321When you don't use the Python interface you don't need it, thus you can use
322Vim without this DLL file.
323
324To use the Python interface the Python DLL must be in your search path. In a
325console window type "path" to see what directories are used.
326
327The name of the DLL must match the Python version Vim was compiled with.
328Currently the name is "python24.dll". That is for Python 2.4. To know for
329sure edit "gvim.exe" and search for "python\d*.dll\c".
330
331==============================================================================
Bram Moolenaar6df6f472010-07-18 18:04:50 +02003327. Python 3 *python3*
333
334Python 3 support can exist next to Python 2.x.
335
336*:py3* *:python3* *:py3file*
337
338TODO
339
340
341==============================================================================
Bram Moolenaar071d4272004-06-13 20:20:40 +0000342 vim:tw=78:ts=8:ft=help:norl: