robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesrefactor(exmode): Ex-mode as cmdwin + Lua #40991359459dec6

master
24.2 KiB655 linesraw
1*if_pyth.txt*   Nvim
2
3
4		  NVIM REFERENCE MANUAL
5
6
7The Python Interface to NVim				*if_pyth* *python* *Python*
8
9See |provider-python| for more information.
10
11                                      Type |gO| to see the table of contents.
12
13==============================================================================
14Commands						*python-commands*
15
16					*:python* *:py* *E263* *E264* *E887*
17:[range]py[thon] {stmt}
18			Execute Python statement {stmt}.  A simple check if
19			the `:python` command is working: >vim
20				:python print("Hello")
21
22:[range]py[thon] << [trim] [{endmarker}]
23{script}
24{endmarker}
25			Execute Python script {script}.  Useful for including
26			python code in Vim scripts.  Requires Python, see
27			|script-here|.
28
29If [endmarker] is omitted from after the "<<", a dot '.' must be used after
30{script}, like for the |:append| and |:insert| commands.  Refer to
31|:let-heredoc| for more information.
32
33Example: >vim
34	function! IcecreamInitialize()
35	python << EOF
36	class StrawberryIcecream:
37		def __call__(self):
38			print('EAT ME')
39	EOF
40	endfunction
41
42To see what version of Python you have: >vim
43	:python print(sys.version)
44
45There is no need to "import sys", it's done by default.
46
47							*python-environment*
48Environment variables set in Vim are not always available in Python.  This
49depends on how Vim and Python were build.  Also see
50https://docs.python.org/3/library/os.html#os.environ
51
52Note: Python is very sensitive to indenting.  Make sure the "class" line and
53"EOF" do not have any indent.
54
55							*:pydo*
56:[range]pydo {body}	Execute Python function "def _vim_pydo(line, linenr):
57			{body}" for each line in the [range], with the
58			function arguments being set to the text of each line
59			in turn, without a trailing <EOL>, and the current
60			line number.  The function should return a string or
61			None.  If a string is returned, it becomes the text of
62			the line in the current turn.  The default for [range]
63			is the whole file: "1,$".
64
65Examples:
66>vim
67	:pydo return "%s\t%d" % (line[::-1], len(line))
68	:pydo if line: return "%4d: %s" % (linenr, line)
69<
70One can use `:pydo` in possible conjunction with `:py` to filter a range using
71python.  For example: >vim
72
73	:py3 << EOF
74	needle = vim.eval('@a')
75	replacement = vim.eval('@b')
76
77	def py_vim_string_replace(str):
78		return str.replace(needle, replacement)
79	EOF
80	:'<,'>py3do return py_vim_string_replace(line)
81<
82							*:pyfile* *:pyf*
83:[range]pyf[ile] {file}
84			Execute the Python script in {file}.  The whole
85			argument is used as a single file name.
86
87Both of these commands do essentially the same thing - they execute a piece of
88Python code, with the "current range" |python-range| set to the given line
89range.
90
91In the case of :python, the code to execute is in the command-line.
92In the case of :pyfile, the code to execute is the contents of the given file.
93
94Python commands cannot be used in the |sandbox|.
95
96To pass arguments you need to set sys.argv[] explicitly.  Example: >vim
97
98	:python sys.argv = ["foo", "bar"]
99	:pyfile myscript.py
100
101Here are some examples					*python-examples*
102>vim
103	:python from vim import *
104	:python current.line = str.upper(current.line)
105	:python print("Hello")
106	:python str = current.buffer[42]
107
108Note that changes (such as the "import" statements) persist from one command
109to the next, just like the Python REPL.
110
111							*script-here*
112When using a script language in-line, you might want to skip this when the
113language isn't supported.
114>vim
115   if has('python')
116     python << EOF
117       print("python works")
118   EOF
119   endif
120<
121Note that "EOF" must be at the start of the line without preceding white
122space.
123
124==============================================================================
125The vim module							*python-vim*
126
127Python code gets all of its access to vim (with one exception - see
128|python-output| below) via the "vim" module.  The vim module implements two
129methods, three constants, and one error object.  You need to import the vim
130module before using it: >vim
131	:python import vim
132
133Overview >vim
134	:py print("Hello")		# displays a message
135	:py vim.command(cmd)		# execute an Ex command
136	:py w = vim.windows[n]		# gets window "n"
137	:py cw = vim.current.window	# gets the current window
138	:py b = vim.buffers[n]		# gets buffer "n"
139	:py cb = vim.current.buffer	# gets the current buffer
140	:py w.height = lines		# sets the window height
141	:py w.cursor = (row, col)	# sets the window cursor position
142	:py pos = w.cursor		# gets a tuple (row, col)
143	:py name = b.name		# gets the buffer file name
144	:py line = b[n]			# gets a line from the buffer
145	:py lines = b[n:m]		# gets a list of lines
146	:py num = len(b)		# gets the number of lines
147	:py b[n] = str			# sets a line in the buffer
148	:py b[n:m] = [str1, str2, str3]	# sets a number of lines at once
149	:py del b[n]			# deletes a line
150	:py del b[n:m]			# deletes a number of lines
151
152
153Methods of the "vim" module
154
155vim.command(str)					*python-command*
156	Executes the Ex command str.  Returns None.
157	Examples: >vim
158	    :py vim.command("set tw=72")
159	    :py vim.command("%s/aaa/bbb/g")
160<	The following definition executes Normal mode commands: >python
161		def normal(str):
162			vim.command("normal "+str)
163		# Note the use of single quotes to delimit a string containing
164		# double quotes
165		normal('"a2dd"aP')
166
167vim.eval(str)						*python-eval*
168	Evaluates the expression str using the vim internal expression
169	evaluator (see |expression|).  Returns the expression result as:
170	- a string if the Vim expression evaluates to a string or number
171	- a list if the Vim expression evaluates to a Vim |list|
172	- a dictionary if the Vim expression evaluates to a Vim |dict|
173	- a boolean if Vim expression evaluates to |v:true| or |v:false|
174	- `None` if Vim expression evaluates to |v:null|
175	Dictionaries and lists are recursively expanded.
176	Examples: >vim
177	    :py text_width = vim.eval("&tw")
178	    :py str = vim.eval("12+12")		# NB result is a string! Use
179						# int() to convert to a
180						# number.
181
182vim.strwidth(str)					*python-strwidth*
183	Like |strwidth()|: returns number of display cells str occupies, tab
184	is counted as one cell.
185
186vim.foreach_rtp(callable)				*python-foreach_rtp*
187	Call the given callable for each path in 'runtimepath' until either
188	callable returns something but None, the exception is raised or there
189	are no longer paths.  If stopped in case callable returned non-None,
190	vim.foreach_rtp function returns the value returned by callable.
191
192`vim.chdir(*args, **kwargs)`				*python-chdir*
193`vim.fchdir(*args, **kwargs)`				*python-fchdir*
194	Run os.chdir or os.fchdir, then all appropriate vim stuff.
195	Note: you should not use these functions directly, use os.chdir and
196	      os.fchdir instead.  Behavior of vim.fchdir is undefined in case
197	      os.fchdir does not exist.
198
199Error object of the "vim" module
200
201vim.error						*python-error*
202	Upon encountering a Vim error, Python raises an exception of type
203	vim.error.
204	Example: >python
205		try:
206			vim.command("put a")
207		except vim.error:
208			# nothing in register a
209
210Constants of the "vim" module
211
212	Note that these are not actually constants - you could reassign them.
213	But this is silly, as you would then lose access to the vim objects
214	to which the variables referred.
215
216vim.buffers						*python-buffers*
217	A mapping object providing access to the list of vim buffers.  The
218	object supports the following operations: >vim
219	    :py b = vim.buffers[i]	# Indexing (read-only)
220	    :py b in vim.buffers	# Membership test
221	    :py n = len(vim.buffers)	# Number of elements
222	    :py for b in vim.buffers:	# Iterating over buffer list
223<
224vim.windows						*python-windows*
225	A sequence object providing access to the list of vim windows.  The
226	object supports the following operations: >vim
227	    :py w = vim.windows[i]	# Indexing (read-only)
228	    :py w in vim.windows	# Membership test
229	    :py n = len(vim.windows)	# Number of elements
230	    :py for w in vim.windows:	# Sequential access
231<	Note: vim.windows object always accesses current tab page.
232	|python-tabpage|.windows objects are bound to parent |python-tabpage|
233	object and always use windows from that tab page (or throw vim.error
234	in case tab page was deleted).  You can keep a reference to both
235	without keeping a reference to vim module object or |python-tabpage|,
236	they will not lose their properties in this case.
237
238vim.tabpages						*python-tabpages*
239	A sequence object providing access to the list of vim tab pages.  The
240	object supports the following operations: >vim
241	    :py t = vim.tabpages[i]	# Indexing (read-only)
242	    :py t in vim.tabpages	# Membership test
243	    :py n = len(vim.tabpages)	# Number of elements
244	    :py for t in vim.tabpages:	# Sequential access
245<
246vim.current						*python-current*
247	An object providing access (via specific attributes) to various
248	"current" objects available in vim:
249		vim.current.line	The current line (RW)		String
250		vim.current.buffer	The current buffer (RW)		Buffer
251		vim.current.window	The current window (RW)		Window
252		vim.current.tabpage	The current tab page (RW)	TabPage
253		vim.current.range	The current line range (RO)	Range
254
255	The last case deserves a little explanation.  When the :python or
256	:pyfile command specifies a range, this range of lines becomes the
257	"current range".  A range is a bit like a buffer, but with all access
258	restricted to a subset of lines.  See |python-range| for more details.
259
260	Note: When assigning to vim.current.{buffer,window,tabpage} it expects
261	valid |python-buffer|, |python-window| or |python-tabpage| objects
262	respectively.  Assigning triggers normal (with |autocommand|s)
263	switching to given buffer, window or tab page.  It is the only way to
264	switch UI objects in python: you can't assign to
265	|python-tabpage|.window attribute.  To switch without triggering
266	autocommands use >vim
267	    py << EOF
268	    saved_eventignore = vim.options['eventignore']
269	    vim.options['eventignore'] = 'all'
270	    try:
271	        vim.current.buffer = vim.buffers[2] # Switch to buffer 2
272	    finally:
273	        vim.options['eventignore'] = saved_eventignore
274	    EOF
275<
276vim.vars						*python-vars*
277vim.vvars						*python-vvars*
278	Dictionary-like objects holding dictionaries with global (|g:|) and
279	vim (|v:|) variables respectively.
280
281vim.options						*python-options*
282	Object partly supporting mapping protocol (supports setting and
283	getting items) providing a read-write access to global options.
284	Note: unlike |:set| this provides access only to global options.  You
285	cannot use this object to obtain or set local options' values or
286	access local-only options in any fashion.  Raises KeyError if no
287	global option with such name exists (i.e. does not raise KeyError for
288	|global-local| options and global only options, but does for window-
289	and buffer-local ones).  Use |python-buffer| objects to access to
290	buffer-local options and |python-window| objects to access to
291	window-local options.
292
293	Type of this object is available via "Options" attribute of vim
294	module.
295
296Output from Python					*python-output*
297	Vim displays all Python code output in the Vim message area.  Normal
298	output appears as information messages, and error output appears as
299	error messages.
300
301	In implementation terms, this means that all output to sys.stdout
302	(including the output from print statements) appears as information
303	messages, and all output to sys.stderr (including error tracebacks)
304	appears as error messages.
305
306							*python-input*
307	Input (via sys.stdin, including input() and raw_input()) is not
308	supported, and may cause the program to crash.  This should probably
309	be fixed.
310
311				  *python3-directory* *pythonx-directory*
312Python 'runtimepath' handling				*python-special-path*
313
314In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
315the list of paths found in 'runtimepath': with this directory in sys.path and
316vim.path_hooks in sys.path_hooks python will try to load module from
317{rtp}/python3 and {rtp}/pythonx for each {rtp} found in 'runtimepath'.
318
319Implementation is similar to the following: >python
320
321    from imp import find_module, load_module
322    import vim
323    import sys
324
325    class VimModuleLoader(object):
326        def __init__(self, module):
327            self.module = module
328
329        def load_module(self, fullname, path=None):
330            return self.module
331
332    def _find_module(fullname, oldtail, path):
333        idx = oldtail.find('.')
334        if idx > 0:
335            name = oldtail[:idx]
336            tail = oldtail[idx+1:]
337            fmr = find_module(name, path)
338            module = load_module(fullname[:-len(oldtail)] + name, *fmr)
339            return _find_module(fullname, tail, module.__path__)
340        else:
341            fmr = find_module(fullname, path)
342            return load_module(fullname, *fmr)
343
344    # It uses vim module itself in place of VimPathFinder class: it does not
345    # matter for python which object has find_module function attached to as
346    # an attribute.
347    class VimPathFinder(object):
348        @classmethod
349        def find_module(cls, fullname, path=None):
350            try:
351                return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
352            except ImportError:
353                return None
354
355        @classmethod
356        def load_module(cls, fullname, path=None):
357            return _find_module(fullname, fullname, path or vim._get_paths())
358
359    def hook(path):
360        if path == vim.VIM_SPECIAL_PATH:
361            return VimPathFinder
362        else:
363            raise ImportError
364
365    sys.path_hooks.append(hook)
366
367vim.VIM_SPECIAL_PATH				*python-VIM_SPECIAL_PATH*
368	String constant used in conjunction with vim path hook.  If path hook
369	installed by vim is requested to handle anything but path equal to
370	vim.VIM_SPECIAL_PATH constant it raises ImportError.  In the only
371	other case it uses special loader.
372
373	Note: you must not use value of this constant directly, always use
374	      vim.VIM_SPECIAL_PATH object.
375
376vim.find_module(...)					*python-find_module*
377vim.path_hook(path)					*python-path_hook*
378	Methods or objects used to implement path loading as described above.
379	You should not be using any of these directly except for vim.path_hook
380	in case you need to do something with sys.meta_path. It is not
381	guaranteed that any of the objects will exist in the future vim
382	versions.
383
384vim._get_paths						*python-_get_paths*
385	Methods returning a list of paths which will be searched for by path
386	hook.  You should not rely on this method being present in future
387	versions, but can use it for debugging.
388
389	It returns a list of {rtp}/python3 and {rtp}/pythonx
390	directories for each {rtp} in 'runtimepath'.
391
392==============================================================================
393Buffer objects						*python-buffer*
394
395Buffer objects represent vim buffers.  You can obtain them in a number of
396ways:
397	- via vim.current.buffer (|python-current|)
398	- from indexing vim.buffers (|python-buffers|)
399	- from the "buffer" attribute of a window (|python-window|)
400
401Buffer objects have two read-only attributes - name - the full file name for
402the buffer, and number - the buffer number.  They also have three methods
403(append, mark, and range; see below).
404
405You can also treat buffer objects as sequence objects.  In this context, they
406act as if they were lists (yes, they are mutable) of strings, with each
407element being a line of the buffer.  All of the usual sequence operations,
408including indexing, index assignment, slicing and slice assignment, work as
409you would expect.  Note that the result of indexing (slicing) a buffer is a
410string (list of strings).  This has one unusual consequence - b[:] is
411different from b.  In particular, "b[:] = None" deletes the whole of the
412buffer, whereas "b = None" merely updates the variable b, with no effect on
413the buffer.
414
415Buffer indexes start at zero, as is normal in Python.  This differs from vim
416line numbers, which start from 1.  This is particularly relevant when dealing
417with marks (see below) which use vim line numbers.
418
419The buffer object attributes are:
420	b.vars		Dictionary-like object used to access
421			|buffer-variable|s.
422	b.options	Mapping object (supports item getting, setting and
423			deleting) that provides access to buffer-local options
424			and buffer-local values of |global-local| options.  Use
425			|python-window|.options if option is window-local,
426			this object will raise KeyError.  If option is
427			|global-local| and local value is missing getting it
428			will return None.
429	b.name		String, RW.  Contains buffer name (full path).
430			Note: when assigning to b.name |BufFilePre| and
431			|BufFilePost| autocommands are launched.
432	b.number	Buffer number.  Can be used as |python-buffers| key.
433			Read-only.
434	b.valid		True or False.  Buffer object becomes invalid when
435			corresponding buffer is wiped out.
436
437The buffer object methods are:
438	b.append(str)	Append a line to the buffer
439	b.append(str, nr)  Idem, below line "nr"
440	b.append(list)	Append a list of lines to the buffer
441			Note that the option of supplying a list of strings to
442			the append method differs from the equivalent method
443			for Python's built-in list objects.
444	b.append(list, nr)  Idem, below line "nr"
445	b.mark(name)	Return a tuple (row,col) representing the position
446			of the named mark (can also get the []"<> marks)
447	b.range(s,e)	Return a range object (see |python-range|) which
448			represents the part of the given buffer between line
449			numbers s and e |inclusive|.
450
451Note that when adding a line it must not contain a line break character '\n'.
452A trailing '\n' is allowed and ignored, so that you can do: >vim
453	:py b.append(f.readlines())
454
455Buffer object type is available using "Buffer" attribute of vim module.
456
457Examples (assume b is the current buffer) >vim
458	:py print(b.name)		# write the buffer file name
459	:py b[0] = "hello!!!"		# replace the top line
460	:py b[:] = None			# delete the whole buffer
461	:py del b[:]			# delete the whole buffer
462	:py b[0:0] = [ "a line" ]	# add a line at the top
463	:py del b[2]			# delete a line (the third)
464	:py b.append("bottom")		# add a line at the bottom
465	:py n = len(b)			# number of lines
466	:py (row,col) = b.mark('a')	# named mark
467	:py r = b.range(1,5)		# a sub-range of the buffer
468	:py b.vars["foo"] = "bar"	# assign b:foo variable
469	:py b.options["ff"] = "dos"	# set fileformat
470	:py del b.options["ar"]		# same as :set autoread<
471
472==============================================================================
473Range objects						*python-range*
474
475Range objects represent a part of a vim buffer.  You can obtain them in a
476number of ways:
477	- via vim.current.range (|python-current|)
478	- from a buffer's range() method (|python-buffer|)
479
480A range object is almost identical in operation to a buffer object.  However,
481all operations are restricted to the lines within the range (this line range
482can, of course, change as a result of slice assignments, line deletions, or
483the range.append() method).
484
485The range object attributes are:
486	r.start		Index of first line into the buffer
487	r.end		Index of last line into the buffer
488
489The range object methods are:
490	r.append(str)	Append a line to the range
491	r.append(str, nr)  Idem, after line "nr"
492	r.append(list)	Append a list of lines to the range
493			Note that the option of supplying a list of strings to
494			the append method differs from the equivalent method
495			for Python's built-in list objects.
496	r.append(list, nr)  Idem, after line "nr"
497
498Range object type is available using "Range" attribute of vim module.
499
500Example (assume r is the current range):
501	# Send all lines in a range to the default printer
502	vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
503
504==============================================================================
505Window objects						*python-window*
506
507Window objects represent vim windows.  You can obtain them in a number of
508ways:
509	- via vim.current.window (|python-current|)
510	- from indexing vim.windows (|python-windows|)
511	- from indexing "windows" attribute of a tab page (|python-tabpage|)
512	- from the "window" attribute of a tab page (|python-tabpage|)
513
514You can manipulate window objects only through their attributes.  They have no
515methods, and no sequence or other interface.
516
517Window attributes are:
518	buffer (read-only)	The buffer displayed in this window
519	cursor (read-write)	The current cursor position in the window
520				This is a tuple, (row,col).
521	height (read-write)	The window height, in rows
522	width (read-write)	The window width, in columns
523	vars (read-only)	The window |w:| variables. Attribute is
524				unassignable, but you can change window
525				variables this way
526	options (read-only)	The window-local options. Attribute is
527				unassignable, but you can change window
528				options this way. Provides access only to
529				window-local options, for buffer-local use
530				|python-buffer| and for global ones use
531				|python-options|. If option is |global-local|
532				and local value is missing getting it will
533				return None.
534	number (read-only)	Window number.  The first window has number 1.
535				This is zero in case it cannot be determined
536				(e.g. when the window object belongs to other
537				tab page).
538	row, col (read-only)	On-screen window position in display cells.
539				First position is zero.
540	tabpage (read-only)	Window tab page.
541	valid (read-write)	True or False. Window object becomes invalid
542				when corresponding window is closed.
543
544The height attribute is writable only if the screen is split horizontally.
545The width attribute is writable only if the screen is split vertically.
546
547Window object type is available using "Window" attribute of vim module.
548
549==============================================================================
550Tab page objects					*python-tabpage*
551
552Tab page objects represent vim tab pages. You can obtain them in a number of
553ways:
554	- via vim.current.tabpage (|python-current|)
555	- from indexing vim.tabpages (|python-tabpages|)
556
557You can use this object to access tab page windows. They have no methods and
558no sequence or other interfaces.
559
560Tab page attributes are:
561	number		The tab page number like the one returned by
562			|tabpagenr()|.
563	windows		Like |python-windows|, but for current tab page.
564	vars		The tab page |t:| variables.
565	window		Current tabpage window.
566	valid		True or False. Tab page object becomes invalid when
567			corresponding tab page is closed.
568
569TabPage object type is available using "TabPage" attribute of vim module.
570
571==============================================================================
572pyeval() and py3eval() Vim functions			*python-pyeval*
573
574To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
575functions to evaluate Python expressions and pass their values to Vim script.
576|pyxeval()| is also available.
577
578==============================================================================
579Python 3						*python3*
580
581As Python 3 is the only supported version in Nvim, "python" is synonymous
582with "python3" in the current version. However, code that aims to support older
583versions of Nvim, as well as Vim, should prefer to use "python3" variants
584explicitly if Python 3 is required.
585
586							*:py3* *:python3*
587:[range]py3 {stmt}
588:[range]py3 << [trim] [{endmarker}]
589{script}
590{endmarker}
591
592:[range]python3 {stmt}
593:[range]python3 << [trim] [{endmarker}]
594{script}
595{endmarker}
596	The `:py3` and `:python3` commands work similar to `:python`.  A
597	simple check if the `:py3` command is working: >vim
598		:py3 print("Hello")
599<
600	To see what version of Python you have: >vim
601		:py3 import sys
602		:py3 print(sys.version)
603<							*:py3file*
604:[range]py3f[ile] {file}
605	The `:py3file` command works similar to `:pyfile`.
606							*:py3do*
607:[range]py3do {body}
608	The `:py3do` command works similar to `:pydo`.
609
610							*E880*
611Raising SystemExit exception in python isn't endorsed way to quit vim, use:
612>vim
613	:py vim.command("qall!")
614<
615							*has-python*
616You can test if Python is available with: >vim
617	if has('pythonx')
618	  echo 'there is Python'
619	endif
620	if has('python3')
621	  echo 'there is Python 3.x'
622	endif
623
624Python 2 is no longer supported. Thus `has('python')` always returns
625zero for backwards compatibility reasons.
626
627==============================================================================
628Python X						*python_x* *pythonx*
629
630The "pythonx" and "pyx" prefixes were introduced for python code which
631works with Python 2.6+ and Python 3. As Nvim only supports Python 3,
632all these commands are now synonymous to their "python3" equivalents.
633
634							*:pyx* *:pythonx*
635`:pyx` and `:pythonx` work the same as `:python3`.  To check if `:pyx` works: >vim
636	:pyx print("Hello")
637
638To see what version of Python is being used: >vim
639	:pyx import sys
640	:pyx print(sys.version)
641<
642					*:pyxfile* *python_x-special-comments*
643`:pyxfile` works the same as `:py3file`.
644
645							*:pyxdo*
646`:pyxdo` works the same as `:py3do`.
647
648							*has-pythonx*
649To check if `pyx*` functions and commands are available: >vim
650	if has('pythonx')
651	  echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
652	endif
653<
654
655 vim:tw=78:ts=8:noet:ft=help:norl: