vim Commands

Using VIM


Using vim editor (+52 to go to line 52, +/text to go to line contain text)

# vim makefile

or

# vim +52 makefile

or

# vim +/getIPAdr ui_task.c


Load vim without plugin, "-N" prevent vi compatible mode)

# vim -u NONE -N


To password protect a vim file

vim -x file.txt


To check version and feature available

:ver


To explore files(Explore, Vexplore=Split new vertical window, Sexplore=Split new horizontal window)

:Exp

or

:E

or

:Sex

or

:S  (Type i to toggle thin/long/wide/tree view)


To reload current file

:e


To open all file in subfolder with *.am

:args ./subfolder/**/*.am


To change working directory to current file

:cd %:p:h

Or put below in .vimrc

:set autochdir


To create new blank file

ctrl + w then n

or

:enew


To list all vi option

:set all


To set indentation

:set tabstop=4

Fix line indentation

==

To make vi show line number

:set number

or

:set nu


To make vi hide line number

:set nonumber


To toggle line number

:set nu!


To toggle relative line number

:set relativenumber!


To insert line number in file

:%! nl -ba

or

:%!cat -n


To make vi show control character (tab show as ^I, enter show as $, space show as nothing)

:set list


To make vi hide control character

:set nolist

or

:set list!


To make vi show control character (tab show as », trailing space show as .)

:set listchars=tab:\»\ ,trail:.,extends:\>,precedes:\<

or

:set lcs=tab:\»\ ,trail:\.,extends:\>,precedes:\<


To make vi display cmd/edit mode at bottom

:set showmode


To off display cmd/edit mode at bottom

:set noshowmode

or

:set showmode!


Set encoding type (After launch vim, before open file)

:set encoding=utf-8

then open the file.


Reload file encoding type (After open file)

:e! ++enc=utf-8


Convert dos to unix

:w ++ff=unix

or

:set ff=unix


Delete dos character ^M

:%s/\r//g


Delete blank line (^ mean start of line, \s* mean zero or more whitespace, $ mean end of line)

:g/^\s*$/d


Copy all lines matching a pattern to register 'a'. qaq is a trick to clear register a (qa starts recording a macro to register a, then q stops recording, leaving a empty).

qaq:g/pattern/y A


Compress multiple occurrences of blank lines into a single blank line

:v/./,/./-j


To highlight the control character, just search for space, with hlsearch on

:set hlsearch

/<space>

/<tab>

/asdf (just search anything else to clear highlight)


To off hlsearch

:nohlsearch

or

:set hls!


To decrease font  size

Ctrl + -


To increase font  size

Ctrl + +


To make vi display full path name beneath

1 then Ctrl + g (Or :f) 


To bookmark current line (mark with register a~z)

mk


To go to line bookmark 'a' (register can be a~z)

'k


To go to position bookmark 'a' (register can be a~z)

`k


To list existing bookmark

:marks


To jump to next line bookmark (lowercase mark)

]'


To jump to previous line bookmark (lowercase mark)

['


To jump to next position bookmark (lowercase mark)

]`


To jump to previous position bookmark (lowercase mark)

[`


To go to last edit line

`.

or

g;


To go to line 115

:115


To list register's content

:reg


To set code fold

:set foldmethod=indent


To list all plugins, vimrcs loaded

:scriptnames


To list all abbrev

:ab


To disable all abbrev

:set paste


To enter hex mode

:%!xxd

or

:%!xxd -s 0x650 (offset to 0x650)

or

:%!hexdump -C


To exit hex mode

:%!xxd -r

or

u


To enter decimal mode (u1 = 1 byte in decimal, u2 = 2 bytes in decimal)

:%!od -t u1

or

:%!od -t u2


To toggle code fold (at cursor position)

za


To toggle code fold (whole file)

zi


To close code fold

zc


To open code fold

zo


To start macro recording

qq


Stop recording

q


Repeat

@q (the first time)

@@ (after that)

20@@ (Repeat 20 times)


To create ctags, at bash shell (-R=recursive, -f=ctags filename)

$ ctags -R -f ~/test.ctags ~/Project/src/test


To set tags file

:set tags=~/test.ctags

:ta func = go to func definition

:ts = shows the list.

:tn = go to the next tag in that list.

:tp = go to the previous tag in that list.

:tf = go to the function which is in the first of the list.

:tl = go to the function which is in the last of the list.


To create cscope, at bash shell (-R=recursive, -q=generate inverted index file, -b=create database only, -k=kernel mode, not look in /usr/include)

$ cscope -Rqbk -f ~/test.cscope

or

$ cscope -Rb

or

$ find . -name '*.{c,h}' > ./cscope.files  (csh shell)

$ find . -name "*.c" -o -name "*.h" > ./cscope.files  (bash shell)

$ cscope -Rb


To set cscope file

:cscope add =~/test.cscope ~/Project/src


To resolve error reading cscope connection 0

:cs kill 0

:cs add cscope.out

:cs f g = find all global definition (Or Ctrl + \ g)

:cs f c = find function calling this function (Or Ctrl + \ c)

:cs f d = find function called by this function (Or Ctrl + \ d)

:cs f e = egrep (Or Ctrl + \ e)

:cs f f = open file (Or Ctrl + \ f)

:cs f s = find C symbol (Or Ctrl + \ s)


To find tags under cursor

Ctrl + ]

