Posts Tagged ‘vimscript’

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: , , , ,