Post your favorite Vim [1] tricks (or plug-ins or scripts). One trick per answer.
Try to come up with something other than the basics, btw. :D
In my ~/.vimrc
:
cmap w!! %!sudo tee > /dev/null %
Will allow you to use :w!!
to write to a file using sudo if you forgot to sudo vim file
(it will prompt for sudo password when writing)
Alternative that allows you to skip reloading the file:
cmap w!! w !sudo dd of=%
sudo: sorry you must have a tty to run sudo
. - Scottie T
/usr/bin/tee
? - pydave
sudo vim
. Better define EDITOR as vim (export EDITOR=vim
in your .bashrc) and run sudoedit. - Gerardo Marset
Using the built-in regions to change text quickly:
ci" -> Cut everything inside "" string and start insert mode
da[ -> Delete the [] region around your cursor
vi' -> Visual select everything inside '' string
ya( -> Yank all text from ( to )
The command and type of region can all be used interchangeably and don't require .vimrc editing. See :help text-objects
.
da<
Delete the HTML tag the cursor is currently inside of – the whole tag, regardless of just where the cursor is.
ci"
Change the content of a doublequote-delimited string.
Etc etc, along the same lines. See
:help text-objects
[1].
yi{
to copy the text from one block, move the to target block, and vi{p
to overwrite it. - naught101
Shortcuts to quit the Insert mode:
Ctrl+C Leave insert mode (faster than Esc)
Ctrl+O Leave insert mode just for the duration of one command
Ctrl+O Shift+I Leave insert mode, go to beginning of line, and return to insert mode
Ctrl+O Shift+A Leave insert mode, jump to end of line, and return to insert mode
*
Highlight all occurrences of word under the cursor, and move the the next one. #
Searches backwards.
nnoremap <silent> <C-l> :nohl<CR><C-l>
- pydave
gd
(which stands for "goto definition") will search for all occurances of the word under the cursor, and immediately go to the first occurance of the word in the current file. - Graphics Noob
[I
list all lines found in current and included files that contain the word under the cursor.
:help [
and scroll down a bit. - Fred Nurk
Correctly indent the entire file currently open.
gg=G
Note that you may need to do :set filetype=<whatever>
and then :filetype indent on
before this will work. Unless they're already specified in your .vimrc file.
Ctrl-N / Ctrl-P
Auto-complete - searches current file for words beginning with the characters under the cursor. Great for finishing long func/var names. Will also search other files you've opened during that session.
.
(period)
Repeats the previous change
:%s/search/replace/g
Global Search and replace
args
and argdo
to apply the search and replace to more than one file! - chands
:e!
Reopen the current file, getting rid of any unsaved changes. Great for when a global search and replace goes awry.
tail -f | less
? - Christian Mann
Ctrl-A / Ctrl-X
Skip to the next number on the line and increment/decrement it. Has a C-like idea of what's decimal, hex or octal. The "skip to the next number" part is what makes this feature really useful, because it potentially saves several keystrokes getting the cursor to the right place.
Ctrl-A Ctrl-A
as Ctrl-A
is meta character for GNU Screen. - Jeffrey Jose
escape ^zz
in your .screenrc - Marten Veldthuis
macros
Record:
q<some key>
<edit one line and move to the next>
q
Play:
@<some key>
@@ (play last macro)
100@<some key> (apply macro 100 times)
EDIT: A slightly complex example might be helpful to get an insight into the power of macros.
Given an array (in C) of 32-bit integers in little endian, we want to convert it into big endian.
uint32_t littleEndian[] = {
0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
...
0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef
};
Now goto the first data line of the array (the line after uint32_t ...) and type (with the RETURN after ..6@b)
0fxqal2xbpfxq2u0qbfx4@axbpq3u0qc6@b
q9@c
if the array has 9+1 lines with six 4-byte integers in each line.
(Explanation, if you are not fluent in vim:
Maybe this example is too complex for "real life", but it should give you an idea about how powerful macros can be.
100@<key>
plays the macro 100 times, not for 100 lines. It's a small but important difference. If your macro doesn't advance to the next line then you just keep applying the cahnge to the same line over and over, or if your macro is based on found words, multiple lines, etc it will vary. - camflan
Change the lineendings in the view:
:e ++ff=dos
:e ++ff=mac
:e ++ff=unix
This can also be used as saving operation (:w alone will not save using the lineendings you see on screen):
:w ++ff=dos
:w ++ff=mac
:w ++ff=unix
And you can use it from the command-line:
for file in $(ls *cpp)
do
vi +':w ++ff=unix' +':q' ${file}
done
for file in *.cpp
- Fred Nurk
:set ff=unix
, then later :w
? - blueyed
=%
Indents the block between two braces/#ifdefs
=ib
and =iB
to indent inside parenthesis and curly-braces respectively. =%
is still good for non-brace matches, though. - nocash
My favorite is:
CTRL-A: Increment a number under the cursor. 99 becomes 100.
CTRL-X: Decrement a number under the cursor. 100 becomes 99.
It's really cool.
0.0
gives you -1.0
or 0.-1
and you are very likely to hit CTRL-Z every once in a while - puk
:%s//replace/g
will replace the last term that was searched for, instead of you having to type it again.
This works well with using * to search for the word under the cursor.
Never underestimate the power of percent.
Basically, it jumps to matching brace (booooring), but when the cursor is not on a brace it goes to the right until it finds one, which is my excuse to call this post a trick.
[x]
means the cursor is on x.
[s]omeObject.methodYouWouldLikeToDelete(arg1, arg2) + stuffToKeep
just type d% to get
[ ]+ stuffToKeep
Obviously, it works with (), [] and {}.
Another examples of percent-not-on-paren:
[m]y_python_list[indexToChange, oneToLeave]
%%lce
fun[c]tion(wrong, wrong, wrong)
%cib
running shell commands on the current file without having to exit, run the command and open it again:
:%!<command>
for example,
:%!grep --invert-match foo
gets rid of all lines containing "foo"
:%!xmllint --format -
nicely tab-ifies the current file (if it's valid xml)
and so on...
Useful in your vimrc,
set directory=/bla/bla/temp/
Makes vim keep its temporary files in /bla/bla/temp instead of in the directory with the file being edited.
.swp
file - Jeffrey Jose
Copy to system clipboard:
"+y
Paste from system clipboard:
"+p
Move between wrapped lines (it's a good idea to map those):
gj
gk
And for my favourite:
:Sex
Split and explore!
:mak
Executes "make" and then will jump to the file that contain the compile errors (if any).
:make
is the command. Unambiguous shorter terms are allowed, so :mak
works. - Paul Biggar
make
and then I thought to myself, vim would be able to do this for me. here's my answer. Thanks - Jeffrey Jose
When doing a search, there are ways to position the cursor search-relative after the search. This is handy for making repeated changes:
/foo/e
Finds foo and positions the cursor at the last 'o' of foo
/myfunc.\*(.\*)/e-1
Finds myfunc and places the cursor just before the closing brace, handy for adding a new argument.
/foobarblah/b+3
finds foobarbarblah and puts the cursor at the beginning of bar
This is handy if you decide to change the name of any identifier (variable or function name) - you can set it up so the cursor is on the part that needs to be changed. After you've done the first one, you can do all the rest in the file with a sequence of 'n' (to repeat the search), and '.' (to repeat the change), while taking only a second to make sure the change is applicable in this spot.
\zs
to place the cursor at an arbitrary position in the match eg /\(foo\)\+\zs\(bar\)\+/
will always put you at the border between the foos and bars in foofoofoobarbar foobarbarbar foofoobarbarbar, etc. - rampion
Ctrl+]
Equivalent to "Go to Definition" in an IDE (one must first create the tags file using e.g. ctags [1]).
Ctrl+T
Pops to the previous element in the tag stack, i.e., the location and file you were in right before you hit Ctrl+].
:help tagsrch
for more details.
I have the following in my vimrc:
nmap <F3> <ESC>:call LoadSession()<CR>
let s:sessionloaded = 0
function LoadSession()
source Session.vim
let s:sessionloaded = 1
endfunction
function SaveSession()
if s:sessionloaded == 1
mksession!
end
endfunction
autocmd VimLeave * call SaveSession()
When I have all my tabs open for a project, I type :mksession. Then, whenever I return to that dir, I just open vim and hit F3 to load my "workspace".
As stated in another Thread, with the same Question:
Ctrl + v -- row visual mode Shift + i -- insert before type text Escape Escape
(Inserts the typed in text into multiple lines at the same time.)
In insert mode:
Ctrl+Y
Inserts the character that is above the cursor at the current cursor position and moves the cursor to the right. Great for duplicating parts of code lines.
Ctrl-E
to insert the character below. - blueyed
:g/search/p
Grep inside this file and print matching lines. You can also replace p with d to delete matching lines.
Ctrl-X then Ctrl-F (while cursor on a path string)
searches for the path and auto-completes it, with multi-optional selection.
My favourite feature is the :g[lobal]
command. It goes to every line that matches (or does not match) a regex and runs a command on that line. The default command is to simple print the line to the screen, so
:g/TODO:/
will list all the lines that contain the string "TODO:". If use the default command then you can leave the last slash off.
The commands can also have their own ranges which will be relative to the current line, so to display from each TODO: to the next blank line you can do this:
:g/TODO:/ .,/^$/p
(p is short for :print).
And to save all the TODO: blocks to another file:
:g/TODO:/ .,/^$/w! todo.txt >>
(Explanation: :w means write to a file, ! means create it if it does not exist, and >> means append if it does exist.)
You can also chain commands with the | operator, e.g.
:g/TODO:/ .,/^$/w! todo.txt >> | .,/^$/d
will write the block to "todo.txt" then delete it from the current file.
Also see this answer [1] for more examples.
[1] http:////stackoverflow.com/questions/2070120/search-and-delete-multiple-lines/2070282#2070282COMMENTING A BLOCK OF LINES IN VISUAL MODE
add the lines below to your .vimrc file, go into visual mode w/ "v", and hit "c" to comment the lines or "u" to uncomment them, this is insanely useful. the lines below make this possible for C, C++, Perl, Python, and shell scripts, but it's pretty easy to extend to other languages
" Perl, Python and shell scripts
autocmd BufNewFile,BufRead *.py,*.pl,*.sh vmap u :-1/^#/s///<CR>
autocmd BufNewFile,BufRead *.py,*.pl,*.sh vmap c :-1/^/s//#/<CR>
" C, C++
autocmd BufNewFile,BufRead *.h,*.c,*.cpp vmap u :-1/^\/\//s///<CR>
autocmd BufNewFile,BufRead *.h,*.c,*.cpp vmap s :-1/^/s//\/\//<CR>
Edit command lines with vim commands under the bash shell
$ set -o vi
Now you can edit command lines using the vim syntax!
Example:
The other day I discovered that Vim has a "server mode". Run a command using
vim --servername <name> <file>
This will create a Vim server with the name . A regular instance of Vim then starts, but other programs can then communicate with the instance of Vim which you are then using. This probably won't help most people, but some programs can make use of this. With Jabref, for example, you can use this feature to push references directly from you bibliography manager (Jabref) into your document which you are editing with Vim.
vim --serverlist
will list all the Vim servers running at that time.
vim --remote
allows you to connect to an already existing Vim server. There are several different --remote commands to do things like commands to the server.
%
Brace/parentheses match.
If you have the cursor on a parenthesis/brace/etc ((){}[]
), and hit % it will jump to the corresponding one.
When I use vim for writing a tidy journal, notes, etc
!}fmt
to format the current paragraph.
Read contents of an external command into the doc:
:r !ls
Shift-~
switches the case of the letter under cursor (and moves right, which allows switching a whole line or combining with the "next number/word" command)
Delete all blank lines in a file:
:g/^$/d
Putting options in comments in a file to be edited. That way the specific options will follow the file. Example, from inside a script:
# vim: ts=3 sw=3 et sm ai smd sc bg=dark nohlsearch
Knowing that the Windows clipboard buffer can be accessed with:
"*
has saved me lots of boring entering-insert-mode shenanigans. Also copy/pasting between vi sessions can be done with:
"+
Jumps.
m[a-z]
Mark location under [a-z]
`[a-z]
Jump to marked location
``
Jump to last location
g;
Jump to last edit
:normal(ize)
plays back all the commands you pass to it as if they were typed on command mode.
for example:
:1,10 normal Iabc^[Axyz
Would add 'abc' to the beginning and append 'xyz' to the end of the first 10 lines.
note: ^[ is the "escape" character (tipically ctrlv+ESC on Unix or ctrlq+ESC on Windows)
:1,10 normal @a
to play back the macro recorded in register a. - Nathan Long
set backup
set backupdir=~/backup/vim
Puts all backup files (file.txt~) in the specified directory instead of cluttering up your working directories.
gd
moves the cursor to the local definition of the variable under the cursor.
gD
moves the cursor to the global definition of the variable under the cursor.
If you have multiple lines and want to append the same text to all lines you can use Ctrl-V to start the visual block mode, move to select the lines, then press $ to extend the selection to the end of the line and the press A to append text (enters insert mode). When you exit insert mode (ESC) the typed text will be appended to all selected lines.
This is useful e.g to append semi-colons and other stuff you need to do when programming.
Summary:
PS: use I in visual block mode to insert text in multiple lines
[[
- Beginning of the current function block.
]]
- Beginning of the next funcion.
[{
- Beginning of the current code block.
]}
- End of the current code block.
z<CR>
- position the current line to the top of the screen.
zz
- position the current line to the center of the screen.
z-
- position the current line to the bottom of the screen.
:%j
To join all lines into a single line.
Remove whitespace from line endings on save.
" Remove trailing whitespace from code files on save
function StripTrailingWhitespace()
" store current cursor location
silent exe "normal ma<CR>"
" store the current search value
let saved_search = @/
" delete the whitespace (e means don't warn if pattern not found)
%s/\s\+$//e
" restore old cursor location
silent exe "normal `a<CR>"
" restore the search value
let @/ = saved_search
endfunction
au BufWritePre *.c call StripTrailingWhitespace()
Put this in your vimrc, and add auto-commands for any file types you want to remove extra whitespace from. The last line above makes this remove trailing whitespace from C files.
g-
Go to previous text state. What does it mean? Browse through all undo branches with g-
(previous change) and g+
(next change).
So if you undo twice in your text, then happen to change something, you suddenly have an undo/redo tree where you can't reach all branches with undo(u
)/redo(Ctrl-r
), but with g+/g- you can browse through all revisions!
Enter a number before any command to repeat it N times. For example:
7dd <-- will delete 7 rows
7 arrow down <-- moves down 7 times
4cw <-- removes the 4 next words and puts you in edit mode to replace them
This is in my opinion the most powerful feature of them all :-)
v
Visual mode for selecting text to copy, delete, etc.
Using Esc all the time is going to cause RSI or something, I'm sure...plus its not fast enough for me.
Instead, in my .vimrc I have
map! ii <Esc>
For the very few times I need to type 'ii', I just need to type i 3 times, which types one i, exits to normal mode, then another i to type a 2nd i.
ft
move to the next occurrence of t
and ;
and ,
to move to forward and backward
tt
to move to the char before t
;
and ,
work here too.
When you have a file (or lots of files) open and the computer crashes, you end up with annoying swap files and you have to open the originals one at a time to see if there are any unsaved changes. The problem is that you've got to hit "r" for "recover", then write out the buffer to a new file, then diff with the original... what a pain!
Here's something nice which cuts down on the last few steps:
Put the following in your .vimrc file:
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
Then after you recover the file, type :DiffOrig to view the changes from the saved version.
From the vim docs: http://vimdoc.sourceforge.net/htmldoc/diff.html#:DiffOrig
in escape mode:
xp - swaps the character under the cursor with the character in front of the cursor.
Xp - swaps the character under the cursor with the character behind the cursor.
Probably too simple for this crowd, but my favorite little vi trick is ZZ
to save and exit. Basically it is the same as :wq
, but can be done one handed.
I suppose the next thing is to colorize tabs so they can be easily distinguished from spaces when working with python code. I'm sure there are better ways to do this, but I do it by putting this in ~/.vim/syntax/python.vim:
syntax match tab "\t"
hi tab gui=underline guifg=blue ctermbg=blue
--jed
VimGolf @ http://vimgolf.com
Yes, shilling for own project, but it is a great way to learn Vim. Pick a challenge and try to do your best.. each time you submit, you'll unlock entries above you. Great way to pickup new tricks.
u <-- undo :-)
vim -o file1 file2 ...
To open multiple files at once in separate panes.
-O
to open in vertical panes and -p
to open in tabs. (I like this one a lot ;) - David Winslow
I don't see buffers mentioned, so I'll mention them.
I finally got around to trying out Emacs the other day, and discovered buffers. I thought, wow, these are awesome, I wish VIM could do this. With a search I discovered that VIM can! For them to work, you may need to do
:set hidden
first, or add "set hidden" to your vimrc file.
Quick:
:ls -- List buffers
:ls! -- List ALL buffers
:bn -- Open next buffer
:bp -- Open previous buffer
:bf -- Open first Buffer
:bl -- Open last buffer
:b # -- Open buffer
:bd # -- Close buffer (# optional)
:bad <name> -- New buffer named <name>
(# represents the buffer number listed via :ls)
and of course:
:help buffers
Windows are also extremely useful when dealing with buffers (Described in "help buffers")
imap jj <esc>
This will make it so that instead of esc you hit jj. Your hands are always on the home keys, you also are instantly moving around using hjkl(arrow keys) and until you get into some funky matrix loops you never use jj.
:e %<.cpp
to open myfile.cpp when currently myfile.h is open. Replace :e by :sp to split the window instead of replacing the whole window.
I figured out a basic method for Vista or 7 that has the same effect as %!sudo tee > /dev/null %
, hoping it would be useful for vim users using Vista/7.
The previous 2 versions(I removed them) were buggy. Here is the newest.
function ElevatedWrite() let tempf = tempname() let targetf = expand('%:p') let lines = getline(1, line('$')) call writefile(lines, tempf) execute '!hstart /UAC /NOCONSOLE "' . 'cmd /c copy /Y ' . shellescape(tempf) . ' ' . shellescape(targetf) . ' /B"' checktime endfunction
A program named HSTART [1] is needed.
P.S. I used to use the silent
command in conjuction with checktime
, but it has the same "problem" as system()
does -- it seems that vim won't wait them to end before it execute the next command, which makes checktime
get called before copy is done. (or it may be because of the UAC popup.)
I really like the VTreeExplorer [1] script for viewing portions of the folders and files in a tree view, and snippetsEmu [2] to get TextMate-like bundles.
My favorite color scheme for the moment is VibrantInk [3].
[1] http://www.vim.org/scripts/script.php?script_id=184ZZ - Save & Exit
o - add blank line below current one and go to insert mode
I know it's basic, but my favorite vi feature is still the % key, which lets you find matching braces, brackets, or parentheses. I still remember learning it from a sentence in a Perl book by Larry Wall which said something about "at least if you do this you'll let some poor schmuck bounce on the % key in vi." I looked it up, saw what it did, and I was hooked.
It's been nearly ten years, and I still obsessively bounce on the % key while I'm sitting and thinking about what to do next, not to mention to help me match up code blocks and parentheses.
Knowing that Ctrl+Q
in gVim on Windows inserts a control character. For example, I often want to replace ^M
characters at the end of lines. It took me a while to find the correct keystroke (Ctrl+P
does not work since that's the shortcut for Paste).
:syn on
For turning on syntax highlighting
:set foldmethod=syntax
To set the code folding method to be based on the language syntax, provided that the syntax is available for your language of choice. You can put this in your .vimrc file, omit the colon if you do.
zc
To close a particular fold (under the cursor)
zo
To open a particular fold (under the cursor)
zr
To unfold all folds by one level
zm
To collapse all folds by one level
zR
Unfold ALL folds
zM
collapse ALL folds
cw
"change word" while editing config files!
#
Search backwards in the file for the word under the cursor. Useful for finding declarations.
Read/write pdf files with Vi as if they were text files: http://vim.wikia.com/wiki/Open_PDF_files
In your ~/vimrc (or c:_vimrc for Windows), add the following lines:
" set characters shown for special cases such as:
" wrap lines, trail spaces, tab key, and end of line.
" (must be turned on whith set list)
set listchars=extends:»,trail:°,tab:>¤,eol:¶
Then you can type in the command to toggle displaying tabs, trail spaces and eol as special characters:
set list
Add these settings to enable normal move around keys back to the previous line or the next line cross eol:
" Set moving around at the end of line back to previous line by
" <backspace> key and coursor keys, and normal movememt h and l keys
set whichwrap=b,s,<,>,h,l
Enjoy VIM!
gqap
reformats an entire paragraph to match the current textwidth, pretty useful for plain text of LaTeX-docs.
[d
to show the definition of a macro
[D
to show the definition of a macro along with where it was defined.
viwp - replace the word under the cursor with what's in the unnamed register.
What's nice about this is that you don't need to be at the beginning of the word to do it.
vmap // y/"
Search for the visually selected text.
I am using this snippet in my .vimrc to select a block of code and adjust indentation by pressing < or > multiple times.
" keep selection on indenting in visual mode
vmap > :><cr>gv
vmap < :<<cr>gv
How about this one I found in The Pragmatic Programmer [1] that sorts 4 lines with the sort command (starting at the line the marker is at):
:.,+4!sort
Or just mark a section with visual mode and then type !sort:
:'<,'>!sort
Kind of cool and useful to sort a headerfile or some includes.
Edit: This is a Unix hack, the Windows port can't call shell commands (?)
Edit: Thanks to Luc Hermitte who pointed out that this should work under Windows as well. So I found a Windows XP with a working gVim installation and tried it. I found out that both !sort and :sort did work.
Very nice :-)
[1] http://en.wikipedia.org/wiki/The%5FPragmatic%5FProgrammerCount the number of matches for the search text:
:%s/search/&/g
Or, leave out the trailing g to count the number of lines the search text occurs on.
As of now my favorite command is probably :retab
. It lets you convert from tabs to spaces and from spaces to tabs. You can check out :help retab
for more details.
Font selection using your system UI, straight from the docs:
For Win32, GTK, Motif, Mac OS and Photon:
:set guifont=*
will bring up a font requester, where you can pick the font you want. In MacVim
:set guifont=*
calls::macaction orderFrontFontPanel:
which is the same as choosing "Show Fonts..." from the main menu.
See :help guifont
for more details. Also,
Inconsolata
[1] is one of the best fixed-width fonts out there.
A tip useful for beginners: I use search combined with other actions. For example to convert
A Lazy Brown Fox
to
A Brown Fox
when currently the cursor is at the end of the line, I would use ?La and enter to jump to Lazy and then dw to delete the word. Next, if I want to delete Brown
, I could use dw or I could use d/Fox to delete till the first occurrence of Fox and enter. To delete till the second occurrence of Fox, use 2d/Fox.
Using
set incsearch
set hlsearch
in vimrc is useful for highlighting searches as they are going on.
gqip
Reformat current line. Use it all the time to reformat comments in code, etc.
gqq
formats only the current line, whereas gqip
actually formats a whole paragraph.
gqip
means: format (gq
) the inner content (i
) of the current paragraph (p
) - ngn
Reaching up to hit ESC all the time is much too slow. I use TAB instead. Put this in your .vimrc:
imap <tab> <esc>
CAPSLOCK is even better if you don't already have that remapped to CTRL.
I never type literal tabs in insert mode so haven't bothered with this but if someone could replace this sentence with how to swap ESC and TAB (or CAPSLOCK), that would be super handy.
v
Visual mode for selecting text to copy, delete, etc.
i also find ctrl+v for visual block and shift+v for visual line quite useful
:ts to search for tags in C/C++
xp
transpose two characters.
e.g. 'teh' move cursor over the 'e' and type 'xp' (x=cut, p=paste cut buffer)
y (or yy) yank a line into the buffer
d (or dd) delete line (and put in buffer)
p put/paste the buffer
really, handy when combined with multipliers.
5yy [move cursor] p copy 5 lines
Vimrc to highlight tabs:
syntax match Tab /\t/
hi Tab guifg=yellow ctermbg=white
dG - delete to the end of the file :vsplit file2 - show current file and file2 side by side. Could also open file1 and file2 at the same time with -o (horizontal split) or -O (vertical split) options
:vsplit [filename]
opens an additional page side by side with the current page (vertically splitting the window).
also:
:split [filename]
opens an additional page, horizontally splitting the current page.
you can move between pages with ctrl+w -> Arrow keys
With vim 7 I love vimgrep.
For example to search for myfunc in all my files under my project I do.
:vimgrep /myFunc/j **/*.cpp
The /j means don't jump to the first find. */.cpp means recursively search only .cpp files.
To view the results you just use the quick fix window
:cw
I've been using vim <branch/tag/rev>:path
with
git:file.vim
[1] a lot lately.
Using gq} to format comments is also one my favorite vim tricks not found in the original vi.
[1] http://www.vim.org/scripts/script.php?script_id=2185I wrote a function to go to the Most Recently Used tab page like Ctrl-a Ctrl-a in screen does or Alt-Tab in common window managers.
if version >= 700
au TabLeave * let g:MRUtabPage = tabpagenr()
fun MRUTab()
if exists( "g:MRUtabPage" )
exe "tabn " g:MRUtabPage
endif
endfun
noremap <silent> gl :call MRUTab()<Cr>
endif
ZZ = :wq
ZQ = :q!
Ctrl+w Ctrl+]
splits current window to open the definition of the tag below the cursor
Page Up/Down From Home Row
I'm always using C-f
and C-b
to move around, so it's better to map to the home row keys. The following .vimrc settings will set PageUp to to C-k
and PageDown to C-j
.
noremap <C-k> <C-u>
noremap <C-j> <C-d
Enhanced Tab View
Most programs have Tabs now, so why not enabled vim Tabs?
How to use it:
Ctr-t opens new tab
Ctr-h activate tab left of current
Ctrl-l activate tab right of current
Alt-1 to Alt-0 jump to tab number
Add in your .gvimrc/.vimrc:
set showtabline=2 " always show tab bar
set tabpagemax=20 " maximum number of tabs to create
Add in your .vimrc
" new tab
nnoremap <C-t> :tabnew<cr>
vnoremap <C-t> <C-C>:tabnew<cr>
inoremap <C-t> <C-C>:tabnew<cr>
"tab left
nnoremap <C-h> :tabprevious<cr>
vnoremap <C-h> <C-C>:tabprevious<cr>
inoremap <C-h> <C-O>:tabprevious<cr>
nnoremap <C-S-tab> :tabprevious<cr>
vnoremap <C-S-tab> <C-C>:tabprevious<cr>
inoremap <C-S-tab> <C-O>:tabprevious<cr>
"tab right
nnoremap <C-l> :tabnext<cr>
vnoremap <C-l> <C-C>:tabnext<cr>
inoremap <C-l> <C-O>:tabnext<cr>
nnoremap <C-tab> :tabnext<cr>
vnoremap <C-tab> <C-C>:tabnext<cr>
inoremap <C-tab> <C-O>:tabnext<cr>
"tab indexes
noremap <A-1> 1gt
noremap <A-2> 2gt
noremap <A-3> 3gt
noremap <A-4> 4gt
noremap <A-5> 5gt
noremap <A-6> 6gt
noremap <A-7> 7gt
noremap <A-8> 8gt
noremap <A-9> 9gt
noremap <A-0> 10gt
Put these two lines in your .vimrc:
map <C-J> zzjzz
map <C-K> zzkzz
Use Ctrl-J/Ctrl-K to scroll up and down while keeping your cursor in the middle of the visible range.
When updating my "blog" at work (which is just an html file) I do ":r !date" to get a timestamp.
If I find myself doing a repeated operation, I will often remap ctrl-O (which isn't used so far as I know by any vim thing) via the :map command, using ctrl-V to escape the ctrl-O.
So, for example, if I have a list of things
x y z
(and maybe 20 more things)
and I want to convert that to C code like:
printf("x = %d\n", x); printf("y = %d\n", y); printf("z = %d\n", z);,
etc.
I might do:
:map ^V^O yypkIprintf("^V^[A = %d\n", ^[JA);^[j
(ok, I didn't test the above, but, something like that.)
Then I just hit ctrl-o, and it converts each line from
x
to
printf("x = %d\n", x);
Then, if I want to kill emacs, I head over to http://wordwarvi.sourceforge.net
Here's a pattern that I use a lot in keymaps. It brackets the current visual selection with a PREFIX and a SUFFIX.
vnoremap <buffer> <silent> ;s <Esc>`>aSUFFIX<Esc>`<iPREFIX<Esc>
Breaking it down, since that looks like line noise.
vnoremap Visual-mode keymap; no further expansion of the right-hand side
<buffer> Buffer-local. Won't apply in other buffers.
<silent> Mapping won't be echoed on the Vim command line
;s Mapping is bound to sequence ;s
<Esc> Cancels selection
`> Go to end of former visual selection
aSUFFIX<Esc> Append SUFFIX
`< Go to beginning of former visual selection
iPREFIX<Esc> Insert PREFIX
For example:
vnoremap <buffer> <silent> ;s u`>a</a><Esc>`<i<a href=""><Esc>
brackets the visual selection with an HTML anchor tag.
I always set my keyboard to swap Caps Lock and Escape.
With the standard Ubuntu/GNOME desktop, go through the menus: System -> Preferences -> Keyboard -> Layouts tab. Then hit the "Layout Options" button, click on the triangle next to "Caps Lock key behaviour" and select "Swap ESC and CapsLock".
Not strictly part of Vim, but makes Vim so much nicer to use.
And other than that, use Vim for everything. Some useful extensions to allow more Vim usage:
etc.
[1] https://addons.mozilla.org/en-US/firefox/addon/4125Here are some Vim [1] commands I use a lot.
gUU
Uppercase the current line.guu
Lowercase the current line.:%s/^I/\r/g
Change all tabs to newlines. (The ^I
is the tab character).Remap your caps lock key to control, and then use the easier to type Ctrl-[ shortcut instead of Escape to leave insert mode. Modern Linux distributions support keyboard remapping through the keyboard settings dialog, under Windows I use SharpKeys [1].
[1] http://www.randyrants.com/sharpkeys/The very best!
:set vb t_vb=
no more beep!
CTRL-O
and CTRL-I
goes back and forward in your jump history (also works between buffers!).
:grep foo -R *
then use :cn
and :cp
to jump between matches.
Also in .vimrc:
set autochdir
was important to me -- it tells Vim to change the current directory to the current buffer's directory.
This matters, for example, when I am in dir1
in the shell and start vim from there, then switch to some file in a different directory and try to do something like grep foo *
.
In *nix
K
opens the man page for the word under cursor. Nice for syscalls (try 2K
and 3K
) and C standard library. (nK
is manual section n)
:make
in a directory containing a Makefile. Then use :cn
and :cp
to jump between errors.
I currently use
:nnoremap <silent> gw "_yiw:s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/<CR><c-o><c-l>
for swapping words (When I mess up argument order or assignment sides, etc.), but this needs improvement as it doesn't always work very well. Also, I'm not sure if there's a nice way to swap two distant words (Anybody?).
EDIT:
Also I like keeping a text file in ~/.vim/doc
in vim's help format which I call cheatsheet.txt where I put some things I don't use very often so I forget, but are nice tricks or important functionality. For example:
*cheatsheet.txt* Some clever tricks that I want to find quickly
1. COMMANDS *cheat-commands*
*cheat-encoding* |++enc|
:e++enc=cp1251 Reopen file with cp1251 encoding
Then in vim i just do :help cheatsheet
(:helptags ~/.vim/doc/
needs to be done to rebuild the help tags) or :help cheat-encoding
(here, even tab-completion works).
The benefit of this is I have only things that I know are relative to me and I don't need to dig in the VIM documentation. Also, this could be used for stuff other than VIM-specific info.
Insert a comment before every line selected in visual line mode.
First, select the lines which need commenting out in visual line mode (SHIFT + V).
Then type this (substitute your own comment symbol):
:s/^/#
Removal:
:s/^#//
:s/^/#/
- I use this one all the time. - Hamish Downer
A "append at the end of the line
The A command was a productivity buster for me. It replaces $a commands. Sorry if it was mentioned before.
If you are using KDE and want to paste from system clipboard you can use CTRL-R +
in insert mode or "+p
in normal mode.
You can also use CTRL-R *
in insert mode / "*p
in normal to paste the selection buffer (mouse's middle button).
Leader key definition:
let mapleader = ","
Remaoing j/k to work properly with very long lines:
nnoremap j gj
nnoremap k gk
Remap something less painful to mimic ESC functionality
imap jj <ESC>
xmodmap -e "clear lock";
xmodmap -e "keycode 0x42 = Escape"
- naught101
NNyl <-- copy NN characters to the right beginning with the cursor position (ie. 7yl to copy 7 characters)
p <-- paste the characters at the position after the cursor position
P <-- paste the characters at the position before the cursor position
I have this in my .vimrc file -- it's helpful for doing Ruby programming.
map R :wall!:!ruby %
This lets me press 'R' and have the file saved and then execute the file in the Ruby interpreter.
At the ex prompt you have command history using up/down arrows.
In my vimrc file:
" Moves this window to the left, center, or right side of my monitor.
nmap ,mh :winpos 0 0<cr>
nmap ,ml :winpos 546 0<cr>
nmap ,m; :winpos 1092 0<cr>
" Starts a new GVim window.
nmap ,new :!start gvim<cr>
I have some shortcuts, ie:
1.Sort a file with a few way
map ,s :%!sort<CR>
map ,su :%!sort -u<CR>
map ,si :%!sort -f<CR>
map ,siu :%!sort -uf<CR>
map ,sui :%!sort -uf<CR>
map ,sn :%!sort -n<CR>
map ,snu :%!sort -n -u<CR>
2.Open new file from current path with vertical split
map ,e :vsp .<CR>
3.Grep file with match
map ,g :%!grep
4.Change show file modes
map ,l :set list<CR>
map ,L :set nolist<CR>
5.Turn on/off highlight
map ,* :se hls<CR>
map ,8 :se nohls<CR>
6.Turn on/off numbering
map ,n :se nu<CR>
map ,N :se nonu<CR>
7.Run - perl
map ,p !perl<CR>
map ,P gg!Gperl<CR>
8.Copy file to specified server
map ,scp :!scp % user@example.com:~/some_folder/
To turn auto indent on/off for pasting with add the following to the .vimrc:
nnoremap <F2> :set invpaste paste?<CR>
imap <F2> <C-O><F2>
set pastetoggle=<F2>
That will give you a visual cue as well
Well, I know the author said no basic.. but I didn't know this one even if I knew less-basic one. Just use o to begin insert a new-line after the present line.. I used to do something like, $a (go to the end, start writing, and create new line).. So now, only o does this :) And by the way, O insert a new line on the present line instead of inserting it after the current.
Editing multiple files simultaneously is very useful.
:sp filename
opens another file name in the same window
ctrl + W (arrow key)
will take you the other window depending on its location
:windo wincmd H (or V)
tiles the windows horizontally (or vertically)
Also, I use . a lot It repeats the last executed command.
:%s/^V^M^M
=> remove CR (DOS/Windows => Unix text format)
(^V = Ctrl-V etc.)
]m [m - for next/previous method start
]M [M - for next/previous method end
They actually match the first and second level of closing/opening braces.
I keep a backup of all my files I edit in Vim using the commands below:
set backup
set backupcopy=yes
set backupskip=/tmp/*,~/.vim/backup/*
set backupdir=~/.vim/backup
au BufWritePre <buffer> let &backupext = '~' . localtime()
function! DeleteOldBackups()
" Delete backups over 14 days old
call system('find ~/.vim/backup -mtime +14 -exec rm "{}" \;')
endfunction
au VimLeave * call DeleteOldBackups()
The code will dump all files in to ~/.vim/backup
, tag them with a Unix timestamp, and delete backups over 14 days old.
It uses the Unix find
command. If anyone can tell me how to use Vim built-in commands, please do so :) Otherwise, this will only work on Unix systems!
CamelCase Motion. Let's you move through and delete/edit CamelCase words.
http://www.vim.org/scripts/script.php?script_id=1905
gg = G (go to top of file and tidy the format) very usefull :D
Indent source line(s) one tab to the left or right
> - Left
< - Right
Remove trailing white-space once the file is saved
Add this to your .vimrc file:
au BufWritePre * silent g/\s\+$/s///
Edit another file without saving changes made to the file currently being edited:
:set hidden
Some times I open files with vim to delete all trailing white spaces: (particularly heplful for git users aswell :)):
:%s/\s\+$//g
If you want to highlight trailing whitespaces (grey color), add the following to your .vimrc:
highlight TrailingSpaces ctermbg=grey guibg=grey
match TrailingSpaces /\s\+$/
Switch spellcheck languages
The function:
let g:myLangList = [ "none", "it", "en_us" ]
function! MySpellLang()
"loop through languages
if !exists( "b:myLang" )
let b:myLang=0
endif
let b:myLang = b:myLang + 1
if b:myLang >= len(g:myLangList) | let b:myLang = 0 | endif
if b:myLang== 0 | setlocal spell nospell | endif
if b:myLang== 1 | setlocal spell spelllang=it | endif
if b:myLang== 2 | setlocal spell spelllang=en_us | endif
echo "language spell:" g:myLangList[b:myLang]
endfunction
And the bindings:
map <F8> :call MySpellLang()<CR>
Make vimdiff a great merge tool
function Vimdiff()
nmap <F7> [czz
nmap <F8> ]czz
nmap <F2> do
nmap <F3> dp
endfunction
au FilterWritePre * if &diff | call Vimdiff() | endif
This will allow you to use F7 and F8 to go to the next/previous change and F2 and F3 will copy changes from left to right and vice-versa.
Autocomplete on tab instead of oddball key combo! Really nice. Will autocomplete if there are characters to the left of the cursor, otherwise will insert a tab.
"Use TAB to complete when typing words, else inserts TABs as usual.
"Uses dictionary and source files to find matching words to complete.
"See help completion for source,
"Note: usual completion is on <C-n> but more trouble to press all the time.
"Never type the same word twice and maybe learn a new spellings!
"Use the Linux dictionary when spelling is in doubt.
"Window users can copy the file to their machine.
function! Tab_Or_Complete()
if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w'
return "\<C-N>"
else
return "\<Tab>"
endif
endfunction
:inoremap <Tab> <C-R>=Tab_Or_Complete()<CR>
:set dictionary="/usr/dict/words"
From Autocomplete with TAB when typing words [1]
[1] http://vim.wikia.com/wiki/Autocomplete_with_TAB_when_typing_words^wf ..... open file under cursor in new window
I have following maps, that will make navigation between windows much easier, just Ctrl + jkhl :
nmap <C-j> <C-W>j
nmap <C-k> <C-W>k
nmap <C-h> <c-w>h
nmap <C-l> <c-w>l
gg=G
Corrects indentation for the entire file. I was missing my trusty <C-a><C-i>
in Eclipse but just found out vim handles it nicely.
autocmd BufReadPost *.pdf silent %!pdftotext "%" -layout -q -eol unix -
Opens up a pdf file in vi.. Works great for programming/SDK(text centric) manuals. You can use all vi constructs on the pdf, to find info, cut-paste etc.
Search any string you want.
Then type this.
:g//d
or
:v//d
You can also use
:g/pattern/d
:v/pattern/d
One nifty feature is recording. qf to start recording your actions in a buffer f and q to quit recording. @f to play recording. I use it quite often for repetitive work.
For your .vimrc file:
nnoremap <leader>v V`]
" this reselects the last inserted text.
This I find to be very neat since sometimes i dont find to cursor when doing search
" Press F4 to toggle highlighting on/off, and show current value.
noremap <F4> :set hlsearch! hlsearch?<CR>
select lines in visual mode and
:sort
:%g/{\s*$/s/$/DEBUG STMT/
For the beginning of a code block ({), add a debug statement. This is more useful in PHP as you can
echo __METHOD__ . '(' . __LINE__ . ")\n";
and get method names and line numbers. I normally insert a newline before the DEBUG STATEMENT to make it a little easier to delete afterwards with:
:%g/^DEBUG STMT/d
:!%
Run the current file you're editing. Never leave VIM when developing scripts!