Customizing Vim
Settings like indentation and keyword-pairs can vary between different programming languages and file types. You might need to adapt style guides based on client requirements. Or perhaps, you wish to create or override commands to suit your preferences.
This chapter will discuss how you can customize Vim for different purposes. Some of the settings will be specific to GVim.
-
— set your settings — make new commands — write a Vim script — using filetypes — reference manual for Options — reference manual for Key mapping, abbreviations and user-defined commands — reference manual for Automatic commands
Editing vimrc
The Vim script language is used for the startup vimrc file, syntax files, and many other things.
The vimrc file can contain all the commands that you type after a colon. The simplest ones are for setting options.
- :e $MYVIMRC if you already have a vimrc file, you can use this predefined variable to open it to find out where the vimrc file should be located for your OS
- :source $MYVIMRC apply changes from within your current Vim session
To view a sample vimrc file, I have one on GitHub. More resources are mentioned in the Further Reading section at the end of this chapter.
defaults.vim
- source $VIMRUNTIME/defaults.vim add this to your vimrc file if you want to keep these defaults describes the settings provided by defaults.vim
Alternatively, you can copy only the parts you want to retain from the defaults.vim file to your vimrc file.
General Settings
set syntax and guidelines were introduced in the Setting options section.
- set history=200 increase default history from 50 to 200
- as mentioned in the Command-line mode chapter, there are separate history lists for : commands, search patterns, etc
- you can use :colorscheme followed by a space and then press Tab or Ctrl + d to get a list of the available color schemes
- first tab will complete as much as possible
- second tab will provide a list
- third and subsequent tabs will cycle through the completion options
:h ‘history’ will give you the documentation for the given option (note the use of single quotes).
You can use these settings from the Command-line mode as well, but will be active for the current Vim session only. Settings specified in the vimrc file will be loaded automatically at startup. You can also load a different file as the vimrc , which will be discussed in the CLI options chapter.
Further Reading
Text and Indent Settings
- filetype plugin indent on enables loading of plugin and indent files
- these files become active based on the type of the file to influence syntax highlighting, indentation, etc
- :echo $VIMRUNTIME gives your installation directory ( indent and plugin directories would be present in this path)
- see :h vimrc-filetype, :h :filetype-overview and :h filetype.txt for more details
- useful for files not affected by indent setting
- see also :h smartindent
- white space is used to break lines, so a line can still be greater than the limit if there’s no white space
- default is 0 which disables this setting
- use highlight ColorColumn setting to customize the color for this vertical bar
- see vi.stackexchange: Keeping lines to less than 80 characters for more details
Search Settings
- set hlsearch highlight all matching portions
- using :noh (short for :nohlsearch ) will clear the current highlighted portions
- pressing Enter key would move the cursor to the matched portion
- pressing Esc key would keep the cursor at the current location
- other matching terms will be highlighted based on hlsearch setting
Custom mapping
- nnoremap Normal mode non-nested, non-recursive mapping
- xnoremap Visual mode non-nested, non-recursive mapping
- inoremap Insert mode non-nested, non-recursive mapping
- inoreabbrev Insert mode non-nested, non-recursive abbreviation
- nmap , xmap , imap and iabbrev allows nested and recursive mappings
- nunmap , xunmap , iunmap and iunabbrev unmaps the given command (usually used from Command-line mode to temporarily disable a mapping, will be available again on startup if it was defined in vimrc )
- use mapclear instead of unmap to clear all the mappings for that particular mode
:nmap , :xmap , :imap and :iab will list all the current mappings for that particular mode. You can provide an argument to display the mapping for that particular command, for example :nmap Y . See :h key-mapping and :h map-overview for reference manuals.
Normal mode
- nnoremap <F2> :w<CR> press F2 function key to save changes
- <F2> represents the F2 function key and <CR> represents the Enter key
- I chose F2 since it is close to the Esc key ( F1 opens help page)
- likewise, you can map the other arrow keys to do nothing as well
- <silent> modifier executes the command without displaying on Command-line
- Note that this mapping also retains the default behavior of the Space key
- I prefer this to make switching tabs consistent with browser and terminal shortcuts
See :h map-which-keys to know which keys are not already Vim commands, which ones are not commonly used, etc.
See :h key-notation for a list of keys that can be represented using the <> notation.
Map leader
- nnoremap <Leader>f gg=G if mapleader hasn’t been set, using \f will auto indent the code for the whole file
- let mapleader = «;» change the leader key to ;
- nnoremap <Leader>f gg=G this will now require ;f since the leader key was changed
Insert mode
- inoremap <F2> <C-o>:w<CR> press F2 to save changes in Insert mode as well
- Ctrl + o to execute a command and return back to Insert mode automatically
- imap <F2> <C-o><F2> can also be used if you’ve already defined the Normal mode mapping
- I’d prefer Ctrl + e but that is useful to cancel autocompletion
- If you need Ctrl + v functionality, the Ctrl + q alias can be used to insert characters like Enter key (but this alias may not work in some terminals)
- See :h i_CTRL-x and :h ins-completion for all the features offered by Ctrl + x
Use noremap! if you want a mapping to work in both Insert and Command-line modes.
Visual mode
- xnoremap * y/<C-R>»<CR> press * to search the visually selected text in the forward direction
- recall that Ctrl + r helps you insert register contents in Command-line mode
Note that xnoremap is used here since vnoremap affects both Visual and Select modes.
Abbreviations
Abbreviations are usually used to correct typos and insert frequently used text. From :h abbreviations documentation:
An abbreviation is only recognized when you type a non-keyword character. This can also be the <Esc> that ends insert mode or the <CR> that ends a command. The non-keyword character which ends the abbreviation is inserted after the expanded abbreviation. An exception to this is the character <C-]> , which is used to expand an abbreviation without inserting any extra characters.
inoreabbrev p #!/usr/bin/env perl<CR>use strict;<CR>use warnings;<CR> expand p to the text as shown in the code snippet below
- you can trigger the abbreviation completion using non-keyword character such as Esc , Space and Enter keys, punctuation characters and so on
- use Ctrl + ] to expand the abbreviation without adding anything extra
inoreabbrev py #!/usr/bin/env python3 expand py to #!/usr/bin/env python3
- this might cause issues if you need py literally (for example, script.py )
- you can use something like [p or @p instead
inoreabbrev teh the automatically correct teh typo to the
inoreabbrev @a always @()<CR>begin<CR>end<Esc>2k$ expand @a to the text as shown in the code snippet below
- this one works best when you type @a followed by Esc key to place the cursor at the end of the first line
:abbreviate or :ab list all abbreviations
See :h 24.7 for more details about using abbreviations.
Matching Pairs
- set matchpairs+=<:> add <> to the list of pairs matched by % command in Normal mode
To match keywords like if — else pairs with % , you can install matchit.vim plugin. This supports filetypes such as HTML, Vim, LaTeX, XML, etc. See :h matchit-install for more details.
GUI options
- set guioptions-=m remove menu bar
- set guioptions-=T remove tool bar
Third-party customizations
See :h ‘runtimepath’ to know the path within which you can add the plugins and packages discussed in this section.
/.vim is commonly used on Unix/Linux systems.
Make sure to backup your directory (
/.vim for example) and the vimrc file, so that you can easily apply your customizations on a new machine.
plugin
Some plugins are loaded by default. Some come with Vim installation but you have to explicitly enable them. You can also write your own or add plugins written by others. From :h add-plugin:
-
global plugin: Used for all kinds of files
-
filetype plugin: Only used for a specific type of file
If you want to add a global plugin created by you or someone else, place it in the plugin directory. If you don’t have that directory yet, you can create it using the below command (assuming Unix/Linux):
If you have multiple related plugin files, you can put them under a subdirectory:
If you want to add plugins that should work based on specific filetype, add them to the ftplugin directory:
package
Packages make it easy to manage projects that require multiple plugins, use a version controlled repository directly and so on. See :h packages for more details. From :h add-package:
A package is a set of files that you can add to Vim. There are two kinds of packages: optional and automatically loaded on startup.
The Vim distribution comes with a few packages that you can optionally use. For example, the matchit plugin.
- packadd! matchit enable matchit package
- this plugin comes with Vim, see :h matchit for further details
- ! is used to prevent loading this plugin when Vim is started with —noplugin CLI option
vim-surround is used here as an example for a third-party package. Installation instructions (provided in this repository) are shown below, assuming you want to enable this package at startup:
- ysiw] will surround a word with [] , for example hello to [hello]
- cs»‘ will change text surrounded by double quotes to single quotes, for example «hi bye» to ‘hi bye’
- :packadd vim-surround enable this package from Command-line mode
- packadd! vim-surround enable this package in vimrc (usually under some condition)
color scheme
There are different ways to add a new color scheme. The simplest is to copy the theme.vim file to the
/.vim/colors directory. Or, follow the installation steps provided by the theme creators. Here are couple of solarized themes you can check out:
After installation, you can use the :colorscheme command to set the new theme. If the theme offers multiple variations, you might need additional settings like set background=dark or set background=light . See the installation instructions provided in the above repositories for more details.
See Where to put what section under :h packages for more details about installation directories.
autocmd
An autocommand is a command that is executed automatically in response to some event, such as a file being read or written or a buffer change.
Autocommands are very powerful. Use them with care and they will help you avoid typing many commands. Use them carelessly and they will cause a lot of trouble.
Open vimrc file
The vimrc file contains optional runtime configuration settings to initialize Vim when it starts. On Unix based systems, the file is named .vimrc , while on Windows systems it is named _vimrc . :help vimrc
You can customize Vim by putting suitable commands in your vimrc. Here is a very simple example:
Lines that begin with » are comments and are not read by vim.
Search for file vimrc_example.vim in your Vim files for another example. :help vimrc-intro :help vimrc_example.vim
To customize Vim for editing a specific file, or a specific type of file, you can use modelines, or auto commands, or filetype plugins. :help auto-setting :help filetype
Location of vimrc [ ]
In Vim, your home directory is specified with $HOME . On Unix systems, this is your
directory. On Windows systems, the best way to find the value of $HOME is from within Vim, as follows. These commands are useful to see what directories your Vim is using:
Note the ‘system vimrc file’ and ‘user vimrc file’ paths displayed by the :version command. The system vimrc file can be created by an administrator to customize Vim for all users. In addition, each user can have his or her own user vimrc.
The output from :version includes the paths of the system and user vimrc and gvimrc files. For example:
If the gvimrc files exist, they are used to configure Vim when the GUI version (gvim) runs (after settings from vimrc are applied).
Settings for gvim can also be placed in the vimrc file using a has(‘gui_running’) check:
Although this can be useful to avoid the clutter of both a vimrc and gvimrc file, using the gvimrc file has distinct benefits over the «gui_running» check. The most notable being that a gvimrc file is sourced when using the :gui command to change a vim session into a gvim session. Anything that was in the vimrc inside a «gui_running» check will not be applied since the vimrc is only sourced when Vim initially starts.
Per-directory vimrc [ ]
Vim can be configured so that, when starting, it reads commands from a vimrc file in the current directory, after reading the primary vimrc. This is configured by adding set exrc to the primary vimrc file. Setting ‘exrc’ can be a security problem because it means Vim will execute commands from any vimrc file in the directory where Vim is started. :help ’exrc’ For that reason, set the ‘secure’ option if you use this option, and you may also want to limit setting this option to when Vim is started from known «safe» directory trees:
Opening vimrc [ ]
If Vim finds your vimrc file during startup, Vim will set the MYVIMRC environment variable to the full path of the vimrc file. Similarly, if your gvimrc file is found, the MYGVIMRC variable is set. Therefore, you can easily edit these files from within Vim:
Using file name completion, you could type :e $M then press Tab until you see the desired variable. If you only want to see the path, type :echo $M then press Tab to see the variable, and press Enter.
In gvim, the Edit menu includes «Startup Settings» which will use $MYVIMRC to edit your vimrc file. If $MYVIMRC does not exist, «Startup Settings» will create a new file using the «user vimrc file» path shown by the :version command.
Sourcing vimrc [ ]
After you have saved changes to your vimrc file, you can see the results by exiting from Vim, then starting Vim again.
If you are making frequent changes, you might want to «source» (execute) the changed vimrc file without exiting:
Warning You may need to plan your vimrc so re-sourcing does not cause problems. If you define commands, functions, or autocmds, you must make them remove or override the previous version when sourced, or you will get errors (for commands and functions) or duplicates (for autocmds). Here are some examples that will work correctly when re-sourced:
Recovering from errors [ ]
Some errors in your vimrc may prevent Vim from starting successfully. A reliable way to handle that would be to rename your vimrc file, then edit the renamed file, then give it the correct name. Alternatively, you could start Vim with a command like this (or use «gvim» if that is how you run Vim):
The -N starts in «not compatible» mode (that is, with extra Vim features). The NONE argument (must be uppercase) skips initializations and does not read any vimrc file ( -u ), and does not read any gvimrc file ( -U ).
You could now use the :version command to show the vimrc path, then enter a command to edit that file.
Comments [ ]
- What else is needed to explain what vimrc is, and how to use it, for a beginner?
- Do something with the following text from the original tip (if keep it, need to fix text because it assumes you have used some standard setup for installation, and assumes $VIM and $HOME are some default, and of course is for Windows):
On Windows, when you start Vim normally, it *either* runs the file «C:\Documents and Settings\(user name)\_vimrc» (where «(user name)» is replaced by the actual user name); *or*, if that file doesn’t exist (it usually doesn’t, for most users), it runs the file «C:\Program Files\vim\_vimrc». Note that if you have more than one disk your home may be different; do an «:echo $HOME» to know where is your home. You should also see the _viminfo file in that directory.
- Include information for Windows:
- When $HOME is not defined, it is created by combining $HOMEDRIVE and $HOMEPATH (if defined).
- The recommended method to define $HOMEDRIVE and $HOMEPATH is to set the «Home folder . Local path» on the Profile tab of the User properties in Local Users and Groups (run lusrmgr.msc).
- I’d say that this (the item above) is the recommended method to set your home folder in Windows. The recommendes method to specify where your _vimrc is located (if it differs from your home folder) is to set the $HOME environment variable. (Spiiph 00:16, 29 July 2009 (UTC))
- Link to the #vim-approved .vimrc ? ;) (Spiiph 00:18, 29 July 2009 (UTC))
Proposal Omit suggestions like the following that attempt to auto-source vimrc. I suspect that anyone needing to read a tip to do this could get themselves in quite a bit of trouble. IMHO it’s a lot more sensible to map a key to source a script so you can control when it is sourced. I haven’t bothered to put such a mapping in the tip so far because the :so % info seems more helpful, and entirely adequate. —JohnBeckett 11:56, 23 August 2008 (UTC)
To source changes immediately, add to vimrc:
Why not use a BufWritePost instead of BufLeave, so it will source whenever you save?
Getting started tip . I hit this page because I could not remember the «mkvim» command. I found it elsewhere and thought I’d throw it in here. If you open vim, change some settings and get things how you like you can use this command
to automatically make a vimrc file based on your current settings. The [file] part is optional; vim will use
/.vimrc by default. If you already have a .vimrc and you attempt this you we will be warned that .vimrc already exists. You can use
to overwrite the existing file if you like. However once you do this your original .vimrc file is gone so you may want to back up any existing .vimrc before you try this.
Using :mkvimrc to create .vimrc isn’t a terribly good idea, since it saves mappings and abbreviations setup by plugins. It can be useful to copy currently set options to .vimrc however. (Spiiph 14:51, 27 July 2009 (UTC))
Vimrc Configuration Guide — How to Customize Your Vim Code Editor with Mappings, Vimscript, Status Line, and More

