aboutsummaryrefslogtreecommitdiff
path: root/plugin/cursorline_current.vim
blob: b0c38b4e7fe79a0ed4781ee1a9b55313b9295073 (plain) (blame)
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
"
" cursorline_current: If 'cursorline' is globally on, only enable it for the
" current window, and only when not in insert mode.  Essentially, make
" 'cursorline' follow the actual normal-mode cursor as much as possible.
"
" Author: Tom Ryder <tom@sanctum.geek.nz>
" License: Same as Vim itself
"
if exists('loaded_cursorline_current') || &compatible
  finish
endif
if !has('autocmd') || !has('windows') || v:version < 700
  finish
endif
let loaded_cursorline_current = 1

" Suspend 'cursorline' when a window is inactive or inserting
function! s:Suspend() abort
  let w:cursorline_current = &l:cursorline
  let &l:cursorline = 0
endfunction

" Restore 'cursorline' when a window is active and non-insert
function! s:Restore() abort
  let &l:cursorline = get(w:, 'cursorline_current', &g:cursorline)
  let w:cursorline_current = &l:cursorline
endfunction

" Call s:Suspend() on all windows besides the current one
function! s:Load() abort

  " Cache current window index
  let wcur = winnr()

  " Iterate through all the windows and suspend all but the current one
  for wnum in range(1, winnr('$'))
    if wnum == wcur
      continue
    endif
    execute wnum . 'wincmd w'
    call s:Suspend()
  endfor

  " Return to the window in which we started
  execute wcur . 'wincmd w'

endfunction

" Set up hooks for toggling 'cursorline'
augroup cursorline_current
  autocmd!

  " Turn off 'cursorline' for other windows on load
  autocmd VimEnter * call s:Load()

  " Turn off 'cursorline' when leaving a window or losing focus.  We call the
  " restore again on BufEnter to handle existent local buffer values for the
  " option overwriting the window value (Vim bug?)
  autocmd WinLeave,FocusLost * call s:Suspend()
  autocmd BufEnter,WinEnter,FocusGained * call s:Restore()

  " Turn off 'cursorline' when in insert mode
  " Check g:cursorline_current_insert, in case the user doesn't want it
  if get(g:, 'cursorline_current_insert', 1)
    autocmd InsertEnter * call s:Suspend()
    autocmd InsertLeave * call s:Restore()
  endif

augroup END