Commands for Vim

Basic, Medium and Advanced Commands for Vim

Vim is a powerful text editor that is used to create and edit text files. It’s an improved version of the older Unix editor, Vi. Vim is popular among programmers and system administrators for its efficiency and versatility. It operates in different modes, such as Normal, Insert, and Visual, allowing users to perform various tasks quickly.

Vim was created by Bram Moolenaar in 1991. It has evolved over the years with contributions from many developers. Vim’s speed and minimalistic design make it ideal for editing code. It’s highly customizable, with countless plugins and scripts available. Vim can boost productivity because of its keyboard-centric approach, reducing the need for mouse interaction.

Getting Started

These basic concepts and commands will help you get started with Vim.

Installing Vim

To install Vim, follow these steps.

  • Linux: Use the package manager of your distribution. For Debian-based systems like Ubuntu, type sudo apt-get install vim. For Red Hat-based systems like Fedora, use sudo yum install vim. Arch Linux users can install it using sudo pacman -S vim.
  • macOS: Use the Homebrew package manager. First, install Homebrew if you haven’t already by running /bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)”. Then, install Vim with the command brew install vim.
  • Windows: Download the installer from the official Vim website and run it. Alternatively, use a package manager like Chocolatey by running Choco install vim.

After installation, you can verify it by opening a terminal or command prompt and typing vim –version.

Basic Concepts

Vim operates in several modes, each serving a specific purpose. 

  • Normal Mode: This is the default mode when you start Vim. In this mode, you can navigate the text, delete or change text, and perform many other operations. To return to Normal Mode from any other mode, press Esc.
  • Insert Mode: Used for inserting and editing text. You can enter Insert Mode by pressing i (insert before the cursor), I (insert at the beginning of the line), a (append after the cursor), or A (append at the end of the line).
  • Visual Mode: Allows selecting and manipulating blocks of text. Enter Visual Mode by pressing v (character-wise selection), V (line-wise selection), or Ctrl+v (block selection).
  • Command-line Mode: For entering commands starting with :, /, or ?. For example, :w saves the file, :q quits Vim, and :wq saves and quits. Use / to search forward and ? to search backward.

Basic Commands

Opening and Closing Files

To open a file in Vim, type vim filename in your terminal or command prompt. If the file doesn’t exist, Vim will create a new one with that name. To close Vim, you can use :q to quit, :q! to quit without saving changes, and :wq or 😡 to save changes and quit. Alternatively, pressing ZZ (Shift+Z twice) will also save and quit.

Moving Around

You can use the arrow keys for basic navigation, but Vim offers more efficient methods. Use h, j, k, and l for left, down, up, and right movements, respectively. To navigate by words, use w to move to the beginning of the next word, b to move to the beginning of the previous word, and e to move to the end of the current word. 

For line navigation, 0 moves to the beginning of the line, $ moves to the end, and ^ moves to the first non-blank character. To quickly move through the document, gg jumps to the top, G to the bottom, Ctrl+u scrolls up half a page, and Ctrl+d scrolls down half a page.

Inserting and Deleting Text

To insert text, press i to insert before the cursor, I to insert at the beginning of the line, a to append after the cursor, and A to append at the end of the line. You can also use o to open a new line below the current one and O to open a new line above. 

To delete text, use x to delete the character under the cursor, dw to delete from the cursor to the end of the word, dd to delete the entire line, d$ to delete from the cursor to the end of the line, and d0 to delete from the cursor to the beginning of the line.

Saving Changes

To save changes, type :w. If you want to save the file with a new name, use :w filename. To save all open files, use :wa. To save and quit, use :wq or :x. These commands ensure that your changes are not lost and allow you to exit Vim cleanly.

Intermediate Commands

Copying, Cutting, and Pasting Text

To copy text, use the y (yank) command. For example, yy yanks the entire line, and yw yanks a word. To yank a specific number of lines, use nyy, where n is the number of lines.

To cut text, use the d (delete) command. dd cuts the entire line, and dw cuts a word. You can also use ndd to delete multiple lines, where n is the number of lines.

To paste text, use the p command to paste after the cursor or P to paste before the cursor. These commands are useful for rearranging text within your document.

Undo and Redo

To undo changes, use the u command. This undoes the last change you made. To redo changes, use Ctrl+r, which redoes the last undone change. These commands help you correct mistakes quickly and efficiently.

Searching and Replacing Text

To search for text, use the / command followed by the text you want to find. For example, /word searches for the word “word” in the document. To search backward, use ?word. You can navigate through search results using n for the next occurrence and N for the previous one.

To replace text, use the :s command. For example, :s/old/new/g replaces all occurrences of “old” with “new” in the current line. To replace text in the entire document, use :%s/old/new/g. The g at the end ensures all occurrences are replaced, not just the first one on each line.

Working with Buffers and Windows

Vim allows you to work with multiple files using buffers. To open a new file in a buffer, use :e filename. To switch between buffers, use :bn for the next buffer and :bp for the previous buffer. To list all open buffers, use :ls.

Vim also supports window splitting for multitasking. To split the window horizontally, use :split or :sp. For a vertical split, use :vsplit or :vsp. You can navigate between windows using Ctrl+w followed by a direction key (h, j, k, or l). To close a window, use :q.

Advanced Commands

Macros and Scripting

Macros allow you to record and replay sequences of commands, which can save time on repetitive tasks. To record a macro, press q followed by a letter to name the macro (e.g., qa starts recording a macro named “a”). Perform the desired sequence of commands, and press q again to stop recording. To replay the macro, press @ followed by the macro name (e.g., @a). You can repeat the macro multiple times by specifying a count before @ (e.g., 5@a).

Customizing Vim with .vimrc

The .vimrc file allows you to customize Vim’s behavior and appearance. Common customizations include setting line numbers (set number), enabling syntax highlighting (syntax on), and customizing the status line (set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%c%V]\ [%-P]). You can also map custom key bindings in your .vimrc file. For example, to map Ctrl+s to save the file, add nmap <C-s> :w<CR>.

Using Plugins

Plugins extend Vim’s functionality. Popular plugins include NERDTree for file browsing, CtrlP for fuzzy file searching, and Vim-airline for an enhanced status bar. To manage plugins, use a plugin manager like Vundle, Pathogen, or Vim-plug. For example, to install Vim-plug, add the following to your .vimrc:

Regular Expressions in Vim

Regular expressions (regex) are powerful for search and replace operations. In Vim, regex allows for complex pattern matching. For example, to find all lines containing digits, use /\d. To replace patterns, use the :s command with regex. For instance, :s/\(\w\+\)\s\+\(\w\+\)/\2 \1/g swaps the first two words in each line. Mastering regex can greatly enhance your text processing capabilities in Vim.

Vim for Programming

Syntax Highlighting

Syntax highlighting helps in differentiating elements of the code visually. To enable syntax highlighting in Vim, simply add syntax on to your .vimrc file. Vim supports syntax highlighting for a wide range of programming languages out of the box. For example, if you are editing a Python file, Vim will automatically highlight keywords, comments, and other elements in different colors.

Code Completion

Code completion can significantly speed up coding by suggesting completions for partially typed keywords. Plugins like YouCompleteMe and Deoplete offer advanced code completion features. To set up YouCompleteMe, follow the instructions on its GitHub page. These plugins provide real-time suggestions as you type, making it easier to write accurate and efficient code.

Debugging Tools

Vim can be integrated with debugging tools to make the debugging process smoother. One popular plugin for debugging is vimspector. Vimspector allows you to set breakpoints, step through code, and inspect variables directly within Vim. To install vimspector, use a plugin manager like Vim-plug and add the following to your .vimrc:

After installing the plugin, you can start debugging by configuring your debug profile and using the provided commands to control the debugging process.

Version Control Integration

Integrating version control with Vim enhances your workflow by allowing you to manage your code repository directly from the editor. The fugitive.vim plugin is a powerful tool for working with Git in Vim. To install fugitive.vim, add the following to your .vimrc:

With fugitive.vim, you can run Git commands like :Gstatus to view the status of your repository, :Gcommit to commit changes, and :Gpush to push changes to a remote repository. This integration streamlines the process of version control, making it more efficient and accessible.

Tips and Tricks

Efficient Editing Techniques

  • Use Macros for Repetitive Tasks: Record macros to automate repetitive tasks. Press q followed by a letter to start recording, perform the actions, and press q again to stop. Replay the macro with @ followed by the letter.
  • Visual Mode: Use Visual Mode to quickly select and manipulate text. Press v for character-wise selection, V for line-wise, and Ctrl+v for block selection.
  • Jump to Matching Parentheses: Quickly navigate to matching parentheses, braces, or brackets by placing the cursor on one and pressing %.

Advanced Get over Tips

  • Marks for Quick Navigation: Set marks to jump to specific points in the file. Press m followed by a letter to set a mark, and ‘ followed by the letter to jump to it.
  • Navigate by Search: Use * to search forward for the word under the cursor and # to search backward. Use n and N to move between search results.
  • Use Buffers Efficiently: Switch between open files (buffers) with :bnext (or :bn) and :bprev (or :bp). List all open buffers with :ls.

Useful Plugins for Developers

  • NERDTree for File Navigation: NERDTree is a file explorer that lets you navigate your project directory. Install it with Plug ‘preservim/nerdtree’. Open and close it with :NERDTreeToggle.
  • CtrlP for Fuzzy File Finding: CtrlP allows for quick file searches. Install it with Plug ‘ctrlpvim/ctrlp.vim’. Invoke it with :CtrlP and start typing the file name.
  • Vim-airline for a Better Status Line: Vim-airline provides a customizable status line with useful information. Install it with Plug ‘vim-airline/vim-airline’.

FAQs

Q. How do I install plugins in Vim?

Plugins can be installed using a plugin manager like Vim-plug, Vundle, or Pathogen. Add the plugin’s repository to your .vimrc file and run the appropriate command to install it.

Q. Can I use Vim to edit files remotely?

Yes, you can use Vim with tools like SSH to edit files on remote servers. Use the command vim scp://user@hostname//path/to/file to open a remote file.

Q. How do I customize Vim’s appearance?

Customize Vim’s appearance by modifying your .vimrc file. You can change color schemes, enable line numbers, and adjust the status line. Use set number for line numbers and colorscheme desert for a different color scheme.

Q. What are some alternatives to Vim?

Alternatives to Vim include text editors like Emacs, Nano, Sublime Text, and Visual Studio Code. Each has its features and advantages.

Q. How can I learn more advanced Vim techniques?

To learn more advanced Vim techniques, explore online tutorials, join Vim communities, and read books like “Practical Vim” by Drew Neil. Practice regularly to improve your skills.

Conclusion

Vim is a powerful and versatile text editor that can greatly enhance your productivity. From basic commands for navigating and editing text to advanced features like macros, plugins, and debugging tools, Vim offers a wide range of functionalities. By mastering these commands, you can work more efficiently and effectively, whether you’re coding, writing, or managing system configurations.

Learning Vim might seem challenging at first, but with practice, you’ll find it to be an incredibly useful tool. Customizing your Vim environment with plugins and personal configurations can tailor the editor to fit your specific needs. With its extensive capabilities and customization options, Vim remains a favorite among programmers and power users.

Share the article

Written By

Author Avatar

July 3, 2024

Ayesha Khan is a highly skilled technical content writer based in Pakistan, known for her ability to simplify complex technical concepts into easily understandable content. With a strong foundation in computer science and years of experience in writing for diverse industries, Ayesha delivers content that not only educates but also engages readers.

Launch Your Vision

Ready to start your project? Let's work together to make it happen! Get in touch with us today and let's bring your ideas to life.

Get In Touch