Vim - ArchWiki

# Vim

Vim is an extended version of vi, with additional features to help with editing source code. Some of Vim's enhancements include comparison of files (vimdiff), syntax highlighting, a comprehensive help system, native scripting (vimscript), and a visual mode for easy selection.

Vim focuses on keyboard use, and is not a simple text editor like nano or pico. It takes time to learn, and a lifetime to master.

## Installation

Install one of the following packages.

CLI version:

- vim-minimal — a lightweight version.
- vim — Python 2, Lua and Ruby interpreters support but without GTK/X support.
- vim-python3 — the same as the `vim` package above but with Python 3 interpreter support.

GUI version:

- gvim — which also provides the same as the above `vim` package.
- gvim-python3 — for the same as the `gvim` package above but with Python 3 interpreter support.

Note:

- The vim* packages are built with no X support. As a consequence, the `+clipboard` feature is missing, so Vim will not be able to operate with the X11 primary and clipboard buffers. The gvim* packages provide also CLI version of Vim with full X support.
- The unofficial repository herecura-stable also provides a number of Vim/gVim variants: `vim-cli`, `vim-gvim-common`, `vim-gvim-gtk`, `vim-gvim-qt`, `vim-rt` and `vim-tiny`.

## Usage

This is a basic overview on how to use Vim. Alternately, running vimtutor/gvimtutor will launch the embedded tutorial.

Vim has four different modes:

- Command mode: keystrokes are interpreted as commands.
- Insert mode: keystrokes are entered into the text.
- Visual mode: keystrokes select, cut, or copy text.
- Ex mode: input mode for additional commands (e.g. saving a file, replacing text and so on).

### Basic editing

If you start Vim with:

    $ vim somefile.txt

you will see a blank document (providing that `somefile.txt` does not exist; if it does, you will see what is 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.

Note: Vim is an example of classic Unix-style ware. It has a difficult learning curve, but once you get started, you will find that it is extremely powerful. Also, all commands are case sensitive. Sometimes the uppercase versions are "blunter" versions (i.e. `s` will replace a character, while `S` will replace a whole line). Other times they are completely different commands (`j` will move down, while `J` will join two lines).

You insert text (stick it before the cursor) with the `i` command. Uppercase `I` inserts text at the beginning of the line. You append text with `a`. Typing `A` will place the cursor at the end of the line. And you return to command mode at any time by pressing `Esc`.

### Moving around

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.

To move down press `j`; to move the cursor back up press `k`. Left is `h`, and right is `l` (lowercase `L`).

`^` will put the cursor at the beginning of the line, and `$` will place it at the end.

Note: `^` and `$` are commonly used in regular expressions to match the beginning and ending of the line. Regular expressions are very powerful and are commonly used in *nix environment, so maybe it is a little bit tricky now, but later you will notice "the idea" behind the use of most of these key mappings.

To advance a word, press the `w` key. `W` will include more characters in what it thinks is a word (e.g. underscores and dashes as a part of a word). 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 beginning 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 beginning 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 to see just `foo`. Move the cursor under the `b` and hit `3x`. Now move to the `b` symbol of the next `foobar` 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. Use `s` to replace a single letter and go into insert mode. `S` will erase the whole line and place you in insert mode. To just replace a single letter use `r`, `R` will put you in replace mode.

### 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. `Ctrl+v` is for blocks of text.

Note: Whenever you delete something, that something is placed inside a buffer and is available for pasting.

### 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`, press `N` for the previous match.

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 occurrence
    :s/xxx/yyy/g    Replace xxx with yyy at every occurrence in the current line
    :s/xxx/yyy/gc   Replace xxx with yyy global with confirm
    :%s/xxx/yyy/g   Replace xxx with yyy global in the whole file
    :#,#s/xxx/yyy/g Replace xxx with yyy line number range

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 you wish to create a new file, `:w filename`. Quitting is done with `:q`. If you choose not to save your changes, use `:q!`. To save and quit type `:x`.

### Additional commands

1. `dd` will delete the current line (`ddp` for quick line switching).
2. `cc` will delete the current line and place you in insert mode.
3. `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.
4. `yy` will yank an entire line to the buffer
5. `*` will highlight the current word and `n` will search it

## Configuration

Vim's user-specific configuration file is located in the home directory: `~/.vimrc`, and Vim files of current user are located inside `~/.vim/`. The global configuration file is located at `/etc/vimrc`. Global Vim files are located inside `/usr/share/vim/`.

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 (such as syntax highlighting, returning to the last known cursor position etc), consider using Vim's example configuration file:

    # mv /etc/vimrc /etc/vimrc.bak
    # cp /usr/share/vim/vim74/vimrc_example.vim /etc/vimrc

### Syntax highlighting

To enable syntax highlighting (Vim supports a huge list of programming languages):

    :filetype plugin on
    :syntax on

### Visual wrapping

The `wrap` option is on by default, which instructs Vim to wrap lines longer than the width of the window, so that the rest of the line is displayed on the next line. The `wrap` option only affects how text is displayed, the text itself is not modified.

The wrapping normally occurs after the last character that fits the window, even when it is in the middle of a word. More intelligent wrapping can be controlled with the `linebreak` option. When it is enabled with `set linebreak`, the wrapping occurs after characters listed in the `breakat` string option, which by default contains a space and some punctuation marks (see `:help breakat`).

Wrapped lines are normally displayed at the beginning of the next line, regardless of any indentation. The breakindent option instructs Vim to take indentation into account when wrapping long lines, so that the wrapped lines keep the same indentation of the previously displayed line. The behaviour of `breakindent` can be fine-tuned with the `breakindentopt` option, for example to shift the wrapped line another four spaces to the right for Python files (see `:help breakindentopt` for details):

    autocmd FileType python set breakindentopt=shift:4

### Using the mouse

Vim has the ability to make use of the mouse, but it only works for certain terminals (on Linux it is xterm and Linux console with gpm, see Console mouse support for details).

To enable this feature, add this line into `~/.vimrc`:

    set mouse=a

Note:

- This even works in PuTTY over SSH.
- In PuTTY, the normal highlight/copy behavior is changed because Vim enters visual mode when the mouse is used. To select text with the mouse normally, hold down the `Shift` key while selecting text.

### Traverse line breaks with arrow keys

By default, pressing `←` at the beginning of a line, or pressing `→` at the end of a line, will not let the cursor traverse to the previous, or following, line.

The default behavior can be changed by adding `set whichwrap=b,s,<,>,[,]` to your `~/.vimrc` file.

### Example ~/.vimrc

See Vim/.vimrc.

## Merging files

Vim includes a diff editor (a program that shows differences between two or more files and aids to conveniently merge them). Use vimdiff to run the diff editor — just specify some couple of files to it: `vimdiff file1 file2`. Here is the list of vimdiff-specific commands. For basic `vim` editing, read the tutorial in the #Usage section.

Action | Shortcut
--- | ---
next change | `]c`
previous change | `[c`
diff obtain | `do`
diff put | `dp`
fold open | `zo`
fold close | `zc`
rescan files | `:diffupdate`
switch windows | `Ctrl+w+w`

## Tips and tricks

Here are some tips and tricks which will allow to use Vim more effectively and help to accomplish some specific tasks.

### Line numbers

1. Show line numbers by `:set number`.
2. Show relative line numbers with `:set relativenumber`.
3. Jump to line number `:line_number`.

### Spell checking

Vim has the ability to do spell checking, enable by entering:

    set spell

By default, only English language dictionaries are installed. More can be found in the official repositories by searching for `vim-spell`. Additional dictionaries can be found in the Vim's FTP archive. They can be put in the `~/.vim/spell/` folder and set enabled with the command: `:setlocal spell spelllang=en_us` (replacing the `en_us` with the name of the needed dictionary).

Action | Shortcut
--- | ---
next spelling | `]s`
previous spelling | `[s`
spelling suggestions | `z=`
spelling good, add | `zg`
spelling good, session | `zG`
spelling wrong, add | `zw`
spelling wrong, session | `zW`
spelling repeat all in file | `:spellr`

Tip:

- To enable spelling in two languages (for instance English and German), add `set spelllang=en,de` into your `~/.vimrc` or `/etc/vimrc`, and then restart Vim.
- You can enable spell checking for arbitrary file types (e.g. .txt) by using the FileType plugin and a custom rule for file type detection. To enable spell checking for any file ending with .txt, create the file `/usr/share/vim/vimfiles/ftdetect/plaintext.vim`, and insert the line `autocmd BufRead,BufNewFile *.txt setfiletype plaintext` into that file. Next, insert the line `autocmd FileType plaintext setlocal spell spelllang=en_us` into your `~/.vimrc` or `/etc/vimrc`, and then restart Vim.
- To enable spell checking for LaTeX (or TeX) documents only, add `autocmd FileType tex setlocal spell spelllang=en_us` into your `~/.vimrc` or `/etc/vimrc`, and then restart Vim.

### Save cursor position

If you want the cursor to appear in its previous position after you open a file, add the following to your `~/.vimrc`:

    augroup resCur
      autocmd!
      autocmd BufReadPost * call setpos(".", getpos("'\""))
    augroup END

### Replace vi command with Vim

Create an alias for `vi` to `vim`.

### DOS/Windows carriage returns

If there is a `^M` at the end of each line then this means you are editing a text file which was created in MS-DOS or Windows. This is because in Linux only a single line feed character (LF) used for line break, but in Windows/MS DOS systems they are using a sequence of a carriage return (CR) and a line feed (LF) for the same. And this carriage returns are displayed as `^M`.

To remove all carriage returns from a file do:

    :%s/^M//g

Note that there `^` is a control letter. To enter the control sequence `^M` press `Ctrl+v,Ctrl+m`.

Alternatively install the package dos2unix and run `dos2unix file` to fix the file.

### Empty space at the bottom of gVim windows

When using a window manager configured to ignore window size hints, gVim will fill the non-functional area with the GTK theme background color.

The solution is to adjust how much space gVim reserves at the bottom of the window. Put the following line in `~/.vimrc`:

    set guiheadroom=0

Note: If you set it to zero, you will not be able to see the bottom horizontal scrollbar.

## Plugins

Adding plugins to Vim can increase your productivity. Plugins can alter Vim's UI, add new commands, code completion support, integrate other programs and utilities with Vim, add support for additional languages and more.

### Installation

#### Using a plugin manager

A plugin manager allows to install ans manage Vim plugins in a similar way independently on which platform you are running Vim. It is a plugin that acts as a package manager for other Vim plugins.

- Vundle is currently the most popular plugin manager for Vim.
- Vim-plug is a minimalist Vim plugin manager with many features like on-demand plugin loading and parallel updating.
- pathogen.vim is a simple plugin for managing Vim's runtimepath.

#### From Arch repositories

The vim-plugins group provides many various plugins. Use `pacman -Sg vim-plugins` command to list available packages which you can then install with pacman.

### cscope

Cscope is a tool for browsing a project. By navigating to a word/symbol/function and calling cscope (usually with shortcut keys) it can find: functions calling the function, the function definition, and more.

Install the cscope package.

Copy the cscope default file where it will be automatically read by Vim:

    mkdir -p ~/.vim/plugin
    wget -P ~/.vim/plugin http://cscope.sourceforge.net/cscope_maps.vim

Note: You will probably need to uncomment these lines in `~/.vim/plugin/cscope_maps.vim` in order to enable cscope shortcuts in Vim 7.x:

    set timeoutlen=4000
    set ttimeout

Create a file which contains the list of files you wish cscope to index (cscope can handle many languages but this example finds .c, .cpp and .h files, specific for C/C++ project):

    cd /path/to/project/dir
    find . -type f -print | grep -E '\.(c(pp)?|h)$' > cscope.files

Create database files that cscope will read:

    cscope -bq

Note: You must browse your project files from this location or set and export the `$CSCOPE_DB` variable, pointing it to the `cscope.out` file.

Default keyboard shortcuts:

     Ctrl-\ and
          c: Find functions calling this function
          d: Find functions called by this function
          e: Find this egrep pattern
          f: Find this file
          g: Find this definition
          i: Find files #including this file
          s: Find this C symbol
          t: Find assignments to

Feel free to change the shortcuts.

    #Maps ctrl-c to find functions calling the function
    nnoremap <C-c> :cs find c <C-R>=expand("<cword>")<CR><CR>

### Taglist

Taglist provides an overview of the structure of source code files and allows you to efficiently browse through source code files in different programming languages.

Install the vim-taglist package.

Useful options to be put in `~/.vimrc`:

    let Tlist_Compact_Format = 1
    let Tlist_GainFocus_On_ToggleOpen = 1
    let Tlist_Close_On_Select = 1
    nnoremap <C-l> :TlistToggle<CR>

## See also

### Official

- Homepage
- Documentation
- Vim Wiki

### Tutorials

- vim Tutorial and Primer
- vi Tutorial and Reference Guide
- Graphical vi-Vim Cheat Sheet and Tutorial
- Vim Introduction and Tutorial
- Open Vim — collection of Vim learning tools
- Learn Vim Progressively
- know vim [dead link 2014-10-29]
- Learning Vim in 2014

#### Videos

- Vimcasts — screencasts in .ogg format.
- Vim Tutorial Videos — covering the basics up to advanced topics.

#### Games

- Vim Adventures
- VimGolf

### Example configurations

- nion's
- A detailed configuration from Amir Salihefendic
- Bart Trojanowski
- Steve Francia's Vim Distribution
- W4RH4WK's Vim configuration
- Fast vimrc/colorscheme from askapache
- Basic vimrc

### Other

- HOWTO Vim — Gentoo wiki article which this article was based on (author unknown).
- Vivify — a colorscheme editor for Vim
- Usevim — frequently updated blog highlighting plugins, tips, etc
- Vim Awesome — a website that lists and ranks Vim plugins by popularity among GitHub users.
- Basic Vim Tips — a reference chart for Vim, primarily aimed at beginners.
- Vim colorscheme tailoring — override installed colorscheme to try-out or permanently alter.

Categories:

- Development
- Text editors