Configuring your .vimrc file lets you use the full power of Vim. With a customized .vimrc file you can increase your Vim powers tenfold.
In this article I will show you a few ways you can customize your .vimrc file.
- Basic Settings
- Plugins
- Folding
- Vimscript
- Status line
First create the following directory structure in your home directory.
Create a .vimrc file in your home directory.
How to Update Basic Settings in Vim
First let’s add some basic settings that will improve your editing experience. I use double quote characters to comment out lines.
Add the following lines to your .vimrc file:
Syntax highlighting is very useful. The next line we add will enable syntax highlighting and make your code easier to read.
This is what it looks like before:

And after:

You can also choose to display line numbers to make navigating the file easier.

You can pinpoint exactly where the cursor is located by highlighting the line it is on horizontally and vertically.
Add these lines to enable this feature.

Here are some more common setting that enhance the editing experience.
Each line contains a comment above it explaining what it does.Add the following lines to the .vimrc file.
Bash completion is a great feature which saves keystrokes by auto completing what you type. Vim has a similar feature called wildmenu.
Add the following lines to enable the wildmenu feature. You will see a list of files matching the file you are searching for. You can also enable auto completion to Vim.
Type :help <command> for more information on specific commands.
How to Fold Long Files in Vim
The .vimrc file can get long so organizing it into sections is a smart idea.
Vim will allow you to fold long files to hide sections of text.Add the following lines to the bottom of your .vimrc to organize the file into sections.
Save the .vimrc file with :w and source the .vimrc file like this :source
/.vimrc to make the changes take effect. Now, once you move your cursor on a fold you can press:
zo to open a single fold under the cursor.
zc to close the fold under the cursor.
zR to open all folds.
zM to close all folds.
Type :help folding for more information.
How to Add Plugins to Vim
You can add plugins to Vim to add extra functionality. Most people use a plugin manager to make plugin installation easy.
There are a variety of plugin managers we can use. I will show you how to install and use the vim-plug plugin manager.
To install the vim-plug plugin, run this command:
On Linux or Mac OS.
On Windows with Powershell.
Add the call plug#begin(‘
/.vim/plugged’) and call plug#end() lines in the plugins section. The plugins we install will be added between the two function calls.
Now installing plugins is as easy as adding the Plug ‘username/plugin-name’ string you find on GitHub in between the function calls.
Add these two lines in between the two call plug#. lines:
Save the .vimrc file with the command :w and source the .vimrc file with this command :source
/.vimrc to make the changes take effect.
Now type :PlugInstall to download and install the two plugins.

How to Map Keyboard Shortcuts in Vim
In the mapping section we will add shortcuts to making typing longer commands easier. This will save you key strokes and lots of time, especially for long commands.
Key mapping syntax is like this:
map_mode <what_you_type> <what_is_executed>
Popular Mapping Modes in Vim
Here are a few popular mapping modes and probably the most useful and important.
- nnoremap – Allows you to map keys in normal mode.
- inoremap – Allows you to map keys in insert mode.
- vnoremap – Allows you to map keys in visual mode.
A common mapping example is to map ‘jj’ to the escape key. You will be pressing the escape key a lot. The escape key is in the far corner of the keyboard.
The letter ‘j’ is in the middle of the keyboard so it is easier to press ‘jj’ instead of reaching for the escape key.This is how you would map the escape key to jj .
inoremap jj <esc>
How to Use Mapleader in Vim
Mapleader will allow you set a key unused by Vim as the <leader> key.
The leader key, in conjunction with another key, will allow you to create new shortcuts.The backslash key is the default leader key but some people change it to a comma «,» .
With the leader key mapped to backslash, I can use it like this:
Turn off search highlighting by pressing \\ .
nnoremap <leader>\ :nohlsearch<CR>Here are some common mappings that people use. See the comments above each line for the explanation.
Add this code in the mappings section:
Type help: map-modes for more information.
How to Add Some Vimscripting
Vimscript is a scripting language that lets you create scripts using variables, if else statements, and functions. Auto commands are waiting for events to occur in order to trigger a command.
Read Learn Vimscript the Hard Way for more information on Vimscript.
Type :help autocmd for more information on auto commands.
How to Add Color Schemes to Vim
You can easily add color schemes to Vim to change the default colors. Do a search for Vim color schemes and you will find many, many choices.
Installing a color scheme is a simple as adding a <colorscheme>.vim file to the
I will add the popular color scheme molokai:
To set the color scheme, type this command:
Example color schemes:

color schemes: molokai, base16-tomorrow, blue, one
How to Configure the Status Bar in Vim
You can configure your Vim status bar with useful information. For example, configure the file type, total number of lines in the file, path to the file, column number, row number, percentage through file, and much more.
Add this code in the status line section:
%F – Display the full path of the current file.
%M – Modified flag shows if file is unsaved.
%Y – Type of file in the buffer.
%R – Displays the read-only flag.
%b – Shows the ASCII/Unicode character under cursor.
0x%B – Shows the hexadecimal character under cursor.
%l – Display the row number.
%c – Display the column number.
%p%% – Show the cursor percentage from the top of the file.

Type help: statusline for more information.
This is the complete .vimrc file.
Conclusion
In this article, I have only scratched the surface of how you can customize Vim.
There are thousands of ways to configure and customize a .vimrc to your liking.
You can even write your own plugins and color schemes and share them with the world.I hope that you have learned a new trick or two by reading this article. So if you use Vim, don’t leave home without a .vimrc file!
Name already in use
Learn-Vim / ch22_vimrc.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
3 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
In the previous chapters, you learned how to use Vim. In this chapter, you will learn how to organize and configure vimrc.
How Vim Finds Vimrc
The conventional wisdom for vimrc is to add a .vimrc dotfile in the home directory
/.vimrc (it might be different depending on your OS).
Behind the scene, Vim looks at multiple places for a vimrc file. Here are the places that Vim checks:
- $VIMINIT
- $HOME/.vimrc
- $HOME/.vim/vimrc
- $EXINIT
- $HOME/.exrc
- $VIMRUNTIME/defaults.vim
When you start Vim, it will check the above six locations in that order for a vimrc file. The first found vimrc file will be used and the rest is ignored.
First Vim will look for a $VIMINIT . If there is nothing there, Vim will check for $HOME/.vimrc . If there is nothing there, Vim will check for $HOME/.vim/vimrc . If Vim finds it, it will stop looking and use $HOME/.vim/vimrc .
The first location, $VIMINIT , is an environment variable. By default it is undefined. If you want to use
/dotfiles/testvimrc as your $VIMINIT value, you can create an environment variable containing the path of that vimrc. After you run export VIMINIT=’let $MYVIMRC=»$HOME/dotfiles/testvimrc» | source $MYVIMRC’ , Vim will now use
/dotfiles/testvimrc as your vimrc file.
The second location, $HOME/.vimrc , is the conventional path for many Vim users. $HOME in many cases is your home directory (
/.vimrc file, Vim will use this as your vimrc file.
The third, $HOME/.vim/vimrc , is located inside the
/.vim directory. You might have the
/.vim directory already for your plugins, custom scripts, or View files. Note that there is no dot in vimrc file name ( $HOME/.vim/.vimrc won’t work, but $HOME/.vim/vimrc will).
The fourth, $EXINIT works similar to $VIMINIT .
The fifth, $HOME/.exrc works similar to $HOME/.vimrc .
The sixth, $VIMRUNTIME/defaults.vim is the default vimrc that comes with your Vim build. In my case, I have Vim 8.2 installed using Homebrew, so my path is ( /usr/local/share/vim/vim82 ). If Vim does not find any of the previous six vimrc files, it will use this file.
For the remaining of this chapter, I am assuming that the vimrc uses the
What to Put in My Vimrc?
A question I asked when I started was, «What should I put in my vimrc?»
The answer is, «anything you want». The temptation to copy-paste other people’s vimrc is real, but you should resist it. If you insist to use someone else’s vimrc, make sure that you know what it does, why and how s/he uses it, and most importantly, if it is relevant to you. Just because someone uses it doesn’t mean you’ll use it too.
Basic Vimrc Content
In the nutshell, a vimrc is a collection of:
- Plugins
- Settings
- Custom Functions
- Custom Commands
- Mappings
There are other things not mentioned above, but in general, this covers most use cases.
In the previous chapters, I have mentioned different plugins, like fzf.vim, vim-mundo, and vim-fugitive.
Ten years ago, managing plugins was a nightmare. However, with the rise of modern plugin managers, installing plugins can now be done in seconds. I am currently using vim-plug as my plugin manager, so I will use it in this section. The concept should be similar with other popular plugin managers. I would strongly recommend you to check out different ones, such as:
There are more plugin managers than the ones listed above, feel free to look around. To install vim-plug, if you have a Unix machine, run:
To add new plugins, drop your plugin names ( Plug ‘github-username/repository-name’ ) between the call plug#begin() and the call plug#end() lines. So if you want to install emmet-vim and nerdtree , put the following snippet down in your vimrc:
Save the changes, source it ( :source % ), and run :PlugInstall to install them.
In the future if you need to remove unused plugins, you just need to remove the plugin names from the call block, save and source, and run the :PlugClean command to remove it from your machine.
Vim 8 has its own built-in package managers. You can check out :h packages for more information. In the next chapter, I will show you how to use it.
It is common to see a lot of set options in any vimrc. If you run the set command from the command-line mode, it is not permanent. You will lose it when you close Vim. For example, instead of running :set relativenumber number from the Command-line mode each time you run Vim, you could just put these inside vimrc:
Some settings require you to pass it a value, like set tabstop=2 . Check out the help page for each setting to learn what kind of values it accepts.
You can also use a let instead of set (make sure to prepend it with & ). With let , you can use an expression as a value. For example, to set the ‘dictionary’ option to a path only if the path exists:
You will learn about Vimscript assignments and conditionals in later chapters.
For a list of all possible options in Vim, check out :h E355 .
Vimrc is a good place for custom functions. You will learn how to write your own Vimscript functions in a later chapter.
You can create a custom Command-line command with command .
To create a basic command GimmeDate to display today’s date:
When you run :GimmeDate , Vim will display a date like «2021-01-1».
To create a basic command with an input, you can use <args> . If you want to pass to GimmeDate a specific time/date format:
If you want to restrict the number of arguments, you can pass it -nargs flag. Use -nargs=0 to pass no argument, -nargs=1 to pass one argument, -nargs=+ to pass at least one argument, -nargs=* to pass any number of arguments, and -nargs=? to pass 0 or one arguments. If you want to pass nth argument, use -nargs=n (where n is any integer).
<args> has two variants: <f-args> and <q-args> . The former is used to pass arguments to Vimscript functions. The latter is used to automatically convert user input to strings.
The functions above will make a lot more sense once you get to the Vimscript functions chapter.
To learn more about command and args, check out :h command and :args .
If you find yourself repeatedly performing the same complex task, it is a good indicator that you should create a mapping for that task.
For example, I have these two mappings in my vimrc:
On the first one, I map Ctrl-F to fzf.vim plugin’s :Gfiles command (quickly search for Git files). On the second one, I map <Leader>tn to call a custom function ToggleNumber (toggles norelativenumber and relativenumber options). The Ctrl-F mapping overwrites Vim’s native page scroll. Your mapping will overwrite Vim controls if they collide. Because I almost never used that feature, I decided that it is safe to overwrite it.
By the way, what is this «leader» key in <Leader>tn ?
Vim has a leader key to help with mappings. For example, I mapped <Leader>tn to run the ToggleNumber() function. Without the leader key, I would be using tn , but Vim already has t (the «till» search navigation). With the leader key, I can now press the key assigned as a leader, then tn without interfering with existing commands. The leader key is a key that you can setup to start your mapping combo. By default Vim uses the backslash as the leader key (so <Leader>tn becomes «backslash-t-n»).
I personally like to use <Space> as the leader key instead of the backslash default. To change your leader key, add this in your vimrc:
The nnoremap command used above can be broken down into three parts:
- n represents the normal mode.
- nore means non-recursive.
- map is the map command.
At minimum, you could have used nmap instead of nnoremap ( nmap <silent> <C-f> :Gfiles<CR> ). However, it is a good practice to use the non-recursive variant to avoid potential infinite loop.
Here’s what could happen if you don’t map non-recursively. Suppose you want to add a mapping to B to add a semi-colon at the end of the line, then go back one WORD (recall that B n Vim is a normal-mode navigation key to go backward one WORD).
When you press B . oh no! Vim adds ; uncontrollably (interrupt it with Ctrl-C ). Why did that happen? Because in the mapping A;<esc>B , the B does not refer to Vim’s native B function (go back one WORD), but it refers to the mapped function. What you have is actually this:
To solve this problem, you need to add a non-recursive map:
Now try calling B again. This time it successfully adds a ; at the end of the line and go back one WORD. The B in this mapping represents Vim’s original B functionality.
Vim has different maps for different modes. If you want to create a map for insert mode to exit insert mode when you press jk :
The other map modes are: map (Normal, Visual, Select, and Operator-pending), vmap (Visual and Select), smap (Select), xmap (Visual), omap (Operator-pending), map! (Insert and Command-line), lmap (Insert, Command-line, Lang-arg), cmap (Command-line), and tmap (terminal-job). I won’t cover them in detail. To learn more, check out :h map.txt .
Create a map that’s most intuitive, consistent, and easy-to-remember.
Over time, your vimrc will grow large and become convoluted. There are two ways to keep your vimrc to look clean:
- Split your vimrc into several files.
- Fold your vimrc file.
Splitting Your Vimrc
You can split your vimrc to multiple files using Vim’s source command. This command reads command-line commands from the given file argument.
Let’s create a file inside the
/.vim directory and name it /settings (
/.vim/settings ). The name itself is arbitrary and you can name it whatever you like.
You are going to split it into four components:
You can edit these files by putting your cursor under the path and press gf .
Your vimrc should works as usual, but now it is only four lines long!
With this setup, you easily know where to go. If you need to add more mappings, add them to the /mappings.vim file. In the future, you can always add more directories as your vimrc grows. For example, if you need to create a setting for your colorschemes, you can add a
Keeping One Vimrc File
If you prefer to keep one vimrc file to keep it portable, you can use the marker folds to keep it organized. Add this at the top of your vimrc:
Vim can detect what kind of filetype the current buffer has ( :set filetype? ). If it is a vim filetype, you can use a marker fold method. Recall that a marker fold uses <<< and >>> to indicate the starting and ending folds.
Add <<< and >>> folds to the rest of your vimrc (don’t forget to comment them with » ):
Your vimrc should look like this:
Running Vim With or Without Vimrc and Plugins
If you need to run Vim without both vimrc and plugins, run:
If you need to launch Vim without vimrc but with plugins, run:
If you need to run Vim with vimrc but without plugins, run:
If you need to run Vim with a different vimrc, say
If you need to run Vim with only defaults.vim and without plugins, which is helpful to fix broken vimrc, run:
Configure Vimrc the Smart Way
Vimrc is an important component of Vim customization. A good way to start building your vimrc is by reading other people’s vimrcs and gradually build it over time. The best vimrc is not the one that developer X uses, but the one that is tailored exactly to fit your thinking framework and editing style.