Advanced tutorial

Created Thursday 05 June 2014

http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html
The full list of options:
http://vimdoc.sourceforge.net/htmldoc/options.html

Vi/Vim Command Line Arguments

vim [arguments] filename1 [filename2 ...]

+[num] - open with cursor on line "num", if "num" isn't specified, the cursor will be on the last line
+/{pat} - open with cursor on the 1st occurence of {pat}
-c {command} - "ex" command in double quotes will be processed against the file specified
--cmd {command} - the same
-b - binary file mode
-C - vi compatibility mode (loses the more advanced vim features)
-v - the same
-d - diff file mode (list 2, 3 or 4 files); the same as vimdiff
-g - GUI gvim mode (if available)
-h - print help messages
--help - the same
-i filename - specify viminfo file (default is ~/.viminfo)
-r - recovery mode, used after a crash, the ".swp" file is used (see ":help recovery")
-L - the same
-M - file modifications and write not allowed
-R - the same
-n - prohibit ".swp" file generation (for special devices or limited space)
-x - use encryption when writing files (will prompt for a crypt key)
--noplugin - skip loading plugins
--version - print vim version

Basic "vi" features (partial commans list)

Movement commands

h/j/k/l - left/down/up/right
spacebar - move right one space
-/+ - move down/up in the 1st column
^d / n^d - scroll down one half of a screen / scroll to "n" lines
^u / n^u - scroll up one half of a screen / scroll to "n" lines
^f / n^f - scroll forward one screen / "n" screens
^b / n^b - scroll back one screen / "n" screens
^y / n^y - scroll down one line / "n" lines
^e / n^e - scroll up one line / "n" lines
M - move to the middle of the page
H - move to the top of the page
L - move to the bottom of the page
W - move a word at a time (white space delimited)
w - move a word at a time (first non-alphanumeric)
nw - move ahead n words
B - move back a word at a time (white space delimited)
b - move back a word at a time (first non-alphanumeric)
nb - move back n words
E - move to end of word (white space delimited)
e - move to end of word (first non-alphanumeric)
ne - move ahead to the end of the 5th word
0 - move to beginning of line
:30 - move to line 30
$ - move to end of line
) - move to beginning of next sentence (delimited by ".", "?" or "!")
( - move to beginning of current sentence
} - move to beginning of next paragraph (delimited by blank line or nroff macros: .IP, .LP, .PP, .QP, .P, .LI and .bp, see "set paragraphs" for defining one)
{ - move to beginning of current paragraph
]] - move to beginning of next section (delimited by nroff macross: .NH, .SH, .H, .HU, see "set sections" for defining a section)
[[ - move to beginning of current section
G - move to end of file
% - move to the matching bracket (use the matchit or xmledit plug-in to extend to XML/XHTML tags)
'. - move to previously modified line
m - mark the line on which the cursor resides (marking requires an identifier)
ma - mark the line as identified by the letter "a"
'a - move cursor to the line mark "a" generated by marking with keystroke "ma"
'A - move cursor to the line mark "A" (global between buffers) generated by marking with keystroke "mA"
]' - move cursor to next lower case mark
[' - move cursor to previous lower case mark

Editing commands

i - insert at cursor
l - insert before the cursor
a - append after cursor
A - append at end of line
o - new line below
O - new line above
ESC - terminate insert mode (terminates most other modes as well)
u - undo the last change
U - undo all changes to entire line
dd - delete line (stored in local buffer)
ndd - delete n lines (stored in local buffer)
D - delete contents of line after cursor
C - delete contents of line after cursor and insert new text
dw - delete word
ndw - delete n words
d) - delete to end of sentence
d$ - delete to end of line
d- - delete current and previous line
dfx - delete from cursor to the 1st occurance of the letter "x"
d'x - delete from the current line to the line marked with the identifier "x"
'ad'b - delete from the line of mark "a" to the line marked "b"
d/cat - delete all chars from the cursor to the next occurance of (not including) "cat"
cw - change word (delete the word and enter the insert mode)
c) - change sentence
c$ - change to end of line
x - delete char at cursor
X - delete char before cursor
Y - yank (copy) current line into "unnamed" storage buffer
yy - the same
p - paste unnamed storage buffer after current line
P - paste unnamed storage buffer before current line
r - replace char
R - overwirte chars from cursor onward
s - substitute one char under cursor cintinue to insert
S - substitute entire line and begin to insert at beginning of line
J - join current and following line into one line
~ - change case of individual char
^a - increment number under the cursor
^x - decrement number under the cursor
. - repeat last command action
Control Characters: to enter control chars while in insert mode, prefix the control char with "^v" and then type the control char (e. g. Carriage control: ^M, Form feed: ^L, Backspace: ^H, Delete: ^P, ...). Each control char must first be preceeded by "^v" while in insert mode
Delete/Restore Buffers: each time you delete or yank a line, it is stored in a local buffer and can be recalled and pasted. See "vi line buffers" examples below.

