Skip to main content

Vim Quickstart Guide

Introduction

 As a reasonably seasoned developer, I do most of my work with vim and vscode. When it comes to efficient coding, every keystroke counts. For developers seeking a tool that prioritizes speed, precision, and flexibility, few editors compare to Vim and its modern counterpart, Neovim. These are powerful, modal text editors, which means that the same keystroke will do a different thing depending on which mode is selected, offer a unique, keyboard-centric approach to writing and editing code that can transform the way you work.

 Vim, a descendant of the even older Vi editor, has long been cherished by seasoned developers for its minimalism and efficiency. Unlike conventional text editors, which rely heavily on mouse interactions, Vim operates almost entirely through keyboard commands. This might seem daunting at first, but once mastered, the ability to navigate and manipulate text without lifting your hands from the keyboard can dramatically boost your productivity. The editor's lightweight nature means it loads instantly and runs smoothly on virtually any system, from a humble Raspberry Pi to a full-fledged server.

 Neovim, on the other hand, is a fork of Vim that brings the beloved editor into the modern age. It retains the core philosophy of Vim but introduces enhanced functionality, better extensibility, and an asynchronous architecture that makes it more responsive and versatile. Neovim’s API allows for better integration with other tools and plugins, offering a more customizable experience while maintaining the same blazing speed.

 Whether you choose Vim or Neovim, both editors excel at making coding faster and more efficient. In this post I intend to cover a few of the main basic configurations for Vim, wating for the next one to set up neovim. There is no right or wrong choice here (although I'm sure emacs users would disagree) so pick your poison. However, I'm going to tell you this, Neovim, as I said before is a modernized fork for Vim, which means more plugins, more comfortable and easier to set up. The shortcuts are a bit odd if you're used to Vim like I am, but other than that it's pretty mint.

File Hierarchy in Vim

  Both Vim and Neovim come with specific directory structures that are essential for ensuring your configurations work correctly. This essentially means creating and naming folders and files where your settings will be stored. While the hierarchies differ slightly between the two, Neovim’s structure is generally considered more intuitive and easier to grasp (at least in my opinion :P).

  Let’s start by exploring the file hierarchy in Vim, the older of the two editors. Typically, these configurations are stored in your home directory (~), so I'll assume that as the root directory. It’s important to note that installing Vim doesn’t automatically create this structure, so you’ll need to set it up manually.

  Here’s the basic structure of Vim’s directory hierarchy:

.vimrc
.vim/
├── autoload/
│   └── plug.vim
├── backup/
├── colors/
├── pack/
│   └── plugins
└── plugged/
    ├── cmp-vsnip/
    ├── fzf.vim/
    ├── jedi-vim/
    ├── vim/
    ├── vim-avro/
    ├── vim-json/
    ├── vim-terraform/
    └── vim-vsnip/

  As you can see, there are a few key components here. First, there’s the .vimrc file, where general configurations are defined. This includes settings like the number of spaces for tabulation, whether syntax highlighting is enabled, and whether you want Vim to be compatible with Vi, among other options.

  Next, we have the directories under .vim/, where most things are stored. The autoload directory contains scripts meant to run at Vim's startup. The backup directory is pretty self-explanatory; it stores backup copies of files you're editing. Under colors, you should store custom themes, though many can also be used as plugins. For example, there’s a dracula theme installed as a plugin in the plugged directory.

  And that’s pretty much it! The directory names must be exact, as Vim looks for files in predefined paths, so make sure to follow the structure carefully.

Vim Basic Configuration

  First, you'll need to create a directory hierarchy like the one shown earlier. Create all but the pack directory and the ones under plugged, as those are related to plugins and will be created automatically. The pack directory, however, needs to be created manually by running the following command, which installs a plugin for autocompletion using the Tab key.

mkdir -p ~/.vim/pack/plugins/start && git clone --depth=1 https://github.com/ervandew/supertab.git ~/.vim/pack/plugins/start/supertab

  Once you’ve set up the directory structure and run the above command (which is optional—you can skip it if you prefer), you should be all set to proceed.

  Now, I’m going to assume you already know how to install software packages for your particular distro and that you’ve got Vim installed. With that out of the way, let’s dive into a quick guide on setting up some basic configurations for your shiny new text editor.

  The first step is to create the .vimrc file if it doesn’t already exist. In this file, we’ll tweak a few settings that I think will make your life easier, especially when navigating through the editor. Most of these configurations won’t be explained in detail for two reasons: First, it would take quite a while, and second, most of them are self-explanatory. So, without further ado, here’s my recommended configuration for .vimrc.

" First, we install the plugins we want
call plug#begin("~/.vim/plugged")

 " Vsnip plugins
 Plug 'hrsh7th/cmp-vsnip'
 Plug 'hrsh7th/vim-vsnip'

 " Personalized theme
 Plug 'dracula/vim'
 
 " Syntax highlighting for various languages
 Plug 'elzr/vim-json'
 Plug 'gurpreetatwal/vim-avro'
 Plug 'junegunn/fzf.vim'
 Plug 'hashivim/vim-terraform'

 " Jedi Vim -- Python Autocompletion
 Plug 'davidhalter/jedi-vim'
call plug#end()

packloadall                 " Enable packloadall for pack plugins
set nocompatible            " Disable compatibility with old-school Vi
set showmatch               " Show matching brackets
set ignorecase              " Case-insensitive searching
set mouse=v                 " Enable middle-click paste
set hlsearch                " Highlight search results
set incsearch               " Incremental search
set tabstop=4               " Number of columns occupied by a tab
set softtabstop=4           " Treat multiple spaces as a tab stop, so <BS> works as expected
set expandtab               " Convert tabs to spaces
set shiftwidth=4            " Width for auto-indents
set autoindent              " Auto-indent new lines to match the previous line
set number                  " Display line numbers
set wildmode=longest,list   " Enable bash-like tab completions
filetype plugin indent on   " Enable auto-indenting based on file type
set mouse=a                 " Enable mouse support
set clipboard=unnamedplus   " Use the system clipboard
filetype plugin on
set cursorline              " Highlight the current line
set ttyfast                 " Speed up scrolling in Vim
syntax on
set backupdir=~/.cache/vim  " Directory to store backup files
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
colorscheme dracula

  The plug#begin function allows you to add new plugins from various online repositories. This functionality comes from a plugin called vim-plug, which lets us easily manage plugins. But how do we install vim-plug in the first place? It’s simple: we just place it in the .vim/autoload/ directory.

  I’ve named the file plug.vim, but you can name it anything you like, as long as it has a .vim extension. You’ll need to create the file and name it as you wish. Since the file is too long to include here, I'll provide a command that will automatically download it to the correct directory:

wget https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim -P ~/.vim/autoload

  Admittedly, this isn’t my original work. This code is available in the vim-plug repository, where you can find more information about this plugin and instructions for installing it on various platforms, including Neovim.

Installing plugins

 Awesome, you now have vim-plug installed, which allows you to easily plug plugins into the vim plugged directory. Nice! However, there's still a bit of work to do. See, whenever you add a Plugin to the plug function in the .vimrc file, you are just declaring what you want, but no work is actually being done. To download the contents and actually have the perks you want vim to have, you need to install them.

  And install them we want. So to do that you just run the following command:

vim +PlugInstall +qa

 Alternatively, you can execute :PlugInstall from within Vim, but this doesn't always work, so you might end up needing to run the first command anyway. Let me explain what this does: When you create the plug.vim file in the autoload directory, you’re installing vim-plug. This plugin provides several functions to help you easily manage all those other plugins. The command essentially tells Vim to execute PlugInstall and then quit all with qa.

Fancy Editing Needs Fancy Shortcuts

 So, you've used Vim to modify the .vimrc file and now you're stuck because you don’t know how to quit. Don’t worry, you might need to do more than just edit and exit. I’m going to leave a list of commands here that will come in handy once you learn how to use them. Just a heads up, this (^) symbol represents the Ctrl key, and this (N) symbol indicates a number that you can type. Also, note that casing matters. Uppercase and lowercase letters perform different actions. It doesn’t matter whether you press "Shift" or "Caps Lock".

 Here’s a short list of commands to get you started. If at some point you want to know a specific shortcut for something, I recommend the Vim Cheat Sheet. This website has most, if not all, Vim shortcuts you might need or dream of. So go ahead, learn them all, I dare you.

Navigation

 Sure, you can use the arrow keys to move the cursor, but we hate them—so don’t use them. Try this instead:

Shortcut Action
h Move left, character by character.
l Move right, character by character.
b Move left, word by word.
w Move right, word by word.
j Move down, line by line.
k Move up, line by line.
N gg Move to the specified line. (NO N-WORD HERE keep moving...)
^f Page down.
^b Page up.
H Move cursor to the top of the screen (High).
M Move cursor to the middle of the screen (Mid).
L Move cursor to the bottom of the screen (Low).

 This might seem like a lot, but trust me, get used to the first seven, which is pretty easy, and you’ll be covered for most cases. Also, the first six commands can take a number to indicate how many characters, words, or lines you want to move at once. For example, typing 3w would move the cursor three words forward.

Switching Modes

 We’ve already mentioned that both Vim and Neovim are modal editors, meaning that the action a keystroke performs depends on which mode is active. So far, we’ve seen how to navigate a file in navigation mode (the default mode when you open a file). But how do we switch modes? Well, there are three main modes: Navigation, Visual, and Edit.

Shortcut Action
i Switch to insert mode, right before the cursor.
I Switch to insert mode at the beginning of the line.
a Switch to insert mode, right after the cursor.
A Switch to insert mode at the end of the line.
o Switch to insert mode, creating a line below the cursor.
O Switch to insert mode, creating a line above the cursor.
^[ Exit insert mode and return to navigation mode.
v Enter visual mode.
^[^[ Exit visual mode and return to navigation mode.
esc Exit both visual and insert modes.

 When you’re in insert mode, keystrokes will insert text into the file. In visual mode, moving the cursor will highlight text, which you can then copy, paste, delete, etc.

Editing

 These shortcuts allow for quick text editing without switching to Insert (or Edit) mode:

Shortcut Action
N yy Yank (copy) N lines (only one if no number is typed).
N dd Delete (cut) N lines.
u Undo changes.
^r Redo changes.
p Paste.
:wq Write and quit (this is how you exit Vim, by the way).
:q Quit (won’t work if the document has unsaved changes).
:q! Force quit, ignoring all changes.

 Remember, deleting lines with N dd will automatically copy them to the clipboard, overwriting the previous content and deleting the lines. There’s no Ctrl+X for cutting in Vim, but this gets pretty close.

Tabs and Splits

 This section is optional reading. With the commands above, you should be more than ready to go. However, one of the great strengths of both Vim and Neovim is the ability to edit multiple files at once, either in the same window using splits or across multiple tabs, allowing you to easily jump between files. If that’s not your thing, no worries, just stop reading here. This is the last part of the article, I promise. There’s a lot of information here, and I’m sure you’re already tired. But if you’re still with me, I hope this also serves as a quick reference guide for any shortcuts you might need.

Shortcut Action
^wv New vertical split.
^wn New horizontal split.
^ww Switch between splits.
^wx Swap splits.
^wq Close the current split.
:tabnew Open a new tab.
:tabn+ Switch to the next tab.
:tabn- Switch to the previous tab.
:tabclose Close the current tab.

 And there you have it! The last four commands aren’t technically shortcuts, they’re commands. Since they’re not mapped to shortcuts by default, you’ll either need to map them yourself or just type them out.

Finally

 Awesome, now you know how to use Vim. Doesn’t it feel great? Of course, there’s a lot more to explore. Both Vim and NeoVim are incredibly customizable and have countless more shortcuts. These are the ones I consider most relevant for a solid start, and they should serve you well during your first 100 hours or so. After that, you might want to dive deeper as you become more advanced.

 I really hope you enjoyed this article. Next, I’ll be coming at you with a configuration setup for NeoVim. Why? Because it’s the one I use most often, and for good reason. NeoVim supports Lua scripts, which means you can have, among other things, real-time code completion and suggestions, with warnings and errors displayed just like they would in a full-blown IDE.

 That said, I hope the next one is shorter! NeoVim shares many shortcuts with Vim, so I won’t cover those again. Instead I’ll refer you back to this post if you need a refresher. However, the configuration process is a bit different, and that’s what I’ll be focusing on.

 See you next time! Happy coding.

Comments