Skip to content

Instantly share code, notes, and snippets.

@dezza
Last active October 27, 2023 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dezza/f02db501a627ae3724590b5aafc49c5b to your computer and use it in GitHub Desktop.
Save dezza/f02db501a627ae3724590b5aafc49c5b to your computer and use it in GitHub Desktop.
" wow
" TODO refactoring cheatsheet
" * Markdown with embedded syntax or .vim solely
" * Better sections (markdown would enable anchor-links/permalinks)
" debugging vim plugins unsilent avoids plugins silencing echom
:unsilent echomsg "debug msg in plugin"
" Commands that take filename modifiers
:vsplit %:h
:edit %:h
" open vim with search term
vim +/foo file.vim
" add matches to list
:let lst = []
:substitute(getbufline("%", 0, "$")->join(), "foo", "\\=add(lst, submatch(0))", "gne")
" These are relevant for the vimgrep below
$ vim * # Add all files to args
:args * # Add all files to args
:args `find . -name 'foo*'`
" vimgrep over open files
:vimgrep /foo/ ##
" vimgrep all files under current directory (getcwd())
:vimgrep /foo/ **/*
unsilent echom "I love vim"
" delete blank and empty lines
:g/^\s*$/d
" change to alternate file
CTRL-6, CTRL-^
" execute current line as commandline (ex)
yy:@"
" execute yank register (") as commandline (ex)
:@"
" execute visual-selection register (*) as commandline (ex)
:@*
" copy last ex command ": register to "+ register, copy pasting the last ex command you ran
let @+=@:
" reselect previously selected text
gv
"insert mode execute one command and return to insert mode
<C-o>:
" highlight all uppercase chars
match Title /[A-Z]/
" regex explained (xml tag)
/<[^>]*>
" match everything that starts with < except > end-chacter and match a > finally
" note: for this to work join all lines first with "ggVGJ" to merge tags across newlines
" replace <br> with actual newlines \r
:%s/<br>/\r/g
" delete html tags
:%s/<[^>]*>//g
" add newline before pattern
:%s/pat/\r&/g
" search without escaping /, you can use any separation-char (#)
:silent g#foo/bar/baz
1. remove Plug from lines
2. remove leading whitespace and replace " with #
3. replace extra ", { option: option }" from vim-plug format
4. delete everything not matching a comment or a repo-word
5. comments are moved to bottom
" replace vim-plug format to voom (remove front-padded whitespace, remove Plug '' around word by putting it in a group () with char class [] and ref with \1)
:%s#^\%[\s]\+Plug '\([a-zA-Z0-9@.:\-/]\+\)'.*#\1
" replace front-padded whitespace and " with # with optional space (\%[<match>]) in front of "
:%s/\s\+"\%[\s]/# <-- WARNING: notice space BEHIND "#"
" replace extra options from vim-plug
:%s/,\%[\s]{.*}//
" delete everything not a comment and not a repo-word
:v/^#\|[a-zA-Z0-9@.:-]\+\/[a-zA-Z0-9.-]\+/d
" lines that start with # are moved to bottom
:g/^#.*/normal ddGp
# one-line vim-plug to voom convert
:%s#^\%[\s]\+Plug '\([a-zA-Z0-9@.:\-/]\+\)'.*#\1#e | %s/\s\+"\%[\s]/#/e | %s/,\%[\s]{.*}//e | :exe 'v/^#\|[a-zA-Z0-9@.:-]\+\/[a-zA-Z0-9.-]\+/de' | g/^#.*/normal ddGp
:edit #reload file
:edit! #force reload file, discard modifications
vim -o file1 file2 #open files in windows
vim -O file1 file2 #open files in vertical splits
========== Navigation ==========
# selfhelp
" this page has lots of info on all kinds of normal mode commands
" both above and below ":help g"
# NOTE: Help always tries to only have 1 window per tab, which makes opening help above/below tricky.
:help user-manual
:help index
:help g
:help which
:helphelp
:help map-which-keys.
:help key-notation
:help map-special-chars.
:vsplit | help " Open new help in vertical spli
:tab help " Open help in a new tab
CTRL+C OR Ctrl+[ instead of ESC.
1/2 ½ BOL (Begin-of-line)
0 BOL (Begin-of-line)
_ First non-whitespace character on line
^ First non-whitespace character on line
$ EOL (End-of-line)
H Goto HEADER (Top of the screen)
M Goto MIDDLE of BUFFER
L Goto last (bottom).
CTRL+F Page down
CTRL+B Page up
CYRL+U Page up
CTRL+D Half Page down
(see :help scroll)
(Handy Page Up / Page Down for Mac where Fn+Up/Down is scrolling Term)
{x}zl Scroll X columns to right
{x}zh Scroll X columns to left
^ Cursor to first non whitespace character
g_ Cursor to last whitespace character
gg (BOF) Beginning of File
G (EOF) End of the file.
10G Goto line 10
10gg Goto line 10
:10 Goto line 10
fc Move forward to c (c= character)
Fc Move back to c
gd Goto Definition of Variable
[m Go to function opening
Ctrl+D Page-by-page scrolling
CTRL+O Last location (cursor)
CTRL-I Next location (cursor)
CTRL+^ Alternate file (last edited file in current window)
e# Edit alternate file (previous opened buffer)
vnew# Vertical split alternate file (previous opened buffer)
CTRL+R+# In Insert-mode insert filename of previous edited file.
* Next word (Cursor on word, press, and search)
# Previous word (Cursor on word, press, and search)
% on brackets {} () [] will find the matching one.
dw - delete word in front of cursor
diw - delete (inside) word (if your cursor is not at start of the word)
2dd - delete 3 lines
d3G - delete till line 3
S - delete line and start insert mode
cc - delete line and start insert mode
1dk - delete 2 lines (current and 1 above)
d2f. - delete to the second period.
d% - delete until next pair [, {, (, etc.
v$% - Select whole function (incl. function name)
vi{ - Select function contents
:n /folder/** Open all files (and directories) in folder as buffers (Delete directories and save session for projects)
# [], [[, ]] and ][ only supported on international keyboards move to next/prev set of braces (functions).
zz Cursor to center of screen
z. Cursor to center of screen
z- Cursor to bottom of screen
zb Cursor to bottom of screen
z Cursor to top of screen
zt Cursor to top of screen
# should work with ALTGR+8/9 + ( / { etc. on nordic keyboard
[{ jump to beginning of code block with {
[( jump to beginning of parenthesis
]) jump to end of parenthesis
}] jump to end of code block with }
In each window that should scroll simultaneously, enter the command:
:set scrollbind
========== Change ==========
I INSERT (at beginning)
A INSERT (at end of line)
go INSERT (at end of file)
ct, Change until ,
ci} Change inside brackets (Starting brace needs to be under cursor)
ci'<C-R>" Paste inside '' quotes with default " register
ya} Select including brackets (Starting brace needs to be under cursor)
vi} Select inside brackets (Starting brace needs to be under cursor)
dit Delete the text between matching XML tags. (it is for "inner tag block".)
cit Change the text between matching XML tags. (it is for "inner tag block".)
vi"p Replace string with quotes with yanked text
s Substitute char
S Substitute line
c2w Change the next 2 words
dgg Delete to top
dG Delete to bottom
d^ Delete to start of line
D Delete to end of line (or d$)
dt; Delete until ;
d/foo Delete until foo
d} Delete next p-graph, Delete function (cursor on function start line)
da" Delete quoted string
dap Within a body, will delete the paragraph/function definition
d{ Delete previous p-graph
"_dd Delete line without overwriting unnamed register (black hole register :help registers)
SHIFT-J Join below line to above ("LINE1\nLINE2" becomes "LINE1 LINE2")
# ^ overriden by VSurround? map S-j
cc Replace Line
S Replace Line
s Replace Letter (Delete then Insert Mode)
cw Replace word
c$ Replace to EOL
c/word Change word and put in INSERT mode.
c?word Change word (search backwards) and put in INSERT mode.
deep Swap two words in front of cursor (Cursor on empty space)
ddp Swap two lines
g- Undo Change
u Undo Change
g+ Redo Change
CTRL+R Redo Change
:earlier Undo by time
:later Redo by time
:undo n Undo by number of actions
:undolist Leaves of undo tree with numbers
y Copy marked text
Y Copy/Yank whole line
y$ Copy/Yank whole line
"Xyy Yank lines into X register
"Xp Paste from X register
2yy Copy 2 lines
yw Copy word
ALT+j Move current line UP
ALT+k Move current line DOWN
CTRL-6 Switch between open buffers
ggVG Select All
ggvG= Auto-indenting
== Indent current line
x Delete current character
CTRL+A Increment Number
1CTRL+A Increment Multi-Digit Number
CTRL+X Decrements Number
1CTRL+X Decrements Multi-Digit Number
CTRL+O (Insert-Mode) run normal mode commands and Ex-commands (:echo) temporarily in insert-mode.
:diffthis In two buffers/windows enables diffmode.
ggVGJ join all lines
~ Toggle case of the character under the cursor, or all visually-selected characters.
3~ Toggle case of the next three characters.
g~3w Toggle case of the next three words.
g~iw Toggle case of the current word (inner word – cursor anywhere in word).
g~$ Toggle case of all characters to end of line.
g~~ Toggle case of the current line (same as V~).
The above uses ~ to toggle case. In each example, you can replace ~ with u to convert to lowercase, or with U to convert to uppercase. For example:
U Uppercase the visually-selected text.
First press v or V then move to select text.
If you don't select text, pressing U will undo all changes to the current line.
gUU Change the current line to uppercase (same as VU).
gUiw Change current word to uppercase.
u Lowercase the visually-selected text.
If you don't select text, pressing u will undo the last change.
guu Change the current line to lowercase (same as Vu).
========== Windows ==========
Debug windows
echomsg bufnr()." ".winbufnr(bufnr())." ".bufwinnr(bufnr())." ".bufname()." ".win_getid()
Find windows containing bufnr 2
win_findbuf(2)
# Find Duplicate windows: All buffers containing current bufnr
win_findbuf(bufnr())
CTRL+H Window Left ̂
CTRL+L Window Right ̂
CTRL+J Window Down ̂
CTRL+K Window Up ^
CTRL+WW Switch between Windows
CTRL+WR Rotate
CTRL+WQ Quit window
CTRL+WV Split Windows Vertical
CTRL+WS Split window horizontal
CTRL-W+ Grow window
CTRL-W- Shrink window
CTRL+W_ Max height
CTRL + W| Max width
CTRL+W= Set all windows to equal size.
CTRL+W+R Rotate windows (swap left/right top/bottom)
CTRL+W+T Put window in a tab.
CTRL+W+O Fullscreen - Close every window but current one. (Zoom to current window?)
========== Macro ==========
q Record Macro
qa Run macro (a)
3@q Run macro 3 times
========== Navigation/Files ==========
:cwd Show current working directory
:lcwd Show current (Tab/Window) directory
:ls Show current buffers
:cd Change directory
:lcd Change current (Tab/Window) directory
:new will create a split window with an unnamed buffer.
:enew will open a new buffer
:vnew will open one in a vertically split window.
:tabnew will open one in a new tab.
vim scp://root@adrafinil//etc/udev/rules.d/10-network.rules
:find Find {file} in 'path' and then :edit| it.
:args *.sh # open all .sh files in path
:argadd *.sh # add all .sh files in path to buffers
" Most recent files (MRU) (short :ol)
:oldfiles
" Goto old file #2
:e #<2
" List the files that have marks stored in the viminfo file.
:browse oldfiles
:bro ol
" use ! behind oldfiles to abandon modified buffer
" Save section of buffer line 23-45
:23,45w part_of_a_page.txt
========== Visual commands ==========
CTRL+V Visual block mode
> Indent Right
< Indent Left
d Delete marked text
~ Switch case
V Select whole line
SHIFT-I Insert at beginning of selection on each line (i.e. column insertion)
SHIFT-S Substitute selection on each line
o Go to other end of selection
O Go to other end of selection
V<movement>gq Reformat <movement> to 80 chars
Vgq Reformat current line to 80 chars
g+CTRL-g Show: Selected 10 of 4123 Lines; 67 of 11111 Words; 400 of 40000 Bytes
========== Insert commands ==========
CTRL-R * will insert in the contents of the clipboard
CTRL-R " (the unnamed register) inserts the the last delete or yank.
CTRL-R : will insert last ex-command into the buffer
========== Commandline ============
CTRL+W Delete a word backward
========== Search / Replace ==========
/ Search
<SPACE> Search
? Backwards Search
n Next Search ¯
N Previous Search
c/word Change word and put in INSERT mode.
c?word Change word (search backwards) and put in INSERT mode.
:noh Turn off search until next search
:g//p List all /? search results
/\clowercasesearch Search for lowercase inverse uppercase \C
:/start/,/end/d Delete from start to end
/foo/+1 The line below the next line containing "foo"
/foo/;// Next match after foo (;// repeats search)
1;/foo The first line after line 1 containing "foo"
:1d 4 Delete 4 lines after line 1
:bufdo /searchstr/ Search in all open files
:bufdo %s/pattern/replace/ge | update Replace in all open files (http://vim.wikia.com/wiki/Search_and_replace_in_multiple_buffers)
/-dev\|-staging\|-test Alternate: search for both -dev -staging and -test
:s/old/new/g replace old with new on current line (s current line vs. %s all lines)
:%s/old/new/g replace all old with new throughout file
:%s/foo/bar/gi The same as above, but ignore the case of the pattern you want to substitute. This replaces foo, FOO, Foo, and so on.
:%s/old/new/gc replace all old with new throughout file with confirmations
:%s/foo/bar/c For each line on the file, replace the first occurrence of foo with bar and confirm every substitution.
:s/foo/bar/g 5 substitute foo to bar in current line and 2 lines below
:%s/\(good\|nice\)/awesome/g Replace good or nice with awesome.
:%s/foo/&bar/g SMART! Insert pattern with & result in replace foo with foobar
:/.*word1\&.*word2 Search for both words simultaneously
#You can use . for the current position, and .+10 for 10 lines down:
:.,.+10s/foo/bar/g
#You can use . for the current position, and .$ for until last line:
:.,$s/foo/bar/g
#You can use . for the current position, and 'M for until mark M:
:.,'Ms/foo/bar/g
:g/^%/s/foo/bar/g Replace every line starting with % with foo with bar
# replace space with newline - literally CTRL-V
:%s/ /<CTRL-V>/g
:sort u - remove duplicate lines
# highlight duplicate lines
:syn clear Repeat | g/^\(.*\)\n\ze\%(.*\n\)*\1$/exe 'syn match Repeat "^' . escape(getline('.'), '".\^$*[]') . '$"' | nohlsearch
:rs/foo/bar/a Substitute foo with bar. r determines the range and a determines the arguments.
:g/^#/d Delete all lines that begins with #
:g/^$/d Delete all lines that are empty
:g/^///d Delete all // comments
:g/^s*$/d Delete all whitespace lines
:v/foo/d Delete lines not containing 'foo'
:g!/price/d Delete lines not containing 'foo'
/test/+1 one line below "test", in column 1
/test/e on the last t of "test"
/test/s+2 on the 's' of "test"
/test/b-3 three characters before "test"
A very special offset is ';' followed by another search command. For example:
/test 1/;/test
/function/;/echo
/test.*/+1;?ing?
:ab mail mail@provider.org Define mail as abbreviation of mail@provider.org (replace when "mail" is written)
:%s/<Ctrl-V><Ctrl-M>//g Remove ^M from files.
:%s//Bar/g You can omit the search pattern if you already have a search active.
========== Marks ==========
'a - 'z lowercase marks, valid within one file
'A - 'Z uppercase marks, also called file marks, valid between files
'0 - '9 numbered marks, set from .viminfo file
m+[A-Z] marks the current line with an alias of the key pressed.
'[A-Z] goes to this mark.
http://vim.wikia.com/wiki/Using_marks
========= Session ==========
:mksession ~/mysession.vim
:source ~/mysession.vim
$ vim -S ~/mysession.vim
========== Misc ==========
. Repeat Command
0p Paste BOL
$p Paste EOL
*p Paste (without indentation) similar to :set paste
" Insert mode
CTRL+R " Paste unnamed/yank register (Insert Mode)
CTRL+R * will insert in the contents of the clipboard (:h i_ctrl-r)
CTRL+R #
CTRL+R : Will insert last cmdline (ex command) (useful for adding a recently typed command to vimrc)
" Normal mode
#p
ZZ Save and quit
g CTRL-G Show Col 1 of 0; Line 5 of 6; Word 1 of 11; Byte 968 of 1019
:help g_CTRL-G
:f Show bufname, modify-status,
"[No Name]" [Modified] line 6 of 6 --100%-- col 49
:help :f
:command show all functions/commands in vim (plugins, custom functions, etc.)
SHIFT+K "Man page" of command under cursor
:%!python -m json.tool - Format JSON pretty in current buffer via Python.
:bn Next Buffer
:bp Previous Buffer
:b # Goto # Buffer. (eg. ':b 1' goto buffer 1)
:b filename
:tab sball Opens a new tab for each open buffer #not recommended
gt Next Tab (normal mode)
gT Previous Tab (normal mode)
<C-PageDown> Next tab (insert mode)
<C-PageUp> Previous tab (insert mode)
:r Read from file into buffer
:r!shellcmd Read shell command into buffer
gf open file under cursor (or import statement)
<c-w>f open in a new window (Ctrl-w f)
<c-w>gf open in a new tab (Ctrl-w gf)
" Set tabline to current directory
:set tabline=[_%{getcwd()}_]
" Relative Directory
:set tabline=%{expand('%:p:h')}
Absolute Path
:set tabline=%{expand('%:p')}
File name
:set tabline=%{expand('%:t')}
" Generate tags (for goto definition, goto file, taglist) for PHP and template files (*.tpl)
ctags -R --languages=php --langmap=PHP:+.tpl .
ctags -R --languages=php --langmap=PHP:+.tpl --tag-relative=yes --PHP-kinds=+cf .
" Avoid loading vimrc/plugins
gvim -N -u NONE -i NONE (to check for .vimrc/_vimrc causing it)
" Who set filetype?
:verbose set filetype
" Who set map?
:verbose map <C-f>
" What is filetype set to?
:set filetype
:set filetype?
" Step-by-step autocmd go-through ..
:debug wincmd p
" Output Vim command to file (:buffers in this case)
:redir > outputFile
:buffers
:redir END
" Show character hex, octal, code under cursor
ga
" Quickfix Window (Compiler Messages etc.)
:cw
" Clear last search highlightning
set nohlsearch
" Reverse line order (explanation: http://vim.wikia.com/wiki/Reverse_all_lines)
:g/^/m0
" Pipe to vim
echo "lel" | vim -
" Show all "set" vim variables
:options
" Switch to ex command console mode
Q
" Profiling syntax files
:syntime on
# do heavy lifting or slow operations
:syntime report
" profiling
:profile
https://github.com/vim-syntastic/syntastic/blob/master/doc/syntastic.txt#L930
" Options descriptions (set option="")
:options
" buffer number
echo expand('#n')
========== Folding ==========
za Toggle folding
zA Toggle folding recursively
zc Close one or count folds under the cursor
zC Close all folds under cursor
zd Delete fold
zD Delete folds recursively
zE Delete ALL Folds
zf motion - Create a fold
zF Create a fold for count lines
zi Toggle foldenable
zM Close all folds, set foldlevel=0, set foldenable
zR Open all folds and set foldlevel to highest fold level.
zn Fold "none": reset foldenable and open all folds
zN Fold "normal": set foldenable and restore all folds
zo Open one or count folds
z0 Open all folds under the cursor
========== netrw / Explorer ==============
(Built-in filebrowser)
<leftmouse> open
<rightmouse> delete
d New directory
D Delete file(s)/directory(ies)
p Preview file
qb list bookmarks (and recent dirs) ?
mb make bookmark
mB delete bookmark
mf OR <s-leftmouse> Mark files
gb goto bookmark
md diff marked files
mp print marked files
mu unmark all
t enter file in new tab
1u go back 1 history (corresponds to qb-listing)
u forward one directory in history
U backwards one directory in history
# Preferred
:e rsync://user@host:/home/user/file.txt
:e scp://user@host//home/user/file.txt
========== Plugins / Extensions ==========
CTRL+J - SnipMate Trigger Snippet
CTRL+R+TAB - SnipMate Show Menu
Benchmark/Profiling Scripts
vim --startuptime vim.log
--- vim-surround ---
# cs = change surround
# ds = delete surround
# https://github.com/tpope/vim-surround/blob/master/doc/surround.txt
cs({ - change () to {} - (cursor inside)
ds" - remove " - y
#cst" - surround with "
cs'<b> - add <b> tag (on 'Text' only)
ysiw] - add [] to word (works for <b> tags too)
yss) - add ) to line (works for <b> tags too)
#Visual mode
S" - surround selection with "
gS" - surround with " with newlines before and after content
(V) select text, S<div class="wrap"> -- wrap in this tag
ysf[whitespace]" = "john" mickey
ys$" quote to end of line
--- vim-mucomplete ---
<c-h> and <c-j> switch between completion method (omni/keyword etc.)
================== Regex ======================
# Example of optional matching
# foo \t
# foo.txt \t Description
%s/\(\.\w\+\)\{-}\s.*// # Optional .ext
BTsync secrets vim regex
- magic vim "perl regex" operator
- A-Z 0-9
- times 33
- \< \> # means word boundary in-between (this is a word/string)
/\<[A-Z0-9]\{33}\>
# match any characters in brackets [ ] like [foo]
\v\[.{-}\]
# \v what is it? {-} is non-greedy
:g!/^[+-]/d
[g]lobally do something to all lines that do NOT [!] match the regular expression: start of line^ followed by either + or -, and that something to do is to delete those lines.
======= Win x32/x64 Optimizations NOTES =======
Download custom build from:
#http://tuxproject.de/projects/vim/ (32-bit, latest)
Haroogan/veegee are best for YCM compatibility and more..
https://bitbucket.org/Haroogan/64-bit-vim-builds-for-windows-64-bit/downloads (64-bit)
#http://sourceforge.net/projects/cream/files/Vim
#http://wyw.dcweb.cn/
====== Personal Hotkeys =====
Ctrl+K - Previous Error # Syntastic and so on
Ctrl+J - Next error
====== Completion =====
Ctrl-X Ctrl-F - filename/dir complete
Ctrl+X Ctrl+N - name complete
CTRL-X CTRL-L Search backwards for a line that starts with the
same characters as those in the current line before
the cursor. Indent is ignored. The matching line is
inserted in front of the cursor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment