Posts Tagged ‘vim’

A little more Eclipse in Vim

June 13th, 2010 2 comments

I am currently coding Java using Eclipse and what I find particularly helpful is that Eclipse highlights all occurrences of the word under the cursor. So I decided that my favorite editor, vim, should do that too. After a lot of struggling and fiddling I finally understood and got it working.

Here is a quick snapshot what it will look like when we are finished:


The following code also serves as a general example on how to use python for scripting vim.

So let’s get started:

First we define a new look for our highlighting. I use simple bold text for that purpose.
Using ctermfg=white and ctermbg=gray (e.g.) you can also adjust the background and foreground color.

highlight MyWordUnderCursorHighlight cterm=bold

The second step is to hook up to the proper input events.
Therefor we use the auto command on cursor moved in normal mode (CursorMoved)
and in insert mode (CursorMovedI). The star stands for “every filetype”.
We simply let it call our to-be-defined function for highlighting.

autocmd CursorMoved * call MyHighlightWordUnderCursor()
autocmd CursorMovedI * call MyHighlightWordUnderCursor()

The function for highlighting (explanation in-lined):

function! MyHighlightWordUnderCursor()
" tell vim to use python from now on
python < < endpython
import vim
# get the character under the cursor
row, col = vim.current.window.cursor
characterUnderCursor = ''
    characterUnderCursor = vim.current.buffer[row-1][col]
# remove last highlight
vim.command("match MyWordUnderCursorHighlight //")
# if the cursor is currently located on a real word, move on and
# highlight it. We don't want to highlight anything when the cursor is not
# on a word.
if characterUnderCursor.isalpha()  or characterUnderCursor.isdigit() or characterUnderCursor is '_':
    # expand cword (a keyword in vim) to get the word under the cursor
    wordUnderCursor = vim.eval("expand(\'<cword>\')")
    if wordUnderCursor is None :
        wordUnderCursor = ""
    else :
        wordUnderCursor = "\< " + wordUnderCursor + "\>"
    currentSearch = vim.eval("@/")
    if currentSearch != wordUnderCursor :
        # highlight it
        vim.command("match MyWordUnderCursorHighlight /" + wordUnderCursor + "/")
# has to be the word after < < in the first line. Ends the python interpreter

all source again

That’s it. Have fun and may the force be with you.

PS: for some reason. wordpress screws up the formatting. Please use the above link for copy and paste

PS2: before pasting indented text into vim use “set paste” / “set nopaste”.

Here is the vimscript only version: (click)
Thanks bart!

Update 2:

  • words can now also consist of numbers and underscores
  • do not highlight the wordUnderCursor if it is the currently searched term

Categories: software Tags: , , , ,

DOS #2: Vim Tips

June 10th, 2009 2 comments

I have been using vim for development for over half a year now and want to share my setup and some commands I use on a daily base. To understand the article you need basic knowledge of how vim works.


Name: Vim (Vi IMproved)
Version: 7.2

How to set default options:

In the .vimrc file, default options can be set. This file is located in your home directory. e.g. ./home/user/.vimrc. There also is a global vimrc: /etc/vim/vimrc.

Default Option Set:

  • Abandon vi compatibility. Needed to get all the extras of vim.
    set nocompatible
  • Backspace is allowed to remove indentions, end of lines and starts.
    set backspace=indent,eol,start
  • Do not create backup files.
    set nobackup
  • Set the length of the history (accessed through arrow up and down, while typing a :-, /- or ?-command) to 400 entries.
    set history=400
  • Show the current cursor position in the status line.
    set ruler
  • Display incomplete commands in the status line.
    set showcmd
  • Display the current mode in the status line.
    set showmode
  • Visually jump to the matching opening bracket for a short time, when typing a closing bracket.
    set showmatch
  • Show intermediate search results, while typing a search term.
    set incsearch
  • Do not insert two spaces after a ‘.’, ‘?’ and ‘!’ with a join command.
    set nojoinspaces
  • Disallow all keys to move to the next line. See :help whichwrap for more information.
    set whichwrap=""
  • Use filetype-specific indention, if possible.
    filetype plugin indent on
  • Enable syntax highlighting. Vim is able to highlight more than 200 distinct filetypes.
    syntax enable
  • Highlight all search hits. Use :nohls to turn it off.
    set hlsearch
  • Indent intelligently, automatically – My favourite indention mode.
    set autoindent
  • Replace tabs with spaces.
    set expandtab
  • How many spaces is a tab?
    set tabstop=4
  • How many spaces is an indention.
    set shiftwidth=4
  • Show line numbers.
    set number
  • Always use the default color scheme.
    colorscheme default
  • Highlight trailing spaces and @todos.
    match Todo /\s\+$/                                                                                                                        
    match Todo /@todo/                                                                                                                        
  • Jump to end of the file, if opening a log file.
    :augroup somethinguseful                                                                                                                  
    :au BufReadPost *.log normal G                                                                                                            
    :augroup END                                                                                                                              


