vimtk.core module

The core API to the vimtk Python module

SeeAlso:

./__init__.py ../autoload/vimtk.vim

vimtk.core.__setup_logger()[source]
vimtk.core.mockvim(fpath=None, text=None)[source]

Setup a dummy “vim” module with a specific buffer

Useful for prototyping new commands and testing

Parameters:
  • fpath (PathLike | None) – File to mock open. Will read the text if it exists.

  • text (str | None) – text of the mock buffer. If none, tries to read from the file path.

Returns:

the mock vim module

Return type:

vimtk._demo.vimmock.mocked.VimMock

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> # The mock mirrors the vim module as best as it can
>>> print('vim.current.buffer = {}'.format(vim.current.buffer))
>>> print('vim.current.buffer.name = {}'.format(vim.current.buffer.name))
>>> vim.eval("let g:custom_global = 'custom_val'")
>>> value = vim.eval('get(g:, "custom_global")')
>>> assert value == 'custom_val'
vimtk.core.reload_vimtk()[source]

Used for development

vimtk.core.reload()

Used for development

class vimtk.core.Config[source]

Bases: object

Query the state of the vim variable namespace.

Notes

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim.eval("let g:vimtk_sys_path = ['$HOME/code/netharn']")
>>> vimtk.CONFIG.get('vimtk_sys_path')
>>> vimtk.CONFIG['vimtk_auto_importable_modules']
>>> # Should the vim variable override or update the default config?
>>> vim.eval("let g:vimtk_auto_importable_modules = {'spam': 'import spam'}")
>>> vimtk.CONFIG['vimtk_auto_importable_modules']
get(key, default=None, context='g')[source]

gets the value of a vim variable and defaults if it does not exist

class vimtk.core.Clipboard[source]

Bases: object

static copy(text)[source]
static paste()[source]
class vimtk.core.TextSelector[source]

Bases: object

Tools for selecting and reading text from Vim

static current_indent(url_ok=False)[source]

Returns the indentation that should be used when inserting new lines.

Example

>>> import vimtk
>>> vim = vimtk.mockvim(text=codeblock(
>>>     '''
>>>     class Foo:
>>>         def __init__(self):
>>>             self.foo = 1
>>>             self.foo = 2
>>>     '''))
>>> vim.move_cursor(1)
>>> n1 = len(vimtk.TextSelector.current_indent())
>>> vim.move_cursor(2)
>>> n2 = len(vimtk.TextSelector.current_indent())
>>> vim.move_cursor(3)
>>> n3 = len(vimtk.TextSelector.current_indent())
>>> assert (n1, n2, n3) == (4, 8, 8)
static word_at_cursor(url_ok=False)[source]

returns the word highlighted by the curor

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim.setup_text(codeblock(
>>>     '''
>>>     class Foo:
>>>         def __init__(self):
>>>             self.foo = 1
>>>             self.bar = 2
>>>     '''))
>>> vim.move_cursor(3, 14)
>>> word = TextSelector.word_at_cursor()
>>> print('word = {!r}'.format(word))
word = 'self.foo'
static get_word_in_line_at_col(line, col, nonword_chars_left=' \t\n\r[](){}:;,"\'\\/', nonword_chars_right=None)[source]
Parameters:
  • line (str)

  • col (int)

CommandLine

python -m vimtk.core TextSelector.get_word_in_line_at_col

Example

>>> import vimtk
>>> line = 'myvar.foo = yourvar.foobar'
>>> line = 'def loadfunc(self):'
>>> col = 6
>>> nonword_chars=' \t\n\r[](){}:;.,"\'\\/'
>>> word = vimtk.TextSelector.get_word_in_line_at_col(line, col, nonword_chars)
>>> result = ('word = %r' % (word,))
>>> print(result)
static selected_text(select_at_cursor=False)[source]

Returns all text in curent selection.

make sure the vim function calling this has a range after ()

Currently used by <ctrl+g>

Refered to [vim_between_selection].

References

SeeAlso:

~/local/vim/rc/custom_misc_functions.vim

Test paragraph. Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-two million miles is an utterly insignificant little blue green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea. % — one. two three. four.

CommandLine

xdoctest -m vimtk.core TextSelector.selected_text

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim.setup_text(codeblock(
>>>     '''
>>>     line n1
>>>     line n2
>>>     line n3
>>>     line n4
>>>     '''))
>>> vim.move_cursor(3)
>>> vim.current.buffer._visual_select(2, 3)
>>> text = TextSelector.selected_text()
>>> print(text)
line n2
line n3
>>> vim.current.buffer._visual_select(2, 3, 0, 5)
>>> text = TextSelector.selected_text()
>>> print(text)
line n
line n
static text_between_lines(lnum1, lnum2, col1=0, col2=9223372036854775806)[source]
static line_at_cursor()[source]

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim.setup_text(codeblock(
>>>     '''
>>>     def foo():
>>>         return 1
>>>     def bar():
>>>         return 2
>>>     '''))
>>> vim.move_cursor(3)
>>> line = vimtk.TextSelector.line_at_cursor()
>>> assert line == 'def bar():'
static paragraph_range_at_cursor()[source]

Get the start and end lines for a paragraph at the cursor

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> text = codeblock(
        '''
        par1 par1 par1
          par1 par1
        par1 par1

par2

par3 par3

par3

‘’’)

>>> vim.setup_text(text)
>>> ranges = []
>>> for lineno in range(1, text.count(chr(10)) + 1):
>>>     vim.move_cursor(lineno)
>>>     par_range = vimtk.TextSelector.paragraph_range_at_cursor()
>>>     ranges.append(par_range)
>>> import ubelt as ub
>>> print('ranges = {}'.format(ub.urepr(ranges, nl=0)))
ranges = [(0, 3), (0, 3), (0, 3), (4, 4), (5, 5), (6, 6), (7, 7)]
class vimtk.core.CursorContext(offset=0)[source]

Bases: object

moves back to original position after context is done

class vimtk.core.Cursor[source]

Bases: object

static move(row, col=0)[source]

move_cursor

static position()[source]

get_cursor_position

class vimtk.core.TextInsertor[source]

Bases: object

Tools for inserting text at various positions

overwrite()[source]

Overwrites all existing text in the current buffer with new text

Example

>>> import vimtk
>>> vim = vimtk.mockvim(text='foo')
>>> vimtk.TextInsertor.overwrite('bar')
>>> print(vim.current.buffer._text)
static insert_at(text, pos)[source]
static insert_under_cursor(text)[source]

Example

>>> import vimtk
>>> vim = vimtk.mockvim(text='foo')
>>> vimtk.TextInsertor.insert_under_cursor('bar')
>>> print(vim.current.buffer._text)
foo
bar
static insert_above_cursor(text)[source]

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim.setup_text('foo')
>>> vimtk.TextInsertor.insert_above_cursor('bar')
>>> print(vim.current.buffer._text)
bar
foo
static insert_over_selection(text)[source]
static insert_between_lines(text, row1, row2)[source]
class vimtk.core.Mode[source]

Bases: object

Helper for checking / switching modes

vim_mode_codes = {'!': 'Shell', 'R': 'Replace', 'Rv': 'VReplace', 'S': 'SLine', 'V': 'VLine', 'c': 'Command', 'ce': 'Ex', 'cv': 'VimEx', 'i': 'Insert', 'n': 'Normal', 'no': 'NOperatorPending', 'r': 'Prompt', 'r?': 'Confirm', 'rm': 'More', 's': 'Select', 'v': 'Visual'}
static current()[source]

Return the current mode

References

http://stackoverflow.com/questions/14013294/vim-how-to-detect-the-mode-in-which-the-user-is-in-for-statusline

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vimtk.Mode.current()
Normal
static ensure_normal()[source]

Switch to normal mode

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vimtk.Mode.ensure_normal()
>>> vimtk.Mode.current()
Normal
class vimtk.core.Python[source]

Bases: object

Tools for handling python-specific functions

static current_module_info()[source]

Returns information about current module

Example

>>> import vimtk
>>> vim = vimtk.mockvim('foo.py', '')
>>> info = vimtk.Python.current_module_info()
>>> print(info)
static is_module_pythonfile()[source]
static find_import_row()[source]

Find lines where import block begins (after __future__)

static prepend_import_block(text)[source]
static format_text_as_docstr(text)[source]

CommandLine

python  ~/local/vim/rc/pyvim_funcs.py  --test-format_text_as_docstr

Example

>>> import vimtk
>>> text = codeblock(
    '''
    a = 1
    b = 2
    ''')
>>> formated_text = vimtk.Python.format_text_as_docstr(text)
>>> unformated_text = vimtk.Python.unformat_text_as_docstr(formated_text)
>>> print(formated_text)
>>> print(unformated_text)
static unformat_text_as_docstr(formated_text)[source]
static find_func_above_row(row='current', maxIter=50)[source]

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim.setup_text(codeblock(
>>>     '''
>>>     class Foo:
>>>         def __init__(self):
>>>             self.foo = 1
>>>             self.foo = 2
>>>     def foo():
>>>         ...
>>>     def bar():
>>>         ...
>>>     def baz():
>>>         ...
>>>     class Biz:
>>>         def __init__(self):
>>>             self.foo = 1
>>>             self.foo = 2
>>>         def buzz(self):
>>>             ...
>>>     '''))
>>> vim.move_cursor(8)
>>> info = vimtk.Python.find_func_above_row()
>>> import ubelt as ub
>>> print(ub.urepr(info))
{
    'callname': 'bar',
    'pos': 6,
    'line': 'def bar():',
}
>>> vim.move_cursor(4)
>>> info = vimtk.Python.find_func_above_row()
>>> print(ub.urepr(info))
{
    'callname': 'Foo.__init__',
    'pos': 1,
    'line': '    def __init__(self):',
}
>>> vim.move_cursor(16)
>>> info = vimtk.Python.find_func_above_row()
>>> print(ub.urepr(info))
{
    'callname': 'Biz.buzz',
    'pos': 14,
    'line': '    def buzz(self):',
}
static _convert_dicts_to_literals(text)[source]

TODO: where does this belong? This is a Python reformater of sorts.

Example

import vimtk vim = text=codeblock(

‘’’ data = dict(

key1=12321321, key2=’24324324’, key3=myfunc(), key4=[

1, 2, 3, 4, dict(a=’b’),

]

) ‘’’)

new_text = vimtk.Python._convert_dicts_to_literals(text) print(new_text)

static _convert_selection_to_literal_dict()[source]

Changes the visual selection from a programatic dictionary to a dictionary literal if possible.

vimtk.core.sys_executable()[source]

Find the system executable. For whatever reason, vim messes with it.

References

https://github.com/ycm-core/YouCompleteMe/blob/ba7a9f07a57c657c684edb5dde1f1f1dda1c0c7a/python/ycm/paths.py https://github.com/davidhalter/jedi-vim/issues/870

vimtk.core.preprocess_executable_text(text)[source]

Handles the case where we are trying to docstrings paste into IPython.

vimtk.core.execute_text_in_terminal(text, return_to_vim=True)[source]

Execute the current text currently selected vim text

The steps taken:

  1. Takes a block of text,

  2. copies it to the clipboard,

  3. finds the most recently used terminal,

  4. pastes the text into the most recently used terminal,

  5. presses enter (if needed),

    • to run what presumably is a command or script,

  6. and then returns focus to vim.

Todo

  • If currently focused on a terminal, then focus in a different

    terminal!

  • User specified terminal pattern

  • User specified paste keypress

  • Allow usage from non-gui terminal vim.
    (ensure we can detect if we are running in a terminal and

    register our window as the active vim, and then paste into the second mru terminal)

vimtk.core.vim_argv(defaults=None)[source]

Helper for parsing vimscript function arguments

Gets the arguments to the current variable args vim function

Notes

For instance if you have a vim function

func! foo(...)
    echo "hi"
    python << EOF
    import vimtk
    # You could use this to extract what the args that it was
    # called with were.
    argv = vimtk.vim_argv()
    print('argv = {!r}'.format(argv))
    EOF
endfunc

Example

>>> import vimtk
>>> vim = vimtk.mockvim()
>>> vim._push_function_stack(name='foo', positional=['val1', 'val2'])
>>> argv = vimtk.vim_argv()
>>> assert argv == ['val1', 'val2']
>>> argv = vimtk.vim_argv(defaults=['a', 'b', 'c'])
>>> assert argv == ['val1', 'val2', 'c']
>>> _ = vim._function_stack.pop()
vimtk.core.get_current_fpath()[source]

Example

>>> import vimtk
>>> vim = vimtk.mockvim(fpath='foo.txt', text='')
>>> fpath = vimtk.get_current_fpath()
>>> assert fpath == 'foo.txt'
vimtk.core.get_current_filetype()[source]

Example

>>> import vimtk
>>> vim = vimtk.mockvim(fpath='foo.sh', text='')
>>> filetype = vimtk.get_current_filetype()
>>> assert filetype == 'sh'
vimtk.core.ensure_normalmode()[source]

TODO: Deprecated in favor or Mode.ensure_normal()

References

http://stackoverflow.com/questions/14013294/vim-how-to-detect-the-mode-in-which-the-user-is-in-for-statusline

vimtk.core.autogen_imports(fpath_or_text)[source]

Generate import statements for python code

Example

>>> # xdoctest: +SKIP
>>> # This test is broken on the windows CI and I dont understand why
>>> import vimtk
>>> source = codeblock(
    '''
    math
    it
    ''')
>>> text = vimtk.autogen_imports(source)
...
>>> print(text)
import itertools as it
import math
vimtk.core.is_url(text)[source]

heuristic check if str is url formatted

vimtk.core.extract_url_embeding(word)[source]

parse several common ways to embed url within a “word”

vimtk.core.find_and_open_path(path, mode='split', verbose=0, enable_python=True, enable_url=True, enable_cli=True)[source]

Fancy-Find. Does some magic to try and find the correct path.

Currently supports:
  • well-formed absolute and relatiave paths

  • ill-formed relative paths when you are in a descendant directory

  • python modules that exist in the PYTHONPATH

vimtk.core.open_path(fpath, mode='e', nofoldenable=False, verbose=0)[source]

Execs new splits / tabs / etc

Weird this wont work with directories (on my machine), see [vim_split_issue].

Parameters:
  • fpath – file path to open

  • mode – how to open the new file (valid options: split, vsplit, tabe, e, new, …)

References

vimtk.core.find_pattern_above_row(pattern, line_list='current', row='current', maxIter=50)[source]

searches a few lines above the curror until it matches a pattern

TODO: move to some class? Perhaps somethig like Finder? TODO: refactor

vimtk.core.get_first_nonempty_line_after_cursor()[source]
vimtk.core.get_indentation(line_)[source]

returns the number of preceding spaces

vimtk.core.get_minimum_indentation(text)[source]

returns the number of preceding spaces

Parameters:

text (str) – unicode text

Returns:

indentation

Return type:

int

Example

>>> text = '    foo\n   bar'
>>> result = get_minimum_indentation(text)
>>> print(result)
3
vimtk.core._linux_install()[source]

Installs vimtk to the standard pathogen bundle directory