summaryrefslogtreecommitdiff
path: root/_posts/2012-05-18-using-vim.md
blob: 09b537a811795e444aa43d93477c55ea3bd72511 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
---
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.

<p></p>
---
<p></p>


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 <silent> <A-h> <C-w><
    map <silent> <A-j> <C-W>-
    map <silent> <A-k> <C-W>+
    map <silent> <A-l> <C-w>>
    " Maps Alt-[s.v] to horizontal and vertical split respectively
    map <silent> <A-s> :split<CR>
    map <silent> <A-v> :vsplit<CR>
    " Maps Alt-[n,p] for moving next and previous window respectively
    map <silent> <A-n> <C-w><C-w>
    map <silent> <A-p> <C-w><S-w>


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.

<p></p>
---
<p></p>



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 <F3> :call ToggleSpl('de')<cr>

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 <F2> :set invpaste paste?
    set pastetoggle=<F2>
    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**.


<p></p>
---
<p></p>


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 <C-d> :NERDTreeToggle<CR>

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 = '<c-p>'
    let g:ctrlp_cmd = 'CtrlP'

For details consult the respective plugin documentation.


<p></p>
---
<p></p>



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.


<p></p>
---
<p></p>



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 = "<C-X><C-O>"

    "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<TAB>

and **Vim** will present you with a list of applicable commands, from which you select `collect`.

![picture](/images/vim-cc.png "Vim code completion")


<p></p>
---
<p></p>



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&" <CR><CR>

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.