Prepending Text to Selected Lines

Occasionally while editing a document the need to prepend text to a sequence of lines comes up. For example, suppose you want to comment out some lines in a file by prepending each line with a "#" character.

A simple way to achieve this is to leverage normal mode commands to apply an operation over each line in a range. To demonstrate, let's start with the following file:

Initial Conditions
one
two
three
four
five
six
NORMAL
Top
1:1
 

First let move the cursor down a few lines and make a visual selection:

Make Selection
2jV2j
one
two
three
four
five
six
V-LINE
71%
5:1
 

Now that we have selected the lines to modify, let's build our command. First, hit : to enter command-line mode then enter normal to indicate that this command should execute in normal-mode. This tells Neovim that the following command should be executed once for each line in the selection.

Finally, we type the same keystrokes that we would execute in normal mode to achieve the desired changes. In this case, we want to execute I to move the cursor to the beginning of each line and enter insert mode, then # to insert this character.

:norm I#
Before Executing Command
one
two
three
four
five
six
COMMAND
71%
5:1
:normal I#

After executing this command, we can confirm that a "#" has been inserted at the start of each line in the selection.

After Executing Command
one
two
#three
#four
#five
six
NORMAL
71%
5:1