Search commands

/search_string{CR} - search for search_string
?search_string{CR} - search backwards for search_string
/\<search_string\>{CR} - search for search_string: /\<s\> will search for var "s" ignoring declaration "string" or words containing "s"; will find "string s;", "s = fn(x);", "x = fn(s);", etc...
n - find next occurence
N - find previous occurence
fx - move to the 1st occurence of letter "x" in the same line
nfx - move to "n" occurence
; - go to the next occurence in line
Fx/nFx/; - the same, backwards
tx - move to one char before the next occurance of letter "x" in line
ntx - move to one char before the "n"th occurance of letter "x" in line
; - next
Tx/nTx/; - the same, backwards

Information commands

^g / :f - list file info: file name, number of lines in file, position of cursor in file
:set list - show tabls and end of line markers
:set nolist - turn off ":set list"
:args - show command arguments used

Terminate / new session

ZZ - save changes to the current file and quit
:wq - the same
:w - just save
:w! - save overriding file permissions
:w filename - save to a new file
:q! - ignore changes and exit
:qa - quit all files opened
:e filename - start new edit session on specified file name without closing the current vi/vim process

Vi/Vim modes

:set all - display all mode settings of your editing session
:set termcap - display terminal settings
:set ic - change default to ignore case for text searches (set ignorecase)
:set autoindent / :set ai - {CR} returns to indent of previous line
:set noautoindent / :set noai
:set shiftwidth=4
:set smartindent
:set autowrite / :set aw - auto write the file when switching to edit another file
:set noautowrite / :set noaw
:set backspace=indent,eol,start / :set bs=... - allow backspacing over an indent, line break or start of an insert
:set backspace / :set bs
:set backup=on|off / :set bk=on|off - backup...
:set cryptmethod=zip - set file encryption for save of buffer contents
:set cryptmethod=blowfish - strong encryption
:set errorbells / :set eb - silence error beep
:set noerrorbells / :set noeb - ...
:set flash / :set fl - screen flashes upon error
:set noflash / :set nofl
:set tabstop=8 / :set ts - tab key displays 8 spaces
:set number / :set nu - display line numbers
:set nonumber / :set nonu
:set showmatch - cursor shows matching ")" and "}"
:set noshowmatch
:set showmode - editor mode is displayed on bottom of screen
:set noshowmode
:set syntax on - set syntax highlighting for a file type
:set syntax off
:set syntax=html - syntax definition files: /usr/share/vim/vim73/syntax/
:set taglength / :set tl - set significant chars (default is 0)
:set closepunct="'.,;)]} - % key shows matching symbol (see also showmatch)
:set linelimit=1048560 - max file size to edit
:set wrapscan / :set ws - breaks line if too long
:set nowrapscan / :set nows
:set wrapmargin=8 / :set wm - wrap when past 8 chars from the edge of column display (often the default is 80)
:set nowrapmargin / :set nowm
:set bg=dark - choose color scheme background
:set bg=light

