Vim tip 33: editing with text objects
Combining motions such as w
, %
and f
with editing commands like d
, c
and y
require precise positioning to be effective.
Vim also provides a list of handy context based options to make certain editing use cases easier using the i
and a
text object selections. You can easily remember the difference between these two options by thinking i
as inner and a
as around.
- diw delete a word regardless of where the cursor is on that word
- equivalent to using de when the cursor is on the first character of the word
- diW delete a WORD regardless of where the cursor is on that WORD
- daw delete a word regardless of where the cursor is on that word as well as a space character to the left/right of the word depending on its position in the current sentence
- dis delete a sentence regardless of where the cursor is on that sentence
- yas copy a sentence regardless of where the cursor is on that sentence as well as a space character to the left/right
- cip delete a paragraph regardless of where the cursor is on that paragraph and change to Insert mode
- dit delete all characters within HTML/XML tags, nesting is taken care as well
- see :h tag-blocks for details about corner cases
- di" delete all characters within a pair of double quotes, regardless of where the cursor is within the quotes
- da' delete all characters within a pair of single quotes along with the quote characters
- ci( delete all characters within
()
and change to Insert mode- works even if the parenthesis are spread over multiple lines, nesting is taken care as well
- ya} copy all characters within
{}
including the{}
characters- works even if the braces are spread over multiple lines, nesting is taken care as well
You can use a count prefix for nested cases. For example, c2i{ will clear the inner braces (including the braces, and this could be nested too) and then only the text between braces for the next level.
See :h text-objects for more details.
Video demo:
See also my Vim Reference Guide and curated list of resources for Vim.