--- layout: post title: "Using Vim on Linux" description: "Using Vim on Linux" category: Development tags: [Ubuntu, Debian, Terminal, Vim, Git, Setup, Linux] --- {% include JB/setup %} Vim is arguably among the best text editors. Text file editing is an everyday task on Linux, as opposed to e.g. Windows, where operating system and applications are configured graphically (by clicking with the mouse). Moreover, Vim is suitable for programming through plug-ins. This page applies to Debian/Ubuntu.

---

Installing **Vim** ============== sudo apt-get install vim Add the following to your `~/.bashrc`: export EDITOR=vim and do source ~/.bashrc Now **Vim** will be invoked as the default text editor and you can start it by entering `vim` at the command line. Basic setup ----------- Put this in your `~/.vimrc`: " enable syntax highlighting syntax on " use spaces instead of tabs set tabstop=2 set expandtab set shiftwidth=2 set softtabstop=2 " always show ^M in DOS files set fileformats=unix " my terminal is white on black set background=dark highlight Comment ctermbg=blue highlight Comment ctermfg=white " always show line and col number and the current command, set title set ruler set showcmd set title titlestring=vim\ %f " caseinsensitive incremental search set ignorecase set incsearch " Show matching brackets set showmatch " disable any autoindenting which could mess with your mouse pastes (and your head) " (not useing 'set paste' here to keep fancy stuff like tab completion working) set nocindent set nosmartindent set noautoindent set indentexpr= filetype indent on " Enable 256 colors set t_Co=256 " Maps Alt-[h,j,k,l] to resizing a window split map < map - map + map > " Maps Alt-[s.v] to horizontal and vertical split respectively map :split map :vsplit " Maps Alt-[n,p] for moving next and previous window respectively map map Your user experience should now be much better. You will have syntax highlighting, and can split the **Vim** window using `Alt+s` and `Alt+v`. See the comments above for more options.

---

Using **Vim** ========= Graphical Cheat Sheet --------------------- ![Vim Cheat Sheet](/images/vi-vim-cheat-sheet.gif) Learn **Vim** with the [graphical cheat sheet](http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html). Spell Checking -------------- [Download](http://ftp.vim.org/vim/runtime/spell/) spell files. Example: for german, download `de.utf-8.spl`, `de.utf-8.sug`. As root, copy the downloaded spell files to `/usr/share/vim/vim7x/spell/`. Put the following in your `~/.vimrc`: " Function to toggle spelling for language 'lang' func! ToggleSpl( lang ) if &l:spl =~ '\v(^|,)\V'.escape(a:lang,'\').'\v(,|$)' "Alternatively, since 'spl' may not contain a comma this also "works: "if index(split(&l:spl,','),a:lang) != -1 exec 'setl spl-='.a:lang else exec 'setl spl+='.a:lang endif :setl spell spl endfun This function toggles spell checking for a given language on/off. For the language files downloaded, you can now map keys to toggle spell checking for each of them. Example for german: " Switch on german spelling (in addition to what is active already!) map :call ToggleSpl('de') Now, `F3` will toggle spell checking for the german language. Go ahead and create keybindings for any needed language in the same way, using different keys for each language. ![spell checking](/images/spell.png "spell checking") Note: Toggling a specific language on/off will not affect the status of other languages. Arbitrary combinations of languages can be enabled at a time. To use spell correction, a few commands are needed: - `]s` next misspelled word - `[s` previous misspelled word - `z=` view spelling suggestions for a mispelled word - `zg` add a word to the dictionary - `zug` undo the addition of a word to the dictionary Note: for the `z*` commands, the cursor must be positioned on the corresponding word. Text wrapping ------------- You can do two things: - Let **Vim** format (i.e.change) your text to have shorter lines, by inserting linebreaks. Type `v` to go to visual mode, select text, and press `gq`. - Leave lines as they are, but display them wrapped. This can be toggled by `:set wrap`, `:set nowrap` Both are independent. Auto-Indenting on Paste ----------------------- In a console or terminal version of **Vim**, there is no standard procedure to paste text from another application. Instead, the terminal emulates pasting by inserting text into the keyboard buffer, so **Vim** thinks the text has been typed by the user. After each line ending, **Vim** moves the cursor so the next line starts with the same indent as the last. However, that will change the indentation already in the pasted text. Put the following in your `~/.vimrc`: nnoremap  :set invpaste paste? set pastetoggle= set showmode The first line sets a mapping so that pressing F2 in normal mode will invert the `'paste'`{.western} option, and will then show the value of that option. The second line allows you to press F2 when in insert mode, to toggle `'paste'`{.western}on and off. The third line enables displaying whether `'paste'`{.western} is turned on in insert mode. To paste from another application: 1. Start insert mode. 2. Press F2 (toggles the `paste` option on). 3. Use your terminal to paste text from the clipboard. 4. Press F2 (toggles the `paste` option off). Then the existing indentation of the pasted text will be retained. Using Vim as a pager -------------------- The standard tool to display (not edit) text files is **Less**. However, you also may want to use **Vim** to display source files. Add alias vless='vim -u /usr/share/vim/vimcurrent/macros/less.vim' to your `~/.bash_aliases`, and, after reading in the file, e.g. by a new login, you have the `vless` command. When viewing a file with `vless`, press `v` to switch to the full **Vim**.

---

Plugins ======= Plugins are installed via 'pathogen', a vim package manager: mkdir -p ~/.vim/autoload ~/.vim/bundle; \ curl -Sso ~/.vim/autoload/pathogen.vim \ https://raw.github.com/tpope/vim-pathogen/master/autoload/pathogen.vim Add this to your `.vimrc`: execute pathogen#infect() Now **Vim** loads all plugins from `.vim/bundle`. Install plugins: cd ~/.vim/bundle git clone git://github.com/vim-ruby/vim-ruby.git git clone git://github.com/msanders/snipmate.vim.git git clone git://github.com/scrooloose/nerdtree.git git clone git://github.com/vim-scripts/delimitMate.vim.git git clone git://github.com/jcf/vim-latex.git git clone git://github.com/ervandew/supertab.git git clone git://github.com/kien/ctrlp.vim.git bundle/ctrlp.vim git clone git://github.com/rking/ag.vim You can install the plugins without git by downloading and expanding them to `~/.vim/bundle`. For complete descriptions see the the github repositories. Here is a sample: Nerdtree displays a directory tree to the right. Add this to your `.vimrc`: " map Ctrl+D to nerdtree map :NERDTreeToggle CtrlP allows fuzzy file searching. Add this to your `.vimrc`: " map Ctrl+P to invoke CtrlP file finder (http://kien.github.com/ctrlp.vim/) let g:ctrlp_map = '' let g:ctrlp_cmd = 'CtrlP' For details consult the respective plugin documentation.

---

Using **Vim** with Git ================== What happens when you type `git diff`? You will receive a simple diff, but there is also a way to do a `vimdiff` with a side-by-side view of a diff in nice colors! See [this tutorial](http://goo.gl/7SH1I) for Vimdiff usage. Step 1: add this to your `.gitconfig` [diff] external = git_diff_wrapper [pager] diff = Step 2: create a file named `git_diff_wrapper` (and put it somewhere in your `$PATH`): #!/bin/sh vimdiff "$2" "$5" Step 3: there is still access to the default `git diff` behavior with the `--no-ext-diff` flag. Here’s a function I put in my bash configuration files: function git_diff() { git diff --no-ext-diff -w "$@" | vim -R - } where the argument's meanings are: - `--no-ext-diff`: to prevent using vimdiff - `-w` : to ignore whitespace - `-R` : to start vim in read-only mode - `-` : to make vim act as a pager It turns out to be very useful to be able to alternate between the two versions of diff.

---

Using **Vim** with Ruby ================== **Vim** and ruby are like beer and pizza -- a perfect couple. Following the above will already give you syntax highlighting on ruby files. Here is how you add code completion, i.e. type a command prefix and use the TAB key and be presented with a list of possible completions. Although ruby support is built into **Vim** 7.x, the vim-ruby plugin should be installed manually for updates. Also install the SuperTab module, see 'Plugins' for both. Then put this in your `.vimrc` " ruby autocompletion autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading = 1 autocmd FileType ruby,eruby let g:rubycomplete_rails = 1 autocmd FileType ruby,eruby let g:rubycomplete_classes_in_global = 1 let g:SuperTabDefaultCompletionType = "" "improve autocomplete menu color highlight Pmenu ctermbg=238 gui=bold Now, for example, if you want to implement a `collect` call on some container (such as a hash), you can type in **Vim** a prefix of `collect` and press TAB: { ... }.c and **Vim** will present you with a list of applicable commands, from which you select `collect`. ![picture](/images/vim-cc.png "Vim code completion")

---

Using **Vim** with Latex ==================== LaTeX is a system for setting characters ('types'). Actually, it is a wrapper of macros around TeX, [created by Donald Knuth](http://www.tug.org/whatis.html). LaTeX is most widely used In technical writing, especially mathematics, physics, and computer science, because it can typeset mathematical formulae beautifully. Install LaTeX: sudo apt-get install \ texlive \ texlive-doc-de \ texlive-latex-extra \ texlive-lang-german \ texlive-science \ texlive-fonts-extra Install **Vim**, the Gnome version: sudo apt-get install \ vim-gnome Install vim-latex as described under 'Plugins'. Basic editing and compiling --------------------------- Add this to your `~/.vimrc`: " REQUIRED. This makes **Vim** invoke Latex-Suite when you open a tex file. filetype plugin on " IMPORTANT: win32 users will need to have 'shellslash' set so that latex " can be called correctly. set shellslash " IMPORTANT: grep will sometimes skip displaying the file name if you " search in a singe file. This will confuse Latex-Suite. Set your grep " program to always generate a file-name. set grepprg=grep\ -nH\ $* " Spelling: autocmd FileType tex setlocal spell spelllang=en_us Now you can edit and compile `.tex` files from within **GVim**. Load a [template document](https://www.dropbox.com/sh/lppr2bhmrm0wpfc/KEokhp0usL) from Dropbox. gvim technical_report.tex In **Vim**, press `\ll` to compile to dvi format. Start xdvi (the dvi viewer) to view results. Change something, compile again and reload (`Ctrl+R`) the viewer. Note: Reduce colors and decrease font size in **Gvim** by setting colorscheme morning set guifont=Monospace\ 8 set guioptions-=m in your `.gvimrc`. **GVim** can interact with xdvi -------------------------- If one clicks at some place in xdvi (usually Ctrl+Button1), **Vim** automatically jumps to the corresponding line in the LaTeX source file ("reverse search"). Also, from inside **Vim**, one can jump to the corresponding line in xdvi which becomes highlighted ("forward search"). Note: This shows only the process for **GVim**, the graphical **Vim** version. It works analogous for the terminal **Vim**. First of all, the LaTeX document need to tell the LaTeX compiler to set marks in the dvi file. Only put: \usepackage{srcltx} in the preamble of your latex document, or compile with: latex --src [your_file.tex] In your `.vimrc` file, add at the end: :map \ld :execute '!xdvi -editor "vim --servername 'v:servername' \ --remote +\%l \%f" -sourceposition ' . line(".") . expand("%") . \ " '" . expand(Tex_GetMainFileName(':r')) . ".dvi' >/dev/null&" Note: The above should be a single line. The `\` are not part of the command and are there to indicate that the command continues on the next line! And in your `.bashrc`: alias gvim='gvim --servername vimtex' Press `\ld` in **GVim** in normal mode to start xdvi with forward search. For things to work you must, in order: 1. Open the tex file with **GVim** (after `source`-ing your changed `~/.bashrc`), 2. Open the dvi file with the command `\ld` 3. reverse-search using Ctrl + left-mouse-click.