Vim
From ArchWiki
Article summary |
---|
A basic introduction to the monstrously-powerful vim editor. |
Available in languages |
English |
Vim is an advanced text editor that seeks to provide the power of the de-facto UNIX editor ‘vi’, with a more complete feature set. Vim is not a simple text editor like nano or pico. It does require some time to learn, and a great amount of time to master.
Vim is designed to make your fingers work as little as possible, and you should never have to use the mouse. This may seem odd, but once you master vim, you’ll begin to understand the reasoning.
Contents |
Features
- Vim is very powerful for advanced editing tasks
- Extensible configuration options
- Simple, robust keybindings
- Syntax highlighting
Installation
Install the commandline version:
# pacman -Sy vim
Get the GUI (optional):
# pacman -Sy gvim
Usage
This is a basic overview on how to use vim. Alternately, you could use vimtutor to further familiarize yourself. Vim has four different modes:
- Command mode: keystrokes are interpreted as commands.
- Insert mode: keystrokes are entered into the file.
- Visual mode: keystrokes select, cut, or copy text
- Ex mode: input mode for additional commands (e.g. saving a file, replacing text...)
Basic Editing
If you start vim with:
$ vim somefile.txt
you’ll see a blank document (providing that somefile.txt does not exist. If it does, you’ll see what’s in there). You will not be able to edit right away – you are in Command Mode. In this mode you are able to issue commands to vim with the keyboard.
You insert text (stick it before the cursor) with the i command. I inserts text at the end of the line. You append text (place text after the cursor, what most people expect) with a. Typing A will place the cursor at the end of the line.
Return to command mode at any time by pressing Esc.
Moving Around
In vim, you can move the cursor with the arrow keys, but this isn't the vim way. You’d have to move your right hand all the way from the standard typing position all the way to the arrow keys, and then back. Not fun.
In vim you can move down by pressing j. You can remember this because the “j” hangs down. You move the cursor back up by pressing k. Left is h (it's left of the “j”), and right is l.
^ will put the cursor at the beginning of the line, and $ will place it at the end.
To advance a word, press the w key. W will include more characters in what it thinks is a word (- dashes,u _ underscores...). To go back a word, b is used. Once again, B will include more characters in what vim considers a word. To advance to the end of a word, use e, E includes more characters.
To advance to the beginning of a sentence, ( will get the job done. ) will do the opposite, moving to the end of a sentence. For an even bigger jump, { will move the the begining a whole paragraph. } will advance to the end of a whole paragraph.
To advance to the header (top) of the screen, H will get the job done. M will advance to the middle of the screen, and L will advance to the last (bottom). gg will go to the begininng of the file, G will go to the end of the file.
Repeating commands
If a command is prefixed by a number, then that command will be executed that number of times over (there are exceptions, but they still make sense, like the s command). For example, pressing 3i then “Help! ” then Esc will print “Help! Help! Help!“. Pressing 2} will advance you two paragraphs. This comes in handy with the next few commands…
Deleting
The x command will delete the character under the cursor. X will delete the character before the cursor. This is where those number functions get fun. 6x will delete 6 characters. Pressing . (dot) will repeat the previous command. So, lets say you have the word foobar in a few places, but after thinking about it, you’d like there just to be “foo”. Move the cursor under the b, hit 3x, move to the next foo bar and hit . (dot).
The d will tell vim that you want to delete something. After pressing d, you need to tell vim what to delete. Here you can use the movement commands. dW will delete up to the next word. d^ will delete up unto the beginning of the line. Prefacing the delete command with a number works well too: 3dW will delete the next three words. D (uppercase) is a shortcut to delete until the end of the line (basically d$). Pressing dd will delete the whole line.
To delete then replace the current word, place the cursor on the word and execute the command cw. This will delete the word and change to insert mode. To replace only a single letter use r.
Undo and Redo
vim has a built-in clipboard (also known as a buffer). Actions can be undone with u and redone with Ctrl+r.
Visual Mode
Pressing v will put you in visual mode . Here you can move around to select text, when you’re done, you press y to yank the text into the buffer (copy), or you may use c to cut. p pastes after the cursor, P pastes before. V, Visual Line mode, is the same for entire lines. C^v is for blocks of text.
Search and Replace
To search for a word or character in the file, simply use / and then the characters your are searching for and press enter. To view the next match in the search press n.
To search and replace use the substitute :s/ command. The syntax is: [range]s///[arguments]. For example:
Command Outcome :s/xxx/yyy/ Replace xxx with yyy at the first occurence :s/xxx/yyy/g Replace xxx with yyy first occurrence, global (whole sentence) :s/xxx/yyy/gc Replace xxx with yyy global with confirm :%s/xxx/yyy/g Replace xxx with yyy global in the whole file
You can use the global :g/ command to search for patterns and then execute a command for each match. The syntax is: [range]:g//[cmd].
Command Outcome :g/^#/d Delete all lines that begins with # :g/^$/d Delete all lines that are empty
Saving and Quitting
To save and/or quit, you will need to use Ex mode. Ex mode commands are preceded by a :. To write a file use :w or if the file doesn’t have a name :w filename. Quitting is done with :q. If you choose not to save your changes, use :q!. To save and quit :x.
Additional Commands
- Pressing s will erase the current letter under the cursor, and place you in insert mode. S will erase the whole line, and place you in insert mode.
- o will create a newline below the line and put you insert mode, O will create a newline above the line and put you in insert mode.
- yy will yank an entire line
- cc will replace the current line with a newline
- * will highlight the current word and n will search it
Configuration
Vim's personal configuration file is located in the home directory: ~/.vimrc. Advanced users tend to keep a well-tailored ~/.vimrc. The global configuration file is located at /etc/vimrc.
Currently the vim global configuration in Arch Linux is very basic and differs from many other distributions' default vim configuration file. To get some commonly expected behaviors (like syntax highlighting, return to the line of the last edit...), consider using vim's example configuration file:
cp /etc/vimrc /etc/vimrc.bak cp /usr/share/vim/vim72/vimrc_example.vim /etc/vimrc
Backup Files
Vim by default creates a backup of an edited file in the same directory as the file called filename~. To prevent clutter, many users tell vim to use a backup directory:
set directory=~/.vim/backup,/tmp
Or, it's possible to even disable this behaviour:
set nobackup set nowritebackup set noswapfile ! (additionally disable swap files)
Wrap Searches
set wrapscan
Check Spelling
set spell
Vim will now highlight incorrectly spelled words. With the cursor on a mis-spelled word, use z= to view suggested corrections.
Only English language dictionaries are installed by default, more can be found at the vim ftp archive. After downloading the spl files for the given language (e.g. hu.cp1250.spl, hu.iso-8859-2.spl and/or hu.utf-8.spl for Hungarian) into ~/.vim/spell, run:
:setlocal spell spelllang=LL
To activate spell checking for the selected language (i.e. :setlocal spell spelllang=hu for the above mentioned example).
Syntax Highlighting
To enable syntax highlighting (vim supports a huge list of programming languages):
filetype plugin on syntax on
Example .vimrc
An example ~/.vimrc covering common options.
" .vimrc " See: http://vimdoc.sourceforge.net/htmldoc/options.html for details " For multi-byte character support (CJK support, for example): "set fileencodings=ucs-bom,utf-8,cp936,big5,euc-jp,euc-kr,gb18030,latin1 set tabstop=4 " Number of spaces that a <Tab> in the file counts for. set shiftwidth=4 " Number of spaces to use for each step of (auto)indent. set expandtab " Use the appropriate number of spaces to insert a <Tab>. " Spaces are used in indents with the '>' and '<' commands " and when 'autoindent' is on. To insert a real tab when " 'expandtab' is on, use CTRL-V <Tab>. set smarttab " When on, a <Tab> in front of a line inserts blanks " according to 'shiftwidth'. 'tabstop' is used in other " places. A <BS> will delete a 'shiftwidth' worth of space " at the start of the line. set showcmd " Show (partial) command in status line. set showmatch " When a bracket is inserted, briefly jump to the matching " one. The jump is only done if the match can be seen on the " screen. The time to show the match can be set with " 'matchtime'. set hlsearch " When there is a previous search pattern, highlight all " its matches. set incsearch " While typing a search command, show immediately where the " so far typed pattern matches. set ignorecase " Ignore case in search patterns. set smartcase " Override the 'ignorecase' option if the search pattern " contains upper case characters. set backspace=indent,eol,start " Influences the working of <BS>, <Del>, CTRL-W " and CTRL-U in Insert mode. This is a list of items, " separated by commas. Each item allows a way to backspace " over something. set autoindent " Copy indent from current line when starting a new line " (typing <CR> in Insert mode or when using the "o" or "O" " command). set smartindent " Do smart autoindenting when starting a new line. Works " for C-like programs, but can also be used for other " languages. set textwidth=79 " Maximum width of text that is being inserted. A longer " line will be broken after white space to get this width. set formatoptions=c,q,r,t " This is a sequence of letters which describes how " automatic formatting is to be done. " " letter meaning when present in 'formatoptions' " ------ --------------------------------------- " c Auto-wrap comments using textwidth, inserting " the current comment leader automatically. " q Allow formatting of comments with "gq". " r Automatically insert the current comment leader " after hitting <Enter> in Insert mode. " t Auto-wrap text using textwidth (does not apply " to comments) set ruler " Show the line and column number of the cursor position, " separated by a comma. set background=dark " When set to "dark", Vim will try to use colors that look " good on a dark background. When set to "light", Vim will " try to use colors that look good on a light background. " Any other value is illegal. set mouse=a " Enable the use of the mouse. filetype plugin indent on syntax on
Some more examples can be found in #Resources.
Merging Files (Vimdiff)
Vim includes a diff editor (a program that can merge differences between two files). Begin with vimdiff file1 file2; to use:
]c : - next difference [c : - previous difference Ctrl+w +w - switch windows do - diff obtain dp - diff put zo - open folded text zc - close folded text :diffupdate - re-scan the files for differences
Vim Tips
Specific user tricks to accomplish tasks.
Line Numbers
- Show line numbers by :set number.
- Jump to line number :<line number>.
Substitute on Lines
To only substitute on certain lines:
:n1,n2s/one/two/g
Resources
Official
Tutorials
Example configurations
Other
- HOWTO Vim -- Gentoo wiki article which this article was based on (author unknown).