Text objects, as in the iw from ciw (“change inner word”), form an important part of your Vim mentalese1. This post details those that I find most useful for Python and Django development.
For brevity, the leading a (mnemonic: “a"n) or i (mnemonic: “inner”), that you combine with the following commands to form the full text-object, are omitted.
From core Vim:
From the (highly recommended)
wellle/targets.vim
plugin:
- , . ; : + - = ~ _ * # / | \ & $ → an area of text delimited by the given character (super useful).
- a → a function argument.
Furthermore wellle/targets.vim
overrides the built-in text objects to seek to the next occurrence of the
text-object if the cursor isn’t already within one. This is useful.
From other language-agnostic, third-party text objects:
- l → a line (via
kana/vim-textobj-line
) - e → the entire buffer (via
kana/vim-textobj-entire
) so you can, say, indent the entire buffer with =ae. - i → an indented block (via
kana/vim-textobj-indent
). This isn’t quite as useful as it sounds for Python work as it stops at a blank line within an indented block – still worth having to hand. - c → a comment block (via
glts/vim-textobj-comment
).
jeetsukumaran/vim-pythonsense
provides some Python text objects:
- f → a Python function
- c → a Python class2
- d → a Python docstring
For editing Django templates (via
mjbrownie/django-template-textobjects
):
- db → a
{% block ... %}...{% endblock %}
block - di → a
{% if ... %}...{% endif %}
conditional block - df → a
{% for ... %}...{% endfor %}
for loop block - dv → a
{{ ... }}
variable - dt → a
{% tagname ... %}
tag
Several of the above plugins are built using
kana/vim-textobj-user
, which
provides a simple framework for building your own text-objects.
Useful references:
- Cheatsheet for
wellle/targets.vim
- A list of all text-object plugins built with
kana/vim-textobj-user
Related articles:
- Vim Text Objects: The Definitive Guide by Jared Carroll (2011).
- Vim Killer Features Part 1: Text Objects by Cody Veal (2013).
- Vim text objects, extend Vim’s natural language! by Owen Garland (2017).
-
In the sense that you combine them with operators (eg c, d, gU) to build describe what you want to do. ↩︎
-
To avoid clashing with the comment text-object binding from
glts/vim-textobj-comment
, you can rebind the class text object to, say, C with:↩︎map <buffer> aC <Plug>(PythonsenseOuterClassTextObject) map <buffer> iC <Plug>(PythonsenseInnerClassTextObject)