Вы находитесь на странице: 1из 46

VIM Vi Improved!

Configuring and using VIM editor By Tusharadri Sarkar July 13, 2009 IBM

July 13, 2009

Tusharadri Sarkar

A Brief History of Vim


Vim is an improvement over the popular Vi editor The Vi editor was developed by Bill Joy in 1976 ed was the original UNIX text editor Bill Joy modified ed and named it ex He developed Vi as a Visual interface to ex Bram Moolenaar developed Vim in November,1991 for the Amiga Computer, added many additional features In 1992 it was ported to UNIX platform GUI feature was added in 1996, gVim appeared
July 13, 2009 Tusharadri Sarkar 2

Features of Vim

Vim has almost full compatibility with vi + extra features and enhancements like: Completion, comparison and merging of files: vimdiff An integrated help system Support for extended regular expressions Support for scripting languages (native: vimscript + others: Perl, Ruby, Python, TCL etc.) Support for plug-ins and a GUI (gVim) version Limited IDE features and mouse interaction (for both GUI and CLI versions)
July 13, 2009 Tusharadri Sarkar 3

Features of Vim

Editing capability of compressed or archived files (.gzip, .bzip2, .zip and .tar files) Editing capability of files over network protocols like SSH, FTP and HTTP Session state prevention Spell checking Splitting of windows (both horizontal & vertical) Support for Unicode + other languages Trans-session command Syntax highlighting Visual mode
July 13, 2009 Tusharadri Sarkar 4

Why use Vim?


You never need not use the mouse or arrow keys!! Powerful navigation capability with minimal use of Ctrl/Meta keys Automatic Keyword Completion Character, line and block wise editing: The Visual mode Use multiple clipboards/buffers: No right clicks!! Use macros: Record and replay multiple macros Powerful command line editing Customize Vim as you like it: Too many vim options
July 13, 2009 Tusharadri Sarkar 5

Configuring Vim
How to configure Vim & Set Vim as the default editor

July 13, 2009

Tusharadri Sarkar

Configuring Vim

Make aliases of the vim path in the .bashrc file of your login directory as follows: alias vi=/usr/local/bin/vim X alias vim=/usr/local/bin/vim X
* Note: The actual path may vary from system to system. This is the most common path.

Create the .vimrc file in the login directory with your preferred Vim options Invoke the bash shell once and you will set vim as your default editor

July 13, 2009

Tusharadri Sarkar

Configuring Vim

Options for the .vimrc file: Most frequently used are


:set nocompatible " use vim defaults :set ls=2 " always show status line (last 2) :set tabstop=4 " numbers of spaces of tab char :set shiftwidth=4 " numbers of spaces to auto indent :set scrolloff=3 " keep 3 lines when scrolling :set showcmd " display incomplete commands :set hlsearch " highlight searches :set incsearch " do incremental searching :set ruler " show the cursor position

July 13, 2009

Tusharadri Sarkar

Configuring Vim
:set visualbell t_vb= " turn off error beep/flash :set number " show line numbers :set ignorecase " ignore case when searching :set viminfo='20,<50,s10,h :set autoindent " always set auto indenting on :set smartindent " smart indent :set expandtab " tabs are converted to spaces :set sm " show matching braces :syntax on " syntax highlighting

July 13, 2009

Tusharadri Sarkar

Configuring Vim

Each option has a short form Using short form is convenient while enabling/disabling any option for current session :set number == se nu enables line number To disable any option, just prefix no before it :se nonu disables line number If you have GUI support (gVim), you can also set the color scheme, font style, window height/width and background and foreground colors

July 13, 2009

Tusharadri Sarkar

10

Using Vim

Navigation Smart Editing Command Execution And more

July 13, 2009

Tusharadri Sarkar

11

Modes of Vim
There are 3 modes with distinct sets of functionalities: 1. Command Mode (For Navigation) 2. Input Mode (Everything shows up on screen)

Entering Text Replacing Text

3. Execution Mode (Last Line Mode)


Saving Exiting Pattern matching and substitutions

Visual Mode (Only in Vim, mainly covers 2 & 3)


July 13, 2009 Tusharadri Sarkar 12

Switching between modes of Vim


Input Mode [Esc ] I, i, A, a, O, o, R, r, S, s Command Mode vi/vim SHELL : x, : q, ZZ : ex Mode

[Enter]

July 13, 2009

Tusharadri Sarkar

13

Vim: Navigation
Keystroke h l/spacebar k/Ctrl+p J/Ctrl+n Crtl+f Ctrl+b Ctrl+d Ctrl+u M (Shift+h) H L W/w Move cursor left * Move cursor right * Move cursor up * Move cursor down * Scroll forward one page Scroll back one page Scroll down one half of a page Scroll up one half of a page Move cursor to middle of page Move cursor to top of page Move cursor to bottom of page Move cursor forward a word at a time*
July 13, 2009 Tusharadri Sarkar 14

