Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat a navigation command in Vim

Tags:

vim

The . key can be used to repeat the last insert command. However, we might do some navigation that is not part of the insert, but we want it repeated.

Imagine commenting out lines like so:

// line of text
// line of text
line of text
line of text

The insert command is to put the two forward slashes and a space. That can be repeated using the . key. The navigation would be to navigate down one line and then left some number of characters. That part is not captured by the . key command.

How can we achieve this functionality? I read that it was not available in Vi some years ago, but I'm wondering if it exists now in the latest version of Vim.

like image 305
Vanilla Godzilla Avatar asked Sep 26 '17 00:09

Vanilla Godzilla


People also ask

How do I repeat the same command in vim?

Move the cursor to a new location, then type S<C-R>0<Esc> ( S then Ctrl-R then 0 then Escape). After moving the cursor to a new location, press . to repeat the operation (the current line will be replaced with the line that was originally copied).

How do you repeat a macro in vim?

Replay macros To replay the macro once, move the cursor to the next line and press @h where h represents the register on which you saved the macro. Notice that the macro automatically moves the cursor to the next line as required. This allows you to repeat its execution. To repeat the macro execution, press @@.

What is the vi command to repeat the last command?

In command mode, to undo the last command u is used and if you want to repeat the last command use dot (.).


2 Answers

  1. Press qX, where X is any of the writable registers (typically: pick any lowercase letter).
  2. Do whatever actions you want to record.
  3. Press q again to stop recording.
  4. Press @X (where X is the same register) to play it back (count times, if used with a count).
  5. Press @@ to replay the most recently used macro (count times).

I read that it was not available in Vi some years ago, but I'm wondering if it exists now in the latest version of Vim.

If the Vim docs are to be believed, Vi did not support recording (steps 1-3), but did support @. Then you would have to manually yank the characters into the target register with "Xy<motion> or some other register-writing command. That also works under Vim, but I can't recommend it because it is much more error prone.

like image 122
Kevin Avatar answered Oct 05 '22 22:10

Kevin


Another approach would be "block select then edit" approach:

  1. ctrl + v - block select

  2. then go down j or down-arrow

  3. shift + i will put you in insert mode. Make the change here where you want it to be reflected on all the other lines you've selected.

  4. esc twice will show/repeat that change you made on the line one.

like image 30
amacharla Avatar answered Oct 05 '22 23:10

amacharla