I've compiled few tips over time on vi which I found very useful and little harder to get on the net.
Tip - Configure your vim
On Linux you configure ~/.vimrc file or set VIMINT variable
On Windows its easier to edit this file by opening a vim session and typing
:edit $MYVIMRC #Start vim with ADMIN privs to edit this file
To figure out what ~ aka home dir is on windows you can do
:echo expand('~')
Few other things you can print out while within vi are
:echo $HOME
:echo $VIM
:echo $VIMRUNTIME
:version
Tip - Getting help
vimtutor #An executable installed with gvim to help you get started on vi
:help
:help subject
Jump to a subject: Position the cursor on a tag (e.g. |bars|) and hit CTRL-].
Jump back: Type CTRL-T or CTRL-O. Repeat to go further back.
Tip - Relocate ~ tilde files
One thing you don't want vim to do is to clutter your directory with ~ tilde
files, especially if you've source controlled the folder. To avoid that place
few settings in this file thus:
(on windows)
set backupdir=c:\\temp\\vim//
set undodir=c:\\temp\\vim/
set dir=c:\\temp\\vim//
Tip - Working with tabs
set tabpagemax=100 #maximum tabs you can open
"C:\Program Files (x86)\Vim\vim80\gvim.exe" -p * #Open all files under the
directory in tabs!
I find the most convenient method of editing multiple files is by using tabs. You can open multiple files in separate tabs via the command line like so:
vim -p file1.txt file2.txt
Or if you already have vim open, you can open a new file in a new tab like so:
:tabe file2.txt
Once you have the tabs open, use gt to view the next tab and gT to view the previous tab.
You can also jump to the first tab with 1gt, the second tab with 2gt, etc.
You can close tabs using :tabc
Finally you can move the current tab to the nth location with :ntabm where n is any number greater than or equal to 0.
Tip - Working with indentations, useful for coding python
First set your variables
:set wrap linebreak nolist ai si nu ic sw=4 ts=4 expandtab softtabstop=4
#wrap Sets line wrap if you're window is small ,then linebreak breaks at word
boundary not in middle of word.
#list display tab with CTRL-I and endofline as $, nolist disables that
behavior.
#ai autoindent , new line starts with similar indentation as earlier line
#si smartindent, useful for C type langs, start indents after line ending with {
#nu enable line number; nuw 8 sets the width to 8 chars for line nu
#ic ignore case
#sw shiftwidth ,default of 8 chars , when indenting with '>', use 4 spaces width
#ts or tabstop=4 show existing tab with 4 spaces width
#On pressing tab, insert 4 spaces ,as a result of expandtab and softtabstop
You can replace all the tabs with spaces in the entire file with
:%retab
4>> , 4<< #For indentations, move next 4 lines and indent them
= #Autoindent, looks at indentation of line above and matches lower lines with it.
# =G indent till end of file
# =5 five line after this
# =ap a paragraph?
Tip - Working with Splits
"C:\Program Files (x86)\Vim\vim80\gvim.exe" -O3 * #Open all files in 3 vertical splits!
:split filename - split window and load another file; :sp
:vsplit file - vertical split; :vs
:e filename - edit another file
:e# toggle files
'A-Z marker between files.
ctrl+w (hjkl) move between windows
ctrl-w up arrow - move cursor up a window
ctrl-w ctrl-w - move cursor to another window (cycle)
ctrl-w_ - maximize current window
ctrl-w= - make all equal size
10 ctrl-w+ - increase window size by 10 lines
:sview file - same as split, but readonly
:hide - close current window
:only - keep only this window open
:ls - show current buffers
:b 2 - open buffer #2 in this window
You can use the option -o to open the files in horizontal splits or -O to open vertical splits. The following commands open a window for each file specified:
vim -o *.cpp
vim -O foo bar baz
You can tell Vim the maximum number of windows to open by putting an integer after o or O options, the following example will open at most two windows no matter how many file matches, you will see the first two file specified on the command line, the rest will remain hidden:
vim -o2 *.cpp
See :help -o for all the details.
:args app/views/*.erb | all #for horizontal splits or
:args app/views/*.erb | vertical all #for vertical.
Tip - Command Line Mode
First / to Go in clm search OR : to go in clm commands
ctrl+p show previous historical search
ctrl+n next search
ctrl+f
q/ history of search patterns
q: history of commands
Tip - Multiple Searches in vim
I'm not sure if there's any editor that can do this, we can search for multiple separate words in a single search, here's couple of mechanisms for doing that:
/w1\|w2\|w3
\vw1|w2|w3
If lets say you want many words highlighted then place this in your .vimrc file - really good way to always highlight few keywords you want. (Ref 9,10)
:match Float /weblogic.home\|-Xmx\|-Xms\|weblogic.Name\|config.dir/
Tip - Handle Multiple Files
You can open multilple files simply by vi a.txt b.txt etc. or lets say you did
a grep and found many files as a result you want to go over ,then you can use
something like this to open all at once:
vi $(!!) ##Output of last command
vi $(grep -il "webcat" *.log)
$ find -name testname.c -exec vi {} +
:n
:N
:args #shows all files opened with current in brackets.
:rew
:help buffer
Ctrl+g #what file
:ls - show current buffers
:b 2 - open buffer #2 in this window
Tip - Copy and paste to a different file within vim opened files
ma #mark the line
go to other line
y`a #yank from the marker to current line
:ex test.txt #open a new file
p #paste it
:rew #go back to old file
Alternatively:
ma
mb
`a,`byz #y->yank z->buffer
"zp #buffer paste
Tip - Pasting text without messing up formatting
:set paste #auto indent destroys paste formatting
:set nopaste
set pastetoggle=<F2> # to easily toggle setting
"*p or "+p for pasting from clipboard.
Tip - Vimdiff
Sorry - but I typically use kdiff for better visualization !
Tip - converting from \r\n to \n only
http://vim.wikia.com/wiki/File_format
:argdo set ff=unix|w
Tip - Highlight cursor
:autocmd CursorMoved * silent! exe printf('match IncSearch /\<%s\>/', expand('<cword>'))
:set hlsearch
Tip - Stop messing with the color and syntax
:syntax off
:set syntax=
syntax off
set nohlsearch
set t_Co=0 #line number color off
set t_Co=0 syntax=strace
Sometimes colors are useful, I typically use zellner which works on most terminals
:colo zellner
Tip - Miscellaneous
gUaw # Uppercase a word
* #search for current word which cursor is on
/echo.*file #Search with pattern
:%s/^\(Martin\)/Mr \1 Wicks/g #Group search and replace
4!!awk '{print "New text",$0}' #Appends New text to front of line for 4 lines. you can do this with substitute ^ too, where awk is not needed.
:1,$!awk '{print $1}' | sort | tr [:lower:] [:upper:] #Just get first column from file sorted and in upper case; replace $1 with $0 to sort have all fields;
:.,$s/^/\t/ #substitue front of line with tabs.
:1,$s/^M//
:s/ \+/\r/g #Break from spaces to newlines
Show special characters
https://yakking.branchable.com/posts/whitespace-safety/
http://www.shsu.edu/~csc_tjm/fall2000/cs431/shellprog.html
Just to clarify, :set list shows newline ($), :e ++ff=unix shows CR (^M); if you want to see both, :set list then :e ++ff=unix
or :set binary or vi -b file
vi -b myfile.txt
Delete
To delete forward up to character 'X' type dtX
To delete forward through character 'X' type dfX
To delete backward up to character 'X' type dTX
To delete backward through character 'X' type dFX
daw #delete a word ; even if you're at middle of word
daw
daW
diw #insert mode
g!/TEXT/d - deletes lines which don't have TEXT in it.. note the !
:g/^$/d - Removes blank lines;
Trim lines ;
remove duplicate lines :sort u ;
Tip - Pad + with spaces - From Ref. 8
f+ #find +
s #delete char at cursor i.e + and go in insert mode
_+_ #pad + with spaces
; #repeat find with f
. #repeat last sequence i.e pad +
Folding
http://vimdoc.sourceforge.net/htmldoc/fold.html
https://www.linux.com/learn/vim-tips-folding-fun
http://stackoverflow.com/questions/8316139/how-to-set-the-default-to-unfolded-when-you-open-a-file
zR #Open all folds
zM #Close all folds
zi #Toggle.
zf#j creates a fold from the cursor down # lines.
zf/string creates a fold from the cursor to string.
zj moves the cursor to the next fold.
zk moves the cursor to the previous fold.
zo opens a fold at the cursor.
zO opens all folds at the cursor.
zm increases the foldlevel by one.
zr decreases the foldlevel by one.
zd deletes the fold at the cursor.
zE deletes all folds.
[z move to start of open fold.
]z move to end of open fold.
Tip - Good Links for VIM
http://www.vim.org/ #Main site - download from here
http://vimhelp.appspot.com/vim_faq.txt.html
https://www.cs.swarthmore.edu/help/vim/markers.html
Tip - Sessions in vim
:mksession ~/sess.vim
:source ~/sess.vim
gvim -S ~/sess.vim
--save with :xa or :wqa
-might want to set this in .vimrc
set ssop-=options " do not store global and local values in a session
set ssop-=folds " do not store folds
Tip - Join multiplie lines
J- Joins next lin
[range]j[lines]
%j - joins whole buffer.
%j! - don't replace newlines with spaces..
Tip - Keep portion of text from lines
%s/\(\[.*, \).*/\1/g
-In \( give pattern to match , then end with \)..then for replace,put that remembered pattern with \1
qd start recording to register d
... your complex series of commands
q stop recording
@d execute your macro
@@ execute your macro again
In the link above the first command should be :s/\s\+/': ' (then press Enter)