How do I expand or shrink a visual selection to the next text object boundary?
Answer
v + repeated iw/aw/i(/a(/ip/ap
Explanation
Once you enter visual mode, you can progressively expand your selection by typing increasingly larger text objects. Start with viw to select a word, then without leaving visual mode, press a" to expand to the surrounding quotes, then a) to expand to the enclosing parentheses, and so on. Each text object grows the selection to the next boundary outward.
How it works
viwstarts visual mode selecting the inner word- While still in visual mode, typing another text object like
i"expands the selection to include everything inside the quotes - Typing
a(further expands to include the parentheses and their contents - Each successive text object replaces the visual selection with the new, larger region
- You can also use
oin visual mode to jump to the opposite end of the selection and then use motions to shrink it from that side
Example
Given the text with the cursor on name:
greet("Hello, " + name + "!")
Progressive expansion:
viwselectsname- (still in visual mode)
i"— no effect here sincenameisn't inside quotes, buta)expands to select"Hello, " + name + "!" a)selects the entire content including the parentheses:("Hello, " + name + "!")
Or starting from a word inside quotes:
result = process(config["timeout"])
viwontimeoutselectstimeouti"expands totimeout(inside quotes)a"expands to"timeout"(including quotes)i[expands to"timeout"(inside brackets)a[expands to["timeout"](including brackets)a)expands to(config["timeout"])(including parentheses)
Tips
- This technique is sometimes called incremental selection — it is the Vim-native equivalent of the expand-region feature popular in other editors
- Press
oin visual mode to toggle the cursor between the start and end of the selection — then use motions likew,b,e,f{char}to fine-tune one side gvreselects the last visual selection if you accidentally exit visual mode — you do not need to start over- In visual block mode (
<C-v>), pressO(uppercase) to jump to the opposite corner on the same line, andoto jump diagonally - You can also shrink by typing a smaller text object: if you selected
a)but only wantedi), pressi)while still in visual mode to shrink inward - Combine with any operator after your selection is right:
dto delete,cto change,yto yank,>to indent,=to auto-indent - The
vim-expand-regionplugin automates this workflow with a single key press (+to expand,_to shrink) if you want even faster incremental selection