1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
|
*if_pyth.txt* For Vim version 9.0. Last change: 2022 Feb 22
VIM REFERENCE MANUAL by Paul Moore
The Python Interface to Vim *python* *Python*
1. Commands |python-commands|
2. The vim module |python-vim|
3. Buffer objects |python-buffer|
4. Range objects |python-range|
5. Window objects |python-window|
6. Tab page objects |python-tabpage|
7. vim.bindeval objects |python-bindeval-objects|
8. pyeval(), py3eval() Vim functions |python-pyeval|
9. Dynamic loading |python-dynamic|
10. Python 3 |python3|
11. Python X |python_x|
12. Building with Python support |python-building|
The Python 2.x interface is available only when Vim was compiled with the
|+python| feature.
The Python 3 interface is available only when Vim was compiled with the
|+python3| feature.
Both can be available at the same time, but read |python-2-and-3|.
NOTE: Python 2 is old and no longer being developed. Using Python 3 is highly
recommended. Python 2 support will be dropped when it does not work properly
anymore.
==============================================================================
1. Commands *python-commands*
*:python* *:py* *E263* *E264* *E887*
:[range]py[thon] {stmt}
Execute Python statement {stmt}. A simple check if
the `:python` command is working: >
:python print "Hello"
:[range]py[thon] << [trim] [{endmarker}]
{script}
{endmarker}
Execute Python script {script}.
Note: This command doesn't work when the Python
feature wasn't compiled in. To avoid errors, see
|script-here|.
If [endmarker] is omitted from after the "<<", a dot '.' must be used after
{script}, like for the |:append| and |:insert| commands. Refer to
|:let-heredoc| for more information.
This form of the |:python| command is mainly useful for including python code
in Vim scripts.
Example: >
function! IcecreamInitialize()
python << EOF
class StrawberryIcecream:
def __call__(self):
print 'EAT ME'
EOF
endfunction
To see what version of Python you have: >
:python print(sys.version)
There is no need to import sys, it's done by default.
*python-environment*
Environment variables set in Vim are not always available in Python. This
depends on how Vim and Python were built. Also see
https://docs.python.org/3/library/os.html#os.environ
Note: Python is very sensitive to the indenting. Make sure the "class" line
and "EOF" do not have any indent.
*:pydo*
:[range]pydo {body} Execute Python function "def _vim_pydo(line, linenr):
{body}" for each line in the [range], with the
function arguments being set to the text of each line
in turn, without a trailing <EOL>, and the current
line number. The function should return a string or
None. If a string is returned, it becomes the text of
the line in the current turn. The default for [range]
is the whole file: "1,$".
Examples:
>
:pydo return "%s\t%d" % (line[::-1], len(line))
:pydo if line: return "%4d: %s" % (linenr, line)
<
One can use `:pydo` in possible conjunction with `:py` to filter a range using
python. For example: >
:py3 << EOF
needle = vim.eval('@a')
replacement = vim.eval('@b')
def py_vim_string_replace(str):
return str.replace(needle, replacement)
EOF
:'<,'>py3do return py_vim_string_replace(line)
<
*:pyfile* *:pyf*
:[range]pyf[ile] {file}
Execute the Python script in {file}. The whole
argument is used as a single file name.
Both of these commands do essentially the same thing - they execute a piece of
Python code, with the "current range" |python-range| set to the given line
range.
In the case of :python, the code to execute is in the command-line.
In the case of :pyfile, the code to execute is the contents of the given file.
Python commands cannot be used in the |sandbox|.
To pass arguments you need to set sys.argv[] explicitly. Example: >
:python sys.argv = ["foo", "bar"]
:pyfile myscript.py
Here are some examples *python-examples* >
:python from vim import *
:python from string import upper
:python current.line = upper(current.line)
:python print "Hello"
:python str = current.buffer[42]
(Note that changes - like the imports - persist from one command to the next,
just like in the Python interpreter.)
==============================================================================
2. The vim module *python-vim*
Python code gets all of its access to vim (with one exception - see
|python-output| below) via the "vim" module. The vim module implements two
methods, three constants, and one error object. You need to import the vim
module before using it: >
:python import vim
Overview >
:py print "Hello" # displays a message
:py vim.command(cmd) # execute an Ex command
:py w = vim.windows[n] # gets window "n"
:py cw = vim.current.window # gets the current window
:py b = vim.buffers[n] # gets buffer "n"
:py cb = vim.current.buffer # gets the current buffer
:py w.height = lines # sets the window height
:py w.cursor = (row, col) # sets the window cursor position
:py pos = w.cursor # gets a tuple (row, col)
:py name = b.name # gets the buffer file name
:py line = b[n] # gets a line from the buffer
:py lines = b[n:m] # gets a list of lines
:py num = len(b) # gets the number of lines
:py b[n] = str # sets a line in the buffer
:py b[n:m] = [str1, str2, str3] # sets a number of lines at once
:py del b[n] # deletes a line
:py del b[n:m] # deletes a number of lines
Methods of the "vim" module
vim.command(str) *python-command*
Executes the vim (ex-mode) command str. Returns None.
Examples: >
:py vim.command("set tw=72")
:py vim.command("%s/aaa/bbb/g")
< The following definition executes Normal mode commands: >
def normal(str):
vim.command("normal "+str)
# Note the use of single quotes to delimit a string containing
# double quotes
normal('"a2dd"aP')
< *E659*
The ":python" command cannot be used recursively with Python 2.2 and
older. This only works with Python 2.3 and later: >
:py vim.command("python print 'Hello again Python'")
vim.eval(str) *python-eval*
Evaluates the expression str using the vim internal expression
evaluator (see |expression|). Returns the expression result as:
- a string if the Vim expression evaluates to a string or number
- a list if the Vim expression evaluates to a Vim list
- a dictionary if the Vim expression evaluates to a Vim dictionary
Dictionaries and lists are recursively expanded.
Examples: >
:" value of the 'textwidth' option
:py text_width = vim.eval("&tw")
:
:" contents of the 'a' register
:py a_reg = vim.eval("@a")
:
:" Result is a string! Use string.atoi() to convert to a number.
:py str = vim.eval("12+12")
:
:py tagList = vim.eval('taglist("eval_expr")')
< The latter will return a python list of python dicts, for instance:
[{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name': ~
'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}] ~
vim.bindeval(str) *python-bindeval*
Like |python-eval|, but returns special objects described in
|python-bindeval-objects|. These python objects let you modify (|List|
or |Dictionary|) or call (|Funcref|) vim objects.
vim.strwidth(str) *python-strwidth*
Like |strwidth()|: returns number of display cells str occupies, tab
is counted as one cell.
vim.foreach_rtp(callable) *python-foreach_rtp*
Call the given callable for each path in 'runtimepath' until either
callable returns something but None, the exception is raised or there
are no longer paths. If stopped in case callable returned non-None,
vim.foreach_rtp function returns the value returned by callable.
vim.chdir(*args, **kwargs) *python-chdir*
vim.fchdir(*args, **kwargs) *python-fchdir*
Run os.chdir or os.fchdir, then all appropriate vim stuff.
Note: you should not use these functions directly, use os.chdir and
os.fchdir instead. Behavior of vim.fchdir is undefined in case
os.fchdir does not exist.
Error object of the "vim" module
vim.error *python-error*
Upon encountering a Vim error, Python raises an exception of type
vim.error.
Example: >
try:
vim.command("put a")
except vim.error:
# nothing in register a
Constants of the "vim" module
Note that these are not actually constants - you could reassign them.
But this is silly, as you would then lose access to the vim objects
to which the variables referred.
vim.buffers *python-buffers*
A mapping object providing access to the list of vim buffers. The
object supports the following operations: >
:py b = vim.buffers[i] # Indexing (read-only)
:py b in vim.buffers # Membership test
:py n = len(vim.buffers) # Number of elements
:py for b in vim.buffers: # Iterating over buffer list
<
vim.windows *python-windows*
A sequence object providing access to the list of vim windows. The
object supports the following operations: >
:py w = vim.windows[i] # Indexing (read-only)
:py w in vim.windows # Membership test
:py n = len(vim.windows) # Number of elements
:py for w in vim.windows: # Sequential access
< Note: vim.windows object always accesses current tab page.
|python-tabpage|.windows objects are bound to parent |python-tabpage|
object and always use windows from that tab page (or throw vim.error
in case tab page was deleted). You can keep a reference to both
without keeping a reference to vim module object or |python-tabpage|,
they will not lose their properties in this case.
vim.tabpages *python-tabpages*
A sequence object providing access to the list of vim tab pages. The
object supports the following operations: >
:py t = vim.tabpages[i] # Indexing (read-only)
:py t in vim.tabpages # Membership test
:py n = len(vim.tabpages) # Number of elements
:py for t in vim.tabpages: # Sequential access
<
vim.current *python-current*
An object providing access (via specific attributes) to various
"current" objects available in vim:
vim.current.line The current line (RW) String
vim.current.buffer The current buffer (RW) Buffer
vim.current.window The current window (RW) Window
vim.current.tabpage The current tab page (RW) TabPage
vim.current.range The current line range (RO) Range
The last case deserves a little explanation. When the :python or
:pyfile command specifies a range, this range of lines becomes the
"current range". A range is a bit like a buffer, but with all access
restricted to a subset of lines. See |python-range| for more details.
Note: When assigning to vim.current.{buffer,window,tabpage} it expects
valid |python-buffer|, |python-window| or |python-tabpage| objects
respectively. Assigning triggers normal (with |autocommand|s)
switching to given buffer, window or tab page. It is the only way to
switch UI objects in python: you can't assign to
|python-tabpage|.window attribute. To switch without triggering
autocommands use >
py << EOF
saved_eventignore = vim.options['eventignore']
vim.options['eventignore'] = 'all'
try:
vim.current.buffer = vim.buffers[2] # Switch to buffer 2
finally:
vim.options['eventignore'] = saved_eventignore
EOF
<
vim.vars *python-vars*
vim.vvars *python-vvars*
Dictionary-like objects holding dictionaries with global (|g:|) and
vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
but faster.
vim.options *python-options*
Object partly supporting mapping protocol (supports setting and
getting items) providing a read-write access to global options.
Note: unlike |:set| this provides access only to global options. You
cannot use this object to obtain or set local options' values or
access local-only options in any fashion. Raises KeyError if no global
option with such name exists (i.e. does not raise KeyError for
|global-local| options and global only options, but does for window-
and buffer-local ones). Use |python-buffer| objects to access to
buffer-local options and |python-window| objects to access to
window-local options.
Type of this object is available via "Options" attribute of vim
module.
Output from Python *python-output*
Vim displays all Python code output in the Vim message area. Normal
output appears as information messages, and error output appears as
error messages.
In implementation terms, this means that all output to sys.stdout
(including the output from print statements) appears as information
messages, and all output to sys.stderr (including error tracebacks)
appears as error messages.
*python-input*
Input (via sys.stdin, including input() and raw_input()) is not
supported, and may cause the program to crash. This should probably be
fixed.
*python2-directory* *python3-directory* *pythonx-directory*
Python 'runtimepath' handling *python-special-path*
In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
the list of paths found in 'runtimepath': with this directory in sys.path and
vim.path_hooks in sys.path_hooks python will try to load module from
{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
each {rtp} found in 'runtimepath'.
Implementation is similar to the following, but written in C: >
from imp import find_module, load_module
import vim
import sys
class VimModuleLoader(object):
def __init__(self, module):
self.module = module
def load_module(self, fullname, path=None):
return self.module
def _find_module(fullname, oldtail, path):
idx = oldtail.find('.')
if idx > 0:
name = oldtail[:idx]
tail = oldtail[idx+1:]
fmr = find_module(name, path)
module = load_module(fullname[:-len(oldtail)] + name, *fmr)
return _find_module(fullname, tail, module.__path__)
else:
fmr = find_module(fullname, path)
return load_module(fullname, *fmr)
# It uses vim module itself in place of VimPathFinder class: it does not
# matter for python which object has find_module function attached to as
# an attribute.
class VimPathFinder(object):
@classmethod
def find_module(cls, fullname, path=None):
try:
return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
except ImportError:
return None
@classmethod
def load_module(cls, fullname, path=None):
return _find_module(fullname, fullname, path or vim._get_paths())
def hook(path):
if path == vim.VIM_SPECIAL_PATH:
return VimPathFinder
else:
raise ImportError
sys.path_hooks.append(hook)
vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
String constant used in conjunction with vim path hook. If path hook
installed by vim is requested to handle anything but path equal to
vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
case it uses special loader.
Note: you must not use value of this constant directly, always use
vim.VIM_SPECIAL_PATH object.
vim.find_module(...) *python-find_module*
vim.path_hook(path) *python-path_hook*
Methods or objects used to implement path loading as described above.
You should not be using any of these directly except for vim.path_hook
in case you need to do something with sys.meta_path. It is not
guaranteed that any of the objects will exist in the future vim
versions.
vim._get_paths *python-_get_paths*
Methods returning a list of paths which will be searched for by path
hook. You should not rely on this method being present in future
versions, but can use it for debugging.
It returns a list of {rtp}/python2 (or {rtp}/python3) and
{rtp}/pythonx directories for each {rtp} in 'runtimepath'.
==============================================================================
3. Buffer objects *python-buffer*
Buffer objects represent vim buffers. You can obtain them in a number of ways:
- via vim.current.buffer (|python-current|)
- from indexing vim.buffers (|python-buffers|)
- from the "buffer" attribute of a window (|python-window|)
Buffer objects have two read-only attributes - name - the full file name for
the buffer, and number - the buffer number. They also have three methods
(append, mark, and range; see below).
You can also treat buffer objects as sequence objects. In this context, they
act as if they were lists (yes, they are mutable) of strings, with each
element being a line of the buffer. All of the usual sequence operations,
including indexing, index assignment, slicing and slice assignment, work as
you would expect. Note that the result of indexing (slicing) a buffer is a
string (list of strings). This has one unusual consequence - b[:] is different
from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
"b = None" merely updates the variable b, with no effect on the buffer.
Buffer indexes start at zero, as is normal in Python. This differs from vim
line numbers, which start from 1. This is particularly relevant when dealing
with marks (see below) which use vim line numbers.
The buffer object attributes are:
b.vars Dictionary-like object used to access
|buffer-variable|s.
b.options Mapping object (supports item getting, setting and
deleting) that provides access to buffer-local options
and buffer-local values of |global-local| options. Use
|python-window|.options if option is window-local,
this object will raise KeyError. If option is
|global-local| and local value is missing getting it
will return None.
b.name String, RW. Contains buffer name (full path).
Note: when assigning to b.name |BufFilePre| and
|BufFilePost| autocommands are launched.
b.number Buffer number. Can be used as |python-buffers| key.
Read-only.
b.valid True or False. Buffer object becomes invalid when
corresponding buffer is wiped out.
The buffer object methods are:
b.append(str) Append a line to the buffer
b.append(str, nr) Idem, below line "nr"
b.append(list) Append a list of lines to the buffer
Note that the option of supplying a list of strings to
the append method differs from the equivalent method
for Python's built-in list objects.
b.append(list, nr) Idem, below line "nr"
b.mark(name) Return a tuple (row,col) representing the position
of the named mark (can also get the []"<> marks)
b.range(s,e) Return a range object (see |python-range|) which
represents the part of the given buffer between line
numbers s and e |inclusive|.
Note that when adding a line it must not contain a line break character '\n'.
A trailing '\n' is allowed and ignored, so that you can do: >
:py b.append(f.readlines())
Buffer object type is available using "Buffer" attribute of vim module.
Examples (assume b is the current buffer) >
:py print b.name # write the buffer file name
:py b[0] = "hello!!!" # replace the top line
:py b[:] = None # delete the whole buffer
:py del b[:] # delete the whole buffer
:py b[0:0] = [ "a line" ] # add a line at the top
:py del b[2] # delete a line (the third)
:py b.append("bottom") # add a line at the bottom
:py n = len(b) # number of lines
:py (row,col) = b.mark('a') # named mark
:py r = b.range(1,5) # a sub-range of the buffer
:py b.vars["foo"] = "bar" # assign b:foo variable
:py b.options["ff"] = "dos" # set fileformat
:py del b.options["ar"] # same as :set autoread<
==============================================================================
4. Range objects *python-range*
Range objects represent a part of a vim buffer. You can obtain them in a
number of ways:
- via vim.current.range (|python-current|)
- from a buffer's range() method (|python-buffer|)
A range object is almost identical in operation to a buffer object. However,
all operations are restricted to the lines within the range (this line range
can, of course, change as a result of slice assignments, line deletions, or
the range.append() method).
The range object attributes are:
r.start Index of first line into the buffer
r.end Index of last line into the buffer
The range object methods are:
r.append(str) Append a line to the range
r.append(str, nr) Idem, after line "nr"
r.append(list) Append a list of lines to the range
Note that the option of supplying a list of strings to
the append method differs from the equivalent method
for Python's built-in list objects.
r.append(list, nr) Idem, after line "nr"
Range object type is available using "Range" attribute of vim module.
Example (assume r is the current range):
# Send all lines in a range to the default printer
vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
==============================================================================
5. Window objects *python-window*
Window objects represent vim windows. You can obtain them in a number of ways:
- via vim.current.window (|python-current|)
- from indexing vim.windows (|python-windows|)
- from indexing "windows" attribute of a tab page (|python-tabpage|)
- from the "window" attribute of a tab page (|python-tabpage|)
You can manipulate window objects only through their attributes. They have no
methods, and no sequence or other interface.
Window attributes are:
buffer (read-only) The buffer displayed in this window
cursor (read-write) The current cursor position in the window
This is a tuple, (row,col).
height (read-write) The window height, in rows
width (read-write) The window width, in columns
vars (read-only) The window |w:| variables. Attribute is
unassignable, but you can change window
variables this way
options (read-only) The window-local options. Attribute is
unassignable, but you can change window
options this way. Provides access only to
window-local options, for buffer-local use
|python-buffer| and for global ones use
|python-options|. If option is |global-local|
and local value is missing getting it will
return None.
number (read-only) Window number. The first window has number 1.
This is zero in case it cannot be determined
(e.g. when the window object belongs to other
tab page).
row, col (read-only) On-screen window position in display cells.
First position is zero.
tabpage (read-only) Window tab page.
valid (read-write) True or False. Window object becomes invalid
when corresponding window is closed.
The height attribute is writable only if the screen is split horizontally.
The width attribute is writable only if the screen is split vertically.
Window object type is available using "Window" attribute of vim module.
==============================================================================
6. Tab page objects *python-tabpage*
Tab page objects represent vim tab pages. You can obtain them in a number of
ways:
- via vim.current.tabpage (|python-current|)
- from indexing vim.tabpages (|python-tabpages|)
You can use this object to access tab page windows. They have no methods and
no sequence or other interfaces.
Tab page attributes are:
number The tab page number like the one returned by
|tabpagenr()|.
windows Like |python-windows|, but for current tab page.
vars The tab page |t:| variables.
window
|