Save file even if it was opened without write permissions
:w !sudo tee %
Write/append lines from file to another file (optionally overwrite)
:5,25w [!] [>>] new_file
Alternatively, just to write to a file in visual mode hit :
and then w <file name>
Save as new file and continue editing it
:sav <file name>
Write changes if there are any (good alternative to :w)
:up
Open multiple files in tabs
vi -p file1 file2
Open multiple files in windows
vi -o file1 file2
Open new, empty tab: :tabnew
Jump between tabs: gt
, gT
, ngt
Show all open files: :ls
, :files
Open file from buffer: :b <number>
, :b <file name>
, :b#
Like the above but in normal mode: <number> <C-^>
Open file from buffer in new window: :sb <number>
or :tabnew | b <number>
Move file in split view out to new tab: Ctrl-W T
Close file: :bd <number>
, Ctrl-w c
Save window arrangement: :mksession! <file name>
Read contents of file and paste it under cursor: :r <file name>
To cut to end of line: d$
, D
Replace more than letter: R
Cut text to register letter:
"<letter>dw
The above also works with multiple characters/words as well as yanking
Paste copied text, regardless of anything that might have been deleted, cut or replaced subsequently:
"0p
Select lines in visual mode and type:
:w ! pbcopy
Matching parentheses search - put cursor on a character and hit %
to find a matching one.
Search for text and go back to the original line
/ <search term>
Ctrl-o
Ctrl-i // to go forward
Go to line and column
:25
16|
Case insensitive search, search term highlighting
:set ic
:set hls
Count number of times a pattern occurs
:%s/pattern//gn
Search and replace with lowercase
:%s/\([A-Z]\)/\L\1/gc
Go to declaration of variable under cursor: gd
Attempt to jump to declaration of method under cursor: g*
Go to beginning of method declaration: [m
Go to file under cursor (doesn't work with .jsx
files): gf
Print the ASCII value of the character under the cursor: ga
Print the hex values of the bytes used in the character under the cursor: g8
These values can then be used e.g. to search for narrow non-break spaces from Shell command line: ag '\xe2\x80\xaf'
Join with next line without inserting space: gJ
Centre text: :ce
Sort text: :[range]sort