Skip to content

Instantly share code, notes, and snippets.

@ZyX-I
Last active December 17, 2015 05:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZyX-I/5561409 to your computer and use it in GitHub Desktop.
Save ZyX-I/5561409 to your computer and use it in GitHub Desktop.

New python objects

vim.mappings/{buffer}.mappings:

Mapping-like object mapping mode constants to vim.modemappings objects below. Unlike vim.buffers iteration is being done for keys. Mode constants are described below in vim.current.mode object description, but for convenience additional constants are defined:

  • vim.MODE_ANY_SELECTION: vim.MODE_VISUAL|vim.MODE_SELECT: stands for the mode list of vnoremap command.
  • vim.MODE_MAPPING_DEFAULT: vim.MODE_NORMAL|vim.MODE_ANY_SELECTION|vim.MODE_OPERATOR_PENDING: stands for the mode list of plain noremap command.
  • vim.MODE_GENERIC_INSERT: vim.MODE_INSERT|vim.MODE_COMMAND: stands for the mode list of noremap! command.

Existing vim.MODE_LANGUAGE stands for lnoremap mappings.

vim.abbreviations/{buffer}.abbreviations:

Same as above, but for abbreviations. Supports only vim.MODE_INSERT, vim.MODE_COMMAND and vim.MODE_GENERIC_INSERT as modes.

modemappings:

Dictionary-like object mapping expanded (see vim.special_expand() below) strings to vim.Mapping objects. Assigning Mapping objects to some key works like :*map. .sid attribute is ignored when assigning. Unlike vim.buffers iteration is being done for keys.

mapping:

Namedtuple-like object with the following attributes:

Attribute Description
rhs Rhs of the mapping.
sid Script ID.
silent True or False, tells whether mapping is silent.
expr True or False, tells whether it is <expr> mapping.
noremap
Depends on the numeric constant:
vim.MAPPING_REMAP False (zero) constant, mapping is remappable
vim.MAPPING_NOREMAP True (non-zero), mapping is noremappable
vim.MAPPING_SCRIPT True (non-zero), mapping is <script> one

No .mode or .buffer attributes: they are expressed in using appropriate vim.mappings[mode] (buffer.mappings[mode]) objects.

vim.menus/{buffer}.menus:

Similar to the above vim.mappings, but with a slightly different end-point objects: in addition to attributes described in mapping, menu object should also contain hint attribute holding the part of the menu after <Tab>.

Supports the following mode constants: vim.MODE_NORMAL, vim.MODE_VISUAL, vim.MODE_SELECT, vim.MODE_INSERT, vim.MODE_COMMAND and vim.MODE_OPERATOR_PENDING. And the following shortcuts: vim.MODE_ANY_SELECTION (see vim.mappings description above), vim.MODE_ANY (vim.MODE_GENERIC_INSERT|vim.MODE_MAPPING_DEFAULT), vim.MODE_MAPPING_DEFAULT.

vim.commands/{buffer}.commands:

Mapping-like object mapping command names to vim.Command objects. Assigning vim.Command object to the key acts like :command, .sid attribute is ignored. Unlike vim.buffers iteration is being done for keys.

command:

Namedtuple-like object with the following attributes:

Attribute Description
command Command string.
sid Script ID.
nargs

One of constants:

vim.COMMAND_ARGS_NO
vim.COMMAND_ARGS_ONE
vim.COMMAND_ARGS_ANY
vim.COMMAND_ARGS_ONE_OR_NO
vim.COMMAND_ARGS_SOME
complete String or None.
range Number or None. Number is either vim.COMMAND_RANGE_CURRENT, vim.COMMAND_RANGE_WHOLE or non-negative integer. All constants are negative integers. None is used when neither range nor count is allowed.
count True or False. Determines whether .range attribute really describes -count argument.
bang, bar, register True or False.  
vim.autocommands:

Mapping-like object mapping autocommand groups to vim.Augroup objects. Iteration is done for keys. Autocommands without groups are autocommands with group None. Defines method .run(event, fname={fname}, modeline=False).

augroup:

Mapping-like object mapping event names to list of vim.Autocommand objects. Iteration is done for keys. Methods:

.append_autocmd(event, autocommand)
.del_autocmds(event, pattern=None)
.clear(event=None)
.run(event, fname={fname}, modeline=False)

