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:

  1. Press the Esc key to enter Command Mode.
  2. Move to the beginning of the lines you want to edit.
  3. Press Ctrl + v to enter Visual Block Mode; the bottom-left corner will show -- VISUAL BLOCK --.
  4. Use the Up/Down arrow keys or the j and k keys to select the lines you want to edit.
  5. Press Shift + i to enter Insert Mode, then type the text you want to add.
  6. Press the Esc key; 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:

  1. Press the Esc key to enter Command mode.
  2. Move to the beginning of the line you want to edit.
  3. Press Ctrl + v to enter Visual Block mode.
  4. Use the up/down arrow keys or j and k to select the lines you want to edit.
  5. Press the x key 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 :norm command 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 .vimrc files.
  • Macro recording: Use the q key 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 + v to enter block selection mode.
  • Folding: Use the za command 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 ,c shortcut.

Reference Links

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.