Vim Cheat Sheet and Tips
Build and Compile full
from source
The default Vim installed on most Linux distros lacks a number of vital features, like xterm_clipboard
(allows copy-and-pasting to the system clipboard) and python
(on which certain plugins rely)
Compile from source
apt-get install libncurses-dev ruby-dev python3-dev libperl-dev liblua5.3-dev xsel xclip
cd ~
git clone https://github.com/vim/vim.git
cd vim
./configure --with-features=huge \
--enable-multibyte \
--enable-rubyinterp=yes \
--enable-python3interp=yes \
--with-python3-config-dir=$(python3-config --configdir) \
--enable-perlinterp=yes \
--enable-luainterp=yes \
--with-tlib=ncurses \
--prefix=/usr/
make
make install
./configure --enable-multibyte \
--enable-rubyinterp=yes \
--enable-python3interp=yes \
--with-python3-config-dir=$(python3-config --configdir) \
--enable-perlinterp=yes \
--enable-luainterp=yes \
--with-tlib=ncurses \
--prefix=/usr/
make
make install
Misc
set cursorcolumn
: This command enables highlighting of the current cursor column.set cursorline
: This command enables highlighting of the current cursor line.set hlsearch
: This command enables highlighting of search matches.set incsearch
: This command enables incremental searching, which highlights matches as you type.set nohlsearch
: This command disables highlighting of search matches.set wildmenu
: This command enables enhanced command-line completion using a menu.set wildoptions=pum
: This command sets the behavior of wildmenu completion to include pop-up menu completion.set noswapfile
: This command disables the creation of swap files, which are used for recovery in case of a crash.set nocompatible
: This command ensures Vim runs in its own mode rather than trying to be compatible with older vi editors.set clipboard=unnamed
: This command sets the default clipboard to the unnamed register, allowing you to yank and paste text.set magic
: This command enables enhanced pattern matching by treating certain characters as special.set ttyfast
: This command optimizes Vim's behavior for faster terminal response.set noruler
: This command disables displaying of the ruler, which shows the current cursor position and other information.set ignorecase
: This command sets case-insensitive searching by default.set showmode
: This command displays the current mode (e.g., insert, command-line) in the status line.set shiftwidth=4
: This command sets the number of spaces to use for each level of indentation when using the<<
and>>
commands.set nofixendofline
: This command disables automatically appending an end-of-line character when writing a file.nnoremap <silent> n n:call clearmatches()<CR>
: This command creates a non-recursive mapping for then
key in normal mode, which clears any search matches before moving to the next match.nnoremap <silent> N N:call clearmatches()<CR>
: This command creates a non-recursive mapping for theN
key in normal mode, which clears any search matches before moving to the previous match.set numberwidth=4
: This command sets the width of the line number column to 4 characters."set cursorline
: This command is commented out and does not have any effect since it is preceded by a double quotation mark. It might be used for temporarily disabling thecursorline
option."set showcmd
: This command is also commented out and does not have any effect since it is preceded by a double quotation mark. It might be used for temporarily disabling theshowcmd
option, which displays incomplete commands in the status line.
*. set autoindent
: This command enables automatic indentation for newly created lines, based on the indentation of the previous line. * set tabstop=4
: This command sets the width of a tab character to 4 spaces. * set expandtab
: This command replaces tab characters with spaces when indenting code. * set nowrap
: This command disables line wrapping, making each line extend beyond the screen width. * set autochdir
: This command automatically changes the current directory to the one containing the file being edited. * set colorcolumn=80
: This command highlights a specific column (in this case, column 80) with a different color to indicate the recommended maximum line length. * set background=dark
: This command sets the color scheme for Vim to be optimized for dark backgrounds. * set hidden
: This command allows switching between buffers without having to save changes, by hiding the buffer instead of closing it. * set title
: This command sets the window title to reflect the currently edited file. * set autowrite
: This command automatically saves the file being edited before running certain commands (e.g., switching buffers).
These additional settings and commands are commonly used to customize the behavior and appearance of Vim.
Installation
Install vim and requirements
echo "app-editors/vim X gpm perl sound tcl terminal vim-pager" \
> /etc/portage/package.use/vim
emerge --ask vim
go install mvdan.cc/sh/v3/cmd/shfmt@latest
emerge --ask xsel figlet
emerge --ask xsel
Commands | Description |
---|---|
:nmap | Display normal mode maps |
:imap | Display insert mode maps |
:vmap | Display visual and select mode maps |
:smap | Display select mode maps |
:xmap | Display visual mode maps |
:cmap | Display command-line mode maps |
:omap | Display operator pending mode maps |
Commands | Description |
---|---|
nunmap | Unmap a normal mode map |
vunmap | Unmap a visual and select mode map |
xunmap | Unmap a visual mode map |
sunmap | Unmap a select mode map |
iunmap | Unmap an insert and replace mode map |
cunmap | Unmap a command-line mode map |
ounmap | Unmap an operator pending mode map |
Commands | Description |
---|---|
mapclear | Clear all normal, visual, select and operating pending mode maps |
mapclear! | Clear all insert and command-line mode maps |
nmapclear | Clear all normal mode maps |
vmapclear | Clear all visual and select mode maps |
xmapclear | Clear all visual mode maps |
smapclear | Clear all select mode maps |
imapclear | Clear all insert mode maps |
vcmapclear | Clear all command-line mode maps |
omapclear | Clear all operating pending mode maps |
Mode-specific maps
Commands | Mode |
---|---|
nmap, nnoremap, nunmap | Normal mode |
imap, inoremap, iunmap | Insert and Replace mode |
vmap, vnoremap, vunmap | Visual and Select mode |
xmap, xnoremap, xunmap | Visual mode |
smap, snoremap, sunmap | Select mode |
cmap, cnoremap, cunmap | Command-line mode |
omap, onoremap, ounmap | Operator pending mode |
Resource(s)
Map Keyboard Shortcuts
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 ",".
let mapleader = ","
Macro
READ AND ADD
https://vim.fandom.com/wiki/Macros
Insert a blank line every 3 lines
:%s/\v(.*\n){3}/&\r
: .............. command
% .............. whole file
s .............. replace
/ .............. start pattern that we will replace
\v ............. very magic mode, see :h very-magic
(.*\n) ......... everything including the line break
{3} ............ quantifier
/ .............. start new pattern to replace
& .............. corresponds to the pattern sought in (.*\n)
\r ............. add line break
Configure
git clone git@github.com:/wuseman/vim.git ~/.vim
Plugins
vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Add to .vimrc
" PLUGINS ---------------------------------------------------------------- {{{
call plug#begin('~/.vim/plugged')
call plug#end()
" }}}
vim-instant-markdown
Install & Usage
Want to instantly preview finicky markdown files, but don't want to leave your favourite editor, or have to do it in some crappy browser text area? vim-instant-markdown is your friend!
When you open a markdown file in Vim, a browser window will open which shows the compiled markdown in real-time, and closes once you close the file in Vim.
Quick start (assuming you have all the necessary dependencies):
Install the Node.js mini-server by running either:
Install with vim-plug:
npm -g install instant-markdown-d
pip install --user smdv
Add the following to your .vimrc, depending on the plugin manager of your choice, since I use vim-plug here is the example for vim-plug
Plug 'instant-markdown/vim-instant-markdown', {'for': 'markdown', 'do': 'yarn install'}
Configuration
Minimal default configuration:
filetype plugin on
"Uncomment to override defaults:
"let g:instant_markdown_slow = 1
"let g:instant_markdown_autostart = 0
"let g:instant_markdown_open_to_the_world = 1
"let g:instant_markdown_allow_unsafe_content = 1
"let g:instant_markdown_allow_external_content = 0
"let g:instant_markdown_mathjax = 1
"let g:instant_markdown_mermaid = 1
"let g:instant_markdown_logfile = '/tmp/instant_markdown.log'
"let g:instant_markdown_autoscroll = 0
"let g:instant_markdown_port = 8888
"let g:instant_markdown_python = 1
Tips and Tricks
Open manual pages in vim
#vman() { vim <(man $1); }
vman() {
man $1 | sh -c "unset PAGER;col -b -x | vim -R -c 'set ft=man nomod nolist' -c 'map q :q<CR>' -c 'map <SPACE> <C-D>' -c 'map b <C-U>' -c 'nmap K :Man <C-R>=expand(\"<cword>\")<CR><CR>' -"
}
Checking for X11-clipboard support in terminal
vim --version | grep clipboard
Print current colortheme in use
echo g:colors_name
View current colors for for syntax
:ru syntax/hitest.vim
Create a mapping for bash
nmap <F6> :exec '!'.getline('.')
Move right align text of match above current line
:%s/\(.*[^ ]\+\) *\(# .*\)/\2\r\1/"
Insert a string/character on selected multiple lines
- Enter default mode.....: esc
- Select lines...........: ctrl-v
- When lines is selected.: shift+i
- Now press..............: esc
----------------------------------
- Done
Insert text end of multiple lines
- Enter default mode.............: esc
- Select lines string............: ctrl-v
- When lines is selected press...: : :
- Now in cmd, type.................: :'<,'>$A string
- Now press........................: esc
----------------------------------
- Done
Insert text end of multiple words vip$A,
- Enter default mode.....: ESC
- Select lines string....: ctrl-v
- When lines is selected.: $ + A
- Now press..............: ESC
----------------------------------
- Done
View NFO files correctly in Vim
mkdir -p ~/.vim/after/ftplugin/
echo "try | silent edit ++enc=cp437 | catch | endtry" >> ~/.~/.vim/after/ftplugin/nfo.vim
echo "autocmd BufRead,BufNewFile *.nfo,*.NFO set ft=nfo" >> ~/.vimrc
Jump to line 10
:10
10G
10gg
Set column width of vim
:set column=238
Set a line number width
:set numberwidth=6
Set wrap width
You can remove the if (&columns > 80) | if you always want 80 columns.
set columns=80
autocmd VimResized * if (&columns > 80) | set columns=80 | endif
set wrap
set linebreak
set showbreak=+++
Registrer
Delete a Recording
To delete a recording just record nothing over it.
For example, qxq erases whatever was recorded to register x.
or :call setreg('x', '')
or :let @x = ''
Replace oldsting/newstring
Here is an example to replace string OldString with NewString contained in multiple *.cpp files:
vim *.cpp
qx # start recording to register x
:%s/OldString/NewString/g
:wnext
q # stop recording
@x # playback to see if it works correctly
999@x # repeat 999 times to complete the job
One way to edit a recording (for example, to register x) is to paste it into a new buffer, then edit the buffer, then copy the results back into the register. For example:
:new # new buffer
"xp # paste register x into the buffer
[edit the keystrokes]
<Esc> # return to normal mode
0"xy$ # go to beginning of line; into register x, yank to end of line
:bd! # delete the new buffer without saving
@x # execute modified recording
Insert text on marked lines
0 ctrl v 5 j (shift + i) # esc
Insert text on line 8
8s/^/#/
Insert text on line 1 to 10
:1,10s/^/#/
Insert text on every line that begins with foo
:%s/foo.*$/&,
Make newspace on every second line
:%s/$/\r/g
:g/.\n\n\@!/norm o
:%s/\n\@<!\n\n\@!/\r\r/g
Add text to end of lines without marking
:%s/$/,/g
:'<,'>s/\s*$/,/
Add text to end of lines after marked lines
:'<,'>norm A,,
:'<,'>s/$/,/
Ex mode
- :%s/$/,
-
- enter command mode % - for every line s/ - substitute $ - the end of the line / - and change it to , - a comma
Insert text on all empty lines above and under the match
:v/^BBB/norm Itest_
Alternatively, edit the contents of register x in the command line:
:let @x="<Ctrl-R><Ctrl-R>x"
Execute a bash command and save stdout in vim
:.! ls
- or
:exec '!'.getline('.')
vimdiff
Diff two binary files from .hex
xxd b1 > b1.hex
xxd b2 > b2.hex
vimdiff b1.hex b2.hex
Diff two binary files from .bin
vimdiff <(xxd foo1.bin) <(xxd foo2.bin)
Diff two binarys via stdin
diff -u <(xxd tinga.tgz) <(xxd dec.out.tinga.tgz) | vim -
Diff two binarys via xxd
vimdiff <(xxd -c1 -p first.bin) <(xxd -c1 -p second.bin)
To insert the string "foo" above and below the string "boo" using Vim commands, you can use the following steps:
Insert "foo" above "boo":
:/boo/normal! Ofoo
Insert "foo" below "boo":
:/boo/normal! ofoo
Move entire line to beginning of line
Ctrl+L
Move line/group of lnie up/down
Ctrl+K Ctrl+J
Mode switching
- i Enter insert mode
- Enter command mode R Enter replace mode v Enter visual mode (highlighting) V Enter visual line mode (highlighting lines) esc Return to normal mode from insert or replace mode esc+esc Return to normal mode from command or visual mode
Copy/pasting
Command | Description |
---|---|
y | Yank (copy) |
c | Change; cut and enter insert mode |
C | Change the rest of the current line |
d | Delete; cut but remain in normal mode |
D | Delete the rest of the current line |
p | Paste after the cursor |
P | Paste before the cursor |
x | Delete characters after the cursor |
X | Delete characters before the cursor |
Modifier | Description |
---|---|
w | Change one word |
4w | Change four words |
4l | Change four letters |
cc | Change current line |
4x | Change four characters after the cursor |
4p | Paste five times after the cursor |
From system clipboard
:set paste Enter paste mode :set nopaste Exit paste mode Ctrl+Shift+V Paste into file, if in paste mode; Command+Shift+V for Mac
Editing
i Insert before current character a Insert after current character I Insert at the first non-whitespace character of the line o Insert a line below the current line, then enter insert mode O Insert a line above the current line, then enter insert mode r Overwrite one character and return to command mode U Undo Ctrl+R Redo
Navigation
h Move left H Top line on screen j Move down M Middle line on screen k Move up L Bottom line on screen l Move right 10j Move down 10 lines gg First line of the file e The end of the current word G Last line of the file b Beginning of current word :20 Line 20 of the file w Beginning of next word 0 Beginning of current line ^ First non-whitespace character of current line $ End of current line % Move to matching parenthesis, bracket or brace
Opening, closing and saving files
:w Save the current file :wq Save the current file and close it; exits vim if no open files remain :w newname Save a copy of the current file as ‘newname,’ but continue editing the original file :sav newname Save a copy of the current file as ‘newname’ and continue editing the file ‘newname’ :q! Close a file without saving :e somefile Opens file in the current buffer :x Write any changes to the file and close the file
Search and Replace
/pattern – search for pattern ?pattern – search backward for pattern vpattern – ‘very magic’ pattern: non-alphanumeric characters are interpreted as special regex symbols (no escaping needed) n – repeat search in same direction N – repeat search in opposite direction :%s/old/new/g – replace all old with new throughout file :%s/old/new/gc – replace all old with new throughout file with confirmations :noh – remove highlighting of search matches
Search in Multiple Files
:vimgrep /pattern/ {file} – search for pattern in multiple files e.g. :vimgrep /foo/ */ :cn – jump to the next match :cp – jump to the previous match :copen – open a window containing the list of matches
Replace
:s/foo/bar/ Replace the first occurrence of foo on the current line with bar :[range]s/foo/bar/[flags] Replace foo with bar in range according to flag
Ranges
% The entire file ’<,’> The current selection; the default range while in visual mode 25 Line 25 25,50 Lines 25-50 $ Last line; can be combined with other lines as in ‘50,$’ . Current line; can be combined with other lines as in ‘.,50’ ,+2 The current lines and the two lines therebelow -2, The current line and the two lines thereabove
Handy tricks
| ~ | Toggle case of character beneath the cursor | xp | Transpose current character with that to its right | J | Join the current line and the line beneath it | :Ni! | Receive inquiry about shrubberies | :help | View vim help file | :help foo | View vim help entry on ‘foo’
Visual Commands
– shift text right < – shift text left y – yank (copy) marked text d – delete marked text ~ – switch case
Registers
:reg – show registers content "xy – yank into register x "xp – paste contents of register x
Tip: Registers are being stored in ~/.viminfo, and will be loaded again on next restart of vim.
Tip: Register 0 contains always the value of the last yank command.
Macros
qa – record macro a q – stop recording macro @a – run macro a @@ – rerun last run macro
Marks
:marks – list of marks ma – set current position for mark A a – jump to position of mark A y
a – yank text to position of mark A
Use nerdtree in gVim only and not vim
" NERDTree settings (only in GUI mode) if has("gui_running") let NERDTreeRoot = '~' let NERDTreeIgnore = ['~\(', '\.swp\)'] let NERDTreeShowHidden = 1 let NERDTreeShowBookmarks = 1 let NERDTreeChDirMode = 2 else let loaded_nerd_tree = 1 endif
https://www.linuxtrainingacademy.com/vim-cheat-sheet/ https://www.cs.cmu.edu/~15131/f17/topics/vim/vim-cheatsheet.pdf
Record a recursive macro
https://vimdoc.sourceforge.net/htmldoc/change.html#registers
One of Vim's most useful features is its ability to record what you type for later playback. :help recording
This is most useful for repeated jobs which cannot easily be done with ".".
To start recording, press q in normal mode followed by a letter (a
to z
). That starts recording keystrokes to the specified register. Vim displays recording in the status line. Type any normal mode commands, or enter insert mode and type text. To stop recording, again press q while in normal mode.
To stop recording while in insert mode press <Ctrl-O>q
To playback your keystrokes, press @
followed by the letter previously chosen. Typing @@
repeats the last playback.
If the file type you are using is not available by default, you can add one
Vim has four methods of indentation, namely:
Method | Description |
---|---|
Autoindent | This method uses indent from the previous line for the file type you are editing. |
Smartindent | Smartindent works similarly to autoindent but recognizes the syntax for some languages such as C language. |
Cindent | Sindent is slightly different from autoindent and smartindent as it is more clever and is configurable to various indexing styles. |
Indexexpr | Is the most efficient and flexible. It uses expressions to calculate the indent of a file. When enabled, indexexpr overrides other indenting methods. |
Previews
Resource(s)
- https://www.vim.org/
- https://vim.fandom.com/wiki/Vim_Tips_Wiki/
- https://www.vim.org/6k/features.en.txt
- https://stackoverflow.com/questions/989093/soft-wrap-at-80-characters-in-vim-in-window-of-arbitrary-width
- http://hackerpublicradio.org/eps.php?id=1091
- https://lug.fh-swf.de/vim/vim-doc/bashsupport.html
- https://lug.fh-swf.de/vim/vim-bash/screenshots-en.html
- https://github.com/WolfgangMehner/vim-plugins
- https://wolfgangmehner.github.io/vim-plugins/awksupport.html