This repo contains everyday vim usage method and .vimrc for future reference.
syntax on
se noerrorbells
se tabstop=4 softtabstop=4
se shiftwidth=4
se expandtab " turns tab into spaces
se smartindent
se nowrap
se noswapfile
se nobackup
se undodir=~/.vim/undodir
se undofile
se incsearch
se colorcolumn=80
highlight ColorColumn ctermbg=0 guibg=lightgrey
se nu " set line number
se history=1000 " set history line to 100
se hls " hightlight search
se rnu " set relative number for better editing experience
let mapleader = "\<Space>" " Set /space as the leader key
" Search and Replace
nnoremap <Leader>r :%s///gc<Left><Left><Left>
" Save all file
nnoremap <Leader>w :wa<CR>
"Save and quit
nnoremap <Leader>x :x<CR>
"Before edit
nnoremap <Leader>e :e!<CR>
" Toogle text wrap
function! ToogleTextWrap()
if (&wrap == 1)
se nowrap | echo "Toggle text wrap OFF"
else
se wrap | echo "Toggle text warp ON"
endif
endfunction
nnoremap <Leader><Leader>z :call ToogleTextWrap()<CR>
" Toggle line numbers
function! ToggleNumber()
if (&relativenumber == 1)
se nonu | se nornu | echo "Toggle line numbers OFF"
else
se nu | se rnu | echo "Toggle line numbers ON"
endif
endfunction
nnoremap <Leader>n :call ToggleNumber()<CR>
" Toggle highlight search
function! ToggleHighlight()
if (&hls == 1)
se nohls | echo "Toggle highlight search OFF"
else
se hls | echo "Toggle hightlight search ON"
endif
endfunction
nnoremap <Leader>h :call ToggleHighlight()<CR>
" Between vim panes
nnoremap <leader>h :wincmd h<CR>
nnoremap <leader>j :wincmd j<CR>
nnoremap <leader>k :wincmd k<CR>
nnoremap <leader>l :wincmd l<CR>
" Toggle undo-tree
nnoremap <leader>u :UndotreeShow<CR>
" Visual Drag Keys
vmap <expr> <S-LEFT> DVB_Drag('left')
vmap <expr> <S-RIGHT> DVB_Drag('right')
vmap <expr> <S-DOWN> DVB_Drag('down')
vmap <expr> <S-UP> DVB_Drag('up')
vmap <expr> D DVB_Duplicate()
" Remove any introduced trailing whitespace after moving
let g:DVB_TrimWS = 1
call plug#begin('~/.vim/plugged')
" Git Function
Plug 'tpope/vim-fugitive'
" Fuzzy Search
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
" CPP Highlighting
Plug 'octol/vim-cpp-enhanced-highlight'
" Undo List
Plug 'mbbill/undotree'
" Manpages
Plug 'vim-utils/vim-man'
" Visual Drag
Plug 'jondkinney/dragvisuals.vim'
call plug#end()
Creating Undo folder:
mkdir -p ~/.vim/undodir
To install plugin:
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
curl -o .vimrc https://raw.githubusercontent.com/BruceChanJianLe/vim/master/.vimrc
vi +PlugInstall +qa
{
"python.defaultInterpreterPath": "/usr/bin/python3",
"window.zoomLevel": 0,
"editor.lineNumbers": "relative",
"cmake.configureOnOpen": true,
"cmake.buildDirectory": "${workspaceFolder}/build-vscode",
"testMate.cpp.log.userId": "82cdd95340a0c3075fb44e7c043c393e1bdb7a70",
"testMate.cpp.log.logSentry": "disable_3",
"vim.leader": "<space>",
"vim.vimrc.path": "/home/chanjl/.vimrc",
"scm.defaultViewMode": "tree",
"vim.normalModeKeyBindingsNonRecursive": [
{
"before": ["<leader>", "w"],
"commands": ["workbench.action.files.saveFiles"]
},
{
"before": ["<leader>", "x"],
"commands": ["workbench.action.files.saveFiles","workbench.action.closeActiveEditor"]
},
{
"before": ["<leader>", "r"],
"after": ["%s///gc<Left><Left><Left>"]
},
{
"before": ["<leader>", "<leader>", "r"],
"after": ["%s///g<Left><Left>"]
},
{
"before": ["<leader>", "e"],
"after": [":e!"]
},
{
"before": ["<leader>", "q"],
"commands": ["workbench.action.closeActiveEditor"]
},
{
"before": ["<leader>", "z"],
"commands": ["workbench.action.toggleEditorWidths"]
},
{
"before": ["<leader>", "h"],
"commands": ["workbench.action.navigateLeft"]
},
{
"before": ["<leader>", "j"],
"commands": ["workbench.action.navigateDown"]
},
{
"before": ["<leader>", "k"],
"commands": ["workbench.action.navigateUp"]
},
{
"before": ["<leader>", "l"],
"commands": ["workbench.action.navigateRight"]
},
{
"before": ["<leader>", ","],
"commands": ["workbench.action.previousEditorInGroup"]
},
{
"before": ["<leader>", "."],
"commands": ["workbench.action.nextEditorInGroup"]
}
]
}
Currently, we are using Plug Vim from plugin_github_link. To install the plugin please type this inside of vim :PlugInstall
. For more information please visit the link above.
How to save vim without sudo
:w !sudo tee %
Info
- :w – Write a file (actually buffer).
- !sudo – Call shell with sudo command.
- tee – The output of write (vim :w) command redirected using tee.
- % – The % is nothing but current file name. In this example, it is /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input (or the buffer) and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself)
Reference
How to set vim as terminal default editor
sudo update-alternatives --config editor
Info
- Select vim as the default editor by providing the corresponding number to the terminal and hitting enter.
How to copy content of website to file
:-1 r !curl https://raw.githubusercontent.com/brucechanjianle/tmux_setup/master/.tmux.conf
Info
- :-1 – Start from the first line (without entering).
- r – Read command (refer to below).
- !curl – Call shell with curl command.
- https...tmux.conf – Provide the url link.
You may also want to use the curl
command alone.
curl -o .tmux.conf https://raw.githubusercontent.com/brucechanjianle/tmux_setup/master/.tmux.conf
Reference
Open file with cursor at the end
vim "+normal G" file.txt
Reference
Read commands from shell into vim
:r !ls
Info
Learn more from the external command video from Linkedin Learning.
Reference
Go to a file inside vim
gf
Info
Just hit gf and you vim will open the right file for you, provided that the file path is correct.
Reference
Tab edit inside vim
:tabe file.txt
Tab edit file.txt.
gt
Go to next tab.
gT
Go to previous tab.
<number>gt
Go to tab.
Use this method to edit several files in different tab.
Reference
Source .vimrc in vim
:so $MYVIMRC
Reference
Info
long | short |
---|---|
set | se |
highlightsearch | hls |
number | nu |
relativenumber | rnu |
syntax | syn |
:help keyword
- open help for keyword:saveas file
- save file as:close
- close current paneK
- open man page for word under the cursor
h
- move cursor leftj
- move cursor downk
- move cursor upl
- move cursor rightH
- move to top of screenM
- move to middle of screenL
- move to bottom of screenw
- jump forwards to the start of a wordW
- jump forwards to the start of a word (words can contain punctuation)e
- jump forwards to the end of a wordE
- jump forwards to the end of a word (words can contain punctuation)b
- jump backwards to the start of a wordB
- jump backwards to the start of a word (words can contain punctuation)%
- move to matching character (default supported pairs: '()', '{}', '[]' - use :h matchpairs in vim for more info)0
- jump to the start of the line^
- jump to the first non-blank character of the line$
- jump to the end of the lineg_
- jump to the last non-blank character of the linegg
- go to the first line of the documentG
- go to the last line of the document5G
- go to line 5fx
- jump to next occurrence of character xtx
- jump to before next occurrence of character xFx
- jump to previous occurence of character xTx
- jump to after previous occurence of character x;
- repeat previous f, t, F or T movement,
- repeat previous f, t, F or T movement, backwards}
- jump to next paragraph (or function/block, when editing code){
- jump to previous paragraph (or function/block, when editing code)zz
- center cursor on screenCtrl + e
- move screen down one line (without moving cursor)Ctrl + y
- move screen up one line (without moving cursor)Ctrl + b
- move back one full screenCtrl + f
- move forward one full screenCtrl + d
- move forward 1/2 a screenCtrl + u
- move back 1/2 a screen
Tip Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.
i
- insert before the cursorI
- insert at the beginning of the linea
- insert (append) after the cursorA
- insert (append) at the end of the lineo
- append (open) a new line below the current lineO
- append (open) a new line above the current lineea
- insert (append) at the end of the wordEsc
- exit insert mode
r
- replace a single characterJ
- join line below to the current one with one space in betweengJ
- join line below to the current one without space in betweengwip
- reflow paragraphcc
- change (replace) entire lineC
- change (replace) to the end of the linec$
- change (replace) to the end of the lineciw
- change (replace) entire wordcw
- change (replace) to the end of the words
- delete character and substitute textS
- delete line and substitute text (same as cc)xp
- transpose two letters (delete and paste)u
- undoCtrl + r
- redo.
- repeat last command
v
- start visual mode, mark lines, then do a command (like y-yank)V
- start linewise visual modeo
- move to other end of marked areaCtrl + v
- start visual block modeO
- move to other corner of blockaw
- mark a wordab
- a block with ()aB
- a block with {}ib
- inner block with ()iB
- inner block with {}Esc
- exit visual mode
>
- shift text right<
- shift text lefty
- yank (copy) marked textd
- delete marked text~
- switch case
: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.
:marks
- list of marksma
- set current position for mark A`a
- jump to position of mark Ay`a
- yank text to position of mark A
qa
- record macro aq
- stop recording macro@a
- run macro a@@
- rerun last run macro
yy
- yank (copy) a line2yy
- yank (copy) 2 linesyw
- yank (copy) the characters of the word from the cursor position to the start of the next wordy$
- yank (copy) to end of linep
- put (paste) the clipboard after cursorP
- put (paste) before cursordd
- delete (cut) a line2dd
- delete (cut) 2 linesdw
- delete (cut) the characters of the word from the cursor position to the start of the next wordD
- delete (cut) to the end of the lined$
- delete (cut) to the end of the linex
- delete (cut) character
:w
- write (save) the file, but don't exit:w !sudo tee %
- write out the current file using sudo:wq
or:x
orZZ
- write (save) and quit:q
- quit (fails if there are unsaved changes):q!
orZQ
- quit and throw away unsaved changes:wqa
- write (save) and quit on all tabs
/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 directionN
- 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
: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
:e file
- edit a file in a new buffer:bnext
or:bn
- go to the next buffer:bprev
or:bp
- go to the previous buffer:bd
- delete a buffer (close a file):ls
- list all open buffers:sp file
- open a file in a new buffer and split window:vsp file
- open a file in a new buffer and vertically split windowCtrl + ws
- split windowCtrl + ww
- switch windowsCtrl + wq
- quit a windowCtrl + wv
- split window verticallyCtrl + wh
- move cursor to the left window (vertical split)Ctrl + wl
- move cursor to the right window (vertical split)Ctrl + wj
- move cursor to the window below (horizontal split)Ctrl + wk
- move cursor to the window above (horizontal split)
:tabnew
or:tabnew
{page.words.file} - open a file in a new tabCtrl + wT
- move the current split window into its own tabgt
or:tabnext
or:tabn
- move to the next tabgT
or:tabprev
or:tabp
- move to the previous tab#gt
- move to tab number #:tabmove #
- move current tab to the #th position (indexed from 0):tabclose
or:tabc
- close the current tab and all its windows:tabonly
or:tabo
- close all tabs except for the current one:tabdo command
- run the command on all tabs (e.g. :tabdo q - closes all opened tabs)
Reference
Search&Replace
LeaderKey
LeaderKeyAs/
Tutorial Missing Semester on Vim
Vimscripting: link1 link2 link3 link4 link5
vimrc_setup