As usual, .sid attribute is ignored when using above methods. Item assignment works by calling first .clear(event=key) and then a sequence of .append_autocmd(event=key, autocmd=item).

autocommand:

Namedtuple-like object with the following attributes:

Attribute Description
command Command string.
sid Script ID.
nested True or False.
pattern Glob.
vim.signs:

Mapping-like object mapping sign names to vim.Sign attributes. Iterates over keys, supports item assignment.

sign:

Namedtuple-like object with the following attributes:

Attribute Description
icon None or file name.
linehl None or string.
text String.
texthl None or string.
{buffer}.signs:

Mapping-like object mapping place ids to signplace objects (note: they is no constructor for this). Iterates over signplace objects in order they are shown in the buffer. Methods:

.place(line, name, id=None):

Place given sign on the given line. Returns id which is equal to id argument if it was given or a new unique id.

.unplace(line=None, id=None):

Unplace sign from the given line or id or all signs if no arguments were given. If both line and id are present then it verifies whether sign with given id is placed on the given line and either unplaces it or raises ValueError.

.find(line):

Returns signplace object describing sign placed on the given line or None if no sign was placed there.

signplace:

Object with the following attributes:

Attribute Description
id Identifier.
line Line number.
name Names of signs: keys in vim.signs.

Also has method .jump().

vim.hlgroups:

Mapping-like object mapping highlight group names to vim.HighlightGroup objects or strings (keys of vim.hlgroups). Iterates over keys, supports item assignment (both vim.HighlightGroup and names).

highlightgroup:

Namedtuple-like object with the following attributes:

Attribute Description
cterm, gui, term Tuples listing attributes or None
ctermfg, ctermbg Integers, color index used or None
guifg, guibg, guisp 3-tuple with floating-point values: color coordinates in RGB space or None if no gui colors were specified or vim was compiled without +gui
_ctermfg, _ctermbg, _guifg, _guibg, _guisp

Strings: colors as specified when defining highlight group or None

 

vim.functions:

Mapping-like object mapping user function names to vim.Function objects. Accepts s: and <SID> in keys, but always expands it when creating objects.

Also uses vim.functions.builtin syntax: e.g. vim.functions.fnameescape(string) will escape the string.

function:

Callable object with the following attributes:

Attribute Description
name Function name
callable (extended funcref only) Return unwrapped python callable used by given function reference.
code Function code
sid Script ID
is_dictionary True or False.
dict For convenience vim.Dictionary can be assigned to this attribute in order to forget about specifying self= arg. Supports assigning any mapping-like object that can be converted.  
vim._tag_files, {buffer}._tag_files:

Iterators yielding tag file names. list(vim._tag_files) is an expanded version of &tags option.

vim.tags, {buffer}.tags:

Mapping-like object mapping tag names to vim.Tag objects. Does not support assignment. Iterates over vim.Tag objects, not over tag names. Iterator loads tags from files lazily, holding file handle while until its destruction or until exhausting tags in that file.

Note: it would be good if parsed contents of tag files was cached and if there added a possibility to define tags not present in files (like with zsh hash command: by adding tags to cache through existing API). Without caching it would not be possible to solve performance problems with taglist().

tag:

Objects with the following attributes:

Attribute Description
name Name of the tag
filename Name of the file where tag is defined
lineno None or line number in that file
pattern None or pattern used to locate tag in that file
cmd None or Ex command used to locate tag; is present in case it is neither lineno nor pattern (should not really ever happen)
kind String, tag kind
static True or False, specifies whether tag is specific to this file

Also has method .jump().

vim.jumps:

Sequence-like object that removes the need of parsing :jumps. Contains jump objects.

{buffer}.changes:

Like vim.jumps, but for :changes in the given buffer.

jump:

Objects with the following attributes:

Attribute Description
line Line number.
col Column number.
file None or file name.
buffer None (file not loaded) or vim.buffer object.

Also has method .jump().

vim.current.jump:

Index of the current jump in vim.jumps.

{buffer}.change:

Index of the current change in {buffer}.changes.

{buffer}.changed_tick:

Value of b:changedtick. Added as it is not available from {buffer}.vars.

vim.qflists:

Sequence-like object that provides access to a list of quickfix lists. Iterates over lists, supports item assignment.

{window}.loclists:

Same as vim.qflists, but for window location lists.

