Daniil Kolesnichenko

Vim tips

Written by Daniil Kolesnichenko on 12.03.2017

Here I'll collect some useful tips for Vim/Neovim users. My full config is here.

Local project's vimrc

To use local.vim and .local.vim as local vimrc in your projects add the following lines in your (global) vimrc:

autocmd BufEnter * silent! source local.vim
autocmd BufEnter * silent! source .local.vim

Note: silent! keyword is used to ignore errors if there's no local.vim or .local.vim files in your project's directory.

I recommend to add the following line in your global gitignore (~/.config/git/ignore by default):

.local.vim

Now, local.vim will be tracked by git and .local.vim won't.

Automatically switch between relative and absolute numbers

To enable relative numbers in normal mode and absolute numbers in insert mode, use the following configuration:

set relativenumber
autocmd InsertEnter * :set number norelativenumber
autocmd InsertLeave * :set nonumber relativenumber

Autoformat your code on file save

The following line will enable autofomatting on file save:

autocmd! BufWritePre * call AutoFormat()

where AutoFormat is your auto-formatting function. E.g. here is my AutoFormat function:

function! AutoFormat() abort
    if &ft =~# '^\%(c\|cpp\|objc\|java\|javascript\|typescript\|proto\)$'
        ClangFormat
    elseif &ft =~# '^\%(rust\)$'
        RustFmt
    endif
endfunction