Vim text-objects for Python development

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 (neumonic: “a”n) or i (neumonic: “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 occurence of the text-object if the cursor isn’t already within one. This is useful.

From other language-agnostic, third-party text objects:

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:

Related articles:


  1. In the sense that you combine them with operators (eg c, d, gU) to build describe what you want to do.

    [return]
  2. To avoid clashing with the comment text-object binding from glts/vim-textobj-comment, you can rebind the class text-objct to, say, C with:

    map <buffer> aC <Plug>(PythonsenseOuterClassTextObject)
    map <buffer> iC <Plug>(PythonsenseInnerClassTextObject)
    [return]
----

Something wrong? Suggest an improvement or add a comment (see article history)
Tagged with: vim, django, python
Filed in: tips

Previous: Debugging Vim by example

Copyright © 2005-2019 David Winterbottom
Content licensed under CC BY-NC-SA 4.0.