Home Downloads Vim Editor: Commands, tips and tricks for advanced editing

Vim Editor: Commands, tips and tricks for advanced editing

Vim, with its steep learning curve, rewards those who master it. Unlock the power of efficient editing with our guide, filled with must-know commands, tips, and tricks.

by John Horan
vim editor commands

Let’s dive into an in-depth exploration of Vim, the famous text editor that is widely used in the Unix and Linux worlds. Vim is well-known for its efficiency, extensibility, and powerful command language. It is an enhanced version of the original Vi editor and offers a modal interface that separates content manipulation from insertion. This feature allows users to execute complex editing commands with minimal keystrokes.

This guide delves into Vim’s array of commands, ranging from basic navigation to advanced file operations, and provides insights into the customization capabilities of the .vimrc file, which empowers users to tailor the environment to their specific coding needs.

Getting started with Vim

Before diving into the nitty-gritty, let’s understand the basics. Vim operates in several modes, but the two you’ll use most are Normal mode and Insert mode. Normal mode is where you can run commands to navigate and manipulate text, while Insert mode is for typing text like you would in a regular text editor.

Opening and closing Vim

  • To open Vim: Type vim in your terminal and press Enter.
  • To open a file with Vim: Type vim filename (replace filename with the actual file name).

Once you’re in, here’s how to get out:

  • To exit Vim: Press Esc to ensure you’re in Normal mode, then type :q and press Enter. If you’ve made changes, Vim will warn you. To exit without saving, use :q!.

Basic navigation

  • Move up, down, left, right: Use the k, j, h, l keys respectively.
  • Go to the start of the line: Press 0.
  • Go to the end of the line: Press $.

Editing basics

  • Enter Insert mode: Press i.
  • Exit Insert mode: Press Esc.
  • Delete a character: In Normal mode, move the cursor over the character and press x.
  • Undo: Press u in Normal mode.
  • Redo: Press Ctrl + r.

Advanced editing

Now, let’s ramp up our Vim prowess with some more advanced commands.

Cutting, copying, and pasting

  • Cut (or delete) a line: In Normal mode, press dd.
  • Copy (or yank) a line: Press yy.
  • Paste below or above: Press p to paste below the cursor, or P to paste above.

Searching and replacing

  • Find text: Type :/pattern and press Enter. Replace pattern with the text you’re searching for.
  • Replace text: Type :%s/old/new/g to replace all occurrences of old with new.

Working with multiple files

  • Open a new file in Vim: Type :e filename.
  • Switch between files: Use :bn (next file) and :bp (previous file).

My personal Vim setup

I like to keep my Vim minimal yet powerful. Here are some of my favorite plugins and settings:

  • NerdTree for file system navigation
  • Syntastic for syntax checking
  • set number in my .vimrc to display line numbers

Mastering Vim motions and shortcuts

Motions and shortcuts are where your Vim skills truly level up. Here are a few:

  • ci( to change inside parentheses – a lifesaver!
  • ggVG to select the entire file
  • :%norm to perform a normal command on all lines

Split windows

  • Horizontal split: :sp filename
  • Vertical split: :vsp filename

I find split windows incredibly useful for comparing files or referencing one file while editing another.

Macros

Recording a macro lets you replay a series of commands. Press q followed by a letter to start recording, perform your series of commands, then press q again to stop. Execute the macro with @ followed by the letter you chose.

Vim commands quick reference cheat sheet

This table covers a range of basic to intermediate commands, providing a solid foundation for anyone looking to improve their Vim skills.

Command Description
:q Quit Vim. If there are unsaved changes, Vim will warn you.
:q! Quit without saving changes. Useful when you need to exit quickly and discard changes.
:w Save (write) the file, but don’t exit.
:wq or :x Save changes and quit.
i Enter insert mode to start editing the file.
Esc Exit insert mode and return to normal mode.
dd Delete (cut) the current line.
yy Yank (copy) the current line.
p Paste what was last deleted or yanked after the cursor.
u Undo the last action.
Ctrl+r Redo the last undone action.
gg Move the cursor to the first line of the file.
G Move the cursor to the last line of the file.
:%s/old/new/g Replace all occurrences of ‘old’ with ‘new’ in the file.
/search_term Search for ‘search_term’ in the file. Press n to go to the next occurrence.
:noh Remove highlighting from the last search.
v Enter visual mode for text selection.
> Indent the selected block (in visual mode).
< Unindent the selected block (in visual mode).
:e filename Open another file named ‘filename’ in Vim.

Customizing Vim

Understanding .vimrc

  • Location: The .vimrc file is typically located in your home directory (~/.vimrc on Unix/Linux systems). If it doesn’t exist, you can create it.
  • Purpose: It’s read every time Vim starts up and applies the configurations set within it.

Basic settings

  1. Line numbering:
    set number
    

    This command turns on line numbering, a helpful feature for navigating code.

  2. Syntax highlighting:
    syntax on
    

    Enables syntax highlighting, making code easier to read and understand.

  3. Indentation settings:
    set tabstop=4
    set shiftwidth=4
    set expandtab
    

    These settings adjust tab sizes and ensure spaces are used instead of tabs.

  4. Line wrapping:
    set wrap
    set linebreak
    

    These enable line wrapping without breaking words.

Key mappings

Custom key mappings can make your workflow much more efficient. Here’s an example:

nnoremap <C-s> :w<CR>

This maps Ctrl+S to save the file in normal mode (nnoremap means non-recursive mapping in normal mode), which can be more intuitive for those used to GUI text editors.

Plugin management

If you’re using a plugin manager like Vundle, you’ll add lines to .vimrc to manage your plugins. For instance:

call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'tpope/vim-fugitive'
call vundle#end()

This example initializes Vundle and then lists the plugins you want to install, including the very popular vim-fugitive.

Advanced configurations

As you get more comfortable with Vim, you might delve into more complex configurations:

  1. Auto commands:
    autocmd BufWritePre * :%s/\s\+$//e
    

    This auto command automatically removes trailing whitespace before saving a file.

  2. Function mappings: Creating custom functions for specific tasks and mapping keys to these functions can significantly boost your productivity.

Example 1: Bulk editing a config file

Scenario: You’re editing a configuration file and need to change an IP address that appears multiple times throughout the file.

Input in Terminal:

  1. Open the file with Vim:
    vim config.txt
  2. Enter command to replace all instances of the old IP with the new one:
    :%s/192.168.1.1/10.0.0.1/g
    

Output in Vim:

  • Every instance of 192.168.1.1 in the file is replaced with 10.0.0.1.
  • Vim displays a message like 42 substitutions on 30 lines.

Example 2: Comparing two code files side by side

Scenario: You have two versions of a Python script and want to compare them side by side.

Input in Terminal:

  1. Open the first file with Vim:
     vim script_v1.py
  2. Split the window and open the second file:
    :vsp script_v2.py
    

Output in Vim:

  • The Vim window is split vertically.
  • script_v1.py is on the left, and script_v2.py is on the right.
  • You can navigate each window independently.

Example 3: Refactoring Code

Scenario: You’re refactoring a piece of code and need to rename a variable across multiple lines.

Input in Terminal:

  1. Open the code file:
     vim main.py
  2. You want to change the variable name tempVar to temporaryVariable. First, you move to the line where tempVar is introduced.
  3. Enter command mode and type:
    :.,+5s/tempVar/temporaryVariable/g
    

Output in Vim:

  • This command changes tempVar to temporaryVariable from the current line (.) to the next five lines (+5).
  • The change is applied only within these specified lines, leaving other instances in the document unchanged.

These examples showcase just a fraction of Vim’s capabilities, but they represent common tasks that many developers encounter daily.

Conclusion

Vim stands out not just as a text editor, but as a testament to the power of efficiency in code editing. Its modal approach, extensive command set, and unparalleled customization options through the .vimrc file offer a rich, adaptable environment for developers and power users. As we’ve explored, from basic navigation and file manipulation to advanced editing techniques and personal configuration, Vim’s capabilities cater to a wide spectrum of needs, making it a staple in many programmers’ toolkits. Embracing Vim requires a commitment to learning and adaptation, but the payoff in terms of productivity and control over your editing environment is substantial.

You may also like

Leave a Comment

fl_logo_v3_footer

ENHANCE YOUR LINUX EXPERIENCE.



FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews written by team of expert authors. FOSS Linux is the go-to source for all things Linux.

Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY.

ALL RIGHTS RESERVED.

“Linux” is the registered trademark by Linus Torvalds in the U.S. and other countries.