Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
if_pyth.txt  ForVim version 9.2.  Last change: 2026 Feb 14VIM REFERENCE MANUAL  by Paul MooreThePythonInterface to VimpythonPython1. Commandspython-commands2. The vim modulepython-vim3. Bufferobjectspython-buffer4. Rangeobjectspython-range5. Windowobjectspython-window6.Tab pageobjectspython-tabpage7. vim.bindevalobjectspython-bindeval-objects8. pyeval(),py3eval() Vimfunctionspython-pyeval9. Dynamic loadingpython-dynamic10.Python 3python311.PythonXpython_x12. Building withPython supportpython-buildingThePython 2.xinterfaceis available only when Vim was compiled with the+python feature.ThePython 3interfaceis available only when Vim was compiled with the+python3 feature.Both can be availableat the same time, but readpython-2-and-3.NOTE:Python 2is old and no longer being developed.  UsingPython 3is highlyrecommended.Python 2 support will be dropped whenit does not work properlyanymore.==============================================================================1. Commandspython-commands:python:pyE263E264E887:[range]py[thon]{stmt}ExecutePython statement{stmt}.A simple check ifthe:python commandis working::python print "Hello":[range]py[thon]<<[trim] [{endmarker}]{script}{endmarker}ExecutePythonscript{script}.Note: This command doesn't work when thePythonfeature wasn't compiled in.  To avoid errors, seescript-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 commandis mainly useful for includingpython codein Vim scripts.Example:function! IcecreamInitialize()python << EOFclass StrawberryIcecream:def __call__(self):print 'EAT ME'EOFendfunctionTo see what version ofPython you have::python print(sys.version)Thereis no need to import sys, it's done by default.python-environmentEnvironmentvariables set in Vim are not always available in Python.  Thisdepends on how Vim andPython were built.  Also seehttps://docs.python.org/3/library/os.html#os.environNote:Pythonis very sensitive to the indenting.  Make sure the "class" lineand "EOF"do not have any indent.:pydo:[range]pydo{body}ExecutePython function "def _vim_pydo(line, linenr):{body}" for each line in the[range], with thefunction arguments being set to the text of each linein turn, withouta trailing<EOL>, and the currentline number.  The function should returnastring orNone.  Ifastringis returned,it becomes the text ofthe 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 tofiltera range usingpython.  For example::py3 << EOFneedle = 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 thePythonscript in{file}.  The wholeargumentis usedasa single file name.Both of these commandsdo essentially the same thing- they executea piece ofPython code, with the "current range"python-range set to the given linerange.In thecase of :python, the code to executeis in the command-line.In thecase of :pyfile, the code to executeis the contents of the given file.Python commands cannot be used in thesandbox.To pass arguments you need to set sys.argv[] explicitly.  Example::python sys.argv = ["foo", "bar"]:pyfile myscript.pyHere are some examplespython-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 thePython interpreter.)==============================================================================2. The vim modulepython-vimPython code gets all of its access to vim (with one exception- seepython-output below) via the "vim" module.  The vim moduleimplements twomethods, three constants, and one error object.  You need to import the vimmodule before using it::python import vimOverview: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 linesMethods of the "vim" modulevim.command(str)python-commandExecutes 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 executesNormal mode commands:def normal(str):vim.command("normal "+str)# Note the use of single quotes to delimit a string containing# double quotesnormal('"a2dd"aP')E659The ":python" command cannot be used recursively withPython 2.2 andolder.  This only works withPython 2.3 and later:    :py vim.command("python print 'Hello again Python'")vim.eval(str)python-evalEvaluates theexpression str using the vim internalexpressionevaluator (seeexpression).  Returns theexpression result as:-astring if the Vimexpression evaluates toastring or number-alist if the Vimexpression evaluates toa Vimlist-atuple if the Vimexpression evaluates toa Vimtuple-a dictionary if the Vimexpression evaluates toa Vimdict-aboolean if Vim exression evaluates tov:true orv:false-None if Vimexpression evaluates tov:null orv:noneDictionaries, lists and tuples 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 tuple = vim.eval('(1, 2, 3)')    :    :py tagList = vim.eval('taglist("eval_expr")')The latter will returnapythonlist ofpython dicts, for instance:[{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name':'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}]NOTE: InVim9 script, localvariables in deffunctions are not visibletopython evaluations.  To pass localvariables topython evaluations,use the{locals}dict when callingpy3eval() and friends.vim.bindeval(str)python-bindevalLikepython-eval, but returns specialobjects described inpython-bindeval-objects.  Thesepythonobjects let you modify(List,Tuple orDictionary) or call(Funcref) vim objects.vim.strwidth(str)python-strwidthLikestrwidth(): returns number of display cells str occupies,tabis countedas one cell.vim.foreach_rtp(callable)python-foreach_rtpCall the given callable for each path in'runtimepath' until eithercallable returns something but None, the exceptionis raised or thereare no longer paths.  If stopped incase callable returned non-None,vim.foreach_rtp function returns the value returned by callable.vim.chdir(*args, **kwargs)python-chdirvim.fchdir(*args, **kwargs)python-fchdirRun os.chdir or os.fchdir, then all appropriate vim stuff.Note: you should not use thesefunctions directly, use os.chdir and      os.fchdir instead.  Behavior of vim.fchdiris undefined incase      os.fchdir does not exist.Errorobject of the "vim" modulevim.errorpython-errorUpon encounteringa Vim error,Python raises an exception of typevim.error.Example:try:vim.command("put a")except vim.error:# nothing in register aConstants of the "vim" moduleNote that these are not actually constants- you could reassign them.But thisis silly,as you would then lose access to the vimobjectsto which thevariables referred.vim.bufferspython-buffersAmappingobject providing access to thelist of vim buffers.  Theobject 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 listvim.windowspython-windowsA sequenceobject providing access to thelist of vim windows.  Theobject 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 accessNote: vim.windowsobject always accesses currenttab page.python-tabpage.windowsobjects are bound to parentpython-tabpageobject and always usewindows from thattab page (or throw vim.errorincasetab page was deleted).  You can keepareference to bothwithout keepingareference to vim moduleobject orpython-tabpage,they will not lose their properties in this case.vim.tabpagespython-tabpagesA sequenceobject providing access to thelist of vimtab pages.  Theobject 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 accessvim.currentpython-currentAnobject providing access (via specific attributes) tovarious"current"objects available invim:vim.current.lineThe current line (RW)Stringvim.current.bufferThe current buffer (RW)Buffervim.current.windowThe currentwindow (RW)Windowvim.current.tabpageThe currenttab page (RW)TabPagevim.current.rangeThe current line range (RO)RangeThe lastcase deservesa little explanation.  When the:python or:pyfile commandspecifiesa range, this range of lines becomes the"current range".A rangeisa bit likea buffer, but with all accessrestricted toa subset of lines.  Seepython-range for more details.Note: When assigning to vim.current.{buffer,window,tabpage}it expectsvalidpython-buffer,python-window orpython-tabpageobjectsrespectively.  Assigning triggers normal (withautocommands)switching to given buffer,window ortab page.  Itis the only way toswitch UIobjects in python: you can't assign topython-tabpage.window attribute.  To switch without triggeringautocommands 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    EOFvim.varspython-varsvim.vvarspython-vvarsDictionary-likeobjects holding dictionaries with global(g:) andvim(v:)variables respectively.  Identical tovim.bindeval("g:"),but faster.vim.optionspython-optionsObject partly supportingmapping protocol (supports setting andgetting items) providinga read-write access to global options.Note: unlike:set this provides access only to global options.  Youcannot use thisobject to obtain or set local options' values oraccess local-onlyoptions in any fashion.  Raises KeyError if noglobal option with such name exists (i.e. does not raise KeyError forglobal-localoptions and global only options, but does for window-and buffer-local ones).  Usepython-bufferobjects to access tobuffer-localoptions andpython-windowobjects to access towindow-local options.Type of thisobjectis available via "Options" attribute of vimmodule.Output fromPythonpython-outputVim displays allPython code output in the Vim message area.Normaloutput appearsas information messages, and error output appearsaserror messages.In implementation terms, this means that all output to sys.stdout(including the output from print statements) appearsas informationmessages, and all output to sys.stderr (including error tracebacks)appearsas error messages.python-inputInput (via sys.stdin, includinginput() and raw_input())is notsupported, and may cause the program to crash.  This should probablybe fixed.python2-directorypython3-directorypythonx-directoryPython'runtimepath' handlingpython-special-pathInpython vim.VIM_SPECIAL_PATH special directoryis usedasa replacement forthelist of paths found in'runtimepath': with this directory in sys.path andvim.path_hooks in sys.path_hookspython will try to load module from{rtp}/python2 (or python3) and{rtp}/pythonx (for bothpython versions) foreach{rtp} found in'runtimepath' (Note: find_module() has been removed fromimp module aroundPython 3.12.0a7).Implementationis 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_PATHpython-VIM_SPECIAL_PATHString constant used in conjunction with vim path hook.  If path hookinstalled by vimis requested to handle anything but path equal tovim.VIM_SPECIAL_PATH constantit raises ImportError.  In the onlyothercaseit uses special loader.Note: youmust not use value of this constant directly, always use      vim.VIM_SPECIAL_PATH object.vim.find_module(...)python-find_modulevim.path_hook(path)python-path_hookvim.find_spec(...)python-find_specMethods orobjects used to implement path loadingas described above.You should not be using any of these directly except for vim.path_hookincase you need todo something with sys.meta_path, vim.find_spec()is availablestarting withPython 3.7.Itis not guaranteed that any of theobjects will exist in future vimversions.vim._get_pathspython-_get_pathsMethods returningalist of paths which will be searched for by pathhook.  You should not rely on thismethod being present in futureversions, but can useit for debugging.It returnsalist of{rtp}/python2 (or{rtp}/python3) and{rtp}/pythonx directories for each{rtp} in'runtimepath'.==============================================================================3. Bufferobjectspython-bufferBufferobjects represent vim buffers.  You can obtain them ina number ofways:- via vim.current.buffer(python-current)- from indexing vim.buffers(python-buffers)- from the "buffer" attribute ofawindow(python-window)Bufferobjects have two read-only attributes- name- the full file name forthe buffer, and number- the buffer number.  They also have three methods(append, mark, and range; see below).You can also treat bufferobjectsas sequence objects.  In this context, theyactas if they were lists (yes, they are mutable) of strings, with eachelement beinga line of the buffer.  All of the usual sequence operations,including indexing,index assignment, slicing andslice assignment, workasyou would expect.Note that the result of indexing (slicing)a bufferisastring (list of strings).  This has one unusual consequence- b[:]isdifferent from b.  In particular, "b[:]=None" deletes the whole of thebuffer, whereas "b=None" merely updates the variable b, with no effect onthe buffer.Buffer indexes startat zero,asis normal in Python.  This differs from vimline numbers, which start from 1.  Thisis particularly relevant when dealingwith marks (see below) which use vim line numbers.The bufferobject attributes are:b.varsDictionary-likeobject used to accessbuffer-variables.b.optionsMappingobject (supports item getting, setting anddeleting) that provides access to buffer-localoptionsand buffer-local values ofglobal-local options.  Usepython-window.options if optionis window-local,thisobject will raise KeyError.  If optionisglobal-local and local valueis missing gettingitwill return None.b.nameString, RW.  Contains buffer name (full path).Note: when assigning to b.nameBufFilePre andBufFilePostautocommands are launched.b.numberBuffer number.  Can be usedaspython-buffers key.Read-only.b.validTrue or False.  Bufferobject becomes invalid whencorresponding bufferis wiped out.The bufferobject methods are:b.append(str)Appenda line to the bufferb.append(str, nr)  Idem, below line "nr"b.append(list)Appendalist of lines to the bufferNote that the option of supplyingalist of strings tothe appendmethod differs from the equivalentmethodfor Python's built-inlist objects.b.append(list, nr)  Idem, below line "nr"b.mark(name)Returnatuple (row,col) representing the positionof the namedmark (can also get the[]"<> marks)b.range(s,e)Returna rangeobject (seepython-range) whichrepresents the part of the given buffer between linenumberss andeinclusive.Note that when addinga lineitmust not containa line break character '\n'.A trailing '\n'is allowed and ignored, so that you can do::py b.append(f.readlines())Bufferobject typeis available using "Buffer" attribute of vim module.Examples (assumebis 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. Rangeobjectspython-rangeRangeobjects representa part ofa vim buffer.  You can obtain them inanumber of ways:- via vim.current.range(python-current)- froma buffer'srange()method(python-buffer)A rangeobjectis almost identical in operation toa buffer object.  However,all operations are restricted to the lines within the range (this line rangecan, of course, changeasa result ofslice assignments, line deletions, orthe range.append() method).The rangeobject attributes are:r.startIndex of first line into the bufferr.endIndex of last line into the bufferThe rangeobject methods are:r.append(str)Appenda line to the ranger.append(str, nr)  Idem, after line "nr"r.append(list)Appendalist of lines to the rangeNote that the option of supplyingalist of strings tothe appendmethod differs from the equivalentmethodfor Python's built-inlist objects.r.append(list, nr)  Idem, after line "nr"Rangeobject typeis available using "Range" attribute of vim module.Example (assumeris the current range):# Send all lines in a range to the default printervim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))==============================================================================5. Windowobjectspython-windowWindowobjects represent vim windows.  You can obtain them ina number ofways:- via vim.current.window(python-current)- from indexing vim.windows(python-windows)- from indexing "windows" attribute ofatab page(python-tabpage)- from the "window" attribute ofatab page(python-tabpage)You can manipulatewindowobjects only through their attributes.  They have nomethods, and no sequence or other interface.Window attributes are:buffer (read-only)The buffer displayed in thiswindowcursor (read-write)The current cursor position in thewindowThisisa tuple, (row,col).height (read-write)Thewindow height, in rowswidth (read-write)Thewindow width, in columnsvars (read-only)Thewindoww: variables. Attributeisunassignable, but you can changewindowvariables this wayoptions (read-only)The window-local options. Attributeisunassignable, but you can changewindowoptions this way. Provides access only towindow-local options, for buffer-local usepython-buffer and for global ones usepython-options. If optionisglobal-localand local valueis missing gettingit willreturn None.number (read-only)Window number.  The firstwindow has number 1.Thisis zero incaseit cannot be determined(e.g. when thewindowobject belongs to othertab page).row, col (read-only)On-screenwindow position in display cells.First positionis zero.tabpage (read-only)Windowtab page.valid (read-write)True or False. Windowobject becomes invalidwhen correspondingwindowis closed.The height attributeis writable only if the screenis split horizontally.The width attributeis writable only if the screenis split vertically.Windowobject typeis available using "Window" attribute of vim module.==============================================================================6.Tab pageobjectspython-tabpageTab pageobjects represent vimtab pages. You can obtain them ina number ofways:- via vim.current.tabpage(python-current)- from indexing vim.tabpages(python-tabpages)You can use thisobject to accesstab page windows. They have no methods andno sequence or other interfaces.Tab page attributes are:numberThetab page number like the one returned bytabpagenr().windowsLikepython-windows, but for currenttab page.varsThetab paget: variables.windowCurrenttabpage window.validTrue or False.Tab pageobject becomes invalid whencorrespondingtab pageis closed.TabPageobject typeis available using "TabPage" attribute of vim module.==============================================================================7. vim.bindevalobjectspython-bindeval-objectsvim.Dictionaryobjectpython-Dictionary    Dictionary-likeobject providing access to vimDictionary type.    Attributes:        Attribute  Description        locked     One ofpython-.locked                    Value           Description                    zero            Variableis not locked                    vim.VAR_LOCKED  Variableis locked, but can be unlocked                    vim.VAR_FIXED   Variableis locked and can't be unlocked                   Read-write. You can unlock locked variable by assigningTrue orFalse to this attribute. No recursive lockingis supported.        scope      One of                    Value              Description                    zeroDictionaryis nota scope one                    vim.VAR_DEF_SCOPEg: orl: dictionary                    vim.VAR_SCOPE      Other scope dictionary,                                       seeinternal-variables    Methods (note: methodsdo not support keyword arguments):        Method      Descriptionkeys()      Returnsalist with dictionary keys.values()    Returnsalist with dictionary values.items()     Returnsalist of 2-tuples with dictionary contents.        update(iterable), update(dictionary), update(**kwargs)                    Adds keys to dictionary.        get(key[, default=None])                    Obtain key from dictionary, returning the default ifitis                    not present.        pop(key[, default])                    Remove specified key from dictionary and return                    corresponding value. If keyis not found and defaultis                    given returns the default, otherwise raises KeyError.        popitem()                    Removerandom key from dictionary and return (key, value)                    pair.        has_key(key)                    Check whether dictionary contains specified key, similar                    to `key in dict`.        __new__(), __new__(iterable), __new__(dictionary), __new__(update)                    You can usevim.Dictionary() to create new vim                    dictionaries.d=vim.Dictionary(arg)is the sameasd=vim.bindeval('{}');d.update(arg). Without arguments                    constructs empty dictionary.    Examples:        d = vim.Dictionary(food="bar")# Constructor        d['a'] = 'b'# Item assignment        print d['a']# getting item        d.update({'c': 'd'})# .update(dictionary)        d.update(e='f')# .update(**kwargs)        d.update((('g', 'h'), ('i', 'j')))# .update(iterable)        for key in d.keys():# .keys()        for val in d.values():# .values()        for key, val in d.items():# .items()        print isinstance(d, vim.Dictionary)# True        for key in d:# Iteration over keys        class Dict(vim.Dictionary):# SubclassingNote: when iterating over keys you should not modify dictionary.vim.Listobjectpython-List    Sequence-likeobject providing access to vimList type.    Supports.locked attribute, seepython-.locked. Also supports the    following methods:        Method          Description        extend(item)    Add items to the list.        __new__(), __new__(iterable)                        You can usevim.List() to create new vim lists.l=vim.List(iterable)is the sameasl=vim.bindeval('[]');l.extend(iterable). Without                        arguments constructs empty list.    Examples:        l = vim.List("abc")# Constructor, result: ['a', 'b', 'c']        l.extend(['abc', 'def'])# .extend() method        print l[1:]# slicing        l[:0] = ['ghi', 'jkl']# slice assignment        print l[0]# getting item        l[0] = 'mno'# assignment        for i in l:# iteration        print isinstance(l, vim.List)# True        class List(vim.List):# Subclassingvim.Tupleobjectpython-Tuple    Sequence-likeobject providing access to vimTuple type.    Supports.locked attribute, seepython-.locked. Also supports the    following methods:        Method          Description        __new__(), __new__(iterable)                        You can usevim.Tuple() to create new vim tuples.                        Without arguments constructs empty list.    Examples:        t = vim.Tuple("abc")# Constructor, result: ('a', 'b', 'c')        print t[1:]# slicing        print t[0]# getting item        for i in t:# iteration        print isinstance(t, vim.Tuple)# True        class Tuple(vim.Tuple):# Subclassingvim.Functionobjectpython-Function    Function-like object, acting like vimFuncref object. Accepts special    keyword argumentself, seeDictionary-function. You can also usevim.Function(name) constructor,itis the sameasvim.bindeval('function(%s)'%json.dumps(name)).    Attributes (read-only):        Attribute    Description        name         Function name.        argsNone orapython-Listobject with arguments.Note                     that thisisa copy of the arguments list, constructed                     each time you request this attribute. Modifications made                     to thelist will be ignored (but not to the containers                     inside argument list: thisis likecopy() and notdeepcopy()).selfNone orapython-Dictionaryobject withself                     dictionary.Note that explicitself keyword used when                     calling resultingobject overrides this attribute.        auto_rebind  Boolean. True ifpartial created from thisPythonobject                     and stored in the Vimscript dictionary should be                     automatically rebound to the dictionaryitis stored in                     when this dictionaryis indexed. Exposes Vim internal                     difference betweendict.func (auto_rebind=True) andfunction(dict.func,dict) (auto_rebind=False). This                     attribute makes no sense ifself attributeisNone.    Constructor additionally acceptsargs,self andauto_rebind    keywords.  Ifargs and/orself argumentis given thenit constructsa partial, seefunction().auto_rebindis only used whenself    argumentis given, otherwiseitis assumed to beTrue regardless of    whetherit was given or not.  Ifselfis given thenit defaults toFalse.    Examples:        f = vim.Function('tr')# Constructor        print f('abc', 'a', 'b')# Calls tr('abc', 'a', 'b')        vim.command('''            function DictFun() dict                return self            endfunction        ''')        f = vim.bindeval('function("DictFun")')        print f(self={})# Like call('DictFun', [], {})        print isinstance(f, vim.Function)# True        p = vim.Function('DictFun', self={})        print f()        p = vim.Function('tr', args=['abc', 'a'])        print f('b')==============================================================================8.pyeval() andpy3eval() Vimfunctionspython-pyevalTo facilitate bi-directional interface, you can usepyeval() andpy3eval()functions to evaluatePython expressions and pass their values to Vim script.pyxeval()is also available.You can inject localvariables into the evaluation using the optional{locals}dict. This can be particularly useful invim9script where vim.evalpython-eval will not find locals ina def func.ThePython value "None"is converted to v:none.==============================================================================9. Dynamic loadingpython-dynamicOnMS-Windows andUnix thePython library can be loaded dynamically.  The:version output then includes+python/dyn or+python3/dyn.This means that Vim will search for thePython DLL or shared library file onlywhen needed.  When you don't use thePythoninterface you don't need it, thusyou can use Vim without this file.MS-WindowsTo use thePythoninterface thePython DLLmust be in your search path.  Inaconsolewindow type "path" to see what directories are used.  If the DLLisnot found in your search path, Vim will check the registry to find the pathwherePythonis installed.  The'pythondll' or'pythonthreedll' option can bealso used to specify thePython DLL.The name of the DLL should match thePython version Vim was compiled with.Currently the name forPython 2is "python27.dll", thatis forPython 2.7.Thatis the default value for'pythondll'.  ForPython 3itis python36.dll(Python 3.6).  To know for sure edit "gvim.exe" and search for"python\d*.dll\c".UnixThe'pythondll' or'pythonthreedll' option can be used to specify thePythonshared library file instead of DYNAMIC_PYTHON_DLL or DYNAMIC_PYTHON3_DLL filewhat were specifiedat compile time.  The version of the shared librarymustmatch thePython 2.x orPython 3 version(v:python3_version) Vim wascompiled with unless usingpython3-stable-abi.Stable ABI and mixing Python versionspython-stablepython-stable-abipython3-stable-abiIf Vim was not compiled with Stable ABI (only available forPython 3), theversion of thePython shared librarymust match the version that Vim wascompiled with.  Otherwise, mixing versions could result in unexpected crashesand failures.  With Stable ABI, this restrictionis relaxed, and anyPython 3library with version ofat leastv:python3_version will work.  Seehas-python for how to check if Stable ABIis supported, or see if versionoutput includes+python3/dyn-stable.On MS-Windows,'pythonthreedll' will be set to "python3.dll".  When searchingthe DLL from the registry, Vim will search the latest version of Python.==============================================================================10.Python 3python3:py3:python3:[range]py3{stmt}:[range]py3<<[trim] [{endmarker}]{script}{endmarker}:[range]python3{stmt}:[range]python3<<[trim] [{endmarker}]{script}{endmarker}The:py3 and:python3 commands work similar to:python.Asimple check if the:py3 commandis working::py3 print("Hello")To see what version ofPython you have::py3 import sys:py3 print(sys.version):py3file:[range]py3f[ile]{file}The:py3file command works similar to:pyfile.:py3do:[range]py3do{body}The:py3do command works similar to:pydo.Vim can be built in four ways (:version output):1. NoPython support    (-python, -python3)2.Python 2 support only    (+python or +python/dyn, -python3)3.Python 3 support only    (-python,+python3 or +python3/dyn)4.Python 2 and 3 support   (+python/dyn, +python3/dyn)Some more details on the specialcase 4:python-2-and-3WhenPython 2 andPython 3 are both supported theymust be loaded dynamically.When doing this on Linux/Unix systems and importing global symbols, this leadstoa crash when the secondPython versionis used.  So either global symbolsare loaded but only onePython versionis activated, or no global symbols areloaded. The latter makes Python's "import" fail on libraries that expect thesymbols to be provided by Vim.E836E837Vim's configurationscript makesa guess for all libraries based on onestandardPython library (termios).  If importing this library succeeds forbothPython versions, then both will be made available in Vimat the sametime.  If not, only the version first used ina session will be enabled.When trying to use the other one you will get theE836 orE837 error message.Here Vim's behavior depends on the system in whichit was configured.  Inasystem where both versions ofPython were configured with --enable-shared,both versions ofPython will be activatedat the same time.  There will stillbe problems with other third party libraries that were not linked tolibPython.To work around such problems there are these options:1. The problematic libraryis recompiled to link to the according   libpython.so.2. Vimis recompiled for only onePython version.3. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration.  This   may crash Vim though.E880Raising SystemExit exception inpython isn't endorsed way to quit vim, use::py vim.command("qall!")E1266This error can occur whenPython 3 cannot load the required modules.  Thismeans that yourPython 3is not correctly installed or there are some mistakesin your settings.  Please check the following items:1. Make sure thatPython 3is correctly installed.  Also check the version of   python.2. Check the'pythonthreedll' option.3. Check the'pythonthreehome' option.4. Check the PATH environment variable if you don't set'pythonthreedll'.   On MS-Windows, you can use where.exe to check which dll will be loaded.   E.g.where.exe python310.dll5. Check the PYTHONPATH and PYTHONHOME environment variables.has-pythonYou can test whatPython versionis available with:if has('python')  echo 'there is Python 2.x'endifif has('python3')  echo 'there is Python 3.x'endifNote however, that whenPython 2 and 3 are both available and loadeddynamically, thesehas() calls will try to load them.  If only one can beloadedata time, just checking ifPython 2 or 3 are available will preventthe other one from being available.To avoid loading the dynamic library, only check if Vim was compiled withpython support:if has('python_compiled')  echo 'compiled with Python 2.x support'  if has('python_dynamic')    echo 'Python 2.x dynamically loaded'  endifendifif has('python3_compiled')  echo 'compiled with Python 3.x support'  if has('python3_dynamic')    echo 'Python 3.x dynamically loaded'  endifendifWhen loading the library dynamically, Vim can be compiled to supportPython 3Stable ABI(python3-stable-abi) which allows you to loada different versionofPython 3 library than the one Vim was compiled with.  To check it:if has('python3_dynamic')  if has('python3_stable')    echo 'support Python 3 Stable ABI.'  else    echo 'does not support Python 3 Stable ABI.'    echo 'only use Python 3 version ' .. v:python3_version  endifendifThis also tells you whetherPythonis dynamically loaded, which will fail ifthe runtime library cannot be found.==============================================================================11.PythonXpython_xpythonxBecause mostpython code can be written so thatit works withPython 2.6+ andPython 3 the pyx*functions and commands have been written.  They work exactlythe sameas thePython 2 and 3 variants, but select thePython version usingthe'pyxversion' setting.You should set'pyxversion' in your.vimrc to preferPython 2 orPython 3forPython commands. If you change this settingat runtime you may risk thatstate of plugins (suchas initialization) may be lost.If you want to usea module, you canputit in the{rtp}/pythonx directory.Seepythonx-directory.:pyx:pythonxThe:pyx and:pythonx commands work similar to:python.A simple checkif the:pyx commandis working::pyx print("Hello")To see what version ofPythonis being used::pyx import sys:pyx print(sys.version):pyxfilepython_x-special-commentsThe:pyxfile command works similar to:pyfile.  However you can add one ofthese comments to force Vim using:pyfile or:py3file:  #!/any string/python2" Shebang. Must be the first line of the file.  #!/any string/python3" Shebang. Must be the first line of the file.  # requires python 2.x" Maximum lines depend on 'modelines'.  # requires python 3.x" Maximum lines depend on 'modelines'.Unlike normal modelines, the bottom of the fileis not checked.If none of them are found, the'pyxversion' settingis used.W20W21If Vim does not support the selectedPython versiona silent message will beprinted.  Use:messages to read them.:pyxdoThe:pyxdo command works similar to:pydo.has-pythonxYou can test if pyx* commands are available with:if has('pythonx')  echo 'pyx* commands are available. (Python ' .. &pyx .. ')'endifWhen compiled with only one of+python or+python3, thehas() returns 1.When compiled with both+python and+python3, the test depends on the'pyxversion' setting.  If'pyxversion'is 0,it testsPython 3 first, and ifitis not available thenPython 2.  If'pyxversion'is 2 or 3,it tests onlyPython 2 or 3 respectively.Note that forhas('pythonx') to workit may try to dynamically loadPython 3or 2.  This may have side effects, especially when Vim can only load one ofthe two.Ifa user prefersPython 2 and want to fallback toPython 3, he needs to set'pyxversion' explicitly in his.vimrc.  E.g.:if has('python')  set pyx=2elseif has('python3')  set pyx=3endif==============================================================================12. Building withPython supportpython-buildingA few hints for building withPython 2 or 3 support.UNIXSee src/Makefile for how to enable including thePython interface.On Ubuntu you will want toinstall thesepackages forPython 2:pythonpython-devForPython 3:python3python3-devForPython 3.6:python3.6python3.6-devIf you have more than one version ofPython 3, you need to linkpython3 to theone you prefer, before running configure.============================================================================== vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2026 Movatter.jp