Text objects are a remarkably useful feature of Vim. They allow you to perform a command inside or around the specified object, where an object is a piece of text with some kind of semantic structure, like a word, paragraph, quoted string, HTML tag, etc.
gqip
to reflow text (gq
) inside the current
paragraph (ip
)
gUiw
to convert inside the current word
(iw
) to uppercase (gU
)
ci"
to change inside the current matching pair of double quotesda{
to delete inside and around the current matching pair of curly braces
See
:help text-objects
for Vim's excellent built-in documentation on text objects.
(
or )
, [
or ]
, {
or
}
, and <
or >
for matching pairs of braces
b
and B
aliases respectively
"
, '
, and `
for matching pairs of quotest
for a matching pair of HTML or XML tagsw
for a word (letters, digits, and underscores, separated by whitespace or a non-word
character)
W
for a WORD (any characters, separated by whitespace)s
and p
for sentences and paragraphs respectivelyThere are various Vim plugins that define new kinds of text objects, or otherwise super-power text objects.
vim-indent-object provides text objects for indented text.
ai
for the current indentation level, and the line above (useful for Python)ii
inner indentation level, no surrounding linesaI
current indentation level, and the surrounding upper/lower lines
vim-textobj-comment provides text objects for
comments, defined by the comments
and commentstring
settings for the given
filetype. It works for /* paired */
and // simple
comment delimiters.
ic
for the comment textac
for the comment text and the comment delimitersvim-surround doesn't provide text objects, but it does provide powerful utilities for surrounding text objects.
ds
- delete surrounding (and only the surrounding, the surrounded text is left alone)
ds<count>
- delete the n
th surrounding<div><p><em>cursor here</em></p></div>
with
the cursor inside the <em>
tags, ds3t
will delete the
surrounding <div>
tags
cs
- change surrounding
cs'"
change surrounding single quotes to double quotesys
- add surrounding (mnemonic: you surround)
ysiw*
will surround the current word in *
'sysa"fprint
will surround a quoted string in a
function call to print()
ysiw<a href="foo">
will surround the current word in
an HTML link to foo