aboutsummaryrefslogtreecommitdiff
path: root/autoload/paste_insert.vim
blob: 277f333139e3c0a1c0418febcc8bf3c382834ed9 (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
70
71
" Autoloaded entry point function
function! paste_insert#() abort

  " Set up an event table
  augroup paste_insert
    autocmd!

    " Set up the paste and tell the user
    autocmd User Start
          \ call s:Start() | echo 'Paste ready'

    " When starting insert mode, add completion hook for when we leave
    autocmd InsertEnter *
          \ autocmd paste_insert InsertLeave *
                \ doautocmd paste_insert User Complete

    " User waits too long in normal mode, timeout
    autocmd CursorHold *
          \ doautocmd paste_insert User Timeout

    " User leaves the buffer or window, abort
    autocmd BufLeave,WinLeave *
          \ doautocmd paste_insert User Abort

    " Exit condition reporting
    autocmd User Abort
          \ echo 'Paste aborted'
    autocmd User Cancel
          \ echo 'Paste cancelled'
    autocmd User Complete
          \ echo 'Paste completed'
    autocmd User Timeout
          \ echo 'Paste timeout'

    " End the paste and clear the events table
    autocmd User Abort,Cancel,Complete,Timeout
          \ call s:Stop() | autocmd! paste_insert

  augroup END

  " Trigger the starting actions
  doautocmd paste_insert User Start

endfunction

" Key that cancels the pending paste in normal mode, defaults to CTRL-C
let s:cancel = get(g:, 'paste_insert_cancel', '<C-C>')

" Start the paste: save cancel key's prior function, remap it, set 'paste'
function! s:Start() abort
  let s:maparg = maparg(s:cancel)
  let command = join([
        \ 'nnoremap'
        \,s:cancel
        \,':<C-U>doautocmd paste_insert User Cancel<CR>'
        \])
  execute command
  set paste
endfunction

" Stop the paste: unset 'paste', restore prior function of cancel key
function! s:Stop() abort
  set nopaste
  let command = join(
        \ s:maparg !=# ''
        \ ? ['nnoremap', s:cancel, s:maparg]
        \ : ['nunmap', s:cancel]
        \)
  execute command
  unlet s:maparg
endfunction