Applying Normal Mode Commands to a Range in Neovim

Suppose you are creating a list in python by yanking and pasting some content from another buffer. After pasting, the items are in place but are missing the trailing , required by python:

Initial Conditions
a·=·[
····"one"
····"two"
····"three"
]
NORMAL
33%
2:1
 

These trailing commas could be added manually, but that is a slow and repetitive task - particularly when working with larger lists. While we could make this significantly easier by defining a macro, Vim provides another solution that can automate these types of edits even more easily.

Vim allows normal mode commands to be applied to each line within a selected range using the :normal command.

To demonstrate, we first create a visual selection that contains each of the lines that we would like to edit:

Select Visual Range
v2j
a·=·[
····"one"
····"two"
····"three"
]
VISUAL
67%
4:1
 

Now, we need to define the command to be applied to each selected line. In this case, we want to:

  1. Move the cursor to the end of each line,
  2. Enter insert mode, then
  3. Insert a ,

As we said earlier, this could be solved easily with a macro, but there is already a normal mode command that performs steps 1 and 2: A, which we can easily follow with the ,:.

A,

Finally, we execute this command by passing it to the :normal command like this:

:normal A,

Executing this command in our buffer provides the desired result:

Execute the Command
a·=·[
····"one",
····"two",
····"three",
]
NORMAL
67%
4:12
 

Although applying normal mode commands in this way isn't as powerful as macros, in cases like this they can provide an even more convenient method of editing text.