{window}.loclist:

Current vim.QFList object representing current location list.

qflist:

Sequence-like object with the following attributes:

Attribute Description
title Quickfix list title.
itervalid Iterator, iterates only over QFItem’s with .valid=True.

Read-only, supports __getitem__, slicing, __len__ and iteration.

qfitem:

Namedtuple-like object with the following attributes:

Attribute Description
valid True or False, determines whether item represents error or is just a text.
text Item text.
lnum Line number if specified, not present otherwise.
pattern Pattern used to search for the item, may be absent.
buffer vim.buffer object pointing to a buffer containing the item.
col Byte offset from the start of the line pointing to the start of the item. May be absent.
vcol Virtual column where the item starts. May be absent.
type Character with the error type. May be absent.
nr Error number.

Additionally contains method .jump().

vim.environ:

Mapping-like object, used like os.environ. If we are mocking os.chdir it also makes sense to mock os.environ with this object as os.environ is not updated.

vim.scripts:

Sequence-like object that removes the need of parsing :scriptnames. Maps script numbers (subtracted by one) to file names.

vim.select(start_line=vim.functions.line('.'), end_line=start_line, start_col=None, end_col=start_col, start_virtcol=None, end_virtcol=None, mode=vim.MODE_VISUAL, type=(vim.SELECT_LINEWISE if not start_col and not start_virtcol else vim.SELECT_CHARACTERWISE)):

Start selection after script execution finishes (like :startinsert). start_virtcol overrides start_col, end_virtcol overrides end_col, mode may only be either vim.MODE_VISUAL or vim.MODE_SELECT. If neither start_col nor start_virtcol is specified end_col and end_virtcol are ignored. type is one of the following:

Type Description
vim.SELECT_CHARACTERWISE Characterwise selection, default if starting column was specified
vim.SELECT_LINEWISE Linewise selection, default if no starting column was specified
vim.SELECT_BLOCK Blockwise selection
vim.current.selection:

Returns dictionary or mapping-like object with current selection that is suitable for passing into vim.select and contains type, start_line, end_line, start_virtcol and end_virtcol keys.

vim.registers:

Mapping-like object providing access to vim registers. Iterates over keys, supports assignment. vim.registers["a"] returns 2-tuple (vim.SELECT_*, text) (or namedtuple-like object with .text and .type attributes? And, probably, more namedtuple-like: subclass of tuple) and expects similar 2-tuple when assigning (though can accept text in place of a tuple deducing type of the register from the last character: if it is newline then register is linewise, else characterwise).

vim.marks:

Mapping-like object providing access to global marks. Returns jump objects.

{buffer}.marks:

Same as vim.marks, but for buffer. Unlike {buffer}.mark function supports iteration, returns jump objects (allowing {buffer}.marks["a"].jump()) and supports item assignment. Also does not provide access to global marks, even if these marks are defined for the current buffer.

vim.history:

Mapping-like object, providing access to command history. Supports the following keys:

Key hist*() argument
vim.HISTORY_COMMAND "cmd"/":"
vim.HISTORY_SEARCH "search"/"/"
vim.HISTORY_EXPRESSION "expr"/"="
vim.HISTORY_INPUT "input"/"@"
vim.HISTORY_DEBUG "debug"/">"

Is assignable.

history:

Sequence-like object providing access to specific history. Supports assignment, slice assignment, deleting, slice deleting, iteration (over history entries).

vim.digraphs:

Dictionary-like object mapping digraph characters (there must be two of them) to inserted text. Supports item assignment and deletion.

vim.argv:

Sequence-like object providing access to vim argument list like argv(). Supports item and slice assignment and iteration.

Notes:

  • “Namedtuple-like” means that all attributes are RO and that there are no methods.
  • “Ignored when assigning” means “set to sid which is current when assigning”.
  • “Dictionary-like” means that object supports iteration over keys, .keys(), .items() and .values() methods. If it is assignable it should also support .update(). If keys can be deleted it should also support .clear().
  • “Mapping-like” means that object supports __getitem__ method without supporting slices. All other restrictions are mentioned in the object description.

New VimL functions

maplist([{mode}[, {bufnr}]]):

Returns a list of strings suitable for maparg().

cmdarg({cmdname}[, {bufnr}]):

Returns a dictionary with the following keys, works with partial commands:

Key Value
name Full {cmdname}.
command Command string.
sid Script ID.
nargs String constant or empty string.
complete String, possibly empty.
range String constant or empty string, stands only for -nargs.
count String constant or empty string, stands only for -count.
bang, bar, register, buffer

One or zero.

 

cmdlist([{bufnr}]):

Returns a list of command names suitable for cmdarg().

aulist({event}[, {augroup}[, {pattern}]]):

Returns a list of dictionaries with the following keys:

Key Value
event {event}
augroup Autocmd group.
patterns List of globs.
command Command string.
nested One or zero.
sid Script ID.
auglist():

Returns a list of autocmd groups.

signarg({name}):

Returns a dictionary with the following keys:

Key Value
name {name}
icon Icon file or empty string.
linehl String or empty string.
texthl String or empty string.
text String.
signlist():

Returns a list of sign names suitable for signarg().

signplacelist({bufnr}):

Returns a list of signs placed in the given buffer: dictionaries with keys

Key Value
name Name suitable for signarg().
id Sign ID.
line Line number.
getjumps():

Returns a list of dictionaries with the following keys:

Key Value
line Line number.
col Column number.
file File name.
getchanges({bufnr}):

Returns a list of lists, latter lists are suitable for cursor(): look like ([{line}, {col}]).

getdigraphs():

Returns a dictionary {digraph : text} where digraph is a two-character sequence and text is text inserted when this sequence is used as an digraph.

setdigraphs({dict}):

Replace digraph table with given dictionary. Format is the same as returned by getdigraphs().

cmdcomplete(command, cursor=len(command)):

Returns a 3-tuple [before, after, variants] with completion variants for the given command. before and after are unchanged parts of original command.

exprcomplete(complete, text, cursor=len(text)):

Like above, but complete using given complete argument (like input() completion).

Note: {bufnr} is {expr} argument from bufnr() function.

Python classes that are made accessible

vim.Mapping(rhs, noremap=vim.MAPPING_NOREMAP, silent=False, expr=False):

Returns mapping object described above. New mappings that are created using vim.Mapping are then to be assigned to appropriate {vim,buffer}.mappings[mode][lhs] thus there are no attributes like mode, buffer or lhs: they are determined by appropriate keys and objects when assigning. sid attribute is created automatically (though in any case it is ignored when assigning).

If rhs is callable it automatically sets expr to True and uses the result of the call as rhs (like other <expr> mappings do).

Defines method .run() that runs given mapping object in the current mode. It is up to developer to make sure current mode is a proper one.

Note: the same object is used for mappings and abbreviations.

vim.Menu(rhs, noremap=vim.MAPPING_NOREMAP, silent=False, expr=False, hint=None):

Like above vim.Mapping, but for menus. Additional hint argument describes a right-aligned hint in the menu. Is a subclass of vim.Mapping.

vim.Command(command, nargs=vim.COMMAND_ARGS_NO, complete=None, range=None, count=False, bang=False, bar=True, register=False):

Returns command object described above. New commands that are created using vim.Command are then to be assigned to {vim,buffer}.commands[cmd] thus there are no attributes like name or buffer. sid attribute is created automatically (though in any case it is ignored when assigning).

If command is a callable, it will receive the following keyword arguments:

Argument Description
args List of command arguments
count (Only for commands with count=True) count received
range (Only for commands with range=True) vim.range object
bang (Only for commands with bang=True) True or False
reg (Only for commands with register=True) Register name
vim.Autocommand(command, pattern, nested=True):

Returns new autocmd group as described above.

If command is a callable, it will receive the following keyword arguments:

Argument Description
buf Buffer number
match Matched string
vim.HighlightGroup(gui=None, guifg=None, guibg=None, guisp=None, cterm=None, ctermfg=None, ctermbg=None, term=None):

Returns new highlight group as described above.

vim.Sign(text, icon=None, linehl=None, texthl=None):

Returns new sign as described above.

vim.Function(args, code, name=None, is_dictionary=False, dict=None):

Returns function object like above (name=None means anonymous function, name is automatically generated). Code is a iterable of strings.

vim.Function(callable):

(extended funcref only) Returns function object like above which contains python callable wrapped into vim Funcref.

vim.QFList(iterable, title=None)/vim.QFList(*iterable, title=None):

Sequence-like object with a list of vim.QFItem objects. Read-only.

