aboutsummaryrefslogtreecommitdiff
path: root/plugin/insert_cancel.vim
blob: 61d0b495b0d73514839487ce102a1a5f975c8d55 (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
"
" insert_cancel.vim: Cancel the current insert operation by undoing the last
" change upon insert exit, if we made a change; intended for remapping
" insert-mode Ctrl-C to do something useful.
"
" Author: Tom Ryder <tom@sanctum.geek.nz>
" License: Same as Vim itself
"
if exists('g:loaded_insert_cancel') || &compatible
  finish
endif
if v:version < 600
  finish
endif
let g:loaded_insert_cancel = 1

" Initialise s:changedtick so vint understands
let s:changedtick = 0

" Set up an appropriate hook to track b:changedtick before we hit InsertLeave
if has('autocmd')
  augroup insert_cancel
    autocmd!

    " Ideal; only runs when the text actually changes
    if v:version > 703 || v:version == 703 && has('patch867')
      autocmd TextChanged * let s:changedtick = b:changedtick

    " Workable but wasteful and not quite as correct; updates every move
    elseif v:version >= 700
      autocmd CursorMoved * let s:changedtick = b:changedtick
    endif

  augroup END
endif

" Try hard to figure out whether we made a change to undo, and undo it if so
function! s:InsertCancel()
  if !&modified
    return
  endif
  if s:changedtick > 0 && b:changedtick > s:changedtick
        \ || line("'[") != line("']")
        \ || col("'[") != col("']")
    silent undo
  endif
endfunction

" Provide plugin mapping
inoremap <silent> <Plug>InsertCancel
      \ <Esc>:<C-U>call <SID>InsertCancel()<CR>