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

How do I yank text from the cursor to the next occurrence of a pattern without entering visual mode?

Answer

y/{pattern}<CR>

Explanation

Any operator in Vim can take a search motion as its argument. Typing y/ starts a forward search, and once you confirm with <CR>, Vim yanks from the current cursor position up to (but not including) the match. This avoids the detour of entering visual mode and manually extending the selection.

How it works

  • y is the yank operator
  • /{pattern} is a forward search motion (you see the search as you type it)
  • <CR> confirms the motion and triggers the yank
  • The yanked text runs from the cursor up to, but not including, the first character of the match
  • The same technique works with any operator: d/end<CR> deletes to the word "end", c/;<CR> changes up to the next semicolon

Example

Given the text with the cursor at s in string:

string = "hello world"; // comment

Typing y/;<CR> yanks string = "hello world" (everything up to the semicolon). Then p pastes it elsewhere.

For exclusive vs inclusive control, append /e offset to include the last char of the match:

y/word/e<CR>

Tips

  • Works in the opposite direction with ?: y?begin<CR> yanks backward to the pattern
  • Combine with n after the operator to reuse the current search: y//e<CR> yanks up to and including the current search match
  • The search is entered using the familiar / prompt with highlighting, so you can see exactly where the motion will land before pressing <CR>

Next

How do I enable matchit so % jumps between if/else/end style pairs?