vim.QFItem(text, lnum=None, pattern=None, type=None, nr=0, col=1, vcol=None, buffer=vim.current.buffer, filename=None):

Returns quickfix/location list item. There are additional inter-argument dependencies:

  • filename=string overrides buffer argument.
  • lnum=None and pattern=None implies .valid=False.
  • buffer=None and filename=None implies .valid=False and ValueError when trying to use .jump() method. Note that buffer=None is not the default.
  • vcol=number implies col=None. Unlike vim, vcol argument does not mean that col argument represents byte offset, instead it accepts virtual column number.
vim.Jump(line=vim.functions.line('.'), col=vim.functions.col('.'), buffer=vim.current.buffer, file=None):

Returns jump object as described earlier. For use when assigning to vim.marks or {buffer}.marks.

vim.History(items=()):

Returns history object for use in vim.input().

Note: here are different (more convenient) defaults:

Place New default
Mapping(noremap=vim.MAPPING_NOREMAP) in place of vim.MAPPING_REMAP
Command(bar=True) in place of False
Autocommand(nested=True) in place of False

Auxilary/helper functions

vim.special_expand(string) + special_expand(string):

Expands special characters like <C-a> in the string. Currently it is done in VimL by using eval('"'.escape(str, '\<"').'"') which is rather hacky.

vim.match_glob(glob, string), match_glob(string, glob):

Match string against glob expression. Order is different in python and VimL: in python it is taken from re.match(pattern, string), in VimL from matchstr({expr}, {pat}).

vim.buffers.find(string):

Similar to vim.buffers[vim.bindeval("bufnr(string)")], but does not raise exception.

returns

vim.buffer object or None.

vim.get_highlighting(hlgroup):

Like vim.hlgroups[hlgroup], but always returns vim.HighlightGroup objects or raises KeyError.

vim._gen_function(callable, args=()):

Generates vim.Function object from python callable object. At this point can only do something like the following (but not exactly this; and also written in C):

id = vim._callables.save(callable) 
return vim.Function(args, ('python import vim', 'return pyeval("vim._callables[{0}]({1})")'.format(id, ','.join((arg+'=vim.bindeval("a:'+arg+'")' for arg in args)))), dict={}) 
# Rather hacky, but standard solution is preferred over 100500 ways 
# plugin writers can reimplement it just to call python function 
# from various places where it is needed. 

. Is not supposed to be used directly: it is for vim.Command(command=callable), vim.Autocommand(command=callable) and vim.Mapping(rhs=callable, expr=True), also for assigning options.

When using pyeval, calling functions or binded types this one will be used to transform python callable into vim function. It is supposed that implementation will eventually change to func_T structure in place of char* in funcrefs.

vim.disabled_autocommands:

Object with defined __enter__ method setting &eventignore to all and __exit__ method restoring previous value. Should be written in pure python. Used to allow expressions like:

…
with vim.disabled_autocommands:
    buffer = vim.buffers.new('aurum://file:…')
    vim.current.buffer = buffer
…
vim.jump(buffer, lnum=None, pattern=None, col=None, vcol=None, window=None):

Function used to implement all .jump methods of all objects. col and vcol arguments are mutually exclusive. vcol argument overrides col one. lnum and pattern are also exclusive, pattern overrides lnum. If neither lnum nor pattern are present it only jumps to the buffer. If neither col nor vcol are present it jumps to the first column. Without window argument it tries to find window which already shows requested buffer and jump to that window.

When used from the object, first five arguments are determined by the object holding the called method. Next arguments (currently only window) are passed from the method arguments. Default of these arguments depends on the object.

vim.input(prompt, text="", complete=None, history=vim.history[vim.HISTORY_INPUT], dialog=False, secret=False):

Like input(), but with two differencies: complete may be a python callable (as in vim.Command()) and history argument that temporary replaces vim.HISTORY_INPUT history with itself.

Unless implementation is altered dialog=True implies ignoring complete. secret=True implies ignoring dialog, complete and history.

Note: should care about nesting: input() and vim.input() calls should use original vim.history[vim.HISTORY_INPUT].

Note 2: built-in vim input() should also support history argument.

Note 3: inputlist() sucks and in the current state would not be supported.

vim.confirm(message, choices=((True, '&OK'),), default=choices[0][0], type="Generic"):

Prompt user for the confirmation. On interrupt (escape) vim.ConfirmInterrupt exception (subclass of vim.Error) is raised. choices is an iterable with 2-tuples; second value in a tuple is used in a prompt; first will be returned if corresponding choice was made. default will be returned if no choice was made. The first choice in choices for which choice[0] is default is true (note: they must be same objects, it is not == comparison) is displayed as the default one. If there are no such choices nothing is displayed as the default choice, but default value always exists. User should use escape or CTRL-C to abort.

vim.undobreak():

Break current undo sequence, like i_CTRL-G_u.

vim.undojoin():

Join current change with the next one.

vim.redraw(all=False, status=False):

:redraw (no arguments), :redraw! (all=True), redrawstatus (status=True) and redrawstatus! (all=True, status=True) replacement. Supports only keyword arguments.

Changes to existing functionality

  • Iterators for *.windows and vim.tabpages that allow:

    for window in vim.windows:
        window.close()

    like it is allowed for buffer list.

  • {function}.sid and {function}.code attributes.
  • {windowlist}.valid and {function}.valid attributes.
  • vim.eval(expr, number_strings=True): sometimes python objects are more desired then what vim.bindeval returns, but numbers represented as strings spoil it all.
  • Some of the keys in *.options will be able to receive callable as an argument. Namely these are &statusline (will use something like %! and receive vim.window argument). &indentexpr, &formatexpr, &balloonexpr, &foldexpr, &diffexpr, &includeexpr, &patchexpr, &printexpr, &omnifunc, &completefunc, &operatorfunc.
  • Make checks for numbers less strict. I.e. it should use number protocol (PyNumber_*) in place of checking for integers and/or long values.
  • {buffer}, {window} and {tabpage} __enter__ and __exit__ methods: temporary switch to given buffer/window/tabpage and switch back afterwards.
  • vim.current.qflist: current quickfix list. Supports assignment.
  • vim.current.word, vim.current.nonblanks (vim.current.WORD looks like a constant), vim.current.script (object with .file, .sid and .lnum attributes representing various expand("<s*>") things), vim.current.file.
  • vim.current.mode: current mode, like mode(), but uses less cryptic vim.MODE_* constants (of course, less cryptic only if developers are sane and use constants in place of embedding magic numbers). Supports assignment, assignment works like :startinsert. Cannot assign vim.MODE_VISUAL|*. Modes:

    • vim.MODE_NORMAL. Assigning this works like CTRL-\_CTRL-N.
    • vim.MODE_OPERATOR_PENDING. Not assignable.
    • vim.MODE_VISUAL. Supports flags: vim.MODE_VISUAL|vim.SELECT_LINEWISE is linewise visual mode. Refer to vim.select() description for a full list of vim.SELECT_* flags. Asssigning this start selects current line or character.
    • vim.MODE_SELECT. Supports flags like above. Assigning this selects current line or character.
    • vim.MODE_INSERT. Supports flags: vim.MODE_INSERT_INSERT, vim.MODE_INSERT_REPLACE, vim.MODE_INSERT_VIRTUAL_REPLACE. Also supports vim.MODE_MENU. Assigning this works like :startinsert.
    • vim.MODE_COMMAND. Supports flags: vim.HISTORY_*, vim.COMMAND_COMMAND, vim.MODE_COMMAND_EX and vim.MODE_COMMAND_NORMAL_EX. Also supports vim.MODE_MENU. Assigning this works like CTRL-\_CTRL-N followed by appropriate character (:, Q or gQ).
    • vim.MODE_PROMPT. Supports flags: vim.MODE_PROMPT_HIT_ENTER, vim.MODE_PROMPT_MORE, vim.MODE_PROMPT_CONFIRM. Not assignable.
    • vim.MODE_SHELL. Not assignable.

    Flags:

    • vim.MODE_MENU: insert and command modes flag; is active when popupmenu (insert) or wild menu (command) is active. Ignored when assigning. See pumvisible() and wildmenumode().
    • vim.MODE_INSERT_INSERT: insert mode flag; is active when mode is regular insert mode.
    • vim.MODE_INSERT_REPLACE: insert mode flag; is active in replace mode.
    • vim.MODE_INSERT_VIRTUAL_REPLACE: insert mode flag; is active in virtual replace mode.
    • vim.MODE_COMMAND_COMMAND: command mode flag; is active
    • vim.MODE_COMMAND_EX: command mode flag; is active in Ex mode.
    • vim.MODE_COMMAND_NORMAL_EX: command mode flag; is active in normal Ex mode.
    • vim.MODE_PROMPT_HIT_ENTER: prompt mode flag; is active when prompt is hit-enter one.
    • vim.MODE_PROMPT_MORE: prompt mode flag; is active when prompt is more prompt.
    • vim.MODE_PROMPT_CONFIRM: prompt mode flag; is active when prompt is :confirm prompt.
    * vim.SELECT_*: visual and select mode flag; represent type of selection. * vim.HISTORY_*: command mode flag: location of history, see vim.history description.
    • vim.MODE_INSERT_CTRL_O: any mode, represents that command entering current mode was launched using i_CTRL-O.
    • vim.MODE_LANGUAGE: any mode, represents that :lmap commands are active.

    Bits:

    No constants
    Modes:
    01 MODE_NORMAL
    02 MODE_OPERATOR_PENDING
    03 MODE_VISUAL
    04 MODE_SELECT
    05 MODE_INSERT
    06 MODE_COMMAND
    07 MODE_PROMPT

    08

    MODE_SHELL Flags:

    09 MODE_LANGUAGE
    10 MODE_MENU
    11 MODE_INSERT_CTRL_O
    12 MODE_INSERT_INSERT, MODE_COMMAND_COMMAND, MODE_PROMPT_HIT_ENTER
    13 MODE_INSERT_REPLACE, MODE_COMMAND_EX, MODE_PROMPT_MORE
    14 MODE_INSERT_VIRTUAL_REPLACE, MODE_COMMAND_NORMAL_EX, MODE_PROMPT_CONFIRM
    15 SELECT_LINEWISE, HISTORY_COMMAND

    16

    SELECT_CHARACTERWISE, HISTORY_SEARCH After 16 bits. Should check out whether this situation is to be avoided

    17 SELECT_BLOCK, HISTORY_EXPRESSION
    18 HISTORY_INPUT
    19 HISTORY_DEBUG
  • {buffer}.map(callable), {range}.map(callable): convenience wrapper for the following code:

    r = []
    for line in buffer:  # or “in range”
        line = callable(line)
        if isinstance(line, (unicode, str)):
            r.append(line)
        else:
            r.extend(line)
    buffer[:] = r        # same

    with a difference that lines are replace right away without delaying the replacement until all lines are processed.

  • vim.current.command: namedtuple-like object with .text and .cursor arguments providing access to current command-line if in command-line mode. Attributes are assignable.
  • vim.Dictionary.copy, vim.Dictionary.clear, vim.Dictionary.setdefault, vim.Dictionary.fromkeys, vim.Dictionary.iter* (also use only iter* for python-3), comparison support, better repr().
  • vim.List.pop, vim.List.remove, vim.List.count, vim.List.index, vim.List.append, vim.List.insert, vim.List.reverse, vim.List.__add__, vim.List.__mul__, vim.List.__imul__, comparison support, better repr().

Buffer- and window-manipulation methods

vim.buffers.open(name=None, encoding={&enc}, binary=False, fileformat={…}, readonly=None):

Create a new buffer. None in place of name means “create buffer with empty name”. Returns vim.Buffer object.

Note: readonly=False should be different from readonly=None: former should raise an exception in case opening file for read-write access failed.

vim.windows.create(direction, buffer=vim.current.buffer, size=0.5, preview=False), also for vim.current.tabpage.windows:

Split the window. size may be either an integer (absolute size) or a floating-point value in the open interval (0.0, 1.0) (size relative to the current window size or total vim size, depending on direction). buffer specifies what buffer will be opened in new window, must be a valid vim.Buffer object. direction may be one of the following:

Direction Description
horizontal Like :split
vertical Like :vsplit
diff Like :diffsplit, but without setting diff* options
above Like :above vsplit
below Like :below vsplit
left Like :lefta split
right Like :rightb split
top Like :top split, uses &lines for relative sizes
bottom Like :bot split, uses &lines for relative sizes
leftmost Like :topleft vsplit, uses &columns for relative sizes
rightmost Like :botright vsplit, uses &columns for relative sizes

May use numeric constants in place of strings as a direction.

Returns vim.Window object.

vim.tabpages.create(after=vim.current.tabpage, before=None, direction=None, buffer=vim.current.buffer, window=None):