Advanced "vi" features

http://stackoverflow.com/questions/3638542/any-way-to-delete-in-vim-without-overwriting-your-last-yank
http://www.vim.org/scripts/script.php?script_id=1234
http://vim.wikia.com/wiki/Remembering_previous_deletes/yanks
"_dd - delete without sticking to registers (see :help registers)
"aY - yank a line into the buffer named "a"
"ap - paste the contents of the "a" buffer
:reg - list all the registers
"t4dd - delete 4 lines into the buffer name "a"

Shift a block of code left or right

v - enter to the visual mode
move cursor
> - shift to the right
< - shift to the left
:set sw=4 - shift width to 4 chars (may place it in $HOME/.vimrc)
OR
:20,40> - shift rows 20-30 to the right
:20,40< - shift rows 20-30 to the left

Command options

:help topic - use TAB to cycle through options; ^d will print the complete list of possibilities

Unix commands in vi

!pwd - show working dir
!ls - show files in the current dir
!sh - open a new Bash shell (type 'exit' to return to vi)

Reading and merging/including external text

:r filename - include the contents of an external file
:r !date - reads the results from the date command into a new line following the cursor
:r !ls - 1 - place after the cursor the current directory listing displayed as a single column

Line numbers

Lines may be referenced by their line numbers. The last line in the file can be referenced by the "$" sign.
The entire file may be referenced by the block "1,$" or "%"
The current line is referred to as "."
A block of text may be referred to by its line numbers or its marked lines, i.e. 5,38 or 't,'b
:5,38 w newfile - write out a block of text denoted by line numbers
't,'bw >> filename - append a marked block to an existing file

Find/Replace

:%s/fff/rrrr/ - all lines: find "fff" and replace with "rrrr" for the 1st instance on a line
:%s/fff/rrrr/g - the same for each instance on a line
:%s/fff/rrrr/gc - the same as before, but ask for confirmation (!!!)
:%s/fff/rrrr/gi - case insensitive
:'a,'bs/fff/rrr/gi - for all lines between line marked "a" (ma) and line marked "b" (mb)
:5,20s/fff/rrrr/gc - for all lines between line 5 and line 20
:1,$s/$/OOO/ - for all lines in the file append 'OOO'
:1,$s/OOO$// - remove 'OOO'
:%s/ *$/ - for all lines delete blank spaces at end of line
:%s/\(.*\):\(.*\)/\2:\1/g - all lines: move the last field (delimited by ":") to the 1st field
:%s#<[^>]\+>##g - find and remove all HTML tags but keep the text contents
:%s/^\(.*\)\n\1$/\1/ - find and remove all duplicate lines
For more info:
:help substitute
:help pattern
:help gdefault
:help cmdline-rangers

Sorting

mt - mark line by "t"
mb - mark another line by "b"
The block is referenced as "'t,'b
:'t,'b !sort - sort lines in the block
:'t,'b !tac - reverse order of lines in block
!}sort - sort lines of text in a paragraph
!}sort -f -k2 - sort by the 2nd column ignoring case
!}sort | pr -4t - sort and arrange into 4 columns

Moving columns, manipulating fields and awk

:'t,. !awk '{print $3 " " $2 " " $1}' - reverse the order of the columns in the block of text

Source Code Formatting: C++/Java

Use vim visual text selection to mark the lines to format (beautify):
e.g., the whole file:
http://stackoverflow.com/questions/5507374/go-to-first-line-in-a-file-in-vim
gg - go to the 1st line (or :1)
v - visual mode
G - go to the last line
= - this will align all braces and identations

Text formatting

https://www.rfc-editor.org/nroff.html
http://learnvimscriptthehardway.stevelosh.com/chapters/50.html
mt
mb
:'t,'b !nroff

Text width formatting

Mark a block of text or reference by line numbers and pipe through fmt, a text formatter which splits lines on word boundaries
:20,30 !fmt -80

Spell checking

:'t,'b !spell - will cause the block to be replaced with misspelled words

Vim/Vi macros

:map letter commands_strung_together
:map - list current key mappings
:map g n cwNEW_WORD{ctrl-v}{esc}i{ctrl-v}{CR} - find the next search occurrence, change the word and insert a line feed after the word. The macro is invoked by typing the letter "g".

Double spacing

:%s/$/{ctrl-V}{CR}/g - apply an extra carriage return at the end of all lines

Strip blanks at end of line

:%s/{TAB}*$//

Delete all lines beginning with or matching a pattern

:1,$ /^#/d - delete all comment lines in file
:g/#/d - delete all lines containing comments
:g!/^#/d - delete all lines except (g! or v) comment lines

Strip DOS ctrl-M's

:1,$ s/{ctrl-V}{ctrl-M}//

Convert tabs to spaces

:% !expand -t4 - converts tabs to 4 spaces for the whole file (%)
:20,30 !expand -t4

Editing multiple files

vi file1 file2 file3
:n - edit next file (file2)
:n - edit next file (file3)
:rewind - rewind to the 1st file (file1) (or shift-ctrl-~)
:rewind! - rewind to the 1st file without saving changes

Line folding

zR - unfold all folded lines in file
za - open/close (toggle) a folded group of lines
zA - open a closed fold or close an open fold recursively
zc - close a folded group of lines
zC - close all folded lines recursively
zd - delete a folded line
zD - delete all folded lines recursively
zE - eliminate all folded lines in file
zF - create "N" folded lines

Hyper-Linking to include files

Batch execution of vi from a command file

Command file contents:
:1,$ s/<HTML>/<html>/g
:1,$ s/<\/HTML>/<\/html>/g
:1,$ s/<HEAD>/<head>/g
:1,$ s/<\/HEAD>/<\/head>/g
:1,$ s/<TITLE>/<title>/g
:1,$ s/<\/TITLE>/<\/title>/g
:1,$ s/<BODY/<body/g
:1,$ s/<\/BODY/<\/body/g
:1,$ s/<UL>/<ul>/g
:1,$ s/<\/UL>/<\/ul>/g
...
..
.
:1,$ s/<A HREF/<a href/g
:1,$ s/<A NAME/<a name/g
:1,$ s/<\/A>/<\/a>/g
:1,$ s/<P>/<p>/g
:1,$ s/<B>/<b>/g
:1,$ s/<\/B>/<\/b>/g
:1,$ s/<I>/<i>/g
:1,$ s/<\/I>/<\/i>/g
:wq

Tagging

http://vimdoc.sourceforge.net/htmldoc/usr_29.html
http://vimdoc.sourceforge.net/htmldoc/tagsrch.html
http://www.softpanorama.org/Editors/ctags.shtml
This functionality allows one to jump between files to locate subroutines
ctags *.h *.c - this creates a file named "tags"
vi -t subroutine_name - this will find the correct file to edit OR
:tag subroutine_name / :ta sub_name - this will jump from the current file to the file containing the subroutine OR
Place cursor on the 1st char of the sub name and press ctrl-]

vim features (not available in vi)

:tag start-of-tag-name_TAB - tag name completion
:tag /search-string - jump to a tag name found by a search
ctrl-] - jump to a new position within the file or in another file
ctrl-t - jump back a level (or :pop)
:tselect <function-name> - the user will be presented with all the references to the function and he will be prompted to enter the number associated with the appropriate one
:tnext / :tn - go to the next answer
:set ignorecase / :set ic - the ignore case directive affects tagging
:tags - show tag stack (history)
:4pop - jump to the 4th from bottom of tag stack (history)
:4tag - jump to the 4th from top
:tprevious
:tfirst
:tlast
:set tags=./tags,./subdir/tags - using multiple tag files (one in each directory). Allows one to specify all tags files in directory tree: set tags=src//tags**

Defaults file

$HOME/.exrc
~/.vimrc
~/.gvimrc
~/.vim/ - dir for vim config files



Backlinks: