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:
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:
Now, we need to define the command to be applied to each selected line. In this case, we want to:
- Move the cursor to the end of each line,
- Enter insert mode, then
- 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:
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.