Post your favorite Vim tricks (or plug-ins or scripts). One trick per answer.
Try to come up with something other than the basics, btw. :D
Post your favorite Vim tricks (or plug-ins or scripts). One trick per answer.
Try to come up with something other than the basics, btw. :D
%
Brace/parentheses match.
If you have the cursor on a parenthesis/brace/etc ((){}[]
), and hit % it will jump to the corresponding one.
:g/search/p
Grep inside this file and print matching lines. You can also replace p with d to delete matching lines.
:e!
Reopen the current file, getting rid of any unsaved changes. Great for when a global search and replace goes awry.
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.
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
gqip
Reformat current line. Use it all the time to reformat comments in code, etc.
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
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 :-)
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.
:mak
Executes "make" and then will jump to the file that contain the compile errors (if any).
I really like the VTreeExplorer script for viewing portions of the folders and files in a tree view, and snippetsEmu to get TextMate-like bundles.
My favorite color scheme for the moment is VibrantInk.
ctrl-x->ctrl-f (while cursor on a path string)
searches for the path and auto-completes it, with multi-optional selection.
At the ex prompt you have command history using up/down arrows.
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)
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
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
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...
Ctrl+]
equivalent to Right click + "Go to Definition" in Visual Studio
(one must first create the tags file using e.g. ctags)
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".
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
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.
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)
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
list all lines found in current and included files that contain the word under the cursor.
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)
Vimrc to highlight tabs:
syntax match Tab /\t/
hi Tab guifg=yellow ctermbg=white
vim -o file1 file2 ...
To open multiple files at once in separate panes.
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
.
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
#
Search backwards in the file for the word under the cursor. Useful for finding declarations.
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
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 % [email protected]:~/some_folder/
control-A / control-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.
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.
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.)
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.
Read/write pdf files with Vi as if they were text files: http://vim.wikia.com/wiki/Open_PDF_files
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.
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
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.
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
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
:%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.
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
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!
COMMENTING 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>
I've been using vim <branch/tag/rev>:path
with git:file.vim a lot lately.
Using gq} to format comments is also one my favorite vim tricks not found in the original vi.
Edit command lines with vim commands under the bash shell
$ set -o vi
Now you can edit command lines using the vim syntax!
Example:
set backup
set backupdir=~/backup/vim
Puts all backup files (file.txt~) in the specified directory instead of cluttering up your working directories.
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
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:
"+
gqap
reformats an entire paragraph to match the current textwidth, pretty useful for plain text of LaTeX-docs.
I 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
Jumps.
m[a-z]
Mark location under [a-z]
`[a-z]
Jump to marked location
``
Jump to last location
g;
Jump to last edit
Using the built-in regions to change text quickly:
ci" -> Delete 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
.
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.
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")
When I use vim for writing a tidy journal, notes, etc
!}fmt
to format the current paragraph.
Ctrl+w Ctrl+]
splits current window to open the definition of the tag below the cursor
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.
: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 ^V+ESC on Unix or ^Q+ESC on Windows)
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.
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.
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.
[d
to show the definition of a macro
[D
to show the definition of a macro along with where it was defined.
:%s/^V^M^M
=> remove CR (DOS/Windows => Unix text format)
(^V = Ctrl-V etc.)
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.
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
]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.
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
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!
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
CamelCase Motion. Let's you move through and delete/edit CamelCase words.
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
[[ - Beginning of the current function block.
]] - Beginning of the next funcion.
[{ - Beginning of the current code block.
]} - End of the current code block.
z - 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.
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.
How about this one I found in The Pragmatic Programmer 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 :-)
Count 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.
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.
Here are some Vim 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).gg = G (go to top of file and tidy the format) very usefull :D
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!
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.
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.
http://vim.wikia.com/wiki/Autocomplete%5Fwith%5FTAB%5Fwhen%5Ftyping%5Fwords
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
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:
:/TODO:/ .,/^$/p
(p is short for :print).
And to save all the TODO: blocks to another file:
:/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.
:/TODO:/ .,/^$/w! todo.txt >> | .,/^$/d
will write the block to "todo.txt" then delete it from the current file.
Also see this answer for more examples.
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
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.
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.
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.
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.
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 is one of the best fixed-width fonts out there.
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/^#//
I can move to a pathfile in my text and press gf. That immediately moves me to that file.
a pathfile could be, /home/john/Desktop/somefile
once in it, ctrl-o takes me back.
So each file can have the most useful file actually written in it making traveling between those designated files veery fast.
Search any string you want.
Then type this.
:g//d
or
:v//d
You can also use
:g/pattern/d
:v/pattern/d
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.
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.
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.