Module vpe

Enhanced module for using Python3 in Vim.

This provides the Vim class, which is a wrapper around Vim’s built-in vim module. It is intended that a Vim instance can be uses as a replacement for the vim module. For example:

from vpe import vim
# Now use 'vim' as an extended version of the *vim* module.
# ...

This is compatible for versions of Vim from 8.0. It also needs Python 3.6 or newer.

Attributes

vpe.log

The Vpe log support object.

This is an instance of the Log class.

vpe.vim

A replacement for (and wrapper around) the python-vim module.

This is in instance of the Vim class.

AutoCmdGroup

class vpe.AutoCmdGroup(name)

A Pythonic way to define auto commands.

This is a context manager that supports definition of autocommands that:

  • Are always in a given group.

  • Invoke Python code when triggered.

It is intended to be used as:

with AutoCmdGroup('mygroup') as g:
    g.delete_all()
    g.add('BufWritePre', handle_bufwrite, ...)
    g.add('BufDelete', handle_bufdelete, ...)

...

# Add more autocommands to the same group.
with AutoCmdGroup('mygroup') as g:
    g.delete_all()
    g.add('BufWritePre', handle_bufwrite, ...)

Parameters

name

The name of the group.

Static methods

static add(event, func, pat='<buffer>', once=False, nested=False)

Add a new auto command to the group.

Parameters

event

The name of the event.

func

The Python function to invoke. Plain functions and instance methods are supported.

pat

The file pattern to match. If not supplied then the special ‘<buffer>’ pattern is used. If the argument is a Buffer then the special pattern for ‘buffer=N> is used.

once

The standard ‘:autocmd’ options.

nested

The standard ‘:autocmd’ options.

static delete_all()

Delete all entries in the group.

Buffer

class vpe.Buffer(buffer)

Wrapper around a python-window.

VPE creates and manages instances of this class as required. It is not intended that user code creates Buffer instances directly.

A number of extensions to the standard python-buffer are provided.

  • The vars property provides access to the buffer’s variables.

  • The list context manager provides a clean, and often more efficient, way to access the buffer’s content.

  • The temp_options context manager provides a clean way to work with a buffer with some of its options temporarily modified.

  • Buffer specific meta-data can be attached using the store.

Properties

property number

The number of this buffer.

property valid → bool

Test of this buffer is valid.

A buffer can become invalid if, for example, the underlying Vim buffer has been wiped out.

property varsVariables

The buffar vars wrapped as a Variables instance.

Methods

append(line_or_lines, nr=None)

Append one or more lines to the buffer.

This is the same as using the append method of python-buffer.

Parameters

line_or_lines

The line or lines to append.

nr

If present then append after this line number.

list()

A sequence context for efficient buffer modification.

As an example:

with vim.current.buffer.lines() as lines:
    # Now lines is a copy of the buffers lines.
    lines[2:4] = ['one']  # Update lines in-place.

# The vim.current.buffer has now been updated with modified lines.

Although this involves taking a copy of the buffer’s lines and then completely replacing the buffer’s set of lines, this is a much more efficient way to make non-trivial modifications to a buffer’s contents.

This will update the buffer, even if ‘modifiable’ is not set.

range(a: int, b: int)Range

Get a Range for the buffer.

This is like getting a python-range object, except that it is wrapped in a Range instance.

Parameters

a: int

The start index of the range.

b: int

The end index of the range. Note that this line is included in the range; i.e. the range is inclusive, unlike Python ranges.

store(key: typing.Any)Struct

Return a Struct for a give key.

This provides a mechanism to store arbitrary data associated with a given buffer. A new Struct is created the first time a given key is used. An example of how this can be used:

vim.current.buffer.store['my-store'].processed = True
...
for buf in vim.buffers:
    if buf.store['my-store'].processed:
        # Treat already processed buffers differently.
        ...

The vpe package arranges to return the same Buffer instance for a given python-buffer so this effectively allows you to associated meta-data with individual Vim buffers.

temp_options(**presets)

Context used to temporarily change options.

This makes it easy, for example, to use a normally unmodifiable buffer to display information in a buffer. To update the displayed buffer’s contents do something like:

with disp_buf.temp_options(modifiable=True):
    disp.buf.append('Another line')

When the context ends, the modifiable option is reset to its original value. An alterative approach is:

with disp_buf.temp_options as opt:
    opt.modifiable = True
    disp.buf.append('Another line')

Only options set using presets or the context object are restored when the context exits.

Parameters

presets

One or more options values may be defined using keyword arguments. The values are applied when the context is entered.

Class methods

classmethod get_known(buffer: typing.Any) → Optional[ForwardRef(‘Buffer’)]

Get the Buffer instance for a given vim.buffer.

This is only intended for internal use.

Parameters

buffer: typing.Any

A standard python-buffer.

Buffers

class vpe.Buffers(obj=None)

Wrapper around the built-in vim.buffers.

This is a proxy that extends the vim.Buffer behaviour in various ways.

Current

class vpe.Current(obj=None)

Wrapper around the built-in vim.current attribute.

GlobalOptions

class vpe.GlobalOptions(vim_options)

Wrapper for vim.options, etc.

This extends the behaviour so that options appear as attributes. The standard dictionary style access still works.

Log

class vpe.Log(name, maxlen=500)

Support for logging to a display buffer.

An instance of this class provides a mechanism to support logging that can be viewed within a buffer. Instances of this class act as a simple print function.:

info = Log('my_info')
info("Created log", info)
info("Starting process")

The output is stored in a Python FIFO structure, up to a maximum number of lines; the default is 500, change this with set_maxlen. No actual Vim buffer is created until required, which is when show is first invoked.:

info.show()   # Make the log visible.

The vpe module provides a predefined log, called ‘VPE’. This is available for general use. VPE also uses it to log significant occurrences - mainly error conditions.

Parameters

name

A name that maps to the corresponding display buffer.

maxlen

The maximum number of lines to store.

Attributes

buf

The corresponding Vim buffer. This will be None if the show method has never been invoked.

name

A name that maps to the corresponding display buffer.

Methods

__call__(*args)

Write to the log.

The arguments are formatted using print and then appended to the log buffer, with a time stamp.

Parameters

args

The same as for Python’s print function.

clear() → None

Clear all lines from the log.

The FIFO is cleared and the corresponding buffer updated.

flush()

File like I/O support.

redirect()

Redirect stdout/stderr to the log.

set_maxlen(maxlen: int) → None

Set the maximum length of the log’s FIFO.

This will discard older lines if necessary.

Parameters

maxlen: int

How many lines to store in the FIFO.

show() → None

Make sure the buffer is visible.

If there is no buffer currently displayed the log then this will:

  • Split the current window.

  • Create a buffer and show it in the new split.

unredirect()

Undo most recent redirection.

write(s)

Write a string to the log buffer.

Parameters

s

The string to write.

PopupAtCursor

class vpe.PopupAtCursor(content, **p_options)

Popup configured to appear near the cursor.

This creates the popup using popup_atcursor().

PopupBeval

class vpe.PopupBeval(content, **p_options)

Popup configured to appear near (v:beval_line, v:beval_col).

This creates the popup using popup_beval().

PopupDialog

class vpe.PopupDialog(content, **p_options)

Popup configured as a dialogue.

This creates the popup using popup_dialog(). It also provides a default PopupDialog.on_key implementation that invokes popup_filter_yesno.

Methods

on_key(key, byte_seq)

Invoke popup_filter_yesno to handle keys for this popup.

PopupMenu

class vpe.PopupMenu(content, **p_options)

Popup configured as a menu.

This creates the popup using popup_menu(). It also provides a default PopupMenu.on_key implementation that invokes popup_filter_menu.

Methods

on_key(key, byte_seq)

Invoke popup_filter_menu to handle keys for this popup.

PopupNotification

class vpe.PopupNotification(content, **p_options)

Popup configured as a short lived notification (default 3s).

This creates the popup using popup_notification().

Range

class vpe.Range(obj=None)

Wrapper around the built-in vim.Range type.

This is a proxy that extends the vim.Buffer behaviour in various ways.

Methods

append(line_or_lines, nr=None)

Append one or more lines to the range.

This is the same as using the append method of python-range.

Parameters

line_or_lines

The line or lines to append.

nr

If present then append after this line number.

Registers

class vpe.Registers

Dictionary like access to the Vim registers.

This allows Vim’s registers to be read and modified. This is typically via the Vim.registers attribute.:

vim.registers['a'] = 'A line of text'
prev_copy = vim.registers[1]

This uses eval’ to read registers and :vim:`setreg to write them. Keys are converted to strings before performing the register lookup. When the key is the special ‘=’ value, the un-evaluated contents of the register is returned.

Methods

__getitem__(reg_name: Union[str, int]) → typing.Any

Allow reading registers as dictionary entries.

The reg_name may also be an integer value in the range 0-9.

__setitem__(reg_name: Union[str, int], value: typing.Any)

Allow setting registers as dictionary entries.

The reg_name may also be an integer value in the range 0-9.

Struct

class vpe.Struct

A basic data storage structure.

This is intended to store arbitrary name, value pairs as attributes. Attempting to read an undefined attribute gives None.

This is provided primarily to support the Buffer.store mechanism. Direct use of this class is not intended as part of the API.

Methods

__getstate__()

Support picking - only intended for testing.

__setstate__(state)

Support picking - only intended for testing.

TabPage

class vpe.TabPage(obj=None)

Wrapper around a python-tabpage.

VPE creates and manages instances of this class as required. It is not intended that user code creates TabPage instances directly.

Properties

property vars

The buffar vars wrapped as a Variables instance.

TabPages

class vpe.TabPages(obj=None)

Wrapper around the built-in vim.tabpages.

This is a proxy that extends the vim.TabPages behaviour in various ways.

Static methods

static new(position='after')

Create a new tab page.

Parameters

position

The position relative to this tab. The standard character prefixes for the ‘:tabnew’ command can be used or one of the more readable strings:

‘after’, ‘before’

Immediately after or before the current tab (same as ‘.’, ‘-‘),

‘first’, ‘last’

As the first or last tab (same as ‘0’, ‘$’),

This defaults to ‘after’.

Timer

class vpe.Timer(ms, func, repeat=None)

Pythonic way to use Vim’s timers.

This can be used as a replacement for the vim functions: timer_start, timer_info, timer_pause, timer_stop.

An example of usage:

def handle_expire(t):
    print(f'Remaining repeats = {t.repeat}')

# This will cause handle_expire to be called twice. The output will be:
#     t.repeat=2
#     t.repeat=1
t = Timer(ms=100, handle_expire, repeat=2)

The status of a timer can be queried using the properties time, repeat, remaining and paused. The methods pause, stop and resume allow an active timer to be controlled.

Parameters

ms

The timer’s interval in milliseconds.

func

The function to be invoked when the timer fires. This is called with the firing Timer instance as the only parameter.

repeat

How many times to fire.

Properties

property id → int

The ID of the underlying vim timer.

property paused → bool

True if the timer is currently paused.

property remaining → int

The time remaining (ms) until the timer will next fire.

property repeat → int

The number of times the timer will still fire.

property time → int

The time value used to create the timer.

Methods

pause()

Pause the timer.

This invokes vim’s timer_pause funciton.

resume()

Resume the timer, if paused.

This invokes vim’s timer_pause funciton.

stop()

Stop the timer.

This invokes vim’s timer_stop function.

Class methods

classmethod stop_all()

Stop all timers and clean up.

Use this in preference to vim.timer_stopall, to ensure that VPE cleans up its underlying administrative structures.

Variables

class vpe.Variables(obj=None)

Wrapper around the various vim variable dictionaries.

This allows entries to be modified.

Vim

class vpe.Vim(*args, **kwargs)

A wrapper around and replacement for the vim module.

This is a instance object not a module, but it provides a API that is extremely compatible with the python-vim module.

Properties

property buffersBuffers

A read-only container of the all the buffers.

property currentCurrent

Convenient access to currently active objects.

Note: Does not support assigment to window, buffer or tabpage.

property error → Type[vim.error]

The plain built-in Vim exception (python-error).

property optionsGlobalOptions

An object providing access to Vim’s global options.

property registers → `Registers`

Dictionary like access to Vim’s registers.

This returns a Registers object.

property tabpagesTabPages

A read-only container of the all the tab pages.

property varsVariables

An object providing access to global Vim variables.

property vvarsVariables

An object providing access to Vim (v:) variables.

property windowsWindows

A read-only container of the windows of the current tab page.

Methods

command(cmd: str) → None

Execute an Ex command.

Parameters

cmd: str

The Ex command to execute:

Exceptions raised

VimError

A more detailed version vim.error (python-error).

eval(expr: str) → Union[dict, list, str]

Evaluate a Vim expression.

Return value

A dict, list or string. See python-eval for details.

Exceptions raised

VimError

A more detailed version vim.error (python-error).

temp_options(**presets)

Context used to temporarily change options.

Static methods

static __new__(cls, *args, **kwargs)

Ensure only a single Vim instance ever exists.

This means that code like:

myvim = vpe.Vim()

Will result in the same object as vpe.vim.

static vim()

Get the underlying built-in vim module.

VimError

class vpe.VimError(error: vim.error)

A parsed version of vim.error.

VPE code raises this in place of the standard vim.error exception. It is a subclass of vim.error, so code that handles vime.error will still work when converted to use the vpe.vim object.

This exception attempts to parse the Vim error string to provide additional attributes:

Attributes

code: int:

The error code. This will be zero if parsing failed to extract the code.

command: str:

The name of the Vim command that raised the error. This may be an empty string.

message: str:

The message part, after extracting the command, error code and ‘Vim’ prefix. If parsing completely fails then is simply the unparsed message.

Window

class vpe.Window(window)

Wrapper around a python-window.

VPE creates and manages instances of this class as required. It is not intended that user code creates Window instances directly.

Properties

property varsVariables

The buffar vars wrapped as a Variables instance.

Methods

goto() → bool

Switch to this window, if possible.

Return value

True if the current window was set successfully.

temp_options(**presets) → TemporaryOptions

Context used to temporarily change options.

This does for a window what Buffer.temp_options does for buffer.

Windows

class vpe.Windows(obj=None)

Wrapper around the built-in vim.windows.

This is a proxy that extends the vim.Window behaviour in various ways.

Parameters

vim_windows

A python-windows object.

saved_winview

class vpe.saved_winview

Context manager that saves and restores the current window’s view.

call_soon

vpe.call_soon(func)

Arrange to call a function ‘soon’.

This uses a Vim timer with a delay of 0ms to schedule the function call. This means that currently executing Python code will complete before the function is invoked.

Parameters

func

The function to be invoked. It takes no arguments.

error_msg

vpe.error_msg(*args)

A print-like function that writes an error message.

Unlike using sys.stderr directly, this does not raise a vim.error.

find_buffer_by_name

vpe.find_buffer_by_name(name: str) → Optional[Buffer]

Find the buffer with a given name.

The name must be an exact match.

Parameters

name: str

The name of the buffer to find.

get_display_buffer

vpe.get_display_buffer(name: str) → Scratch

Get a named display-only buffer.

The actual buffer name will be of the form ‘/[[name]]’. The buffer is created if it does not already exist.

Parameters

name: str

An identifying name for this buffer.

highlight

vpe.highlight(...)
highlight(
    *,
    group=None,
    clear=False,
    default=False,
    link=None,
    disable=False,
    **kwargs)

Python version of the highlight command.

This provides keyword arguments for all the command parameters. These are generally taken from the :highlight command’s documentation.

Parameters

group

The name of the group being defined. If omitted then all other arguments except clear are ignored.

clear

If set then the command highlight clear [<group>] is generated. All other arguments are ignored.

disable

If set then the specified group is disabled using the command:

highlight <group> NONE

link

If set then a link command will be generated of the form:

highlight link <group> <link>.

Other arguments are ignored.

default

If set then the generated command has the form highlight default....

kwargs

The remain keyword arguments act like the :highlight command’s keyword arguments.

pedit

vpe.pedit(path: str, silent=True, noerrors=False)

Edit file in the preview window.

Parameters

path: str

The files path.

silent

If true then run the :pedit command silently.

noerrors

If true then add ‘!’ to suppress errors.

script_py_path

vpe.script_py_path() → str

Derive a python script name from the current Vim script name.

timer_stopall

vpe.timer_stopall()

Convenience function that invokes Timer.stop_all.