Wikia

Vim Tips Wiki

Highlight cursor line after cursor jump

Talk0
1,612pages on
this wiki
Tip 1380 Printable Monobook Previous Next

created 2006 · complexity basic · author pulp · version n/a


Use this code to highlight the cursor line after a jump. This makes it easy to spot the new cursor position. The highlight will be removed automatically when you move the cursor within the current line, or down or up by one line.

function s:Cursor_Moved()
  let cur_pos = winline()
  if g:last_pos == 0
    set cul
    let g:last_pos = cur_pos
    return
  endif
  let diff = g:last_pos - cur_pos
  if diff > 1 || diff < -1
    set cul
  else
    set nocul
  endif
  let g:last_pos = cur_pos
endfunction
autocmd CursorMoved,CursorMovedI * call s:Cursor_Moved()
let g:last_pos = 0

CommentsEdit

 TO DO 

  • Should use autogroup and remove old autocmd when source again.
  • Need WinEnter autocmd?
  • Nice if could handle split windows reasonably (highlight when enter split).

If you want the current line highlighted when moving even by one line, use:

if diff >= 1 || diff <= -1

instead of

if diff > 1 || diff < -1

If you still want to be able to manually set the cursor line:

In your autocmd section:

let g:manual_cursor = 0

Create a mapping to manually toggle the cursorline and set a global var for the function to check:

nnoremap <silent> <LocalLeader>tc :set invcul cul?<CR>:let g:manual_cursor=&cul<CR>

In the function definition:

if g:manual_cursor
  return
endif

Then, \tc in normal mode allows you to toggle a persistent or transient cursorline ('tc' is a mnemonic for "toggle cursor").


By default, in a cterm, this highlights the current line by underlining it. Is it possible to highlight some other way, e.g. by changing the background colour of that line, or formatting the line's text in bold?

The format of the highlight can be set using 'hi CursorLine', eg. 'hi cursorline cterm=bold ctermbg=grey'

It is probably better to use
setlocal cul
and
setlocal nocul
to only change the setting for the buffer you're working in. Also, for some "special" buffers you may add the following code at the beginning of the function to avoid changing the setting (the following skips the function for the NERDTree window):
if bufname ('%') =~ '^NERD_tree_'
    return
endif

(Or check for some buffer-local variable and skip based on that...)

Around Wikia's network

Random Wiki