set nocompatible                    " deactivated compatibility to vi
set backspace=indent,eol,start      " what is the backspace allowed to delete
set nobackup                        " do not keep a backup files, use versions instead
set history=400                     " keep 400 lines of command line history          
set ruler                           " show the cursor position all the time           
set showcmd                         " display incomplete commands                     
set showmode                        " show in which mode we are in the status line    
set showmatch                       " visually jumps the matching bracket when typing closing brackets
set incsearch                       " do incremental searching                                        
set nojoinspaces                    " do not insert a space, when joining lines                       
set whichwrap=""                    " do not jump to the next line when deleting                      
filetype plugin indent on           " if there is an indention plugin matching the filetype, use it   
syntax enable                       " syntax highlighting on                                          
set hlsearch                        " highlight all search hits                                       
set autoindent                      " indent intelligently automatically                              
set expandtab                       " expand tabs to spaces                                           
set tabstop=4                       " how many spaces make one tab                                    
set shiftwidth=4                    " how many spaces to indent, using < and >                        
set number                          " show line numbers                                               
colorscheme default                                                                                   

match Todo /\s\+$/                  " highlight trailing white spaces
match Todo /@todo/                  " highlight doxygen todos        

:augroup somethinguseful
:au BufReadPost *.log normal G " jump to the end of the file if it is a logfile
:augroup END                                                                   


Since vim has a multitude of commands, having a cheat sheet is a must. Here is my favorite: Graphical Cheat Sheet.
Disclaimer: The following commands are likely to be more powerful than shown here.
This is only a narrow view on which commands and command combinations I use every day.


  • [] : optional argument
  • <> : mandatory argument
  • count : any number
  • movement : any movement command. e.g.: w,b,e,ge,arrows,^,$,…
  • {v} : being in visual mode
  • {i} : being in insertion mode


  • w, b : Move to the first character of the next/previous word.
  • e, ge : Move to the last character of the next/previous word.
  • /<find>/, ?<find>? : Search the term <find> forward/backward.
  • //, ?? : Repeat the last search.
  • *, # : Search the word under the cursor forward/backward.
  • n, N : Jump to the first letter of the next hit. I often use this in conjunction with the . command (The dot will be explained later on.)
  • :[no]hls : Switch off/on the highlight for the previous search. Use this when you are done with your search to not get distracted by the highlight.
  • % : Jump between matching starting and ending bracket.
  • ^ : Jump to the first non-blank character of this line.
  • [count]G : Jump to line [count]. Jump to the start of the file if [count] is omitted.
  • gg : Jump to the end of the file.


  • i,a : Switch to insertion mode before/after the current position.
  • I,A : Switch to insertion mode at the begin/end of the line.
  • [count]r<replacementcharacter> : Replace the [count] next characters with [count] <replacementcharacter>s starting at the current cursor position.
  • R : Switch to replacement mode.
  • c[count]<movement> : Delete the next [count] <movement>s and switch to insertion mode. I very often use cw.
  • cc : Change the whole line and preserve the indention.
  • d[count]<movement> : Delete the next [count] <movement>s. I very often use dw.
  • dd : Remove the current line.
  • J : Join the current line with next.
  • :0,$ s/<find>/<replace>/g : starting from line 0, ranging to the last line: Replace all appearances of <find> with <replace>.
  • . : Repeat the last insertion command. This is a very powerful tool, when you have to change something similarly in multiple places!


  • [linecount]>>, [linecount]<< : Indent the next [linecount] lines, starting with the current.
  • {v} [indentcount]>, [indentcount]< : Indent the selected lines by [indentcount] indents.
  • {v} = : Automatically indent the selected lines according to the filetype’s rules.


Vim has an automatically changing clipboard. It changes on every deletion/change of anything. E.g.: d,x,c,s,…

  • y[count]<movement> : yank/copy the next [count] <movements>. I very often use y[count]w to copy whole words.
  • yy : Yank the current line.
  • p, P : Paste after/before the current position.
  • {i} Alt+p : Paste before the current position and leave insertion mode.


  • vim -p [files] : Open vim opening one tab for each file specified.
  • :tabnew [file] : Open a new tab, loading file [file].
  • :tabdo <command> : Execute command <command> in each tab separately.
  • :tabmove [count] : Move this tab to position [count] or to the last position if no [count] is specified.
  • Ctrl+Page Up, Ctrl+Page Down : Switch between tabs.

Visual Mode

  • v : Switch to visual mode.
  • V : Switch to visual mode, selecting whole lines.
  • Ctrl+v : Switch to visual mode, selecting whole blocks. For example to comment out a block in c++, you just need: Ctr+v (select some lines vertically) I // Esc Esc. This puts // in each of the selected lines at the current column.
  • gv : Restore the last selection.


  • u, Ctrl+r : Undo, Redo
  • Ctrl+p, Ctrl+n : Word completion searching forward/backward. This command also searches through included header files in c/c++.
  • :mks[!] <file> : Save the current session to file <file>.
  • vim -S <sessionfile> : Start vim using session <sessionfile>.
  • :set [no]paste : Switch on/off auto indention. Use this when pasting already indented text into vim.

This is probably too much to remember at once, so I suggest you have a look at this once in a while and try to apply one feature at a time. If you got used to it, move on to next.
Happy Coding!

Categories: DOS, software Tags: ,

vim magic

February 24th, 2009 5 comments

Categories: nerdcore, software Tags: