if_pyth.txt 25 KB

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