vimtricks.wiki Concise Vim tricks, one at a time.

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

  • viw starts 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 o in 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:

  1. viw selects name
  2. (still in visual mode) i" — no effect here since name isn't inside quotes, but a) expands to select "Hello, " + name + "!"
  3. a) selects the entire content including the parentheses: ("Hello, " + name + "!")

Or starting from a word inside quotes:

result = process(config["timeout"])
  1. viw on timeout selects timeout
  2. i" expands to timeout (inside quotes)
  3. a" expands to "timeout" (including quotes)
  4. i[ expands to "timeout" (inside brackets)
  5. a[ expands to ["timeout"] (including brackets)
  6. 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 o in visual mode to toggle the cursor between the start and end of the selection — then use motions like w, b, e, f{char} to fine-tune one side
  • gv reselects the last visual selection if you accidentally exit visual mode — you do not need to start over
  • In visual block mode (<C-v>), press O (uppercase) to jump to the opposite corner on the same line, and o to jump diagonally
  • You can also shrink by typing a smaller text object: if you selected a) but only wanted i), press i) while still in visual mode to shrink inward
  • Combine with any operator after your selection is right: d to delete, c to change, y to yank, > to indent, = to auto-indent
  • The vim-expand-region plugin automates this workflow with a single key press (+ to expand, _ to shrink) if you want even faster incremental selection

Next

How do I edit multiple lines at once using multiple cursors in Vim?