Create new tabpage. buffer is handled in the same fashion as above; direction, before and after arguments are mutually exclusive. window argument is here to simulate <C-w>T (“Move the current window to a new tab page”), exppects vim.Window object. after and before accept only vim.TabPage objects, direction is one of the following:

Direction Shortcut for
before .create(before=vim.current.tabpage)
after .create(after=vim.current.tabpage) or just .create()
first .create(before=vim.tabpages[0])
last .create(after=vim.tabpages[-1])

Returns vim.TabPage object.

vim.TabPage.move(after=None, before=None, direction=None):

Move tabpage before or after the given one or to the given direction (see above). All arguments are mutually exclusive.

vim.Window.move(direction):

Move the window in the given direction which is one of the following:

Direction Description
left To the left, raises exception if already at the far left
right To the right, raises exception if already at the far right
above Move upwards, raises exception if already at the very top
below Move downwards, raises exception if already at the very bottom
leftmost Like <C-w>H, do not raise an exception
rightmost Like <C-w>L, do not raise an exception
top Like <C-w>K, do not raise an exception
bottom Like <C-w>J, do not raise an exception

XXX Implementation (and existence) of first four variants is subjectable.

vim.Window.exchange(window):

Exchange the window with the given one. Expects vim.Window object. Works like <C-w>x.

vim.Window.resize(horizontal=None, vertical=None, relative=True):

Resize window to the given value (i.e. vim.current.window.resize(horizontal=0.8) should make window 20% less wide; vim.current.window.resize(vertical=20) should make window be 20 lines taller). relative option (TODO: provide better name) determines whether floating-point values should be relative to the resized window (default) or to the overall available space. Use assigning to vim.Window.height and vim.Window.width if you want to resize to some exact value.

vim.Window.close(force=False), vim.Buffer.close(force=False), vim.TabPage.close(force=False):

Guess it is obvious what they do.

Also del vim.windows[number], del vim.buffers[number] and del vim.tabpages[number] as an alternatives.

vim.Window.diffthis():

Like :diffthis.

Exceptions

Vim errors and exceptions will be transformed into python exceptions (implementation: pretend that there is :try block active).

In addition to transforming exceptions there will be some subclasses of vim.error and vim.VimError (that is the same object as vim.error; latter will be marked as deprecated):

vim.VimDeletedError:

Exception thrown by Check{Buffer,Window,TabPage}.

vim.VimEvalError:

To this exception vim exceptions will be transformed.

vim.VimLockedError:

Used when trying to modify locked structure. Also when trying to change lock state of fixed object.

vim.VimValueError:

Expected exceptions that do not fall into one of the previous categories (e.g. “cursor position outside buffer”).

vim.VimRuntimeError:

Other errors which should not normally happen. E.g. errors starting with "internal error: …". Usually indicates a bug or problems with allocating memory.

Plugin loading

The following is additional stuff to ease creating python-only plugins by adding basic plugin management support:

'pythoninstallprg'/'pip' and 'python3installprg'/'pip3' options:

Specify what program is used by :pyload/:py3load commands below in case importing failed.

:pyload[!] module.submodule[ args] (and :py3load) commands:

Try to import module.submodule python module and run function __viminit__ from it. In case importing module fails runs &pythoninstallprg . " " . args. If there are no arguments uses module (without .submodule) as an argument. Does not run &pythoninstallprg if bang was specified. If module was successfully imported, but it does not contain __viminit__ function it errors out. Pseudo-code:

def pyload(module, args=None, bang=False):
    try:
        # Don’t use this in real code, there is __import__!
        exec('import ' + module + ' as m')
    except ImportError:
        if not bang:
            vim.command('!'
                        + vim.options['pip' + ('' if sys.version_info < (3,) else '3')] +
                        + ' '
                        + (args or module.partition('.')[0]))
            pyload(module, bang=True)
    else:  # Runs code if there was no exception, but outside of try: block
        # May raise AttributeError. Or any other error occurred in __viminit__
        m.__viminit__()

:confirm pyload should run confirmation before installing anything, otherwise program is installed using regular ! (well, underlying C functions) without asking.

silent pyload should supress any messages and installation process output like silent !pip install … would do. I guess this part will be gained “for free”.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment