Mastering Vim in 2023: A Guide to Enhanced Productivity

Umur Alpay
CodeResult
Published in
15 min readMay 18, 2023

This story is originally published at https://coderesult.com/blog/mastering-vim-in-2023-a-guide-to-enhanced-productivity/

Vim, an acronym for “Vi Improved”, is a highly configurable text editor that has been enhancing productivity for decades. Originally released in 1991, Vim is based on the earlier Vi text editor, but it boasts a plethora of features and improvements, positioning itself as a go-to tool for many programmers, developers, system administrators, and data scientists.

You might wonder, why learn Vim in 2023? In an era where we have numerous modern text editors and Integrated Development Environments (IDEs), why should we turn our gaze towards a tool born from a time before the internet had even become mainstream? The answer is simple: Efficiency and Ubiquity. Vim, with its keyboard-centric design, allows you to perform tasks with fewer keystrokes, boosting your productivity significantly. Moreover, it is ubiquitous. Regardless of which Unix or Linux system you work on, you’re almost certain to find Vim installed.

Vim’s modal nature, customization, and powerful features have contributed to its legendary status. Yet, despite its potent capabilities, newcomers often find it intimidating. The steep learning curve associated with Vim deters many. But once the initial hurdle is crossed, Vim’s potential to enhance productivity is unmatched.

The purpose of this guide is to demystify Vim and present it not as a relic of the past but as a modern tool capable of handling today’s needs just as effectively, if not more so, as when it was first created. Whether you’re a seasoned developer seeking to boost productivity or a curious beginner keen to unravel the mystique surrounding Vim, this guide aims to be a comprehensive resource to mastering Vim in 2023.

In the following sections, we’ll explore the basics, delve into advanced techniques, discuss customization, showcase must-have plugins, and provide plenty of tips and tricks to enhance your productivity with Vim. It’s time to roll up our sleeves and start our Vim journey in earnest!

Basics of Vim

Before we delve into the magic of Vim, it’s essential to understand its basic principles. Let’s start with a brief introduction and then dive into its various modes and the fundamental commands.

What is Vim?

Vim is a text editor that operates in a console or terminal, though a graphical version called GVim also exists. It’s a tool built for editing text at lightning speed, and it achieves this through various modes and keyboard shortcuts. Let’s install it first:

On Ubuntu or Debian-based systems, you can install Vim using the following command:

sudo apt-get install vim

For macOS users:

brew install vim

On Windows, you can download GVim from the Vim website.

Understanding Vim Modes

Vim operates in several modes, but the three most important ones you need to know initially are:

  • Normal Mode: This is the default mode when you open Vim. You can navigate around the file, delete text, copy and paste, and more. You are not inserting text in this mode.
  • Insert Mode: You can enter this mode from Normal mode by pressing i. Now you can insert text into your document. Press ESC to return to Normal mode.
  • Visual Mode: This mode allows you to select text. Press v to enter Visual mode, move the cursor to select text, then you can copy (y) or delete (d) the selected text.

Basic Vim Commands

Vim has a plethora of commands, but let’s focus on the basic ones that you’ll use frequently:

  • Open a file: vim filename
  • Save a file: While in Normal mode, :w
  • Save and quit: While in Normal mode, :wq
  • Quit without saving: While in Normal mode, :q!

For movement in Normal mode, instead of using the arrow keys, you can use h (left), j (down), k (up), l (right).

For deleting, copying, and pasting:

  • Delete a character: In Normal mode, move to the character and press x.
  • Delete a line: In Normal mode, press dd.
  • Copy a line: In Normal mode, press yy.
  • Paste a line: In Normal mode, press p to paste after the cursor or P to paste before.

The power of Vim is its combination of commands. For example, to delete 5 lines, you would type 5dd in Normal mode.

The basic knowledge outlined here will get you started with Vim. But remember, mastering Vim is a journey, and the first step is to get comfortable with these commands and modes. As you proceed through the following sections, you will unveil Vim’s real power, and using it will become second nature. Keep practicing, stay patient, and soon enough, you’ll start experiencing the enhanced productivity that Vim promises.

Advanced Vim Techniques

Once you are comfortable with the basics of Vim, it’s time to delve deeper into more advanced techniques. These features are where Vim truly shines, enabling a level of speed and productivity that few other text editors can match.

Vim Macros

Macros in Vim allow you to record a series of commands and replay them. This is extremely useful for repetitive tasks. To record a macro, press q followed by any letter (for example, a) in Normal mode. This will start recording your macro. Once you've finished your series of commands, press q again to stop recording. Now, you can replay the macro by pressing @a. If you want to replay the macro 10 times, you can type 10@a.

Complex Text Manipulation

Vim excels at manipulating text. In addition to simple operations like deletion and insertion, you can perform more complex operations. For instance, the c command changes text. To change until the end of a word, you can use ce in Normal mode. This deletes the rest of the word and puts you in Insert mode. If you want to change the entire line, you can use cc.

Vim also allows powerful search and replace functionality. You can use the :%s/old/new/gc command to replace all occurrences of 'old' with 'new'. The g flag means "global" (i.e., every occurrence in the line), and the c flag means "confirm" (i.e., ask for confirmation).

Buffers, Windows and Tabs

Vim supports multiple windows and tabs, allowing you to edit multiple files at once. Each file you open in Vim is loaded into a buffer. You can view the list of buffers with the :ls command. To switch to a buffer, you can use the :b command followed by the buffer number or name.

You can split your Vim screen into multiple windows with the :split or :vsplit command (or :sp and :vsp for short). This allows you to view and edit multiple buffers at the same time. You can navigate between windows using Ctrl-w followed by the arrow keys.

Vim also supports tabs, which can contain one or more windows. You can create a new tab with the :tabnew command and switch between tabs with gt (next tab) and gT (previous tab).

Navigating Large Codebases

When dealing with large codebases, navigating through files can become a daunting task. Vim offers several commands to ease this process, including:

  • :e . opens a file explorer for the current directory.
  • gf opens the file under the cursor.
  • ]c and [c jump to the next and previous change, respectively.
  • Ctrl-] jumps to the tag (definition) under the cursor, useful for navigating codebases (requires a tags file generated, for example, by ctags).
  • Ctrl-o and Ctrl-i navigate the jump list, taking you back and forth where you’ve been.

These advanced techniques unlock a new level of productivity with Vim. In the next sections, we’ll see how to tailor Vim to your preferences and explore some powerful plugins.

Customizing Vim

One of the reasons developers love Vim is its high level of customizability. Nearly every aspect of Vim can be tweaked to fit your personal workflow and coding style. Let’s explore how you can create a tailored Vim environment.

The .vimrc File

The heart of Vim customization lies in a file named .vimrc. This is a configuration file that Vim reads every time it starts up. It's usually located in your home directory (~/.vimrc). If it doesn't exist, you can create it.

In the .vimrc file, you can specify various settings to customize Vim's behavior. Here are a few examples of settings you might include:

" Enable line numbers set number " Set the tab width set tabstop=4 " Enable syntax highlighting syntax on " Show matching brackets set showmatch " Automatically indent based on file type filetype indent on

These are just a few examples of the numerous options available for customization in the .vimrc file. You can learn more about these options by typing :help option-name in Vim, replacing option-name with the name of the option you're interested in.

Vim Themes and Color Schemes

Vim supports various color schemes that can be set in your .vimrc file. Here's an example of how to set the color scheme:

" Set color scheme colorscheme desert

The desert color scheme is included with Vim. If you want to use a custom color scheme, you have to download it and place it in your ~/.vim/colors/ directory. After doing that, you can set it in your .vimrc file using the colorscheme command followed by the name of your custom color scheme.

Custom Keybindings

Vim also allows you to create custom keybindings. This means you can map a specific key or key combination to a command or a series of commands. For instance, you can map the F2 key to save the current file:

" Map F2 to save the current file nnoremap <F2> :w<CR>

In this example, <F2> is the key we're mapping, :w<CR> is the command we're mapping it to (:w saves the file, <CR> is the "Enter" key), and nnoremap is a command that creates a mapping in Normal mode.

Vim Plugins

Vim’s capabilities can be extended even further with plugins. Plugins can add new commands, provide integration with external tools, and more. You can install plugins manually by placing their files in the appropriate directories, or you can use a plugin manager like Vundle, Pathogen, or Vim-Plug.

For instance, to install plugins using Vim-Plug, you would specify them in your .vimrc file like so:

call plug#begin('~/.vim/plugged') Plug 'tpope/vim-fugitive' Plug 'junegunn/fzf', { 'do': { -> fzf#install() } } call plug#end()

You can then install the plugins by running :PlugInstall in Vim.

In the next section, we’ll dive deeper into must-have Vim plugins available in 2023. Customizing Vim can make it a powerful ally that suits your unique workflow, so don’t be afraid to tweak it.

Must-Have Vim Plugins in 2023

Vim’s core functionality is powerful, but plugins can greatly expand its capabilities, making it an even more potent tool for programmers. Here are some must-have Vim plugins in 2023 that can enhance your productivity:

1. Vim-Plug

Before diving into specific plugins, it’s important to have a solid plugin manager. Vim-Plug is a minimalist and speedy plugin manager. It allows you to install and update plugins efficiently, supports on-demand loading of plugins, and manages the required dependencies.

2. NERDTree

NERDTree is a file explorer plugin that provides a tree view of your filesystem. It’s an invaluable tool for navigating through projects and manipulating files directly within Vim.

3. FZF

FZF is a general-purpose command-line fuzzy finder integrated with Vim. It’s blazingly fast and can be used to open files, search file content, jump to tags, etc.

4. Ale (Asynchronous Lint Engine)

Ale uses the power of Vim’s asynchronous job control to lint your code on the fly as you type. It can be integrated with a large number of linters for different programming languages.

5. CtrlP

CtrlP is a fuzzy file finder. It allows you to quickly open files by typing a partial file name. This is extremely handy when working with large projects.

6. Vim-Fugitive

Vim-Fugitive is the premier Git plugin for Vim. It allows you to perform a variety of Git operations directly from Vim, including diffing, committing, and even resolving merge conflicts.

7. Coc.nvim

Coc.nvim provides intellisense and language server protocol support. This gives Vim capabilities like autocomplete, code linting, and navigation, akin to modern IDEs.

8. Vim-airline

Vim-airline provides a fancy status bar for Vim. It shows useful information like the current mode, line number, and git branch.

9. Vim-surround

Vim-surround is a small plugin that makes it easier to deal with pairs of “surroundings” like brackets, quotes, and HTML tags.

10. Vim-commentary

Vim-commentary provides an easy way to comment out lines of code in many different programming languages.

Installing and making good use of these plugins can drastically enhance your Vim experience. Remember, the power of Vim lies not just in its core features but also in its extensibility. These plugins represent just a small sample of what’s available, so don’t be afraid to explore and find the tools that work best for you.

Mastering Vim Scripting

Once you are comfortable with Vim’s interface and have set up your desired plugins and configurations, it’s time to take a step into the world of Vim scripting. By learning to write scripts for Vim, you can extend and automate its functionality to suit your personal workflow and drastically increase your productivity.

What is Vim Script?

Vim script, also known as VimL, is the scripting language built into Vim. You can use it to create new commands, automate repetitive tasks, customize your Vim environment, and even create complex plugins.

Basic Syntax and Data Types

Vim script syntax may look a bit foreign if you’re used to languages like Python or JavaScript, but it’s relatively straightforward once you get the hang of it.

Here are some basic data types in Vim script:

  • Numbers: let a = 1
  • Strings: let s = "hello"
  • Lists (like arrays in other languages): let l = [1, 2, 3]
  • Dictionaries (like objects in JavaScript): let d = {'key': 'value'}

Vim script also supports control flow constructs like if, else, and while:

let a = 5 if a > 10 echo "a is greater than 10" else echo "a is not greater than 10" endif

Functions

You can define your own functions in Vim script. Here’s an example:

function! SayHello() echo "Hello, Vim!" endfunction

You can then call this function with :call SayHello().

The a! after function means that the function can be redefined. This is a good practice while developing your scripts, as it allows you to reload your .vimrc without running into errors about functions being already defined.

Creating Custom Commands

Vim script allows you to define your own custom commands. For example, let’s create a command that saves all open buffers:

command! SaveAll :wa

You can now use :SaveAll to save all open buffers. The ! after command works just like in functions, allowing the command to be redefined.

Automating Tasks

With Vim script, you can automate repetitive tasks. For example, you might find yourself frequently switching to a specific coding style for a project. You could create a function to set up your preferred settings:

function! SetUpCodingStyle() set tabstop=4 set shiftwidth=4 set expandtab set number endfunction

You can then call this function whenever you start working on that project.

Extending Vim with Vim Script

Beyond automating tasks and setting options, Vim script allows you to create new features that deeply integrate with Vim. You can create complex scripts that react to events, modify the buffer, interact with the filesystem, and more. If you’re interested in this level of Vim scripting, a good place to start is by looking at existing plugins. Most Vim plugins are open-source, and their code can serve as useful examples.

Mastering Vim scripting can take time, but the payoff in terms of increased productivity and a deeply personalized coding environment is well worth it.

Tips and Tricks for Productivity

Having explored the depths of Vim, from its basic commands to the intricacies of Vim scripting, let’s wrap up this guide with a collection of various tips and tricks that can enhance your productivity when using Vim.

1. Use Buffers, Windows, and Tabs

Vim provides buffers, windows, and tabs to manage multiple files and views:

  • Buffers: A buffer is essentially an open file. :ls shows all open buffers, :bnext and :bprev let you cycle through buffers, and :bn {buffer number} lets you switch to a specific buffer.
  • Windows: A window is a viewport onto a buffer. You can split your Vim screen into multiple windows with :split or :vsplit, then switch between windows with Ctrl-w followed by a movement key (h, j, k, or l).
  • Tabs: A tab page is a collection of windows. You can create a new tab with :tabnew, and switch between tabs with :tabnext, :tabprev, or gt and gT.

Understanding and making use of buffers, windows, and tabs can greatly improve your workflow when working with multiple files.

2. Use Vim’s Visual Mode

Visual mode is a powerful tool for manipulating blocks of text. Press v to start visual mode, then move to select text. Once you have a block of text selected, you can copy it with y, paste with p, or delete with d.

3. Use Vim’s Search and Replace

Vim’s search and replace function is a powerful tool. Use / to search for text, n to find the next occurrence, and N to find the previous occurrence. To replace text, you can use :s/old/new/g to replace all occurrences of "old" with "new" in the current line, or :%s/old/new/g to replace in the entire file.

4. Make Use of the .vimrc File

As we discussed earlier, your .vimrc file is the key to customizing Vim to suit your needs. Don't be afraid to continually tweak your .vimrc file as you discover new commands or plugins that improve your workflow.

5. Master Vim’s Keyboard Shortcuts

Vim’s keyboard shortcuts can be a huge time-saver. Spend time learning the shortcuts for the commands you use most frequently. Over time, this can greatly speed up your coding.

6. Explore Plugins

We’ve already discussed several valuable Vim plugins, but there are many more out there. Spend time exploring the Vim plugin ecosystem and trying out new plugins that might improve your workflow.

7. Use Macros

Vim’s macro feature lets you record and replay sequences of commands. This can be a huge time-saver for repetitive tasks. Use q followed by a letter to start recording a macro, perform the sequence of commands, then press q again to stop recording. You can replay the macro with @ followed by the letter you used to record it.

Mastering Vim Shortcuts

One of the most important aspects of working effectively with Vim is becoming comfortable with its keyboard shortcuts. Mastering these shortcuts not only speeds up your editing but also keeps you in the “flow” state by eliminating the need to reach for the mouse. Here are some crucial Vim shortcuts you should master:

Movement Shortcuts

  • h, j, k, l: Move left, down, up, and right, respectively.
  • w: Move to the beginning of the next word.
  • e: Move to the end of the word.
  • b: Move to the beginning of the previous word.
  • 0 (zero): Move to the beginning of the line.
  • $: Move to the end of the line.
  • gg: Move to the start of the file.
  • G: Move to the end of the file.
  • Ctrl + u: Move half a page up.
  • Ctrl + d: Move half a page down.
  • %: Jump to the matching bracket ({[)}].

Editing Shortcuts

  • i: Enter insert mode before the current cursor position.
  • a: Enter insert mode after the current cursor position.
  • o: Insert a new line below the current line and enter insert mode.
  • O: Insert a new line above the current line and enter insert mode.
  • u: Undo the last operation.
  • Ctrl + r: Redo the last operation.
  • y: Yank (copy) the current line or selection.
  • p: Paste after the cursor or on the next line.
  • P: Paste before the cursor or on the previous line.
  • d: Delete the current line or selection.
  • x: Delete the character under the cursor.
  • c: Change the current line or selection.

Visual Mode Shortcuts

  • v: Enter visual mode.
  • V: Enter visual line mode (select whole lines).
  • Ctrl + v: Enter visual block mode (select rectangular blocks of text).

Search and Replace Shortcuts

  • /: Search for a pattern in the document, then press n or N to move to next/previous occurrence.
  • :%s/old/new/g: Replace all occurrences of 'old' with 'new' in the entire file.
  • :s/old/new/g: Replace all occurrences of 'old' with 'new' in the current line.

Window Management Shortcuts

  • :split: Split the window horizontally.
  • :vsplit: Split the window vertically.
  • Ctrl + w: Followed by a movement command, switches windows.

Miscellaneous Shortcuts

  • .: Repeat the last operation.
  • ggVG: Select all text in the file.
  • :e .: Open a file explorer in the current directory.
  • :help: Open Vim's built-in help system.

Mastering Vim requires a combination of understanding the editor’s philosophy, learning the basics, adapting to the modal nature of editing, learning to customize it through the .vimrc file, understanding and using plugins, and optionally delving into Vim scripting and NeoVim. As you progress on this journey, you'll find that Vim's power and flexibility can lead to a significant boost in your productivity.

While the learning curve can seem steep initially, investing time in Vim is worth the effort. Remember, learning Vim is not a sprint, but a marathon. Each step you take in mastering Vim contributes towards shaping Vim as an extension of your mind, allowing you to transform thoughts into code efficiently.

Vim, being open-source and having a large community, offers countless resources to assist you in your learning process. From plugins to tutorials to forums, the Vim community is an excellent source of learning and is always ready to help.

In this era, where IDEs and text editors emerge with GUI and a mouse-oriented approach, Vim stands unique with its keyboard-focused philosophy. If you master Vim, you will have a skill that not only boosts your productivity but also distinguishes you as a developer.

With the tips, tricks, and guides shared in this blog post, you are on your way to mastering Vim in 2023. So embrace the journey of learning Vim and keep experimenting.

Follow me on Instagram, Facebook or Twitter if you like to keep posted about tutorials, tips and experiences from my side.

You can support me from Patreon, Github Sponsors, Ko-fi or Buy me a coffee

--

--