or

:ta


To return from tags jump

Ctrl + t

or

:pop


To return from point of departure

Ctrl + o


To return from point of departure (Reverse)

Ctrl + i


List changes

:changes


Cycle thru recent changes

g,


List jumps

:jumps or :ju


Open cmd history window (Ctrl + c to exit)

:Ctrl + f

or

q:


Search history window

q/


To enter edit mode (o will add one blank line)

a

or i

or o


To enter command mode

escape

or Ctrl + c

or Ctrl + [


To navigate

h = left

j = down

l = up

k = right

0 = Go to beginning of line

$ = Go to end of line

w = forward one word (or Ctrl + right)

b = backward one word (or Ctrl + left)

B = to beginning of white space delimited word

e = to end of word

E = to end of white space delimited word

:124 = Go to line 124 (Or 124G)

% = jump to matching #if, #else {}, (), [], /* */

Ctrl + b = page up

Ctrl + f = page down

H = high (top of screen)

M = mid (medium of screen)

L = low (bottom of screen)

gg = go to beginning of file(Or 1G) (Or [[) 

G = go to end of file(Or ]])

Ctrl + o = navi forward one old cursor position

Ctrl + i = navi backward one old cursor position

Ctrl + w then s = split the current window horizontally (Or :sp)

Ctrl + w then v = split the current window vertically (Or :vs)

Ctrl + w then c = close the current window

Switch two or more windows to vertically or horizontally

Ctrl + w then H = to vertically

:windo wincmd H = to vertically

Ctrl + w then K = to horizontally

:windo wincmd K = to horizontally

Ctrl + w then down = navigate to window below current window (Or Ctrl + w j)

Ctrl + w then up = navigate to window above current window (Or Ctrl + w k)

Ctrl + w then left = navigate to window left to current window

Ctrl + w then right = navigate to window right to current window

Ctrl + w then w = navigate to window above (wrap)

Ctrl + w then Ctrl + w = navigate to window below (wrap)

Ctrl + w then p = navigate to previous window

Ctrl + w then o = close other window except this (only)

Ctrl + w then < = make window wider

Ctrl + w then > = make window narrower

Ctrl + w then + = make window higher

Ctrl + w then - = make window lower


To have 30 more characters wide

:30winc >


To have 30 less characters wide

:30winc <


To have 4 more lines (window higher)

:set lines+=4


To have 4 less lines (window lower)

:set lines-=4

:vertical resize 150 = make window size 150 character wide

:resize +50 = make window horizontal size 50 character more

Ctrl + w then H = move window vertically split at right

Ctrl + w then L = move window vertically split at left

Ctrl + w then J = move window horizontally split at bottom

Ctrl + w then K = move window horizontally split at top


To open file

:e ../myFile.c = edit/open a file (Or edit in new filetab :tabe ../myFile.c)

:b myFile.c = to switch between filetab

:b <tab-key> = providing auto-completion (awesome !!)

:sp ../myFile.c = edit/open a file as horizontal split

:vsp ../myFile.c = edit/open a file as vertical split

:ls = to list buffer(filetab)

:3b = to switch to 3rd buffer(filetab)

:3sb = to switch to 3rd buffer(filetab) with split window

:3bd = to delete 3rd buffer(filetab)

:3bw = to wipe 3rd buffer(really freed memory)

:bw% = to wipe current buffer(really freed memory)

Ctrl + 6 = to toggle between now and previous buffer(filetab)

:%bd = to close all buffer

:bufdo bdelete = to close all buffer

:tabe <filename> = opens new file in filetab

:tabn = go to next filetab (Or Ctrl + pageup)

:tabp = go to previous filetab (Or Ctrl + pagedown)

:tabc = close current filetab

:tab sball = opens a new tab for each open buffer (Or :tab sba)

gt = go to next filetab

gT = go to previous filetab

`. = go back to previous modification spot


Buffer indicator

Indicators (chars in the same column are mutually exclusive):

u       an unlisted buffer (only displayed when [!] is used)

           |unlisted-buffer|

 %      the buffer in the current window

 #      the alternate buffer for ":e #" and CTRL-^

  a     an active buffer: it is loaded and visible

  h     a hidden buffer: It is loaded, but currently not

           displayed in a window |hidden-buffer|

   -    a buffer with 'modifiable' off

   =    a readonly buffer

    +   a modified buffer                      

    x   a buffer with read errors


To find string

/searchstring

or

?searchstring (search backward)

# = search the word under cursor, previous

* = search the word under cursor, next


To find next string

n


To find previous string

N


To find string and ignore case

/\csearchstring


To find string and match whole word, enclose with <>

/\<searchstring\>


To list find result with line number

:g/searchstring/

To show lines matching word under cursor <cword>

[I


Pull word under the cursor into a command line or search

/<C-R><C-W>


To find string and list

:g/searhstring


To make case sensitive find

:set noignorecase or :set noic


To make case insensitive find

:set ignorecase or :set ic


To find string in open files

:bufdo vimgrepadd "searchstring" %

:copen or :cw


To find string in files

:grep -Hrn "searchstring" ~/Project/src

:copen or :cw


To select text, cut/copy,paste

(first plan the cursor at 1st location)

v = character selection

V = line selection

Ctrl + v = column mode selection

(then copy or cut)

y = copy the selection

d = cut the selection

(then paste)

p = paste selection after cursor

P = paste selection before cursor

(then find and replace)

:%s/find/replace/gc

:%s#find#replace#gc

:%s_find_replace_

:%s:find:replace:

:%s%find%replace%

:%s!find!replace!

(then sort, after visual line selection)

!sort


To sort current file, remove duplicate

:%!sort -u


To select word

viw = got to visual mode and select inner word

o = exchange cursor position in the highlight


To show the number of lines, words and bytes selected

g Ctrl-G


To indent a line visual block

V = Line selection mode

cursor up, down = Line selection

< = unindent

. = repeat the unindent

> = indent

>aB = indent a block

>iB = indent inner block


To copy/yank the current string

yw (Or inner word yiw)


To copy/yank the current line

yy


To copy/yank the current line and next 5 lines

5yy

or

y5y


To paste/put

p


To enter visual mode (to highlight text for copy/yank, character selection)

v


To enter visual mode (line selection)

V


To enter visual mode (column mode, block selection)

Ctrl + v


To reselect last visual area

gv


To insert character in column mode/block selection

Ctrl + v

Select the columns and rows where you want to enter your text

Shift + i = go into insert mode in column mode

Type in the text you want to enter. Don't be discouraged by the fact that only the first row is changed.

Esc = apply your change (or alternately Ctrl+c)


To delete character in column mode/block selection

Ctrl + v

Select the columns and rows where you want to enter your text

Shift + i = go into insert mode in column mode

x = delete

Esc = apply your change (or alternately Ctrl+c)


To comment/un-comment

Shift + v

Select the rows where you want to enter your text

:norm i// = add // in front, ":'<,'>norm i//" will appear at cmdline

gv = reselect previous selection

:norm xx = remove // in front, ":'<,'>norm xx" will appear at cmdline


To copy/yank the current line to register a

"ayy


To paste/put from register a

"ap


To copy/yank selection and paste in other buffer

Shift + v (do line selection at current)

"ay  (copy to register "a", "a mean refer to register a)

"Ay (copy and Append to register "a")

:2b (switch to buffer no 2) (Or gt)

"ap (paste from register "a", "a mean refer to register a)


To paste/put at cmdline (retrieve default register 0)

Ctrl + r then 0 (from vi clipboard, i.e. after yiw cmd) (Or Ctrl + r then ")

or

Shift + Insert (from windows clipboard)

or

"*p (Register * is windows clipboard)


To paste/put current filename

Ctrl + r then % (in edit mode)


To paste/put current cursor word

Ctrl + r then Ctrl + w (in edit mode)


Deleting without updating the default register(" register )(black hole register "_" is the /dev/null of registers)

noremap x "_x


Paste in visual mode without updating the default register(" register)

vnoremap p "_dP


To know mapping key bounding

:verbose nmap <C-Right>


To delete selection

d


To delete a character

x


To delete current line

dd


To undo last edit

u


To redo last edit

. (Or Ctrl + r)


To repeat command line command

@:


To repeat normal/insert mode command

.


To call up auto completion

Ctrl + p

Or

Ctrl + n


To call up calculator (in insert mode)

Ctrl + r then = Calculation result will be in the doc

or in command mode

:echo (2+3)*0xA


To convert hex to dec

:echo 0x123


To convert dec to hex

:echo printf('%x',56)


To find and replace whole file (%=entire file, or 1,$, gc = global and confirmation)

:%s/find/replace/gc

or

:%s#find#replace#gc

:%s:find:replace:gc

:%s!find!replace!gc

:%s%find%replace%gc

or

:1,$s/find/replace/gc


To find and replace whole word only, "findthis" with "replacethis" (Use "\<" and "\>" to enclose

:%s/\<findthis\>/replacethis/g


To find and replace "Martin" with "Mr Martin" (Use "\(" and "\)" to enclose pattern and "\1" to refer)

:%s/^\(Martin\)/Mr \1/g


To trim blanks off at end of line

:%s/[ <tab>]*$//

or

:%s_\s\+$__

or

:%s#\s\+$##

or

:1,$s/[ <tab>]*$//


Clean both trailing spaces and DOS returns

:%s#\s*\r\?$##


Delete blocks of 3 empty lines

:%s/^\n\{3}//


Reverse fields separated by :

:s/\(.*\):\(.*\)/\2 : \1/


Delete duplicate lines

:%s/^\(.*\)\n\1/\1$/


Delete lines which appears twice

:%s/^\(.*\)\n\1$/\1/


To operate selected line only, just select line"Shift + v" and type ":"

Shift + v

:'<,'>%s#abc#xyz#


To open file under cursor

gf = open file in same window

Ctrl + w then f = open file in new window


To display ascii of current character under cursor

ga


To display utf-8 of current character under cursor

g8


To invert case of current character under cursor

~


To lowercase line

Vu


To uppercase line

VU


To increment number (In cmd mode)

ctrl + a


To decrement number (In cmd mode)

ctrl + x


To fork another shell

:sh


To return from temporary shell

Ctrl + d


To run a shell cmd call "tmake.sh" in current directory

:!./tmake.sh


To issue cmd prompt command

:!ls -al


To read in date

:r!date

or

:.!date


To save

:w


To save file as root user (tee to redirect w to %, i.e. is the file itself)

:w !sudo tee %


To save and quit vi

:wq


To save as

:sav newfile.txt


To quit vi and save if changes made

:x

or :wq

or ZZ


To quit without save

:q

or :q!

or :qall!

or ZQ


To use vimdiff

vimdiff file1 file2 (Or in vi with file1, :vert diffsplit file2)

or

vi -d file1 file2


To launch plugin DirDiff.vim and compare two folder

vim -c ':DirDiff /tmpfolder1 /tmp/folder2'


To diff with current file

:diffthis


To refresh diff

:diffupdate


To diff within vim two file

:sp <filename>

:windo diffthis


To diff off

:diffoff!


To ignore white space in vimdiff

:set diffopt+=iwhite

or

vim -c 'set diffopt+=iwhite' file1 file2


To revert ignore white space in vimdiff

:set diffopt-=iwhite


To go to previous diff (zz to centre window to current diff)

[c (Or [czz)


To go to next diff (zz to centre window to current diff)

]c (Or ]czz)


To get/obtain diff to current window

do (Or :diffget)


To put diff to other window

dp (Or :diffput)


To update diff window

:diffupdate


To open fold

zo


To close fold

zc


To unfold all

zR


To fold all

zM


To invert fold

zi


To save session

:mks (Default session file Session.vim)

or

:mks! (Overwrite)

or

:mks myproject.ses (or :mksession -f myproject.ses)


To retrieve session

$ vim -S (Default session file Session.vim)

or

$ vim -S myproject.ses

or within vi

:source myproject.ses (or :so myproject.ses)


To list current key mapping

:verbose map


To list current key F12 mapping

:verbose map <F12>


Mapping

remap = recursive mapping

noremap = no recursive mapping

nnoremap = normal, no recursive mapping

vnoremap = visual, no recursive mapping

Mode letters

n : normal only

v : visual and select

o : operator-pending

x : visual only

s : select only

i : insert

c : command-line

l : insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)


Disable PuTTY application keypad mode

Run PuTTY Configuration.

In the left pane, select Terminal, Features.

Put a check mark next to "Disable application keypad mode".

In the left pane, select Session.

Save the settings.


Reference

https://www.zinkwazi.com/unix/notes/vimtips.html

Sample .vimrc at home directory

"General

let bg=dark

:colorscheme murphy

syntax on

set number

set numberwidth=5     "Set line numbering to take up 5 spaces

set tabstop=4         "Set tab character to 4 characters

set shiftwidth=4      "Indent width for autoindent

set cursorline        "Highlight current line

set autoread          "Set to auto read when a file is changed from the outside

set hlsearch          "Set highlight search on

set dir=~/.vim-tmp    "Set swp file directory

set nobackup

set nowritebackup

set noswapfile

"Code folding settings

set foldmethod=marker   "fold based on marker

set foldmarker={,}      "fold marker is {,} instead of default {{{,}}}

set foldnestmax=10      "deepest fold is 10 levels

set nofoldenable        "don't fold by dault

set foldlevel=0         "this is just what i use

"Default encoding

set encoding=utf-8

set fileencoding=utf-8

"Custom template definition

:ab #s <TAB>switch(RemoteKeycode){<CR><TAB><TAB>case KEY_PLAY:<CR><TAB><TAB><TAB>//<CR><TAB><TAB><TAB>break;<CR><TAB><TAB>default:<CR><TAB><TAB><TAB>//<CR><TAB><TAB><TAB>break;<CR><TAB>}<CR>

:ab #i <TAB>if(IsComBusy() == TRUE){<CR><TAB><TAB>;<CR><TAB>}else<CR><TAB>if(IsMoveAckNG()){<CR><TAB><TAB>;<CR><TAB>}<CR><TAB>else{<CR><TAB><TAB>;<CR><TAB>}<CR>

:ab #p printf("%s %s() line%d m_value=0x%x \n",__FILE__,__func__,__LINE__,m_value);

:ab #d // BugID 00000 AngKH <c-r>=strftime("%Y-%m-%d %a %I:%Mpm")<CR>

"For DirDiff

let g:DirDiffExcludes = "CVS,*.class,*.exe,.*.swp,*.o,.git,.deps,.svn,*.lsp,*.a,*.log"

"Keymapping, find in files

map <C-M-f> <ESC>:grep -Hrns <c-r>=expand("<cword>")<CR>:copen<CR><CR>

"Keymapping, find in files

map <F3> <ESC>/<c-r>=expand("<cword>")<CR><CR>

"Keymapping, previous diff

map <F7> <ESC>\[c<CR><Tab>

"Keymapping, next diff

map <F8> <ESC>\]c<CR><Tab>

"Keymapping, convert open files to filetabs

map <F9> <ESC>:tab sba<CR>

"Keymapping, show tag list on right hand side

map <F10> <ESC>:TlistToggle<CR><CR>

"Keymapping, find symbol/definition

map <F11> <ESC>:cs find g <C-R>=expand("<cword>")<CR><CR><Tab>

"Comment/Uncomment

map <Leader>. :call ClojureCommentUncomment()<CR>

function! ClojureCommentUncomment()

  let search_saved = @/

  if getline('.') =~ '^\/'

    s/^\/\///  " remove ';' at beginning of line

  else

    s/^/\/\//  " insert ';' at beginning of line

  endif

  let @/ = search_saved

endfunction