Here are a handful of useful tips for using Vim that I've picked up over the years.
Custom functions
Defining a custom function can be done like:
function! InsertDate()
execute "normal \"=strftime('%FT%T%z')\<CR>p"
endfunction
" names must start with an uppercase letter
then called using :call InsertDate() or simplified with a user-defined command:
command! Date call InsertDate()
and simply called with :Date
Maps
I try not to rely on too many maps, but I do use these everyday:
" open netrw in directory of current file
nnoremap <ESC> :Ex<CR>
" move visually selected blocks up/down
vnoremap K :m '<-2<CR>gv=gv
vnoremap J :m '>+1<CR>gv=gv
" escape terminal mode
tnoremap <Esc> <C-\><C-n>
and some for working with multiple windows:
" resize windows
nnoremap <C-Up> 2<C-w>+<CR>
nnoremap <C-Down> 2<C-w>-<CR>
nnoremap <C-Left> 2<C-w><<CR>
nnoremap <C-Right> 2<C-w>><CR>
" switch windows
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
Settings
A few of the more important settings in my .vimrc file:
- set lazyredraw - makes macros complete faster by not redrawing the screen each time.
- set smartcase/ignorecase - both of these on allows for searches without capital letters to be case insensitive, while searches with a capital character are case sensitive.
- set undofile - persistent undo even after closing Vim.
Shell commands
Vim can execute shell commands using :!{command}. The command is run in a new window before prompting you to hit ENTER to return where you were.
This can be modified in a few useful ways:
:r !{command} execute {command} and read output into Vim
:.!{command} execute {command} and replace current line with output
:w !{command} execute {command} with text as input to {command}
:3,6!{command} filter lines 3-6 through {command}
Note: pressing !! in Normal mode results in :.!
Other
Lines in a file can be sorted using :sort - this also works on visually selected lines.
Use :sort u to remove any duplicates when sorting.
Numbers in Vim can be incremented and decremented with Ctrl-a and Ctrl-x respectively. This jumps to the next number on the line after the cursor. A count can also be specified like 5<C-a> to increment the value by 5. Even better, this works on numbers in binary (0b1010), hexadecimal (0x1abc), and octal (07) as well.
The ASCII value of the character under the cursor can be displayed by pressing ga in Normal mode or :as / :ascii on the command line.
vimtutor
A program called vimtutor comes installed with Vim and is designed to help learn concepts through hands on examples.
Vim 9.2 was just released and includes a new built-in tutor plugin started via :Tutor. It looks like a nice modern version of the original, and after trying it I would highly recommend checking it out.