Title: vim_help.tx Subject: using the vim editor to write code Author: Steve Metz (some additions John Stile) update: 01.18.11 INSERT/APPEND MODES: i insert mode I insert at beginning of line shft ^ move to 1st non-blank char of line) a append mode A append at the end of the line ea append at the end of the word esc leave mode o open new line and enter insert mode alt x viper-mode change to vi mode in emacs *------------------------------------------------------------------------------* SELECT viw select inner word vis select inner sentence; delineated by a period. vip select inner paragraph shift # select all strings *------------------------------------------------------------------------------* MOVE TO: zt scroll current line to top of window ^e scroll up ??? scroll down gg to top of file g_ last non-blank char of line ge to prev word end gE to prev word end, ignore punctuation : go to line # ^u move up half a page ^d move down half a pg h,l left, righ k,j up, down 0 begin of the line ^ move to 1st non-blank char of line $ to last char of line w move forward one word b move bckward one word e move to end of word ^u move up half a page ^d move down half a pg 999k to the top of the file 999j to the bottom of the file undo/redo: u undo ^r undo undo ^z undo *------------------------------------------------------------------------------* DELETE: x delete current char dd delete line into buf (for paste) D delete to the end of the line dw delete word d#w delete # num of words (then paste w/ 'p') df<#> delete until the letter # d'a delete to mark :1,$s/[ ]*$// trim the blanks off the end of all lines in a file Explanation: The colon (:) tells Vim to enter ex command mode. All ex commands start with line range, in this case, the entire file (line 1 to the last line: $). The first set of slashes enclose the "from text". The square brackets indicate that either character can be a match. So [ ] matches either space or tab. The star (*) means that the previous character specification (space or tab) can be repeated any of number times. The dollar sign ($) indicates an end of line. So [ ]*$ tells Vim to look for any number of spaces or tabs followed by an end of line. These are then replaced by the text in the next set of slashes. This text is nothing, so the spaces and tabs are effectively removed. *------------------------------------------------------------------------------* COPY, PASTE, JOIN, REPLACE, ETC: cc change (replace) an entire line cw change (replace) to the end of the word c$ change (replace) to end of line s delete character at cursor and substitute text 5s delete 5 chars at cursor and substitute text xp swap letters r<#> replace w/ # R<#> replace insert mode 5ra replace 1st 5 char w/ 'a' m mark w/ letter a-z y yank (copy) text into a buf w/out removing i y'a yank to mark a (then use p to paste) yw yank word yy yank line 2yy yank 2 lines y$ yank to the end of the line Y<#> yank # number of lines into the buf p paste to line below/after cursor (doesn't work if you're in insert mode P paste above cursor J join the current line w/ the nex ~ change char case :%s/\/manager/g replace every occurrence of the word "idiot" with the word "manager" Explanation: : Enter command mode % Perform this command on all lines (% is means first to last line.) s The short form of the :substitute command. /\/ This text specifies the text we are looking for and want. The \< tells Vim to match a word start and the \> tells Vim to match the end of a word. /manager/ The replacement text g Global flag -- This flag tells Vim to change every occurance on the line, not use the first one. If needed, add 'c' for confirmation. *------------------------------------------------------------------------------* STRINGS MANIPULATION: 't,^s///q substitute from mark to curren position, the orig string w/ the new string :%s///g replace all old with new throughout file :%s///gc replace all old with new throughout file w/ confirmations :%s/^M$//g replace carriage return expressions w/ nothing; BE SURE YOU MAKE the ^M USING "CTRL-V CTRL-M" NOT BY TYPING "CARROT M"! This expression will replace all the ^M's that have carriage returns after them with nothing. (The dollar sign ties the search to the end of a line). Note that ctlr-v doesn't work in insert mode. :%s/^M/ /g replace all ^M's that need to have carriage returns at the end. Remove all trailing whitespace :%s/\s\+$// Remove all tabs. Notice you must copy and paste in the ^I vim tab symbol. :%s/ find the next letter # in the line 5f move 5 's forward t<#> move to the letter before # F<#> find the prev # in the line T<#> find the prev letter before # in the line *------------------------------------------------------------------------------* WINDOWS VIM COMMANDS: : repeat previous command; keep hitting up for prev cmd :split split current window in two (horizontally) :close close current window (horizontal or vertical) :bdelete delete buffer :bdelete! close buf, no changes :buffer <#> move this buffer into the active window :b <#> same as above :buffers show buf list (w/ status) ^ww change to next window ^wj scroll down a window ^wk scroll up a window ^wc close window *------------------------------------------------------------------------------* SYSTEM COMMANDS: :e open :??? put vim into background $fg in shell, to starts what's in the bckgnd :q! quit without saving :marks show marks :w save :w save as :^wc close window :^Wn new window :shell jumps to shell, to leave shell, type: 'exit' :g see range commands :pwd print working directory :cd %:p:h change directory to dir of what's in the current buffer *------------------------------------------------------------------------------* SEARCH COMMANDS: /enter search forword ?enter search back /\ search for a special string, i.e /\[ searches for fwd bracket n(ext) once you've found the strings, go to the nex macros: start macro-recording using q and one of {0-9a-zA-Z} for example qq records the macro to buffer 'q'. Hit q when you are finished recording. Replay the macro at any time using '@q'. tags: $ ctags *.c creates a tags file of functions names :tag jump to function name :Tlist opens/closes tags list column ^] jumps to the tage of the word under the cursor Tlist_Ctags_Cmd *------------------------------------------------------------------------------* RANGE COMMANDS: ranges may precede most "colon" commands and cause them to be executed on a line(s). :n,m range n-m :. range - current line :$ range - last line :'c range - marker c :% range - all lines in file :g/pattern/ range - all lines that contain pattern examples: :3,7d would delete line 3-7. :.,$s/pattern/string/g replace pattern string with string to eof examples: *------------------------------------------------------------------------------* TEXT FORMATTING (tabs, colors, width, font, etc): :set tabstop=4 sets tabs to width of 4 :retab transfer tab settings to another tab setting :set expandtab forces the 'no tabs' option, use "retab to conver tabs to spaces. :set softtabstop=4 fake 4 col tab; 2nd tab results in 8col :set ignorecase ignore case in searches :set noignorecase restore case sensitivity :set smartcase figures out which case to use: vim majic :set expandtab forces 'no tabs' option :set tabstop=4 :set shiftwidth=4 :set autoinden // @@@doesn't work :set textwidth=75 forces a line wrap at 75 char :set backup :set list shows tabs, spaces, end of lines, etc :set nolist turns off list (above) To get the following coding style: * No tabs in the source file. * All tab characters are 4 space characters. :set tabstop=4 :set shiftwidth=4 :set expandtab *-----------------------------------------------------------------------------* MAPPING and COMMANDS :map 44 // will scroll up 44 lines :map ipost_SysError(ea) // adds: post_SysError(type in text) - i insert the following string then escape the insert - e move to the end of the word added after the 1st insert - a) append the ')' to the word :command CD cd %:p:h change directory to dir of what's in the current buffer % current filename :p expand the % to a full path :h expand the % to an empty string which will avoid a cd error if you're already in the correct directory. There is no option '-h' in gvim. *------------------------------------------------------------------------------* EMACS COMMANDS ^x right arrow scroll to next buffer ^x left arrow move 1 buffer back ^x 3 open window ^x s save altx right arrow change windows altx left arrow change windows back *------------------------------------------------------------------------------* CTAGS & TLIST Context Tags and Tag Lists help navigate and view source code accross files, one level of abstatction above the actual statements. Install exuberant-ctags and taglist Debian/Ubuntu: aptitude install exuberant-ctags install taglist.vim plugin Gentoo: emerge exuberant-ctags app-vim/taglist Generate 'tags' file in source directlry ctags *.cpp *.h 1. Add this to vimrc to auto load files named 'tags' " ---Context Tags (ctags)--- set tags=tags;/ Open file in vim, move cursor over a function, and press -] - go to definition -T - Jump back from the definition. This is what Context Tags lest you do 2. Add these lines in vimrc: map :tab split:exec("tag ".expand("")) map :vsp :exec("tag ".expand("")) Open file in vim, -\ - Open the definition in a new tab -] - Open the definition in a vertical split -W -] - Open the definition in a horizontal split -w r - Swap viewport positions -w R - Swap viewport positions -q - close one viewport 3. Add these lines to vimrc: " ---Tag Lists (tlist)---- " selectively enable mouse support for specific modes only by using something other than 'a' (for 'all'). set mouse=a let Tlist_CTags='/usr/bin/ctags' map :TlistToggle Open file in vim, press F5 to toggle the tag list viewport 4. Download autotag.vim to ~/.vim/, and add this to your vimrc: " Auto Update tags file when file is written, by sourcing this " From: http://vim.wikia.com/wiki/Autocmd_to_update_ctags_file " From: http://www.vim.org/scripts/script.php?script_id=1343 " Requires: vim with python support so ~/.vim/autotag.vim Open file in vim, Press to open tag list window Add a function, and save You will see the tag list window update 5. Add these lines to vimrc: set selectmode=mouse Open file in vim, You can use the following keys to tag into and tag out of functions: Ctrl-Left_MouseClick - Go to definition Ctrl-Right_MouseClick - Jump back from definition 6. To make a toggle for line numbers, add this to ~/.vimrc " Set toggle for line number set nonumber nnoremap :set number! ========================================= TABS: Open multiple files in tabs vi -p # Show tabs set showtabline=2 # show list of opened files :args :ls # Hop to next file :n # Hop to previous file :prev # Move between tabs (vim7) :tabn and :tabp # close :(w)q # close a tab :tabc # next tab :tabn # previous tab :tabp # jump to tab 2 :tabn 2 # first tab (tabrewind) :tabr # tablast :tabl (tablast). # tabs :tabs # close all other tabs :tabo # Close all tabs and quit, without saving :qa # Close all tabs and quit, saving :wqa #----------------- For your .vimrc: " set tab shortcuts set showtabline=2 map :tabn map :tabp " List open buffers map :ls " other optional stuff map :tabr map :tabl map :tabp map :tabn