When editing text in Vim, we often need to perform uniform operations on multiple lines, such as adding or removing specific characters. Here are some practical Vim tips to help us get these done quickly.
Inserting Characters at the Beginning of Multiple Lines
If we want to insert the same text at the beginning of multiple lines, follow these steps:
- Press the
Esckey to enter Command Mode. - Move to the beginning of the lines you want to edit.
- Press
Ctrl+vto enter Visual Block Mode; the bottom-left corner will show-- VISUAL BLOCK --. - Use the Up/Down arrow keys or the
jandkkeys to select the lines you want to edit. - Press
Shift+ito enter Insert Mode, then type the text you want to add. - Press the
Esckey; after a moment, Vim will insert the text you typed on every selected line.
Deleting Characters at the Beginning of Multiple Lines
If we want to delete the same characters at the beginning of multiple lines, we can take the following steps:
- Press the
Esckey to enter Command mode. - Move to the beginning of the line you want to edit.
- Press
Ctrl+vto enter Visual Block mode. - Use the up/down arrow keys or
jandkto select the lines you want to edit. - Press the
xkey to delete the first character of each selected line. Note that if a line is empty or its first character is not highlighted, that line will not have any characters removed.
Other Tips and Plugins
Besides basic Vim commands, there are also some advanced tips and plugins that can help us edit multiple lines more efficiently:
- Regular expressions: Use
:%s/^/#/to add#characters at the beginning of each line for commenting. - Batch operations: The
:normcommand lets you execute a series of normal-mode commands across multiple lines; for example,:'<,'>norm I//adds//at the start of the selected lines. - Vim scripting: Automate editing tasks by writing scripts and saving them in
.vimrcfiles. - Macro recording: Use the
qkey to record a macro, then replay it with@followed by the letter used during recording. - Block operations: Vim's block operations let you select and manipulate text blocks; use
Ctrl+vto enter block selection mode. - Folding: Use the
zacommand to fold or unfold code blocks for easier viewing and editing.
Simplifying Operations with Plugins
- NERD Commenter: A popular Vim plugin that lets you quickly comment or uncomment code blocks.
- EnhCommentify: Another plugin that provides smarter commenting features, allowing you to comment or uncomment selected lines with the
,cshortcut.
Reference Links
- How to use a command in Vim to delete the first few characters of selected lines?
- How to insert text at the beginning of a multi-line selection in vi/Vim?
With these techniques, we can use Vim more efficiently for text editing, whether we're performing simple character additions or deletions, or tackling more complex block-commenting operations.
Comments · 1