Function

Vim: Navigation
Keystroke B/b E/e 0 (Zero) / | $ ) ( G % . (Apostrophe dot) a (Apostrophe a) Function Move cursor to bottom of page * Move cursor to end of word * Move cursor to beginning of line * Move cursor to end of line Move cursor to beginning of next sentence Move cursor to beginning of current sentence Move cursor to end of file * Move cursor to the matching bracket; Place cursor on {}[]() Move cursor to previously modified line Move cursor to line mark "a" generated by marking "ma"

July 13, 2009

Tusharadri Sarkar

15

Vim: Navigation
Keystroke A (Apostrophe A) gg ] [ +/^ Function Move cursor to line mark "a" (global between buffers) generated by marking with keystroke "mA" Move to the beginning of the file Move cursor to next lower case mark Move cursor to previous lower case mark Move cursor down/up in first column Move to the first character of first word

Functions marked with * also support motions; e.g. # 10w will take the cursor 10 words forward. 40G will take you to the 40th line from beginning

July 13, 2009

Tusharadri Sarkar

16

Vim: Inserting/Editing Text


Keystroke i a A u U o O ~ (Tilde) D C Ctrl+a Ctrl+x Insert at cursor * Append after cursor Append at end of line Undo last change Undo all changes to entire line Open a new line below cursor Open a new line above cursor Change case of individual character Delete contents of line after cursor Delete contents of line after cursor and insert new text Increment number under the cursor Decrement number under the cursor
July 13, 2009 Tusharadri Sarkar 17

Action

Vim: Inserting/Editing Text


Keystroke x r R s S dw cw d0 (d+Zero) dd d$ xp Replace character * Overwrite characters from cursor onward Substitute one character under cursor continue to insert * Substitute entire line and begin to insert at beginning of the line Delete word * Change word Delete to beginning of the line Delete line * Delete to the end of a line * Transpose two characters
July 13, 2009 Tusharadri Sarkar 18

Action Delete character at cursor *

Vim: Inserting/Editing Text


Keystroke P p /string{CR} ?string{CR} n N /\<string\>{CR} Action Put deleted/cut text above cursor Put deleted/cut text below cursor /string{CR} Search backwards (up in file) for string Find next occurrence of search string downward Find previous occurrences of search string upwards Search for word string; e.g. # /\<s\> Search for variable "s" but ignore declaration "string" or words containing "s". This will find "string s;", "s = fn(x);", "x = fn(s);" Search forward and backward for character c in current line Repeat forward and backward search for char in same line
July 13, 2009 Tusharadri Sarkar 19

fc / Fc ; / , (semi/coma)

Vim: Inserting/Editing Text


Keystroke xp Amazing . (dot) d yy yw y c !tr [a-z] [A-Z] !tr [A-Z] [a-z] Ctrl+r Action Transpose two characters Repeat the last action in command mode Delete a region (Vim only; Supported in V mode) Copy current line * Copy word * Copy region (Vim only, V mode) Change text of region (Vim only, V mode) Convert region to uppercase (Vim only, V mode) Convert region to lowercase (Vim only, V mode) Redo last undo (Vim only)

The same rule of motion applies here also with actions marked *
July 13, 2009 Tusharadri Sarkar 20

Advance editing: Buffers, Marks & Macros


Command Bdd Bp Byy ma (2 apostrophes) Ctrl+o / Ctrl+I q register q @register Function Delete current line to buffer B * Restore content from buffer B * Copy current line to buffer B * Set mark a to a line Toggle between current and previous marked positions Same as above but not marked places Start recording a macro Stop recording current macro Play the macro i.e. write down the register content

Remember: macro only records the keystrokes entered


July 13, 2009 Tusharadri Sarkar 21

Advanced editing: Multiple Files


Command :e abc :e! abc :e! Crtl+^ :n :set autowrite (: se aw) :rew :r abc Function Stop editing current file and edit file abc Same as above but discarding all the changes in current file Load latest saved version of the current file Return to the most recently edited file Edit the next file (When vim is opened with multiple files) Automatically save the current file before switching to the next file Rewind files list to start editing first file (When vim is opened with multiple files) Insert contents of file abc below current line
July 13, 2009 Tusharadri Sarkar 22

Advanced editing: Multiple Windows


This is a Vim only feature
Command :sp :vsp vim O [n | files] :new :on :q :qa :xa [Ctrl+w]+/Function Split current window horizontally in two Split current window vertically into two Opens n windows, files split vertically Open a new blank window Make current window the only window Quit current window Quit all windows Save and quit all windows Increase/decrease window size

[Ctrl+w] [Ctrl+w] Toggle between windows


July 13, 2009 Tusharadri Sarkar 23

Advance editing: Abbreviation & Interface to SHELL


Command :ab blr Bangalore :unab blr :ab :!cmd :!% :r!cmd :sh Ctrl+z :!cc% :!javac% Action Abbreviate Bangalore to blr Kill the above abbreviation List of all abbreviations Run any UNIX command cmd Execute the current file as a Shell/Perl Script Insert output of UNIX command cmd below current line Escape to the UNIX shell Suspend editor (use fg to return to vim) Compile currently edited C file Compile currently edited Java file
July 13, 2009 Tusharadri Sarkar 24

Pattern Substitutions
General format of substitution :[.|$|%]s/s1/s1[switches] or :n1,n2s/s1/s2/[switches]

[switches] are: g|c|i|I meaning global/confirmation/ignore-case/no-ignore-case


Some interesting examples of pattern substitutions
Command :1,$s/#//g :3,10s/^/#/ :$s/$/;/ :%s/abc/xyz/gc :1,$s/include/<&>/g Globally remove # Insert # at the beginning of line 3 to 10 Insert a ; at the end of last line Globally replace abc by xyz interactively Globally replace include by <include>
July 13, 2009 Tusharadri Sarkar 25

Function

Starting, Saving & Quitting


Command vim +100 abc vim +/pat abc vim + abc vim f1 f2 f3 vim r abc vim R abc Function Open file abc at line no. 100 Open file abc at the first occurrence of pattern pat Open file abc at end First open file f1, then switch to f2 using :n, then switch to f3 using :n and so on Recover buffer from swap file Open file in read-only mode

July 13, 2009

Tusharadri Sarkar

26

Starting, Saving & Quitting


Command :w :w abc :w! abc :n1,n2w abc :n1,n2w >> abc :.w abc :$w abc :x / :wq/ZZ :q! / :qa :q Function Save file remaining in editing mode Save current file content by file name abc Same as above but overwriting existing file abc Write line n1 to n2 to file abc Append lines n1 to n2 to file abc Write the current line to file abc Write the last line to file abc Save file and quit editing mode Quit editing mode discarding all the changes Quit as above when no changes are made
July 13, 2009 Tusharadri Sarkar 27

Vim: Graphical Cheat Sheet!

July 13, 2009

Tusharadri Sarkar

28

Some useful features of Vim

Vimdiff Ctags Cscope

July 13, 2009

Tusharadri Sarkar

29

Vimdiff: Find the differences


To start vim in diff mode: vimdiff f1 f2 [f3 [f4]] or Alternatively you can use: vim d f1 f2 [f3 [f4]] Vim enables the following options while using diff:

diff scrollbind scrollopt wrap foldmethod foldcolumn

on on includes hor off diff 2

Vim sets them as local to the window when using diff mode. Otherwise they are set to global values while editing other files.
July 13, 2009 Tusharadri Sarkar 30

Vimdiff: Find the differences

When already in editing mode, diff mode can be invoked in 3 ways :diffsplit <filename> :diffthis :diffpatch <patchfile> To ensure these commands use a vertical split, use option :vert :vert diffpatch /tmp/diff :vert diffsplit main.c
July 13, 2009 Tusharadri Sarkar 31

Vimdiff: Find the differences

Force the difference to be updated :diffupdate To jump between the differences [c:Jump backward to the previous start of a change ]c: Jump forward to the previous start of a change

July 13, 2009

Tusharadri Sarkar

32

Vimdiff: Find the differences

Highlight the differences with the following groups: hl-DiffAdd Added/inserted lines hl-DiffChange Changed text hl-DiffText Changed text inside a changed line hl-DiffDelete Deleted lines

July 13, 2009

Tusharadri Sarkar

33

Vimdiff: Find the differences

Diff Copying: Two commands to copy test from one buffer to another: [range] diffg[et] [buffspace]: Modify current buffer to undo differences with another buffer within range [range] diffpu[t] [buffspace]: Modify another buffer to undo differences with the current buffer within range do: Same as diffg[et] without argument or range dp: Same as diffpu[t] without argument or range

July 13, 2009

Tusharadri Sarkar

34

Ctags with Vim


Ctags helps to jump to the references under cursor Add tags to a particular sets of file or entire directory: ctags R <path>; It will create a tags file Alternatively you can use: ctags *.h *.c to create tags Most frequently used commands for ctags: Ctrl+] The vim editor will jump into the tag to follow it to a new position in the file or to a new file Ctrl+t/pop The vim editor will allow the user to jump back a level
July 13, 2009 Tusharadri Sarkar 35

Ctags with Vim

Other ctags options to be used with Vim:


Command :tag start-of-tagname_TAB :tag /search-string :tselect <functionname> :tnext :tags :n pop/n tag :tprevious :tfirst / :tlast Action Vim supports tag name completion; completes the tag name for you Jump to a tag name found by a search If multiple entries exist in the tags file, the operator can choose by issuing this command. Jump to the next matching tag Show tag stack (history) Jump to a particular position in the tag stack (history) Jump to the previous matching tag Jump to first/last matching tag Add multiple tags files
July 13, 2009 Tusharadri Sarkar 36

:set tags=./tags1,./tag2

Cscope with Vim


Cscope: Developed to cross-reference C code It can also be used to with C++ and Java Using cscope to cross reference source code will create a database Traverse the source to find calls to a function, occurrences of a function, variable, macros, class or object and their respective declarations cscope offers more complete navigation than ctags To use cscope, vim must be compiled with cscope support

July 13, 2009 Tusharadri Sarkar 37

Cscope with Vim


To generate the cscope database use the command: cscope b *.cpp/(or .cc/.c) *.h or cscope b R Invoke cscope from vim: cscope find search_type serach_string
Description Find all references to a symbol Find global definition Find calls of this function Find functions that the specified function calls Find specified text string Open file Find files that "#include" the specified file
July 13, 2009 Tusharadri Sarkar 38

search_type symbol (s) global (g) calls (c) called (d) text (t) file (f) include (i)

Cscope with Vim

List of cscope environment variables


Variables EDITOR INCLUDEDIRS SOURCEDIRS VPATH Description Default: /usr/bin/vim List of directories separated by : List of search directories separated by : Same as above. If not set cscope will search in the current directory only

CSCOPE_EDOTOR Editor to use: /usr/bin/vim

You can manually generate a cscope file with a shell script #!/bin/bash find ./ -name "*.[ch]pp" -print > cscope.files cscope -b -q -k
July 13, 2009 Tusharadri Sarkar 39

Some more additional features

Sorting:
Mark a block of text at the top line and bottom line of the block of text. i.e. "mt" and "mb" on two separate lines. This text block is then referenced as "'t,'b. Now :'t,'b !sort

Moving columns, manipulating fields with awk:


't,. !awk '{print $3 " " $2 " " $1}' - This will reverse the order of the columns in the block of text

July 13, 2009

Tusharadri Sarkar

40

Some more additional features

Source code formatting in C++/Java:


Use visual mode. Goto first line (Shift+v) then goto last line (Shift+g) and then select =

Text formatting:
Use bookmark as above i.e. mt and mb. Now apply the command # :t,b !nroff

Spell checking:
Same as above. Command # :t,b !spell You can undo the changes by pressing u

July 13, 2009

Tusharadri Sarkar

41

Configuring gVim of Cygwin


Use the Xtreminal of Cygwin Run Vim in GUI mode (gVim) Customize Cygwin XTerminal

July 13, 2009

Tusharadri Sarkar

42

gVim on Cygwin
Location of gVim in cygwin: /usr/bin/gvim.exe Also you can find vim here: /usr/bin/vim.exe In the login directory, create suitable aliases in .bashrc

alias gv=/usr/bin/gvim.exe

Create a .gvimrc file in the same directory with your preferred options set Launch the Xserver by command: startx from cygwin window. This will open the XTreminal Launch the gVim from Xterm using your alias

July 13, 2009

Tusharadri Sarkar

43

Configure your XTerminal: tips


You can launch multiple XTerminal from one XTerminal using command: xterm Change the default display setting of your XTerminal:
$ xterm -ls -bg <background> -fg <foreground> -title <Title> -fn '*<fontsize>* $ xterm ls bg blue fg azure title <TITLE> fn *16*

You can directly open the XTerminal using a set of options:


$ rxvt -fn '*-courier-*-r-*-16-*' -sl 9999 -bg Black -fg Cyan -e /bin/bash login

Best way would be to create one or more aliases of this in .bashrc file
July 13, 2009 Tusharadri Sarkar 44

References:

http://www.yolinux.com/TUTORIALS/LinuxTutori alAdvanced_vi.html http://vimdoc.sourceforge.net/htmldoc/intro.html http://www.vim.org/ http://www.viemu.com/vi-vim-cheat-sheet.gif

July 13, 2009

Tusharadri Sarkar

45

THANK YOU !!
And Happy Vimming

July 13, 2009

Tusharadri Sarkar

46

Вам также может понравиться