robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
159.2 KiB5531 linesraw
1" Tests for autocommands
2
3source shared.vim
4source check.vim
5source term_util.vim
6source screendump.vim
7source vim9.vim
8source load.vim
9
10func s:cleanup_buffers() abort
11  for bnr in range(1, bufnr('$'))
12    if bufloaded(bnr) && bufnr('%') != bnr
13      execute 'bd! ' . bnr
14    endif
15  endfor
16endfunc
17
18func CleanUpTestAuGroup()
19  augroup testing
20    au!
21  augroup END
22  augroup! testing
23endfunc
24
25func Test_vim_did_enter()
26  call assert_false(v:vim_did_enter)
27
28  " This script will never reach the main loop, can't check if v:vim_did_enter
29  " becomes one.
30endfunc
31
32" Test for the CursorHold autocmd
33func Test_CursorHold_autocmd()
34  CheckRunVimInTerminal
35  call writefile(['one', 'two', 'three'], 'XoneTwoThree', 'D')
36  let before =<< trim END
37    set updatetime=10
38    au CursorHold * call writefile([line('.')], 'XCHoutput', 'a')
39  END
40  call writefile(before, 'XCHinit', 'D')
41  let buf = RunVimInTerminal('-S XCHinit XoneTwoThree', {})
42  call term_sendkeys(buf, "G")
43  call term_wait(buf, 50)
44  call term_sendkeys(buf, "gg")
45  call term_wait(buf)
46  call WaitForAssert({-> assert_equal(['1'], readfile('XCHoutput')[-1:-1])})
47  call term_sendkeys(buf, "j")
48  call term_wait(buf)
49  call WaitForAssert({-> assert_equal(['1', '2'], readfile('XCHoutput')[-2:-1])})
50  call term_sendkeys(buf, "j")
51  call term_wait(buf)
52  call WaitForAssert({-> assert_equal(['1', '2', '3'], readfile('XCHoutput')[-3:-1])})
53  call StopVimInTerminal(buf)
54
55  call delete('XCHoutput')
56endfunc
57
58if has('timers')
59
60  func ExitInsertMode(id)
61    call feedkeys("\<Esc>")
62  endfunc
63
64  func Test_cursorhold_insert()
65    " depends on timing
66    let g:test_is_flaky = 1
67
68    " Need to move the cursor.
69    call feedkeys("ggG", "xt")
70
71    let g:triggered = 0
72    au CursorHoldI * let g:triggered += 1
73    set updatetime=20
74    call timer_start(LoadAdjust(200), 'ExitInsertMode')
75    call feedkeys('a', 'x!')
76    call assert_equal(1, g:triggered)
77    unlet g:triggered
78    au! CursorHoldI
79    set updatetime&
80  endfunc
81
82  func Test_cursorhold_insert_with_timer_interrupt()
83    CheckFeature job
84    " Need to move the cursor.
85    call feedkeys("ggG", "xt")
86
87    " Confirm the timer invoked in exit_cb of the job doesn't disturb
88    " CursorHoldI event.
89    let g:triggered = 0
90    au CursorHoldI * let g:triggered += 1
91    set updatetime=100
92    call job_start(has('win32') ? 'cmd /D /c echo:' : 'echo',
93          \ {'exit_cb': {-> timer_start(200, 'ExitInsertMode')}})
94    call feedkeys('a', 'x!')
95    call assert_equal(1, g:triggered)
96    unlet g:triggered
97    au! CursorHoldI
98    set updatetime&
99  endfunc
100
101  func Test_cursorhold_insert_ctrl_x()
102    let g:triggered = 0
103    au CursorHoldI * let g:triggered += 1
104    set updatetime=20
105    call timer_start(LoadAdjust(100), 'ExitInsertMode')
106    " CursorHoldI does not trigger after CTRL-X
107    call feedkeys("a\<C-X>", 'x!')
108    call assert_equal(0, g:triggered)
109    unlet g:triggered
110    au! CursorHoldI
111    set updatetime&
112  endfunc
113
114  func Test_cursorhold_insert_ctrl_g_U()
115    au CursorHoldI * :
116    set updatetime=20
117    new
118    call timer_start(100, { -> feedkeys("\<Left>foo\<Esc>", 't') })
119    call feedkeys("i()\<C-g>U", 'tx!')
120    sleep 200m
121    call assert_equal('(foo)', getline(1))
122    undo
123    call assert_equal('', getline(1))
124
125    bwipe!
126    au! CursorHoldI
127    set updatetime&
128  endfunc
129
130  func Test_OptionSet_modeline()
131    call Ntest_override('starting', 1)
132    au! OptionSet
133    augroup set_tabstop
134      au OptionSet tabstop call timer_start(1, {-> execute("echo 'Handler called'", "")})
135    augroup END
136    call writefile(['vim: set ts=7 sw=5 :', 'something'], 'XoptionsetModeline', 'D')
137    set modeline
138    let v:errmsg = ''
139    call assert_fails('split XoptionsetModeline', 'E12:')
140    call assert_equal(7, &ts)
141    call assert_equal('', v:errmsg)
142
143    augroup set_tabstop
144      au!
145    augroup END
146    bwipe!
147    set ts&
148    call Ntest_override('starting', 0)
149  endfunc
150
151endif "has('timers')
152
153func Test_bufunload()
154  augroup test_bufunload_group
155    autocmd!
156    autocmd BufUnload * call add(s:li, "bufunload")
157    autocmd BufDelete * call add(s:li, "bufdelete")
158    autocmd BufWipeout * call add(s:li, "bufwipeout")
159  augroup END
160
161  let s:li = []
162  new
163  setlocal bufhidden=
164  bunload
165  call assert_equal(["bufunload", "bufdelete"], s:li)
166
167  let s:li = []
168  new
169  setlocal bufhidden=delete
170  bunload
171  call assert_equal(["bufunload", "bufdelete"], s:li)
172
173  let s:li = []
174  new
175  setlocal bufhidden=unload
176  bwipeout
177  call assert_equal(["bufunload", "bufdelete", "bufwipeout"], s:li)
178
179  au! test_bufunload_group
180  augroup! test_bufunload_group
181endfunc
182
183" SEGV occurs in older versions.  (At least 7.4.2005 or older)
184func Test_autocmd_bufunload_with_tabnext()
185  tabedit
186  tabfirst
187
188  augroup test_autocmd_bufunload_with_tabnext_group
189    autocmd!
190    autocmd BufUnload <buffer> tabnext
191  augroup END
192
193  quit
194  call assert_equal(2, tabpagenr('$'))
195
196  autocmd! test_autocmd_bufunload_with_tabnext_group
197  augroup! test_autocmd_bufunload_with_tabnext_group
198  tablast
199  quit
200endfunc
201
202func Test_argdelete_in_next()
203  au BufNew,BufEnter,BufLeave,BufWinEnter * argdel
204  call assert_fails('next a b', 'E1156:')
205  au! BufNew,BufEnter,BufLeave,BufWinEnter *
206endfunc
207
208func Test_autocmd_bufwinleave_with_tabfirst()
209  tabedit
210  augroup sample
211    autocmd!
212    autocmd BufWinLeave <buffer> tabfirst
213  augroup END
214  call setline(1, ['a', 'b', 'c'])
215  edit! a.txt
216  tabclose
217endfunc
218
219" SEGV occurs in older versions.  (At least 7.4.2321 or older)
220func Test_autocmd_bufunload_avoiding_SEGV_01()
221  split aa.txt
222  let lastbuf = bufnr('$')
223
224  augroup test_autocmd_bufunload
225    autocmd!
226    exe 'autocmd BufUnload <buffer> ' . (lastbuf + 1) . 'bwipeout!'
227  augroup END
228
229  call assert_fails('edit bb.txt', 'E937:')
230
231  autocmd! test_autocmd_bufunload
232  augroup! test_autocmd_bufunload
233  bwipe! aa.txt
234  bwipe! bb.txt
235endfunc
236
237" SEGV occurs in older versions.  (At least 7.4.2321 or older)
238func Test_autocmd_bufunload_avoiding_SEGV_02()
239  setlocal buftype=nowrite
240  let lastbuf = bufnr('$')
241
242  augroup test_autocmd_bufunload
243    autocmd!
244    exe 'autocmd BufUnload <buffer> ' . (lastbuf + 1) . 'bwipeout!'
245  augroup END
246
247  normal! i1
248  call assert_fails('edit a.txt', 'E517:')
249
250  autocmd! test_autocmd_bufunload
251  augroup! test_autocmd_bufunload
252  bwipe! a.txt
253endfunc
254
255func Test_autocmd_dummy_wipeout()
256  " prepare files
257  call writefile([''], 'Xdummywipetest1.txt', 'D')
258  call writefile([''], 'Xdummywipetest2.txt', 'D')
259  augroup test_bufunload_group
260    autocmd!
261    autocmd BufUnload * call add(s:li, "bufunload")
262    autocmd BufDelete * call add(s:li, "bufdelete")
263    autocmd BufWipeout * call add(s:li, "bufwipeout")
264  augroup END
265
266  let s:li = []
267  split Xdummywipetest1.txt
268  silent! vimgrep /notmatched/ Xdummywipetest*
269  call assert_equal(["bufunload", "bufwipeout"], s:li)
270
271  bwipeout
272  au! test_bufunload_group
273  augroup! test_bufunload_group
274endfunc
275
276func Test_win_tab_autocmd()
277  let g:record = []
278
279  defer CleanUpTestAuGroup()
280  augroup testing
281    au WinNewPre * call add(g:record, 'WinNewPre')
282    au WinNew * call add(g:record, 'WinNew')
283    au WinClosed * call add(g:record, 'WinClosed')
284    au WinEnter * call add(g:record, 'WinEnter')
285    au WinLeave * call add(g:record, 'WinLeave')
286    au TabNew * call add(g:record, 'TabNew')
287    au TabClosed * call add(g:record, 'TabClosed')
288    au TabEnter * call add(g:record, 'TabEnter')
289    au TabLeave * call add(g:record, 'TabLeave')
290  augroup END
291
292  split
293  tabnew
294  close
295  close
296
297  call assert_equal([
298	\ 'WinNewPre', 'WinLeave', 'WinNew', 'WinEnter',
299	\ 'WinLeave', 'TabLeave', 'WinNew', 'WinEnter', 'TabNew', 'TabEnter',
300	\ 'WinLeave', 'TabLeave', 'WinClosed', 'TabClosed', 'WinEnter', 'TabEnter',
301	\ 'WinLeave', 'WinClosed', 'WinEnter'
302	\ ], g:record)
303
304  let g:record = []
305  tabnew somefile
306  tabnext
307  bwipe somefile
308
309  call assert_equal([
310	\ 'WinLeave', 'TabLeave', 'WinNew', 'WinEnter', 'TabNew', 'TabEnter',
311	\ 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter',
312	\ 'WinClosed', 'TabClosed'
313	\ ], g:record)
314
315  let g:record = []
316  copen
317  help
318  tabnext
319  vnew
320
321  call assert_equal([
322	\ 'WinNewPre', 'WinLeave', 'WinNew', 'WinEnter',
323	\ 'WinNewPre', 'WinLeave', 'WinNew', 'WinEnter',
324	\ 'WinNewPre', 'WinLeave', 'WinNew', 'WinEnter'
325	\ ], g:record)
326
327  unlet g:record
328endfunc
329
330func Test_WinNewPre()
331  " Test that the old window layout can be accessed before a new window is created.
332  let g:layouts_pre = []
333  let g:layouts_post = []
334  augroup testing
335    au WinNewPre * call add(g:layouts_pre, winlayout())
336    au WinNew * call add(g:layouts_post, winlayout())
337  augroup END
338  defer CleanUpTestAuGroup()
339  split
340  call assert_notequal(g:layouts_pre[0], g:layouts_post[0])
341  split
342  call assert_equal(g:layouts_pre[1], g:layouts_post[0])
343  call assert_notequal(g:layouts_pre[1], g:layouts_post[1])
344  " not triggered for tabnew
345  tabnew
346  call assert_equal(2, len(g:layouts_pre))
347  unlet g:layouts_pre
348  unlet g:layouts_post
349
350  " Test modifying window layout during WinNewPre throws.
351  let g:caught = 0
352  augroup testing
353    au!
354    au WinNewPre * split
355  augroup END
356  try
357    vnew
358  catch
359    let g:caught += 1
360  endtry
361  augroup testing
362    au!
363    au WinNewPre * tabnew
364  augroup END
365  try
366    vnew
367  catch
368    let g:caught += 1
369  endtry
370  augroup testing
371    au!
372    au WinNewPre * close
373  augroup END
374  try
375    vnew
376  catch
377    let g:caught += 1
378  endtry
379  augroup testing
380    au!
381    au WinNewPre * tabclose
382  augroup END
383  try
384    vnew
385  catch
386    let g:caught += 1
387  endtry
388  call assert_equal(4, g:caught)
389  unlet g:caught
390endfunc
391
392func Test_WinResized()
393  CheckRunVimInTerminal
394
395  let lines =<< trim END
396    set scrolloff=0
397    call setline(1, ['111', '222'])
398    vnew
399    call setline(1, ['aaa', 'bbb'])
400    new
401    call setline(1, ['foo', 'bar'])
402
403    let g:resized = 0
404    au WinResized * let g:resized += 1
405
406    func WriteResizedEvent()
407      call writefile([json_encode(v:event)], 'XresizeEvent')
408    endfunc
409    au WinResized * call WriteResizedEvent()
410  END
411  call writefile(lines, 'Xtest_winresized', 'D')
412  let buf = RunVimInTerminal('-S Xtest_winresized', {'rows': 10})
413
414  " redraw now to avoid a redraw after the :echo command
415  call term_sendkeys(buf, ":redraw!\<CR>")
416  call TermWait(buf)
417
418  call term_sendkeys(buf, ":echo g:resized\<CR>")
419  call WaitForAssert({-> assert_match('^0$', term_getline(buf, 10))}, 1000)
420
421  " increase window height, two windows will be reported
422  call term_sendkeys(buf, "\<C-W>+")
423  call TermWait(buf)
424  call term_sendkeys(buf, ":echo g:resized\<CR>")
425  call WaitForAssert({-> assert_match('^1$', term_getline(buf, 10))}, 1000)
426
427  let event = readfile('XresizeEvent')[0]->json_decode()
428  call assert_equal({
429        \ 'windows': [1002, 1001],
430        \ }, event)
431
432  " increase window width, three windows will be reported
433  call term_sendkeys(buf, "\<C-W>>")
434  call TermWait(buf)
435  call term_sendkeys(buf, ":echo g:resized\<CR>")
436  call WaitForAssert({-> assert_match('^2$', term_getline(buf, 10))}, 1000)
437
438  let event = readfile('XresizeEvent')[0]->json_decode()
439  call assert_equal({
440        \ 'windows': [1002, 1001, 1000],
441        \ }, event)
442
443  call delete('XresizeEvent')
444  call StopVimInTerminal(buf)
445endfunc
446
447func Test_WinScrolled()
448  CheckRunVimInTerminal
449
450  let lines =<< trim END
451    set nowrap scrolloff=0
452    for ii in range(1, 18)
453      call setline(ii, repeat(nr2char(96 + ii), ii * 2))
454    endfor
455    let win_id = win_getid()
456    let g:matched = v:false
457    func WriteScrollEvent()
458      call writefile([json_encode(v:event)], 'XscrollEvent')
459    endfunc
460    execute 'au WinScrolled' win_id 'let g:matched = v:true'
461    let g:scrolled = 0
462    au WinScrolled * let g:scrolled += 1
463    au WinScrolled * let g:amatch = str2nr(expand('<amatch>'))
464    au WinScrolled * let g:afile = str2nr(expand('<afile>'))
465    au WinScrolled * call WriteScrollEvent()
466  END
467  call writefile(lines, 'Xtest_winscrolled', 'D')
468  let buf = RunVimInTerminal('-S Xtest_winscrolled', {'rows': 6})
469
470  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
471  call WaitForAssert({-> assert_match('^0 ', term_getline(buf, 6))}, 1000)
472
473  " Scroll left/right in Normal mode.
474  call term_sendkeys(buf, "zlzh:echo g:scrolled\<CR>")
475  call WaitForAssert({-> assert_match('^2 ', term_getline(buf, 6))}, 1000)
476
477  let event = readfile('XscrollEvent')[0]->json_decode()
478  call assert_equal({
479        \ 'all': {'leftcol': 1, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
480        \ '1000': {'leftcol': -1, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}
481        \ }, event)
482
483  " Scroll up/down in Normal mode.
484  call term_sendkeys(buf, "\<c-e>\<c-y>:echo g:scrolled\<CR>")
485  call WaitForAssert({-> assert_match('^4 ', term_getline(buf, 6))}, 1000)
486
487  let event = readfile('XscrollEvent')[0]->json_decode()
488  call assert_equal({
489        \ 'all': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
490        \ '1000': {'leftcol': 0, 'topline': -1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}
491        \ }, event)
492
493  " Scroll up/down in Insert mode.
494  call term_sendkeys(buf, "Mi\<c-x>\<c-e>\<Esc>i\<c-x>\<c-y>\<Esc>")
495  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
496  call WaitForAssert({-> assert_match('^6 ', term_getline(buf, 6))}, 1000)
497
498  let event = readfile('XscrollEvent')[0]->json_decode()
499  call assert_equal({
500        \ 'all': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
501        \ '1000': {'leftcol': 0, 'topline': -1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}
502        \ }, event)
503
504  " Scroll the window horizontally to focus the last letter of the third line
505  " containing only six characters. Moving to the previous and shorter lines
506  " should trigger another autocommand as Vim has to make them visible.
507  call term_sendkeys(buf, "5zl2k")
508  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
509  call WaitForAssert({-> assert_match('^8 ', term_getline(buf, 6))}, 1000)
510
511  let event = readfile('XscrollEvent')[0]->json_decode()
512  call assert_equal({
513        \ 'all': {'leftcol': 5, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
514        \ '1000': {'leftcol': -5, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}
515        \ }, event)
516
517  " Ensure the command was triggered for the specified window ID.
518  call term_sendkeys(buf, ":echo g:matched\<CR>")
519  call WaitForAssert({-> assert_match('^v:true ', term_getline(buf, 6))}, 1000)
520
521  " Ensure the expansion of <amatch> and <afile> matches the window ID.
522  call term_sendkeys(buf, ":echo g:amatch == win_id && g:afile == win_id\<CR>")
523  call WaitForAssert({-> assert_match('^v:true ', term_getline(buf, 6))}, 1000)
524
525  call delete('XscrollEvent')
526  call StopVimInTerminal(buf)
527endfunc
528
529func Test_WinScrolled_mouse()
530  CheckRunVimInTerminal
531
532  let lines =<< trim END
533    set nowrap scrolloff=0
534    set mouse=a term=xterm ttymouse=sgr mousetime=200 clipboard=
535    call setline(1, ['foo']->repeat(32))
536    split
537    let g:scrolled = 0
538    au WinScrolled * let g:scrolled += 1
539  END
540  call writefile(lines, 'Xtest_winscrolled_mouse', 'D')
541  let buf = RunVimInTerminal('-S Xtest_winscrolled_mouse', {'rows': 10})
542
543  " With the upper split focused, send a scroll-down event to the unfocused one.
544  call test_setmouse(7, 1)
545  call term_sendkeys(buf, "\<ScrollWheelDown>")
546  call TermWait(buf)
547  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
548  call WaitForAssert({-> assert_match('^1', term_getline(buf, 10))}, 1000)
549
550  " Again, but this time while we're in insert mode.
551  call term_sendkeys(buf, "i\<ScrollWheelDown>\<Esc>")
552  call TermWait(buf)
553  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
554  call WaitForAssert({-> assert_match('^2', term_getline(buf, 10))}, 1000)
555
556  call StopVimInTerminal(buf)
557endfunc
558
559func Test_WinScrolled_close_curwin()
560  CheckRunVimInTerminal
561
562  let lines =<< trim END
563    set nowrap scrolloff=0
564    call setline(1, ['aaa', 'bbb'])
565    vsplit
566    au WinScrolled * close
567    au VimLeave * call writefile(['123456'], 'Xtestout')
568  END
569  call writefile(lines, 'Xtest_winscrolled_close_curwin', 'D')
570  let buf = RunVimInTerminal('-S Xtest_winscrolled_close_curwin', {'rows': 6})
571
572  " This was using freed memory
573  call term_sendkeys(buf, "\<C-E>")
574  call TermWait(buf)
575  call StopVimInTerminal(buf)
576
577  " check the startup script finished to the end
578  call assert_equal(['123456'], readfile('Xtestout'))
579  call delete('Xtestout')
580endfunc
581
582func Test_WinScrolled_once_only()
583  CheckScreendump
584  CheckRunVimInTerminal
585
586  let lines =<< trim END
587      set cmdheight=2
588      call setline(1, ['aaa', 'bbb'])
589      let trigger_count = 0
590      func ShowInfo(id)
591        echo g:trigger_count g:winid winlayout()
592      endfunc
593
594      vsplit
595      split
596      " use a timer to show the info after a redraw
597      au WinScrolled * let trigger_count += 1 | let winid = expand('<amatch>') | call timer_start(100, 'ShowInfo')
598      wincmd j
599      wincmd l
600  END
601  call writefile(lines, 'Xtest_winscrolled_once', 'D')
602  let buf = RunVimInTerminal('-S Xtest_winscrolled_once', #{rows: 10, cols: 60, statusoff: 2})
603
604  call term_sendkeys(buf, "\<C-E>")
605  call VerifyScreenDump(buf, 'Test_winscrolled_once_only_1', {})
606
607  call StopVimInTerminal(buf)
608endfunc
609
610" Check that WinScrolled is not triggered immediately when defined and there
611" are split windows.
612func Test_WinScrolled_not_when_defined()
613  CheckScreendump
614  CheckRunVimInTerminal
615
616  let lines =<< trim END
617      call setline(1, ['aaa', 'bbb'])
618      echo 'nothing happened'
619      func ShowTriggered(id)
620        echo 'triggered'
621      endfunc
622  END
623  call writefile(lines, 'Xtest_winscrolled_not', 'D')
624  let buf = RunVimInTerminal('-S Xtest_winscrolled_not', #{rows: 10, cols: 60, statusoff: 2})
625  call term_sendkeys(buf, ":split\<CR>")
626  call TermWait(buf)
627  " use a timer to show the message after redrawing
628  call term_sendkeys(buf, ":au WinScrolled * call timer_start(100, 'ShowTriggered')\<CR>")
629  call VerifyScreenDump(buf, 'Test_winscrolled_not_when_defined_1', {})
630
631  call term_sendkeys(buf, "\<C-E>")
632  call VerifyScreenDump(buf, 'Test_winscrolled_not_when_defined_2', {})
633
634  call StopVimInTerminal(buf)
635endfunc
636
637func Test_WinScrolled_long_wrapped()
638  CheckRunVimInTerminal
639
640  let lines =<< trim END
641    set scrolloff=0
642    let height = winheight(0)
643    let width = winwidth(0)
644    let g:scrolled = 0
645    au WinScrolled * let g:scrolled += 1
646    call setline(1, repeat('foo', height * width))
647    call cursor(1, height * width)
648  END
649  call writefile(lines, 'Xtest_winscrolled_long_wrapped', 'D')
650  let buf = RunVimInTerminal('-S Xtest_winscrolled_long_wrapped', {'rows': 6})
651
652  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
653  call WaitForAssert({-> assert_match('^0 ', term_getline(buf, 6))}, 1000)
654
655  call term_sendkeys(buf, 'gj')
656  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
657  call WaitForAssert({-> assert_match('^1 ', term_getline(buf, 6))}, 1000)
658
659  call term_sendkeys(buf, '0')
660  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
661  call WaitForAssert({-> assert_match('^2 ', term_getline(buf, 6))}, 1000)
662
663  call term_sendkeys(buf, '$')
664  call term_sendkeys(buf, ":echo g:scrolled\<CR>")
665  call WaitForAssert({-> assert_match('^3 ', term_getline(buf, 6))}, 1000)
666
667  call StopVimInTerminal(buf)
668endfunc
669
670func Test_WinScrolled_diff()
671  CheckRunVimInTerminal
672
673  let lines =<< trim END
674    set diffopt+=foldcolumn:0
675    call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])
676    vnew
677    call setline(1, ['d', 'e', 'f', 'g', 'h', 'i'])
678    windo diffthis
679    func WriteScrollEvent()
680      call writefile([json_encode(v:event)], 'XscrollEvent')
681    endfunc
682    au WinScrolled * call WriteScrollEvent()
683  END
684  call writefile(lines, 'Xtest_winscrolled_diff', 'D')
685  let buf = RunVimInTerminal('-S Xtest_winscrolled_diff', {'rows': 8})
686
687  call term_sendkeys(buf, "\<C-E>")
688  call WaitForAssert({-> assert_match('^d', term_getline(buf, 3))}, 1000)
689
690  let event = readfile('XscrollEvent')[0]->json_decode()
691  call assert_equal({
692        \ 'all': {'leftcol': 0, 'topline': 1, 'topfill': 1, 'width': 0, 'height': 0, 'skipcol': 0},
693        \ '1000': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
694        \ '1001': {'leftcol': 0, 'topline': 0, 'topfill': -1, 'width': 0, 'height': 0, 'skipcol': 0}
695        \ }, event)
696
697  call term_sendkeys(buf, "2\<C-E>")
698  call WaitForAssert({-> assert_match('^f', term_getline(buf, 3))}, 1000)
699
700  let event = readfile('XscrollEvent')[0]->json_decode()
701  call assert_equal({
702        \ 'all': {'leftcol': 0, 'topline': 2, 'topfill': 2, 'width': 0, 'height': 0, 'skipcol': 0},
703        \ '1000': {'leftcol': 0, 'topline': 2, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
704        \ '1001': {'leftcol': 0, 'topline': 0, 'topfill': -2, 'width': 0, 'height': 0, 'skipcol': 0}
705        \ }, event)
706
707  call term_sendkeys(buf, "\<C-E>")
708  call WaitForAssert({-> assert_match('^g', term_getline(buf, 3))}, 1000)
709
710  let event = readfile('XscrollEvent')[0]->json_decode()
711  call assert_equal({
712        \ 'all': {'leftcol': 0, 'topline': 2, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
713        \ '1000': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
714        \ '1001': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}
715        \ }, event)
716
717  call term_sendkeys(buf, "2\<C-Y>")
718  call WaitForAssert({-> assert_match('^e', term_getline(buf, 3))}, 1000)
719
720  let event = readfile('XscrollEvent')[0]->json_decode()
721  call assert_equal({
722        \ 'all': {'leftcol': 0, 'topline': 3, 'topfill': 1, 'width': 0, 'height': 0, 'skipcol': 0},
723        \ '1000': {'leftcol': 0, 'topline': -2, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0},
724        \ '1001': {'leftcol': 0, 'topline': -1, 'topfill': 1, 'width': 0, 'height': 0, 'skipcol': 0}
725        \ }, event)
726
727  call StopVimInTerminal(buf)
728  call delete('XscrollEvent')
729endfunc
730
731func Test_WinClosed()
732  " Test that the pattern is matched against the closed window's ID, and both
733  " <amatch> and <afile> are set to it.
734  new
735  let winid = win_getid()
736  let g:matched = v:false
737  augroup test-WinClosed
738    autocmd!
739    execute 'autocmd WinClosed' winid 'let g:matched = v:true'
740    autocmd WinClosed * let g:amatch = str2nr(expand('<amatch>'))
741    autocmd WinClosed * let g:afile = str2nr(expand('<afile>'))
742  augroup END
743  close
744  call assert_true(g:matched)
745  call assert_equal(winid, g:amatch)
746  call assert_equal(winid, g:afile)
747
748  " Test that WinClosed is non-recursive.
749  new
750  new
751  call assert_equal(3, winnr('$'))
752  let g:triggered = 0
753  augroup test-WinClosed
754    autocmd!
755    autocmd WinClosed * let g:triggered += 1
756    autocmd WinClosed * 2 wincmd c
757  augroup END
758  close
759  call assert_equal(1, winnr('$'))
760  call assert_equal(1, g:triggered)
761
762  autocmd! test-WinClosed
763  augroup! test-WinClosed
764  unlet g:matched
765  unlet g:amatch
766  unlet g:afile
767  unlet g:triggered
768endfunc
769
770func Test_WinClosed_throws()
771  vnew
772  let bnr = bufnr()
773  call assert_equal(1, bufloaded(bnr))
774  augroup test-WinClosed
775    autocmd WinClosed * throw 'foo'
776  augroup END
777  try
778    close
779  catch /.*/
780  endtry
781  call assert_equal(0, bufloaded(bnr))
782
783  autocmd! test-WinClosed
784  augroup! test-WinClosed
785endfunc
786
787func Test_WinClosed_throws_with_tabs()
788  tabnew
789  let bnr = bufnr()
790  call assert_equal(1, bufloaded(bnr))
791  augroup test-WinClosed
792    autocmd WinClosed * throw 'foo'
793  augroup END
794  try
795    close
796  catch /.*/
797  endtry
798  call assert_equal(0, bufloaded(bnr))
799
800  autocmd! test-WinClosed
801  augroup! test-WinClosed
802endfunc
803
804" This used to trigger WinClosed twice for the same window, and the window's
805" buffer was NULL in the second autocommand.
806func Test_WinClosed_switch_tab()
807  edit Xa
808  split Xb
809  split Xc
810  tab split
811  new
812  augroup test-WinClosed
813    autocmd WinClosed * tabprev | bwipe!
814  augroup END
815  close
816  " Check that the tabline has been fully removed
817  call assert_equal([1, 1], win_screenpos(0))
818
819  autocmd! test-WinClosed
820  augroup! test-WinClosed
821  %bwipe!
822endfunc
823
824" This used to trigger WinClosed/WinLeave/BufLeave twice for the same window,
825" and the window's buffer was NULL in the second autocommand.
826func Run_test_BufUnload_close_other(extra_cmd)
827  let oldtab = tabpagenr()
828  tabnew Xb1
829  let g:tab = tabpagenr()
830  let g:w1 = win_getid()
831  new Xb2
832  let g:w2 = win_getid()
833  let g:log = []
834  exe a:extra_cmd
835
836  augroup test-BufUnload-close-other
837    autocmd BufUnload * ++nested ++once bwipe! Xb1
838    for event in ['WinClosed', 'BufLeave', 'WinLeave', 'TabLeave']
839      exe $'autocmd {event} * call tabpagebuflist(g:tab)'
840      exe $'autocmd {event} * let g:log += ["{event}:" .. expand("<afile>")]'
841    endfor
842  augroup END
843
844  close
845  " WinClosed is triggered once for each of the 2 closed windows.
846  " Others are only triggered once.
847  call assert_equal(['BufLeave:Xb2', 'WinLeave:Xb2', $'WinClosed:{g:w2}',
848        \ $'WinClosed:{g:w1}', 'TabLeave:Xb2'], g:log)
849  call assert_equal(oldtab, tabpagenr())
850  call assert_equal([0, 0], win_id2tabwin(g:w1))
851  call assert_equal([0, 0], win_id2tabwin(g:w2))
852
853  unlet g:tab
854  unlet g:w1
855  unlet g:w2
856  unlet g:log
857  autocmd! test-BufUnload-close-other
858  augroup! test-BufUnload-close-other
859  %bwipe!
860endfunc
861
862func Test_BufUnload_close_other()
863  call Run_test_BufUnload_close_other('')
864  call Run_test_BufUnload_close_other('setlocal bufhidden=wipe')
865endfunc
866
867func Run_test_BufUnload_tabonly(first_cmd)
868  exe a:first_cmd
869  tabnew Xa
870  setlocal bufhidden=wipe
871  tabprevious
872  autocmd BufWinLeave Xa ++once tabnext
873  autocmd BufUnload Xa ++once tabonly
874  tabonly
875
876  %bwipe!
877endfunc
878
879func Test_BufUnload_tabonly()
880  " This used to dereference a NULL curbuf.
881  call Run_test_BufUnload_tabonly('setlocal bufhidden=hide')
882  " This used to dereference a NULL firstbuf.
883  call Run_test_BufUnload_tabonly('setlocal bufhidden=wipe')
884endfunc
885
886func Run_test_BufUnload_tabonly_nested(second_autocmd)
887  file Xa
888  tabnew Xb
889  setlocal bufhidden=wipe
890  tabnew Xc
891  setlocal bufhidden=wipe
892  autocmd BufUnload Xb ++once ++nested bwipe! Xa
893  exe $'autocmd BufUnload Xa ++once ++nested {a:second_autocmd}'
894  autocmd BufWinLeave Xc ++once tabnext
895  tabfirst
896  2tabclose
897
898  %bwipe!
899endfunc
900
901func Test_BufUnload_tabonly_nested()
902  " These used to cause heap-use-after-free.
903  call Run_test_BufUnload_tabonly_nested('tabonly')
904  call Run_test_BufUnload_tabonly_nested('tabonly | tabprevious')
905endfunc
906
907func s:AddAnAutocmd()
908  augroup vimBarTest
909    au BufReadCmd * echo 'hello'
910  augroup END
911  call assert_equal(3, len(split(execute('au vimBarTest'), "\n")))
912endfunc
913
914func Test_early_bar()
915  " test that a bar is recognized before the {event}
916  call s:AddAnAutocmd()
917  augroup vimBarTest | au! | let done = 77 | augroup END
918  call assert_equal(1, len(split(execute('au vimBarTest'), "\n")))
919  call assert_equal(77, done)
920
921  call s:AddAnAutocmd()
922  augroup vimBarTest| au!| let done = 88 | augroup END
923  call assert_equal(1, len(split(execute('au vimBarTest'), "\n")))
924  call assert_equal(88, done)
925
926  " test that a bar is recognized after the {event}
927  call s:AddAnAutocmd()
928  augroup vimBarTest| au!BufReadCmd| let done = 99 | augroup END
929  call assert_equal(1, len(split(execute('au vimBarTest'), "\n")))
930  call assert_equal(99, done)
931
932  " test that a bar is recognized after the {group}
933  call s:AddAnAutocmd()
934  au! vimBarTest|echo 'hello'
935  call assert_equal(1, len(split(execute('au vimBarTest'), "\n")))
936endfunc
937
938func RemoveGroup()
939  autocmd! StartOK
940  augroup! StartOK
941endfunc
942
943func Test_augroup_warning()
944  augroup TheWarning
945    au VimEnter * echo 'entering'
946  augroup END
947  call assert_match("TheWarning.*VimEnter", execute('au VimEnter'))
948  redir => res
949  augroup! TheWarning
950  redir END
951  call assert_match("W19:", res)
952  call assert_match("-Deleted-.*VimEnter", execute('au VimEnter'))
953
954  " check "Another" does not take the pace of the deleted entry
955  augroup Another
956  augroup END
957  call assert_match("-Deleted-.*VimEnter", execute('au VimEnter'))
958  augroup! Another
959
960  " no warning for postpone aucmd delete
961  augroup StartOK
962    au VimEnter * call RemoveGroup()
963  augroup END
964  call assert_match("StartOK.*VimEnter", execute('au VimEnter'))
965  redir => res
966  doautocmd VimEnter
967  redir END
968  call assert_notmatch("W19:", res)
969  au! VimEnter
970
971  call assert_fails('augroup!', 'E471:')
972endfunc
973
974func Test_BufReadCmdHelp()
975  " This used to cause access to free memory
976  au BufReadCmd * e +h
977  help
978
979  au! BufReadCmd
980endfunc
981
982func Test_BufReadCmdHelpJump()
983  " This used to cause access to free memory
984  au BufReadCmd * e +h{
985  " } to fix highlighting
986  call assert_fails('help', 'E434:')
987
988  au! BufReadCmd
989endfunc
990
991" BufReadCmd is triggered for a "nofile" buffer. Check all values.
992func Test_BufReadCmdNofile()
993  for val in ['nofile',
994            \ 'nowrite',
995            \ 'acwrite',
996            \ 'quickfix',
997            \ 'help',
998            "\ 'terminal',
999            "\ 'prompt',
1000            "\ 'popup',
1001            \ ]
1002    new somefile
1003    exe 'set buftype=' .. val
1004    au BufReadCmd somefile call setline(1, 'triggered')
1005    edit
1006    call assert_equal('triggered', getline(1))
1007
1008    au! BufReadCmd
1009    bwipe!
1010  endfor
1011endfunc
1012
1013func Test_augroup_deleted()
1014  " This caused a crash before E936 was introduced
1015  augroup x
1016    call assert_fails('augroup! x', 'E936:')
1017    au VimEnter * echo
1018  augroup end
1019  augroup! x
1020  call assert_match("-Deleted-.*VimEnter", execute('au VimEnter'))
1021  au! VimEnter
1022endfunc
1023
1024" Tests for autocommands on :close command.
1025" This used to be in test13.
1026func Test_three_windows()
1027  " Clean up buffers, because in some cases this function fails.
1028  call s:cleanup_buffers()
1029
1030  " Write three files and open them, each in a window.
1031  " Then go to next window, with autocommand that deletes the previous one.
1032  " Do this twice, writing the file.
1033  e! Xtestje1
1034  call setline(1, 'testje1')
1035  w
1036  sp Xtestje2
1037  call setline(1, 'testje2')
1038  w
1039  sp Xtestje3
1040  call setline(1, 'testje3')
1041  w
1042  wincmd w
1043  au WinLeave Xtestje2 bwipe
1044  wincmd w
1045  call assert_equal('Xtestje1', expand('%'))
1046
1047  au WinLeave Xtestje1 bwipe Xtestje3
1048  close
1049  call assert_equal('Xtestje1', expand('%'))
1050
1051  " Test deleting the buffer on a Unload event.  If this goes wrong there
1052  " will be the ATTENTION prompt.
1053  e Xtestje1
1054  au!
1055  au! BufUnload Xtestje1 bwipe
1056  call assert_fails('e Xtestje3', 'E937:')
1057  call assert_equal('Xtestje3', expand('%'))
1058
1059  e Xtestje2
1060  sp Xtestje1
1061  call assert_fails('e', 'E937:')
1062  call assert_equal('Xtestje1', expand('%'))
1063
1064  " Test changing buffers in a BufWipeout autocommand.  If this goes wrong
1065  " there are ml_line errors and/or a Crash.
1066  au!
1067  only
1068  e Xanother
1069  e Xtestje1
1070  bwipe Xtestje2
1071  bwipe Xtestje3
1072  au BufWipeout Xtestje1 buf Xtestje1
1073  bwipe
1074  call assert_equal('Xanother', expand('%'))
1075
1076  only
1077
1078  help
1079  wincmd w
1080  1quit
1081  call assert_equal('Xanother', expand('%'))
1082
1083  au!
1084  enew
1085  call delete('Xtestje1')
1086  call delete('Xtestje2')
1087  call delete('Xtestje3')
1088endfunc
1089
1090func Test_BufEnter()
1091  au! BufEnter
1092  au Bufenter * let val = val . '+'
1093  let g:val = ''
1094  split NewFile
1095  call assert_equal('+', g:val)
1096  bwipe!
1097  call assert_equal('++', g:val)
1098
1099  " Also get BufEnter when editing a directory
1100  call mkdir('Xbufenterdir', 'D')
1101  split Xbufenterdir
1102  call assert_equal('+++', g:val)
1103
1104  " On MS-Windows we can't edit the directory, make sure we wipe the right
1105  " buffer.
1106  bwipe! Xbufenterdir
1107  au! BufEnter
1108
1109  " Editing a "nofile" buffer doesn't read the file but does trigger BufEnter
1110  " for historic reasons.  Also test other 'buftype' values.
1111  for val in ['nofile',
1112            \ 'nowrite',
1113            \ 'acwrite',
1114            \ 'quickfix',
1115            \ 'help',
1116            "\ 'terminal',
1117            "\ 'prompt',
1118            "\ 'popup',
1119            \ ]
1120    new somefile
1121    exe 'set buftype=' .. val
1122    au BufEnter somefile call setline(1, 'some text')
1123    edit
1124    call assert_equal('some text', getline(1))
1125    bwipe!
1126    au! BufEnter
1127  endfor
1128
1129  new
1130  new
1131  autocmd BufEnter * ++once close
1132  call assert_fails('close', 'E1312:')
1133
1134  au! BufEnter
1135  only
1136endfunc
1137
1138func Test_autocmd_SessLoadPre()
1139  tabnew
1140  set noswapfile
1141  mkview! Xview.vim
1142  mksession! Session.vim
1143
1144  call assert_false(exists('g:session_loaded_var'))
1145
1146  let content =<< trim [CODE]
1147    set nocp noswapfile
1148
1149    func! Assert(cond, msg)
1150      if !a:cond
1151        echomsg "ASSERT_FAIL: " .. a:msg
1152      else
1153        echomsg "ASSERT_OK: " .. a:msg
1154      endif
1155    endfunc
1156
1157    func! OnSessionLoadPre()
1158      call Assert(exists('g:SessionLoad'), 'SessionLoadPre: session IS loading')
1159      call Assert(!exists('g:session_loaded_var'),
1160            \ 'SessionLoadPre: var NOT set')
1161    endfunc
1162    au SessionLoadPre * call OnSessionLoadPre()
1163
1164    func! OnSessionLoadPost()
1165      call Assert(exists('g:session_loaded_var'),
1166            \ 'SessionLoadPost: var IS set')
1167      echomsg "SessionLoadPost DONE"
1168    endfunc
1169    au SessionLoadPost * call OnSessionLoadPost()
1170
1171    func! WriteErrors()
1172      call writefile([execute("messages")], "XerrorsPost")
1173    endfunc
1174    au VimLeave * call WriteErrors()
1175  [CODE]
1176
1177  call writefile(content, 'Xvimrc', 'D')
1178
1179  call writefile(
1180        \ ['let g:session_loaded_var = 1'],
1181        \ 'Sessionx.vim',
1182        \ 'b'
1183        \ )
1184
1185  " --- Run child Vim ---
1186  call system(
1187        \ GetVimCommand('Xvimrc')
1188        \ .. ' --headless --noplugins -S Xview.vim -S Session.vim -c cq'
1189        \ )
1190
1191  call WaitForAssert({-> assert_true(filereadable('XerrorsPost'))})
1192
1193  let errors = join(readfile('XerrorsPost'), "\n")
1194  call assert_notmatch('ASSERT_FAIL', errors)
1195  call assert_match('ASSERT_OK: SessionLoadPre: var NOT set', errors)
1196  call assert_match('ASSERT_OK: SessionLoadPost: var IS set', errors)
1197  call assert_match('SessionLoadPost DONE', errors)
1198
1199  set swapfile
1200  for file in ['Session.vim', 'Sessionx.vim', 'Xview.vim', 'XerrorsPost']
1201    call delete(file)
1202  endfor
1203endfunc
1204
1205" Closing a window might cause an endless loop
1206" E814 for older Vims
1207func Test_autocmd_bufwipe_in_SessLoadPost()
1208  set noswapfile
1209  edit Xtest
1210  tabnew
1211  file Xsomething
1212  mksession!
1213
1214  let content =<< trim [CODE]
1215    set nocp noswapfile
1216    let v:swapchoice = "e"
1217    augroup test_autocmd_sessionload
1218    autocmd!
1219    autocmd SessionLoadPost * exe bufnr("Xsomething") . "bw!"
1220    augroup END
1221
1222    func WriteErrors()
1223      call writefile([execute("messages")], "XerrorsBwipe")
1224    endfunc
1225    au VimLeave * call WriteErrors()
1226  [CODE]
1227
1228  call writefile(content, 'Xvimrc', 'D')
1229  call system(GetVimCommand('Xvimrc') .. ' --headless --noplugins -S Session.vim -c cq')
1230  sleep 100m
1231  let errors = join(readfile('XerrorsBwipe'))
1232  call assert_match('E814:', errors)
1233
1234  set swapfile
1235  for file in ['Session.vim', 'XerrorsBwipe']
1236    call delete(file)
1237  endfor
1238endfunc
1239
1240" Using :blast and :ball for many events caused a crash, because b_nwindows was
1241" not incremented correctly.
1242func Test_autocmd_blast_badd()
1243  let content =<< trim [CODE]
1244      au BufNew,BufAdd,BufWinEnter,BufEnter,BufLeave,BufWinLeave,BufUnload,VimEnter foo* blast
1245      edit foo1
1246      au BufNew,BufAdd,BufWinEnter,BufEnter,BufLeave,BufWinLeave,BufUnload,VimEnter foo* ball
1247      edit foo2
1248      call writefile(['OK'], 'XerrorsBlast')
1249      qall
1250  [CODE]
1251
1252  call writefile(content, 'XblastBall', 'D')
1253  call system(GetVimCommand() .. ' --clean -S XblastBall')
1254  sleep 100m
1255  call assert_match('OK', readfile('XerrorsBlast')->join())
1256
1257  call delete('XerrorsBlast')
1258endfunc
1259
1260" SEGV occurs in older versions.
1261func Test_autocmd_bufwipe_in_SessLoadPost2()
1262  tabnew
1263  set noswapfile
1264  mksession!
1265
1266  let content =<< trim [CODE]
1267    set nocp noswapfile
1268    function! DeleteInactiveBufs()
1269      tabfirst
1270      let tabblist = []
1271      for i in range(1, tabpagenr(''$''))
1272        call extend(tabblist, tabpagebuflist(i))
1273      endfor
1274      for b in range(1, bufnr(''$''))
1275        if bufexists(b) && buflisted(b) && (index(tabblist, b) == -1 || bufname(b) =~# ''^$'')
1276          exec ''bwipeout '' . b
1277        endif
1278      endfor
1279      echomsg "SessionLoadPost DONE"
1280    endfunction
1281    au SessionLoadPost * call DeleteInactiveBufs()
1282
1283    func WriteErrors()
1284      call writefile([execute("messages")], "XerrorsPost")
1285    endfunc
1286    au VimLeave * call WriteErrors()
1287  [CODE]
1288
1289  call writefile(content, 'Xvimrc', 'D')
1290  call system(GetVimCommand('Xvimrc') .. ' --headless --noplugins -S Session.vim -c cq')
1291  sleep 100m
1292  let errors = join(readfile('XerrorsPost'))
1293  " This probably only ever matches on unix.
1294  call assert_notmatch('Caught deadly signal SEGV', errors)
1295  call assert_match('SessionLoadPost DONE', errors)
1296
1297  set swapfile
1298  for file in ['Session.vim', 'XerrorsPost']
1299    call delete(file)
1300  endfor
1301endfunc
1302
1303func Test_empty_doau()
1304  doau \|
1305endfunc
1306
1307func s:AutoCommandOptionSet(match)
1308  let template = "Option: <%s>, OldVal: <%s>, OldValLocal: <%s>, OldValGlobal: <%s>, NewVal: <%s>, Scope: <%s>, Command: <%s>\n"
1309  let item     = remove(g:options, 0)
1310  let expected = printf(template, item[0], item[1], item[2], item[3], item[4], item[5], item[6])
1311  let actual   = printf(template, a:match, v:option_old, v:option_oldlocal, v:option_oldglobal, v:option_new, v:option_type, v:option_command)
1312  let g:opt    = [expected, actual]
1313  "call assert_equal(expected, actual)
1314endfunc
1315
1316func Test_OptionSet()
1317  " Use test/functional/legacy/autocmd_option_spec.lua
1318  throw 'Skipped: Nvim changed types of OptionSet v: variables'
1319  CheckOption autochdir
1320
1321  call test_override('starting', 1)
1322  set nocp
1323  au OptionSet * :call s:AutoCommandOptionSet(expand("<amatch>"))
1324
1325  " 1: Setting number option"
1326  let g:options = [['number', 0, 0, 0, 1, 'global', 'set']]
1327  set nu
1328  call assert_equal([], g:options)
1329  call assert_equal(g:opt[0], g:opt[1])
1330
1331  " 2: Setting local number option"
1332  let g:options = [['number', 1, 1, '', 0, 'local', 'setlocal']]
1333  setlocal nonu
1334  call assert_equal([], g:options)
1335  call assert_equal(g:opt[0], g:opt[1])
1336
1337  " 3: Setting global number option"
1338  let g:options = [['number', 1, '', 1, 0, 'global', 'setglobal']]
1339  setglobal nonu
1340  call assert_equal([], g:options)
1341  call assert_equal(g:opt[0], g:opt[1])
1342
1343  " 4: Setting local autoindent option"
1344  let g:options = [['autoindent', 0, 0, '', 1, 'local', 'setlocal']]
1345  setlocal ai
1346  call assert_equal([], g:options)
1347  call assert_equal(g:opt[0], g:opt[1])
1348
1349  " 5: Setting global autoindent option"
1350  let g:options = [['autoindent', 0, '', 0, 1, 'global', 'setglobal']]
1351  setglobal ai
1352  call assert_equal([], g:options)
1353  call assert_equal(g:opt[0], g:opt[1])
1354
1355  " 6: Setting global autoindent option"
1356  let g:options = [['autoindent', 1, 1, 1, 0, 'global', 'set']]
1357  set ai!
1358  call assert_equal([], g:options)
1359  call assert_equal(g:opt[0], g:opt[1])
1360
1361  " 6a: Setting global autoindent option"
1362  let g:options = [['autoindent', 1, 1, 0, 0, 'global', 'set']]
1363  noa setlocal ai
1364  noa setglobal noai
1365  set ai!
1366  call assert_equal([], g:options)
1367  call assert_equal(g:opt[0], g:opt[1])
1368
1369  " Should not print anything, use :noa
1370  " 7: don't trigger OptionSet"
1371  let g:options = [['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']]
1372  noa set nonu
1373  call assert_equal([['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']], g:options)
1374  call assert_equal(g:opt[0], g:opt[1])
1375
1376  " 8: Setting several global list and number option"
1377  let g:options = [['list', 0, 0, 0, 1, 'global', 'set'], ['number', 0, 0, 0, 1, 'global', 'set']]
1378  set list nu
1379  call assert_equal([], g:options)
1380  call assert_equal(g:opt[0], g:opt[1])
1381
1382  " 9: don't trigger OptionSet"
1383  let g:options = [['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid'], ['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']]
1384  noa set nolist nonu
1385  call assert_equal([['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid'], ['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']], g:options)
1386  call assert_equal(g:opt[0], g:opt[1])
1387
1388  " 10: Setting global acd"
1389  let g:options = [['autochdir', 0, 0, '', 1, 'local', 'setlocal']]
1390  setlocal acd
1391  call assert_equal([], g:options)
1392  call assert_equal(g:opt[0], g:opt[1])
1393
1394  " 11: Setting global autoread (also sets local value)"
1395  let g:options = [['autoread', 0, 0, 0, 1, 'global', 'set']]
1396  set ar
1397  call assert_equal([], g:options)
1398  call assert_equal(g:opt[0], g:opt[1])
1399
1400  " 12: Setting local autoread"
1401  let g:options = [['autoread', 1, 1, '', 1, 'local', 'setlocal']]
1402  setlocal ar
1403  call assert_equal([], g:options)
1404  call assert_equal(g:opt[0], g:opt[1])
1405
1406  " 13: Setting global autoread"
1407  let g:options = [['autoread', 1, '', 1, 0, 'global', 'setglobal']]
1408  setglobal invar
1409  call assert_equal([], g:options)
1410  call assert_equal(g:opt[0], g:opt[1])
1411
1412  " 14: Setting option backspace through :let"
1413  let g:options = [['backspace', 'indent,eol,start', 'indent,eol,start', 'indent,eol,start', '', 'global', 'set']]
1414  let &bs = ''
1415  call assert_equal([], g:options)
1416  call assert_equal(g:opt[0], g:opt[1])
1417
1418  " 15: Setting option backspace through setbufvar()"
1419  let g:options = [['backup', 0, 0, '', 1, 'local', 'setlocal']]
1420  " try twice, first time, shouldn't trigger because option name is invalid,
1421  " second time, it should trigger
1422  let bnum = bufnr('%')
1423  call assert_fails("call setbufvar(bnum, '&l:bk', 1)", 'E355:')
1424  " should trigger, use correct option name
1425  call setbufvar(bnum, '&backup', 1)
1426  call assert_equal([], g:options)
1427  call assert_equal(g:opt[0], g:opt[1])
1428
1429  " 16: Setting number option using setwinvar"
1430  let g:options = [['number', 0, 0, '', 1, 'local', 'setlocal']]
1431  call setwinvar(0, '&number', 1)
1432  call assert_equal([], g:options)
1433  call assert_equal(g:opt[0], g:opt[1])
1434
1435  " 17: Setting key option, shouldn't trigger"
1436  let g:options = [['key', 'invalid', 'invalid1', 'invalid2', 'invalid3', 'invalid4', 'invalid5']]
1437  setlocal key=blah
1438  setlocal key=
1439  call assert_equal([['key', 'invalid', 'invalid1', 'invalid2', 'invalid3', 'invalid4', 'invalid5']], g:options)
1440  call assert_equal(g:opt[0], g:opt[1])
1441
1442
1443  " 18a: Setting string global option"
1444  let oldval = &backupext
1445  let g:options = [['backupext', oldval, oldval, oldval, 'foo', 'global', 'set']]
1446  set backupext=foo
1447  call assert_equal([], g:options)
1448  call assert_equal(g:opt[0], g:opt[1])
1449
1450  " 18b: Resetting string global option"
1451  let g:options = [['backupext', 'foo', 'foo', 'foo', oldval, 'global', 'set']]
1452  set backupext&
1453  call assert_equal([], g:options)
1454  call assert_equal(g:opt[0], g:opt[1])
1455
1456  " 18c: Setting global string global option"
1457  let g:options = [['backupext', oldval, '', oldval, 'bar', 'global', 'setglobal']]
1458  setglobal backupext=bar
1459  call assert_equal([], g:options)
1460  call assert_equal(g:opt[0], g:opt[1])
1461
1462  " 18d: Setting local string global option"
1463  " As this is a global option this sets the global value even though
1464  " :setlocal is used!
1465  noa set backupext& " Reset global and local value (without triggering autocmd)
1466  let g:options = [['backupext', oldval, oldval, '', 'baz', 'local', 'setlocal']]
1467  setlocal backupext=baz
1468  call assert_equal([], g:options)
1469  call assert_equal(g:opt[0], g:opt[1])
1470
1471  " 18e: Setting again string global option"
1472  noa setglobal backupext=ext_global " Reset global and local value (without triggering autocmd)
1473  noa setlocal backupext=ext_local " Sets the global(!) value!
1474  let g:options = [['backupext', 'ext_local', 'ext_local', 'ext_local', 'fuu', 'global', 'set']]
1475  set backupext=fuu
1476  call assert_equal([], g:options)
1477  call assert_equal(g:opt[0], g:opt[1])
1478
1479
1480  " 19a: Setting string global-local (to buffer) option"
1481  let oldval = &tags
1482  let g:options = [['tags', oldval, oldval, oldval, 'tagpath', 'global', 'set']]
1483  set tags=tagpath
1484  call assert_equal([], g:options)
1485  call assert_equal(g:opt[0], g:opt[1])
1486
1487  " 19b: Resetting string global-local (to buffer) option"
1488  let g:options = [['tags', 'tagpath', 'tagpath', 'tagpath', oldval, 'global', 'set']]
1489  set tags&
1490  call assert_equal([], g:options)
1491  call assert_equal(g:opt[0], g:opt[1])
1492
1493  " 19c: Setting global string global-local (to buffer) option "
1494  let g:options = [['tags', oldval, '', oldval, 'tagpath1', 'global', 'setglobal']]
1495  setglobal tags=tagpath1
1496  call assert_equal([], g:options)
1497  call assert_equal(g:opt[0], g:opt[1])
1498
1499  " 19d: Setting local string global-local (to buffer) option"
1500  let g:options = [['tags', 'tagpath1', 'tagpath1', '', 'tagpath2', 'local', 'setlocal']]
1501  setlocal tags=tagpath2
1502  call assert_equal([], g:options)
1503  call assert_equal(g:opt[0], g:opt[1])
1504
1505  " 19e: Setting again string global-local (to buffer) option"
1506  " Note: v:option_old is the old global value for global-local string options
1507  " but the old local value for all other kinds of options.
1508  noa setglobal tags=tag_global " Reset global and local value (without triggering autocmd)
1509  noa setlocal tags=tag_local
1510  let g:options = [['tags', 'tag_global', 'tag_local', 'tag_global', 'tagpath', 'global', 'set']]
1511  set tags=tagpath
1512  call assert_equal([], g:options)
1513  call assert_equal(g:opt[0], g:opt[1])
1514
1515  " 19f: Setting string global-local (to buffer) option to an empty string"
1516  " Note: v:option_old is the old global value for global-local string options
1517  " but the old local value for all other kinds of options.
1518  noa set tags=tag_global " Reset global and local value (without triggering autocmd)
1519  noa setlocal tags= " empty string
1520  let g:options = [['tags', 'tag_global', '', 'tag_global', 'tagpath', 'global', 'set']]
1521  set tags=tagpath
1522  call assert_equal([], g:options)
1523  call assert_equal(g:opt[0], g:opt[1])
1524
1525
1526  " 20a: Setting string local (to buffer) option"
1527  let oldval = &spelllang
1528  let g:options = [['spelllang', oldval, oldval, oldval, 'elvish,klingon', 'global', 'set']]
1529  set spelllang=elvish,klingon
1530  call assert_equal([], g:options)
1531  call assert_equal(g:opt[0], g:opt[1])
1532
1533  " 20b: Resetting string local (to buffer) option"
1534  let g:options = [['spelllang', 'elvish,klingon', 'elvish,klingon', 'elvish,klingon', oldval, 'global', 'set']]
1535  set spelllang&
1536  call assert_equal([], g:options)
1537  call assert_equal(g:opt[0], g:opt[1])
1538
1539  " 20c: Setting global string local (to buffer) option"
1540  let g:options = [['spelllang', oldval, '', oldval, 'elvish', 'global', 'setglobal']]
1541  setglobal spelllang=elvish
1542  call assert_equal([], g:options)
1543  call assert_equal(g:opt[0], g:opt[1])
1544
1545  " 20d: Setting local string local (to buffer) option"
1546  noa set spelllang& " Reset global and local value (without triggering autocmd)
1547  let g:options = [['spelllang', oldval, oldval, '', 'klingon', 'local', 'setlocal']]
1548  setlocal spelllang=klingon
1549  call assert_equal([], g:options)
1550  call assert_equal(g:opt[0], g:opt[1])
1551
1552  " 20e: Setting again string local (to buffer) option"
1553  " Note: v:option_old is the old global value for global-local string options
1554  " but the old local value for all other kinds of options.
1555  noa setglobal spelllang=spellglobal " Reset global and local value (without triggering autocmd)
1556  noa setlocal spelllang=spelllocal
1557  let g:options = [['spelllang', 'spelllocal', 'spelllocal', 'spellglobal', 'foo', 'global', 'set']]
1558  set spelllang=foo
1559  call assert_equal([], g:options)
1560  call assert_equal(g:opt[0], g:opt[1])
1561
1562
1563  " 21a: Setting string global-local (to window) option"
1564  let oldval = &statusline
1565  let g:options = [['statusline', oldval, oldval, oldval, 'foo', 'global', 'set']]
1566  set statusline=foo
1567  call assert_equal([], g:options)
1568  call assert_equal(g:opt[0], g:opt[1])
1569
1570  " 21b: Resetting string global-local (to window) option"
1571  " Note: v:option_old is the old global value for global-local string options
1572  " but the old local value for all other kinds of options.
1573  let g:options = [['statusline', 'foo', 'foo', 'foo', oldval, 'global', 'set']]
1574  set statusline&
1575  call assert_equal([], g:options)
1576  call assert_equal(g:opt[0], g:opt[1])
1577
1578  " 21c: Setting global string global-local (to window) option"
1579  let g:options = [['statusline', oldval, '', oldval, 'bar', 'global', 'setglobal']]
1580  setglobal statusline=bar
1581  call assert_equal([], g:options)
1582  call assert_equal(g:opt[0], g:opt[1])
1583
1584  " 21d: Setting local string global-local (to window) option"
1585  noa set statusline& " Reset global and local value (without triggering autocmd)
1586  let g:options = [['statusline', oldval, oldval, '', 'baz', 'local', 'setlocal']]
1587  setlocal statusline=baz
1588  call assert_equal([], g:options)
1589  call assert_equal(g:opt[0], g:opt[1])
1590
1591  " 21e: Setting again string global-local (to window) option"
1592  " Note: v:option_old is the old global value for global-local string options
1593  " but the old local value for all other kinds of options.
1594  noa setglobal statusline=bar " Reset global and local value (without triggering autocmd)
1595  noa setlocal statusline=baz
1596  let g:options = [['statusline', 'bar', 'baz', 'bar', 'foo', 'global', 'set']]
1597  set statusline=foo
1598  call assert_equal([], g:options)
1599  call assert_equal(g:opt[0], g:opt[1])
1600
1601
1602  " 22a: Setting string local (to window) option"
1603  let oldval = &foldignore
1604  let g:options = [['foldignore', oldval, oldval, oldval, 'fo', 'global', 'set']]
1605  set foldignore=fo
1606  call assert_equal([], g:options)
1607  call assert_equal(g:opt[0], g:opt[1])
1608
1609  " 22b: Resetting string local (to window) option"
1610  let g:options = [['foldignore', 'fo', 'fo', 'fo', oldval, 'global', 'set']]
1611  set foldignore&
1612  call assert_equal([], g:options)
1613  call assert_equal(g:opt[0], g:opt[1])
1614
1615  " 22c: Setting global string local (to window) option"
1616  let g:options = [['foldignore', oldval, '', oldval, 'bar', 'global', 'setglobal']]
1617  setglobal foldignore=bar
1618  call assert_equal([], g:options)
1619  call assert_equal(g:opt[0], g:opt[1])
1620
1621  " 22d: Setting local string local (to window) option"
1622  noa set foldignore& " Reset global and local value (without triggering autocmd)
1623  let g:options = [['foldignore', oldval, oldval, '', 'baz', 'local', 'setlocal']]
1624  setlocal foldignore=baz
1625  call assert_equal([], g:options)
1626  call assert_equal(g:opt[0], g:opt[1])
1627
1628  " 22e: Setting again string local (to window) option"
1629  noa setglobal foldignore=glob " Reset global and local value (without triggering autocmd)
1630  noa setlocal foldignore=loc
1631  let g:options = [['foldignore', 'loc', 'loc', 'glob', 'fo', 'global', 'set']]
1632  set foldignore=fo
1633  call assert_equal([], g:options)
1634  call assert_equal(g:opt[0], g:opt[1])
1635
1636
1637  " 23a: Setting global number global option"
1638  noa setglobal cmdheight=8 " Reset global and local value (without triggering autocmd)
1639  noa setlocal cmdheight=1 " Sets the global(!) value!
1640  let g:options = [['cmdheight', '1', '', '1', '2', 'global', 'setglobal']]
1641  setglobal cmdheight=2
1642  call assert_equal([], g:options)
1643  call assert_equal(g:opt[0], g:opt[1])
1644
1645  " 23b: Setting local number global option"
1646  noa setglobal cmdheight=8 " Reset global and local value (without triggering autocmd)
1647  noa setlocal cmdheight=1 " Sets the global(!) value!
1648  let g:options = [['cmdheight', '1', '1', '', '2', 'local', 'setlocal']]
1649  setlocal cmdheight=2
1650  call assert_equal([], g:options)
1651  call assert_equal(g:opt[0], g:opt[1])
1652
1653  " 23c: Setting again number global option"
1654  noa setglobal cmdheight=8 " Reset global and local value (without triggering autocmd)
1655  noa setlocal cmdheight=1 " Sets the global(!) value!
1656  let g:options = [['cmdheight', '1', '1', '1', '2', 'global', 'set']]
1657  set cmdheight=2
1658  call assert_equal([], g:options)
1659  call assert_equal(g:opt[0], g:opt[1])
1660
1661  " 23d: Setting again number global option"
1662  noa set cmdheight=8 " Reset global and local value (without triggering autocmd)
1663  let g:options = [['cmdheight', '8', '8', '8', '2', 'global', 'set']]
1664  set cmdheight=2
1665  call assert_equal([], g:options)
1666  call assert_equal(g:opt[0], g:opt[1])
1667
1668
1669  " 24a: Setting global number global-local (to buffer) option"
1670  noa setglobal undolevels=8 " Reset global and local value (without triggering autocmd)
1671  noa setlocal undolevels=1
1672  let g:options = [['undolevels', '8', '', '8', '2', 'global', 'setglobal']]
1673  setglobal undolevels=2
1674  call assert_equal([], g:options)
1675  call assert_equal(g:opt[0], g:opt[1])
1676
1677  " 24b: Setting local number global-local (to buffer) option"
1678  noa setglobal undolevels=8 " Reset global and local value (without triggering autocmd)
1679  noa setlocal undolevels=1
1680  let g:options = [['undolevels', '1', '1', '', '2', 'local', 'setlocal']]
1681  setlocal undolevels=2
1682  call assert_equal([], g:options)
1683  call assert_equal(g:opt[0], g:opt[1])
1684
1685  " 24c: Setting again number global-local (to buffer) option"
1686  noa setglobal undolevels=8 " Reset global and local value (without triggering autocmd)
1687  noa setlocal undolevels=1
1688  let g:options = [['undolevels', '1', '1', '8', '2', 'global', 'set']]
1689  set undolevels=2
1690  call assert_equal([], g:options)
1691  call assert_equal(g:opt[0], g:opt[1])
1692
1693  " 24d: Setting again global number global-local (to buffer) option"
1694  noa set undolevels=8 " Reset global and local value (without triggering autocmd)
1695  let g:options = [['undolevels', '8', '8', '8', '2', 'global', 'set']]
1696  set undolevels=2
1697  call assert_equal([], g:options)
1698  call assert_equal(g:opt[0], g:opt[1])
1699
1700
1701  " 25a: Setting global number local (to buffer) option"
1702  noa setglobal wrapmargin=8 " Reset global and local value (without triggering autocmd)
1703  noa setlocal wrapmargin=1
1704  let g:options = [['wrapmargin', '8', '', '8', '2', 'global', 'setglobal']]
1705  setglobal wrapmargin=2
1706  call assert_equal([], g:options)
1707  call assert_equal(g:opt[0], g:opt[1])
1708
1709  " 25b: Setting local number local (to buffer) option"
1710  noa setglobal wrapmargin=8 " Reset global and local value (without triggering autocmd)
1711  noa setlocal wrapmargin=1
1712  let g:options = [['wrapmargin', '1', '1', '', '2', 'local', 'setlocal']]
1713  setlocal wrapmargin=2
1714  call assert_equal([], g:options)
1715  call assert_equal(g:opt[0], g:opt[1])
1716
1717  " 25c: Setting again number local (to buffer) option"
1718  noa setglobal wrapmargin=8 " Reset global and local value (without triggering autocmd)
1719  noa setlocal wrapmargin=1
1720  let g:options = [['wrapmargin', '1', '1', '8', '2', 'global', 'set']]
1721  set wrapmargin=2
1722  call assert_equal([], g:options)
1723  call assert_equal(g:opt[0], g:opt[1])
1724
1725  " 25d: Setting again global number local (to buffer) option"
1726  noa set wrapmargin=8 " Reset global and local value (without triggering autocmd)
1727  let g:options = [['wrapmargin', '8', '8', '8', '2', 'global', 'set']]
1728  set wrapmargin=2
1729  call assert_equal([], g:options)
1730  call assert_equal(g:opt[0], g:opt[1])
1731
1732
1733  " 26: Setting number global-local (to window) option.
1734  " Such option does currently not exist.
1735
1736
1737  " 27a: Setting global number local (to window) option"
1738  noa setglobal foldcolumn=8 " Reset global and local value (without triggering autocmd)
1739  noa setlocal foldcolumn=1
1740  let g:options = [['foldcolumn', '8', '', '8', '2', 'global', 'setglobal']]
1741  setglobal foldcolumn=2
1742  call assert_equal([], g:options)
1743  call assert_equal(g:opt[0], g:opt[1])
1744
1745  " 27b: Setting local number local (to window) option"
1746  noa setglobal foldcolumn=8 " Reset global and local value (without triggering autocmd)
1747  noa setlocal foldcolumn=1
1748  let g:options = [['foldcolumn', '1', '1', '', '2', 'local', 'setlocal']]
1749  setlocal foldcolumn=2
1750  call assert_equal([], g:options)
1751  call assert_equal(g:opt[0], g:opt[1])
1752
1753  " 27c: Setting again number local (to window) option"
1754  noa setglobal foldcolumn=8 " Reset global and local value (without triggering autocmd)
1755  noa setlocal foldcolumn=1
1756  let g:options = [['foldcolumn', '1', '1', '8', '2', 'global', 'set']]
1757  set foldcolumn=2
1758  call assert_equal([], g:options)
1759  call assert_equal(g:opt[0], g:opt[1])
1760
1761  " 27d: Setting again global number local (to window) option"
1762  noa set foldcolumn=8 " Reset global and local value (without triggering autocmd)
1763  let g:options = [['foldcolumn', '8', '8', '8', '2', 'global', 'set']]
1764  set foldcolumn=2
1765  call assert_equal([], g:options)
1766  call assert_equal(g:opt[0], g:opt[1])
1767
1768
1769  " 28a: Setting global boolean global option"
1770  noa setglobal nowrapscan " Reset global and local value (without triggering autocmd)
1771  noa setlocal wrapscan " Sets the global(!) value!
1772  let g:options = [['wrapscan', '1', '', '1', '0', 'global', 'setglobal']]
1773  setglobal nowrapscan
1774  call assert_equal([], g:options)
1775  call assert_equal(g:opt[0], g:opt[1])
1776
1777  " 28b: Setting local boolean global option"
1778  noa setglobal nowrapscan " Reset global and local value (without triggering autocmd)
1779  noa setlocal wrapscan " Sets the global(!) value!
1780  let g:options = [['wrapscan', '1', '1', '', '0', 'local', 'setlocal']]
1781  setlocal nowrapscan
1782  call assert_equal([], g:options)
1783  call assert_equal(g:opt[0], g:opt[1])
1784
1785  " 28c: Setting again boolean global option"
1786  noa setglobal nowrapscan " Reset global and local value (without triggering autocmd)
1787  noa setlocal wrapscan " Sets the global(!) value!
1788  let g:options = [['wrapscan', '1', '1', '1', '0', 'global', 'set']]
1789  set nowrapscan
1790  call assert_equal([], g:options)
1791  call assert_equal(g:opt[0], g:opt[1])
1792
1793  " 28d: Setting again global boolean global option"
1794  noa set nowrapscan " Reset global and local value (without triggering autocmd)
1795  let g:options = [['wrapscan', '0', '0', '0', '1', 'global', 'set']]
1796  set wrapscan
1797  call assert_equal([], g:options)
1798  call assert_equal(g:opt[0], g:opt[1])
1799
1800
1801  " 29a: Setting global boolean global-local (to buffer) option"
1802  noa setglobal noautoread " Reset global and local value (without triggering autocmd)
1803  noa setlocal autoread
1804  let g:options = [['autoread', '0', '', '0', '1', 'global', 'setglobal']]
1805  setglobal autoread
1806  call assert_equal([], g:options)
1807  call assert_equal(g:opt[0], g:opt[1])
1808
1809  " 29b: Setting local boolean global-local (to buffer) option"
1810  noa setglobal noautoread " Reset global and local value (without triggering autocmd)
1811  noa setlocal autoread
1812  let g:options = [['autoread', '1', '1', '', '0', 'local', 'setlocal']]
1813  setlocal noautoread
1814  call assert_equal([], g:options)
1815  call assert_equal(g:opt[0], g:opt[1])
1816
1817  " 29c: Setting again boolean global-local (to buffer) option"
1818  noa setglobal noautoread " Reset global and local value (without triggering autocmd)
1819  noa setlocal autoread
1820  let g:options = [['autoread', '1', '1', '0', '1', 'global', 'set']]
1821  set autoread
1822  call assert_equal([], g:options)
1823  call assert_equal(g:opt[0], g:opt[1])
1824
1825  " 29d: Setting again global boolean global-local (to buffer) option"
1826  noa set noautoread " Reset global and local value (without triggering autocmd)
1827  let g:options = [['autoread', '0', '0', '0', '1', 'global', 'set']]
1828  set autoread
1829  call assert_equal([], g:options)
1830  call assert_equal(g:opt[0], g:opt[1])
1831
1832
1833  " 30a: Setting global boolean local (to buffer) option"
1834  noa setglobal nocindent " Reset global and local value (without triggering autocmd)
1835  noa setlocal cindent
1836  let g:options = [['cindent', '0', '', '0', '1', 'global', 'setglobal']]
1837  setglobal cindent
1838  call assert_equal([], g:options)
1839  call assert_equal(g:opt[0], g:opt[1])
1840
1841  " 30b: Setting local boolean local (to buffer) option"
1842  noa setglobal nocindent " Reset global and local value (without triggering autocmd)
1843  noa setlocal cindent
1844  let g:options = [['cindent', '1', '1', '', '0', 'local', 'setlocal']]
1845  setlocal nocindent
1846  call assert_equal([], g:options)
1847  call assert_equal(g:opt[0], g:opt[1])
1848
1849  " 30c: Setting again boolean local (to buffer) option"
1850  noa setglobal nocindent " Reset global and local value (without triggering autocmd)
1851  noa setlocal cindent
1852  let g:options = [['cindent', '1', '1', '0', '1', 'global', 'set']]
1853  set cindent
1854  call assert_equal([], g:options)
1855  call assert_equal(g:opt[0], g:opt[1])
1856
1857  " 30d: Setting again global boolean local (to buffer) option"
1858  noa set nocindent " Reset global and local value (without triggering autocmd)
1859  let g:options = [['cindent', '0', '0', '0', '1', 'global', 'set']]
1860  set cindent
1861  call assert_equal([], g:options)
1862  call assert_equal(g:opt[0], g:opt[1])
1863
1864
1865  " 31: Setting boolean global-local (to window) option
1866  " Currently no such option exists.
1867
1868
1869  " 32a: Setting global boolean local (to window) option"
1870  noa setglobal nocursorcolumn " Reset global and local value (without triggering autocmd)
1871  noa setlocal cursorcolumn
1872  let g:options = [['cursorcolumn', '0', '', '0', '1', 'global', 'setglobal']]
1873  setglobal cursorcolumn
1874  call assert_equal([], g:options)
1875  call assert_equal(g:opt[0], g:opt[1])
1876
1877  " 32b: Setting local boolean local (to window) option"
1878  noa setglobal nocursorcolumn " Reset global and local value (without triggering autocmd)
1879  noa setlocal cursorcolumn
1880  let g:options = [['cursorcolumn', '1', '1', '', '0', 'local', 'setlocal']]
1881  setlocal nocursorcolumn
1882  call assert_equal([], g:options)
1883  call assert_equal(g:opt[0], g:opt[1])
1884
1885  " 32c: Setting again boolean local (to window) option"
1886  noa setglobal nocursorcolumn " Reset global and local value (without triggering autocmd)
1887  noa setlocal cursorcolumn
1888  let g:options = [['cursorcolumn', '1', '1', '0', '1', 'global', 'set']]
1889  set cursorcolumn
1890  call assert_equal([], g:options)
1891  call assert_equal(g:opt[0], g:opt[1])
1892
1893  " 32d: Setting again global boolean local (to window) option"
1894  noa set nocursorcolumn " Reset global and local value (without triggering autocmd)
1895  let g:options = [['cursorcolumn', '0', '0', '0', '1', 'global', 'set']]
1896  set cursorcolumn
1897  call assert_equal([], g:options)
1898  call assert_equal(g:opt[0], g:opt[1])
1899
1900
1901  " 33: Test autocommands when an option value is converted internally.
1902  noa set backspace=1 " Reset global and local value (without triggering autocmd)
1903  let g:options = [['backspace', 'indent,eol', 'indent,eol', 'indent,eol', '2', 'global', 'set']]
1904  set backspace=2
1905  call assert_equal([], g:options)
1906  call assert_equal(g:opt[0], g:opt[1])
1907
1908
1909  " Cleanup
1910  au! OptionSet
1911  " set tags&
1912  for opt in ['nu', 'ai', 'acd', 'ar', 'bs', 'backup', 'cul', 'cp', 'backupext', 'tags', 'spelllang', 'statusline', 'foldignore', 'cmdheight', 'undolevels', 'wrapmargin', 'foldcolumn', 'wrapscan', 'autoread', 'cindent', 'cursorcolumn']
1913    exe printf(":set %s&vim", opt)
1914  endfor
1915  call test_override('starting', 0)
1916  delfunc! AutoCommandOptionSet
1917endfunc
1918
1919func Test_OptionSet_diffmode()
1920  call Ntest_override('starting', 1)
1921  " 18: Changing an option when entering diff mode
1922  new
1923  au OptionSet diff :let &l:cul = v:option_new
1924
1925  call setline(1, ['buffer 1', 'line2', 'line3', 'line4'])
1926  call assert_equal(0, &l:cul)
1927  diffthis
1928  call assert_equal(1, &l:cul)
1929
1930  vnew
1931  call setline(1, ['buffer 2', 'line 2', 'line 3', 'line4'])
1932  call assert_equal(0, &l:cul)
1933  diffthis
1934  call assert_equal(1, &l:cul)
1935
1936  diffoff
1937  call assert_equal(0, &l:cul)
1938  call assert_equal(1, getwinvar(2, '&l:cul'))
1939  bw!
1940
1941  call assert_equal(1, &l:cul)
1942  diffoff!
1943  call assert_equal(0, &l:cul)
1944  call assert_equal(0, getwinvar(1, '&l:cul'))
1945  bw!
1946
1947  " Cleanup
1948  au! OptionSet
1949  call Ntest_override('starting', 0)
1950endfunc
1951
1952func Test_OptionSet_diffmode_close()
1953  call Ntest_override('starting', 1)
1954  " 19: Try to close the current window when entering diff mode
1955  " should not segfault
1956  new
1957  au OptionSet diff close
1958
1959  call setline(1, ['buffer 1', 'line2', 'line3', 'line4'])
1960  call assert_fails(':diffthis', 'E788')
1961  call assert_equal(1, &diff)
1962  vnew
1963  call setline(1, ['buffer 2', 'line 2', 'line 3', 'line4'])
1964  call assert_fails(':diffthis', 'E788')
1965  call assert_equal(1, &diff)
1966  set diffopt-=closeoff
1967  bw!
1968  call assert_fails(':diffoff!', 'E788')
1969  bw!
1970
1971  " Cleanup
1972  au! OptionSet
1973  call Ntest_override('starting', 0)
1974  "delfunc! AutoCommandOptionSet
1975endfunc
1976
1977" Test for Bufleave autocommand that deletes the buffer we are about to edit.
1978func Test_BufleaveWithDelete()
1979  new | edit XbufLeave1
1980
1981  augroup test_bufleavewithdelete
1982      autocmd!
1983      autocmd BufLeave XbufLeave1 bwipe XbufLeave2
1984  augroup END
1985
1986  call assert_fails('edit XbufLeave2', 'E143:')
1987  call assert_equal('XbufLeave1', bufname('%'))
1988
1989  autocmd! test_bufleavewithdelete BufLeave XbufLeave1
1990  augroup! test_bufleavewithdelete
1991
1992  new
1993  bwipe! XbufLeave1
1994endfunc
1995
1996" Test for autocommand that changes the buffer list, when doing ":ball".
1997func Test_Acmd_BufAll()
1998  enew!
1999  %bwipe!
2000  call writefile(['Test file Xxx1'], 'Xxx1', 'D')
2001  call writefile(['Test file Xxx2'], 'Xxx2', 'D')
2002  call writefile(['Test file Xxx3'], 'Xxx3', 'D')
2003
2004  " Add three files to the buffer list
2005  split Xxx1
2006  close
2007  split Xxx2
2008  close
2009  split Xxx3
2010  close
2011
2012  " Wipe the buffer when the buffer is opened
2013  au BufReadPost Xxx2 bwipe
2014
2015  call append(0, 'Test file Xxx4')
2016  ball
2017
2018  call assert_equal(2, winnr('$'))
2019  call assert_equal('Xxx1', bufname(winbufnr(winnr('$'))))
2020  wincmd t
2021
2022  au! BufReadPost
2023  %bwipe!
2024  enew! | only
2025endfunc
2026
2027" Test for autocommand that changes current buffer on BufEnter event.
2028" Check if modelines are interpreted for the correct buffer.
2029func Test_Acmd_BufEnter()
2030  %bwipe!
2031  call writefile(['start of test file Xxx1',
2032	      \ "\<Tab>this is a test",
2033	      \ 'end of test file Xxx1'], 'Xxx1', 'D')
2034  call writefile(['start of test file Xxx2',
2035	      \ 'vim: set noai :',
2036	      \ "\<Tab>this is a test",
2037	      \ 'end of test file Xxx2'], 'Xxx2', 'D')
2038
2039  au BufEnter Xxx2 brew
2040  set ai modeline modelines=3
2041  edit Xxx1
2042  " edit Xxx2, autocmd will do :brew
2043  edit Xxx2
2044  exe "normal G?this is a\<CR>"
2045  " Append text with autoindent to this file
2046  normal othis should be auto-indented
2047  call assert_equal("\<Tab>this should be auto-indented", getline('.'))
2048  call assert_equal(3, line('.'))
2049  " Remove autocmd and edit Xxx2 again
2050  au! BufEnter Xxx2
2051  buf! Xxx2
2052  exe "normal G?this is a\<CR>"
2053  " append text without autoindent to Xxx
2054  normal othis should be in column 1
2055  call assert_equal("this should be in column 1", getline('.'))
2056  call assert_equal(4, line('.'))
2057
2058  %bwipe!
2059  set ai&vim modeline&vim modelines&vim
2060endfunc
2061
2062" Test for issue #57
2063" do not move cursor on <c-o> when autoindent is set
2064func Test_ai_CTRL_O()
2065  enew!
2066  set ai
2067  let save_fo = &fo
2068  set fo+=r
2069  exe "normal o# abcdef\<Esc>2hi\<CR>\<C-O>d0\<Esc>"
2070  exe "normal o# abcdef\<Esc>2hi\<C-O>d0\<Esc>"
2071  call assert_equal(['# abc', 'def', 'def'], getline(2, 4))
2072
2073  set ai&vim
2074  let &fo = save_fo
2075  enew!
2076endfunc
2077
2078" Test for autocommand that deletes the current buffer on BufLeave event.
2079" Also test deleting the last buffer, should give a new, empty buffer.
2080func Test_BufLeave_Wipe()
2081  %bwipe!
2082  let content = ['start of test file Xxx',
2083	      \ 'this is a test',
2084	      \ 'end of test file Xxx']
2085  call writefile(content, 'Xxx1', 'D')
2086  call writefile(content, 'Xxx2', 'D')
2087
2088  au BufLeave Xxx2 bwipe
2089  edit Xxx1
2090  split Xxx2
2091  " delete buffer Xxx2, we should be back to Xxx1
2092  bwipe
2093  call assert_equal('Xxx1', bufname('%'))
2094  call assert_equal(1, winnr('$'))
2095
2096  " Create an alternate buffer
2097  %write! test.out
2098  call assert_equal('test.out', bufname('#'))
2099  " delete alternate buffer
2100  bwipe test.out
2101  call assert_equal('Xxx1', bufname('%'))
2102  call assert_equal('', bufname('#'))
2103
2104  au BufLeave Xxx1 bwipe
2105  " delete current buffer, get an empty one
2106  bwipe!
2107  call assert_equal(1, line('$'))
2108  call assert_equal('', bufname('%'))
2109  let g:bufinfo = getbufinfo()
2110  call assert_equal(1, len(g:bufinfo))
2111
2112  call delete('test.out')
2113  %bwipe
2114  au! BufLeave
2115
2116  " check that bufinfo doesn't contain a pointer to freed memory
2117  call test_garbagecollect_now()
2118endfunc
2119
2120func Test_QuitPre()
2121  edit Xfoo
2122  let winid = win_getid(winnr())
2123  split Xbar
2124  au! QuitPre * let g:afile = expand('<afile>')
2125  " Close the other window, <afile> should be correct.
2126  exe win_id2win(winid) . 'q'
2127  call assert_equal('Xfoo', g:afile)
2128 
2129  unlet g:afile
2130  bwipe Xfoo
2131  bwipe Xbar
2132endfunc
2133
2134func Test_Cmdline_Trigger()
2135  autocmd CmdlineLeavePre : let g:log = "CmdlineLeavePre"
2136  autocmd CmdlineLeave : let g:log2 = "CmdlineLeave"
2137  new
2138  let g:log = ''
2139  let g:log2 = ''
2140  nnoremap <F1> <Cmd>echo "hello"<CR>
2141  call feedkeys("\<F1>", 'x')
2142  call assert_equal('', g:log)
2143  call assert_equal('', g:log2)
2144  nunmap <F1>
2145
2146  let g:log = ''
2147  let g:log2 = ''
2148  nnoremap <F1> :echo "hello"<CR>
2149  call feedkeys("\<F1>", 'x')
2150  call assert_equal('CmdlineLeavePre', g:log)
2151  call assert_equal('CmdlineLeave', g:log2)
2152  nunmap <F1>
2153
2154  let g:log = ''
2155  let g:log2 = ''
2156  call feedkeys(":\<bs>", "tx")
2157  call assert_equal('CmdlineLeavePre', g:log)
2158  call assert_equal('CmdlineLeave', g:log2)
2159
2160  let g:log = ''
2161  let g:log2 = ''
2162  split
2163  call assert_equal('', g:log)
2164  call feedkeys(":echo hello", "tx")
2165  call assert_equal('CmdlineLeavePre', g:log)
2166  call assert_equal('CmdlineLeave', g:log2)
2167
2168  let g:log = ''
2169  let g:log2 = ''
2170  close
2171  call assert_equal('', g:log)
2172  call feedkeys(":echo hello", "tx")
2173  call assert_equal('CmdlineLeavePre', g:log)
2174  call assert_equal('CmdlineLeave', g:log2)
2175
2176  let g:log = ''
2177  let g:log2 = ''
2178  tabnew
2179  call assert_equal('', g:log)
2180  call feedkeys(":echo hello", "tx")
2181  call assert_equal('CmdlineLeavePre', g:log)
2182  call assert_equal('CmdlineLeave', g:log2)
2183
2184  let g:log = ''
2185  let g:log2 = ''
2186  split
2187  call assert_equal('', g:log)
2188  call feedkeys(":echo hello", "tx")
2189  call assert_equal('CmdlineLeavePre', g:log)
2190  call assert_equal('CmdlineLeave', g:log2)
2191
2192  let g:log = ''
2193  let g:log2 = ''
2194  tabclose
2195  call assert_equal('', g:log)
2196  call feedkeys(":echo hello", "tx")
2197  call assert_equal('CmdlineLeavePre', g:log)
2198  call assert_equal('CmdlineLeave', g:log2)
2199
2200  autocmd CmdlineLeavePre * let g:cmdline += [getcmdline()]
2201
2202  for end_keys in ["\<CR>", "\<NL>", "\<kEnter>", "\<C-C>", "\<Esc>",
2203                 \ "\<C-\>\<C-N>", "\<C-\>\<C-G>"]
2204    let g:cmdline = []
2205    let g:log = ''
2206    let g:log2 = ''
2207    call assert_equal('', g:log)
2208    let keys = $':echo "hello"{end_keys}'
2209    let msg = keytrans(keys)
2210    call feedkeys(keys, "tx")
2211    call assert_equal(['echo "hello"'], g:cmdline, msg)
2212    call assert_equal('CmdlineLeavePre', g:log, msg)
2213    call assert_equal('CmdlineLeave', g:log2, msg)
2214  endfor
2215
2216  let g:cmdline = []
2217  call feedkeys(":let c = input('? ')\<cr>ABCDE\<cr>", "tx")
2218  call assert_equal(["let c = input('? ')", 'ABCDE'], g:cmdline)
2219
2220  au! CmdlineLeavePre
2221  unlet! g:cmdline
2222  unlet! g:log
2223  unlet! g:log2
2224  bw!
2225endfunc
2226
2227" Ensure :cabbr does not cause a spurious CmdlineLeavePre.
2228func Test_CmdlineLeavePre_cabbr()
2229  " For unknown reason this fails intermittently on MS-Windows
2230  CheckNotMSWindows
2231  CheckFeature terminal
2232  let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile'], {'term_rows': 3})
2233  call assert_equal('running', term_getstatus(buf))
2234  call term_sendkeys(buf, ":let g:a=0\<cr>")
2235  call term_wait(buf, 50)
2236  call term_sendkeys(buf, ":cabbr v v\<cr>")
2237  call term_wait(buf, 50)
2238  call term_sendkeys(buf, ":command! -nargs=* Foo echo\<cr>")
2239  call term_wait(buf, 50)
2240  call term_sendkeys(buf, ":au! CmdlineLeavePre * :let g:a+=1\<cr>")
2241  call term_wait(buf, 50)
2242  call term_sendkeys(buf, ":Foo v\<cr>")
2243  call term_wait(buf, 50)
2244  call term_sendkeys(buf, ":echo g:a\<cr>")
2245  call term_wait(buf, 50)
2246  call WaitForAssert({-> assert_match('^2.*$', term_getline(buf, 3))})
2247  bwipe!
2248endfunc
2249
2250func Test_Cmdline()
2251  au! CmdlineChanged : let g:text = getcmdline()
2252  let g:text = 0
2253  call feedkeys(":echom 'hello'\<CR>", 'xt')
2254  call assert_equal("echom 'hello'", g:text)
2255  au! CmdlineChanged
2256
2257  au! CmdlineChanged : let g:entered = expand('<afile>')
2258  let g:entered = 0
2259  call feedkeys(":echom 'hello'\<CR>", 'xt')
2260  call assert_equal(':', g:entered)
2261  au! CmdlineChanged
2262
2263  autocmd CmdlineChanged : let g:log += [getcmdline()]
2264
2265  let g:log = []
2266  cnoremap <F1> <Cmd>call setcmdline('ls')<CR>
2267  call feedkeys(":\<F1>", 'xt')
2268  call assert_equal(['ls'], g:log)
2269  cunmap <F1>
2270
2271  let g:log = []
2272  call feedkeys(":sign \<Tab>\<Tab>\<C-N>\<C-P>\<S-Tab>\<S-Tab>\<Esc>", 'xt')
2273  call assert_equal([
2274        \ 's',
2275        \ 'si',
2276        \ 'sig',
2277        \ 'sign',
2278        \ 'sign ',
2279        \ 'sign define',
2280        \ 'sign jump',
2281        \ 'sign list',
2282        \ 'sign jump',
2283        \ 'sign define',
2284        \ 'sign ',
2285        \ ], g:log)
2286  let g:log = []
2287  set wildmenu wildoptions+=pum
2288  call feedkeys(":sign \<S-Tab>\<PageUp>\<kPageUp>\<kPageDown>\<PageDown>\<Esc>", 'xt')
2289  call assert_equal([
2290        \ 's',
2291        \ 'si',
2292        \ 'sig',
2293        \ 'sign',
2294        \ 'sign ',
2295        \ 'sign unplace',
2296        \ 'sign jump',
2297        \ 'sign define',
2298        \ 'sign undefine',
2299        \ 'sign unplace',
2300        \ ], g:log)
2301  set wildmenu& wildoptions&
2302
2303  let g:log = []
2304  let @r = 'abc'
2305  call feedkeys(":0\<C-R>=@r\<CR>1\<C-R>\<C-O>r2\<C-R>\<C-R>r3\<Esc>", 'xt')
2306  call assert_equal([
2307        \ '0',
2308        \ '0a',
2309        \ '0ab',
2310        \ '0abc',
2311        \ '0abc1',
2312        \ '0abc1abc',
2313        \ '0abc1abc2',
2314        \ '0abc1abc2abc',
2315        \ '0abc1abc2abc3',
2316        \ ], g:log)
2317
2318  " <Del> should trigger CmdlineChanged
2319  let g:log = []
2320  call feedkeys(":foo\<Left>\<Left>\<Del>\<Del>\<Esc>", 'xt')
2321  call assert_equal([
2322        \ 'f',
2323        \ 'fo',
2324        \ 'foo',
2325        \ 'fo',
2326        \ 'f',
2327        \ ], g:log)
2328
2329  unlet g:log
2330  au! CmdlineChanged
2331
2332  au! CmdlineEnter : let g:entered = expand('<afile>')
2333  au! CmdlineLeave : let g:left = expand('<afile>')
2334  au! CmdlineLeavePre : let g:leftpre = expand('<afile>')
2335  let g:entered = 0
2336  let g:left = 0
2337  let g:leftpre = 0
2338  call feedkeys(":echo 'hello'\<CR>", 'xt')
2339  call assert_equal(':', g:entered)
2340  call assert_equal(':', g:left)
2341  call assert_equal(':', g:leftpre)
2342  au! CmdlineEnter
2343  au! CmdlineLeave
2344  au! CmdlineLeavePre
2345
2346  let save_shellslash = &shellslash
2347  " Nvim doesn't allow setting value of a hidden option to non-default value
2348  if exists('+shellslash')
2349    set noshellslash
2350  endif
2351  au! CmdlineEnter / let g:entered = expand('<afile>')
2352  au! CmdlineLeave / let g:left = expand('<afile>')
2353  au! CmdlineLeavePre / let g:leftpre = expand('<afile>')
2354  let g:entered = 0
2355  let g:left = 0
2356  let g:leftpre = 0
2357  new
2358  call setline(1, 'hello')
2359  call feedkeys("/hello\<CR>", 'xt')
2360  call assert_equal('/', g:entered)
2361  call assert_equal('/', g:left)
2362  call assert_equal('/', g:leftpre)
2363  bwipe!
2364  au! CmdlineEnter
2365  au! CmdlineLeave
2366  au! CmdlineLeavePre
2367  let &shellslash = save_shellslash
2368
2369  let g:left = "cancelled"
2370  let g:leftpre = "cancelled"
2371  au! CmdlineLeave : let g:left = "triggered"
2372  au! CmdlineLeavePre : let g:leftpre = "triggered"
2373  call feedkeys(":echo 'hello'\<esc>", 'xt')
2374  call assert_equal('triggered', g:left)
2375  call assert_equal('triggered', g:leftpre)
2376  let g:left = "cancelled"
2377  let g:leftpre = "cancelled"
2378  au! CmdlineLeave : let g:left = "triggered"
2379  call feedkeys(":echo 'hello'\<c-c>", 'xt')
2380  call assert_equal('triggered', g:left)
2381  call assert_equal('triggered', g:leftpre)
2382  au! CmdlineLeave
2383  au! CmdlineLeavePre
2384
2385  au! CursorMovedC : let g:pos += [getcmdpos()]
2386  let g:pos = []
2387  call feedkeys(":foo bar baz\<C-W>\<C-W>\<C-W>\<Esc>", 'xt')
2388  call assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 9, 5, 1], g:pos)
2389  let g:pos = []
2390  call feedkeys(":hello\<C-B>\<Esc>", 'xt')
2391  call assert_equal([2, 3, 4, 5, 6, 1], g:pos)
2392  let g:pos = []
2393  call feedkeys(":hello\<C-U>\<Esc>", 'xt')
2394  call assert_equal([2, 3, 4, 5, 6, 1], g:pos)
2395  let g:pos = []
2396  call feedkeys(":hello\<Left>\<C-R>=''\<CR>\<Left>\<Right>\<Esc>", 'xt')
2397  call assert_equal([2, 3, 4, 5, 6, 5, 4, 5], g:pos)
2398  let g:pos = []
2399  call feedkeys(":12345678\<C-R>=setcmdpos(3)??''\<CR>\<Esc>", 'xt')
2400  call assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 3], g:pos)
2401  let g:pos = []
2402  call feedkeys(":12345678\<C-R>=setcmdpos(3)??''\<CR>\<Left>\<Esc>", 'xt')
2403  call assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 3, 2], g:pos)
2404  au! CursorMovedC
2405
2406  " setcmdpos() is no-op inside an autocommand
2407  au! CursorMovedC : let g:pos += [getcmdpos()] | call setcmdpos(1)
2408  let g:pos = []
2409  call feedkeys(":hello\<Left>\<Left>\<Esc>", 'xt')
2410  call assert_equal([2, 3, 4, 5, 6, 5, 4], g:pos)
2411  au! CursorMovedC
2412
2413  unlet g:entered
2414  unlet g:left
2415  unlet g:pos
2416endfunc
2417
2418" Test for BufWritePre autocommand that deletes or unloads the buffer.
2419func Test_BufWritePre()
2420  %bwipe
2421  au BufWritePre Xxx1 bunload
2422  au BufWritePre Xxx2 bwipe
2423
2424  call writefile(['start of Xxx1', 'test', 'end of Xxx1'], 'Xxx1', 'D')
2425  call writefile(['start of Xxx2', 'test', 'end of Xxx2'], 'Xxx2', 'D')
2426
2427  edit Xtest
2428  e! Xxx2
2429  bdel Xtest
2430  e Xxx1
2431  " write it, will unload it and give an error msg
2432  call assert_fails('w', 'E203:')
2433  call assert_equal('Xxx2', bufname('%'))
2434  edit Xtest
2435  e! Xxx2
2436  bwipe Xtest
2437  " write it, will delete the buffer and give an error msg
2438  call assert_fails('w', 'E203:')
2439  call assert_equal('Xxx1', bufname('%'))
2440  au! BufWritePre
2441endfunc
2442
2443" Test for BufUnload autocommand that unloads all the other buffers
2444func Test_bufunload_all()
2445  let g:test_is_flaky = 1
2446  call writefile(['Test file Xxx1'], 'Xxx1', 'D')
2447  call writefile(['Test file Xxx2'], 'Xxx2', 'D')
2448
2449  let content =<< trim [CODE]
2450    func UnloadAllBufs()
2451      let i = 1
2452      while i <= bufnr('$')
2453        if i != bufnr('%') && bufloaded(i)
2454          exe  i . 'bunload'
2455        endif
2456        let i += 1
2457      endwhile
2458    endfunc
2459    au BufUnload * call UnloadAllBufs()
2460    au VimLeave * call writefile(['Test Finished'], 'Xout')
2461    set nohidden  " Accommodate Nvim default
2462    edit Xxx1
2463    split Xxx2
2464    q
2465  [CODE]
2466
2467  call writefile(content, 'Xbunloadtest', 'D')
2468
2469  call delete('Xout')
2470  call system(GetVimCommandClean() .. ' -N --headless -S Xbunloadtest')
2471  call assert_true(filereadable('Xout'))
2472
2473  call delete('Xout')
2474endfunc
2475
2476" Some tests for buffer-local autocommands
2477func Test_buflocal_autocmd()
2478  let g:bname = ''
2479  edit xx
2480  au BufLeave <buffer> let g:bname = expand("%")
2481  " here, autocommand for xx should trigger.
2482  " but autocommand shall not apply to buffer named <buffer>.
2483  edit somefile
2484  call assert_equal('xx', g:bname)
2485  let g:bname = ''
2486  " here, autocommand shall be auto-deleted
2487  bwipe xx
2488  " autocmd should not trigger
2489  edit xx
2490  call assert_equal('', g:bname)
2491  " autocmd should not trigger
2492  edit somefile
2493  call assert_equal('', g:bname)
2494  enew
2495  unlet g:bname
2496endfunc
2497
2498" Test for "*Cmd" autocommands
2499func Test_Cmd_Autocmds()
2500  call writefile(['start of Xxx', "\tabc2", 'end of Xxx'], 'Xxx', 'D')
2501
2502  enew!
2503  au BufReadCmd XtestA 0r Xxx|$del
2504  edit XtestA			" will read text of Xxd instead
2505  call assert_equal('start of Xxx', getline(1))
2506
2507  au BufWriteCmd XtestA call append(line("$"), "write")
2508  write				" will append a line to the file
2509  call assert_equal('write', getline('$'))
2510  call assert_fails('read XtestA', 'E484')	" should not read anything
2511  call assert_equal('write', getline(4))
2512
2513  " now we have:
2514  " 1	start of Xxx
2515  " 2		abc2
2516  " 3	end of Xxx
2517  " 4	write
2518
2519  au FileReadCmd XtestB '[r Xxx
2520  2r XtestB			" will read Xxx below line 2 instead
2521  call assert_equal('start of Xxx', getline(3))
2522
2523  " now we have:
2524  " 1	start of Xxx
2525  " 2		abc2
2526  " 3	start of Xxx
2527  " 4		abc2
2528  " 5	end of Xxx
2529  " 6	end of Xxx
2530  " 7	write
2531
2532  au FileWriteCmd XtestC '[,']copy $
2533  normal 4GA1
2534  4,5w XtestC			" will copy lines 4 and 5 to the end
2535  call assert_equal("\tabc21", getline(8))
2536  call assert_fails('r XtestC', 'E484')	" should not read anything
2537  call assert_equal("end of Xxx", getline(9))
2538
2539  " now we have:
2540  " 1	start of Xxx
2541  " 2		abc2
2542  " 3	start of Xxx
2543  " 4		abc21
2544  " 5	end of Xxx
2545  " 6	end of Xxx
2546  " 7	write
2547  " 8		abc21
2548  " 9	end of Xxx
2549
2550  let g:lines = []
2551  au FileAppendCmd XtestD call extend(g:lines, getline(line("'["), line("']")))
2552  w >>XtestD			" will add lines to 'lines'
2553  call assert_equal(9, len(g:lines))
2554  call assert_fails('$r XtestD', 'E484')	" should not read anything
2555  call assert_equal(9, line('$'))
2556  call assert_equal('end of Xxx', getline('$'))
2557
2558  au BufReadCmd XtestE 0r Xxx|$del
2559  sp XtestE			" split window with test.out
2560  call assert_equal('end of Xxx', getline(3))
2561
2562  let g:lines = []
2563  exe "normal 2Goasdf\<Esc>\<C-W>\<C-W>"
2564  au BufWriteCmd XtestE call extend(g:lines, getline(0, '$'))
2565  wall				" will write other window to 'lines'
2566  call assert_equal(4, len(g:lines), g:lines)
2567  call assert_equal("asdf", g:lines[2])
2568
2569  au! BufReadCmd
2570  au! BufWriteCmd
2571  au! FileReadCmd
2572  au! FileWriteCmd
2573  au! FileAppendCmd
2574  %bwipe!
2575  enew!
2576endfunc
2577
2578func s:ReadFile()
2579  setl noswapfile nomodified
2580  let filename = resolve(expand("<afile>:p"))
2581  execute 'read' fnameescape(filename)
2582  1d_
2583  exe 'file' fnameescape(filename)
2584  setl buftype=acwrite
2585endfunc
2586
2587func s:WriteFile()
2588  let filename = resolve(expand("<afile>:p"))
2589  setl buftype=
2590  noautocmd execute 'write' fnameescape(filename)
2591  setl buftype=acwrite
2592  setl nomodified
2593endfunc
2594
2595func Test_BufReadCmd()
2596  autocmd BufReadCmd *.test call s:ReadFile()
2597  autocmd BufWriteCmd *.test call s:WriteFile()
2598
2599  call writefile(['one', 'two', 'three'], 'Xcmd.test', 'D')
2600  edit Xcmd.test
2601  set noruler
2602  call assert_match('Xcmd.test" line 1 of 3', execute('file'))
2603  set ruler
2604  call assert_match('Xcmd.test" 3 lines --33%--', execute('file'))
2605  normal! Gofour
2606  write
2607  call assert_equal(['one', 'two', 'three', 'four'], readfile('Xcmd.test'))
2608
2609  bwipe!
2610  au! BufReadCmd
2611  au! BufWriteCmd
2612endfunc
2613
2614func Test_BufWriteCmd()
2615  autocmd BufWriteCmd Xbufwritecmd let g:written = 1
2616  new
2617  file Xbufwritecmd
2618  set buftype=acwrite
2619  call mkdir('Xbufwritecmd', 'D')
2620  write
2621  " BufWriteCmd should be triggered even if a directory has the same name
2622  call assert_equal(1, g:written)
2623  unlet g:written
2624  au! BufWriteCmd
2625  bwipe!
2626endfunc
2627
2628func SetChangeMarks(start, end)
2629  exe a:start .. 'mark ['
2630  exe a:end .. 'mark ]'
2631endfunc
2632
2633" Verify the effects of autocmds on '[ and ']
2634func Test_change_mark_in_autocmds()
2635  edit! Xtest
2636  call feedkeys("ia\<CR>b\<CR>c\<CR>d\<C-g>u\<Esc>", 'xtn')
2637
2638  call SetChangeMarks(2, 3)
2639  write
2640  call assert_equal([1, 4], [line("'["), line("']")])
2641
2642  call SetChangeMarks(2, 3)
2643  au BufWritePre * call assert_equal([1, 4], [line("'["), line("']")])
2644  write
2645  au! BufWritePre
2646
2647  if has('unix')
2648    write XtestFilter
2649    write >> XtestFilter
2650
2651    call SetChangeMarks(2, 3)
2652    " Marks are set to the entire range of the write
2653    au FilterWritePre * call assert_equal([1, 4], [line("'["), line("']")])
2654    " '[ is adjusted to just before the line that will receive the filtered
2655    " data
2656    au FilterReadPre * call assert_equal([4, 4], [line("'["), line("']")])
2657    " The filtered data is read into the buffer, and the source lines are
2658    " still present, so the range is after the source lines
2659    au FilterReadPost * call assert_equal([5, 12], [line("'["), line("']")])
2660    %!cat XtestFilter
2661    " After the filtered data is read, the original lines are deleted
2662    call assert_equal([1, 8], [line("'["), line("']")])
2663    au! FilterWritePre,FilterReadPre,FilterReadPost
2664    undo
2665
2666    call SetChangeMarks(1, 4)
2667    au FilterWritePre * call assert_equal([2, 3], [line("'["), line("']")])
2668    au FilterReadPre * call assert_equal([3, 3], [line("'["), line("']")])
2669    au FilterReadPost * call assert_equal([4, 11], [line("'["), line("']")])
2670    2,3!cat XtestFilter
2671    call assert_equal([2, 9], [line("'["), line("']")])
2672    au! FilterWritePre,FilterReadPre,FilterReadPost
2673    undo
2674
2675    call delete('XtestFilter')
2676  endif
2677
2678  call SetChangeMarks(1, 4)
2679  au FileWritePre * call assert_equal([2, 3], [line("'["), line("']")])
2680  2,3write Xtest2
2681  au! FileWritePre
2682
2683  call SetChangeMarks(2, 3)
2684  au FileAppendPre * call assert_equal([1, 4], [line("'["), line("']")])
2685  write >> Xtest2
2686  au! FileAppendPre
2687
2688  call SetChangeMarks(1, 4)
2689  au FileAppendPre * call assert_equal([2, 3], [line("'["), line("']")])
2690  2,3write >> Xtest2
2691  au! FileAppendPre
2692
2693  call SetChangeMarks(1, 1)
2694  au FileReadPre * call assert_equal([3, 1], [line("'["), line("']")])
2695  au FileReadPost * call assert_equal([4, 11], [line("'["), line("']")])
2696  3read Xtest2
2697  au! FileReadPre,FileReadPost
2698  undo
2699
2700  call SetChangeMarks(4, 4)
2701  " When the line is 0, it's adjusted to 1
2702  au FileReadPre * call assert_equal([1, 4], [line("'["), line("']")])
2703  au FileReadPost * call assert_equal([1, 8], [line("'["), line("']")])
2704  0read Xtest2
2705  au! FileReadPre,FileReadPost
2706  undo
2707
2708  call SetChangeMarks(4, 4)
2709  " When the line is 0, it's adjusted to 1
2710  au FileReadPre * call assert_equal([1, 4], [line("'["), line("']")])
2711  au FileReadPost * call assert_equal([2, 9], [line("'["), line("']")])
2712  1read Xtest2
2713  au! FileReadPre,FileReadPost
2714  undo
2715
2716  bwipe!
2717  call delete('Xtest')
2718  call delete('Xtest2')
2719endfunc
2720
2721func Test_Filter_noshelltemp()
2722  CheckExecutable cat
2723
2724  enew!
2725  call setline(1, ['a', 'b', 'c', 'd'])
2726
2727  let shelltemp = &shelltemp
2728  set shelltemp
2729
2730  let g:filter_au = 0
2731  au FilterWritePre * let g:filter_au += 1
2732  au FilterReadPre * let g:filter_au += 1
2733  au FilterReadPost * let g:filter_au += 1
2734  %!cat
2735  call assert_equal(3, g:filter_au)
2736
2737  if has('filterpipe')
2738    set noshelltemp
2739
2740    let g:filter_au = 0
2741    au FilterWritePre * let g:filter_au += 1
2742    au FilterReadPre * let g:filter_au += 1
2743    au FilterReadPost * let g:filter_au += 1
2744    %!cat
2745    call assert_equal(0, g:filter_au)
2746  endif
2747
2748  au! FilterWritePre,FilterReadPre,FilterReadPost
2749  let &shelltemp = shelltemp
2750  bwipe!
2751endfunc
2752
2753func Test_TextYankPost()
2754  enew!
2755  call setline(1, ['foo'])
2756
2757  let g:event = []
2758  au TextYankPost * let g:event = copy(v:event)
2759
2760  call assert_equal({}, v:event)
2761  call assert_fails('let v:event = {}', 'E46:')
2762  call assert_fails('let v:event.mykey = 0', 'E742:')
2763
2764  norm "ayiw
2765  call assert_equal(
2766    \{'regcontents': ['foo'], 'inclusive': v:true, 'regname': 'a', 'operator': 'y', 'visual': v:false, 'regtype': 'v'},
2767    \g:event)
2768  norm y_
2769  call assert_equal(
2770    \{'regcontents': ['foo'], 'inclusive': v:false, 'regname': '',  'operator': 'y', 'visual': v:false, 'regtype': 'V'},
2771    \g:event)
2772  norm Vy
2773  call assert_equal(
2774    \{'regcontents': ['foo'], 'inclusive': v:true, 'regname': '',  'operator': 'y', 'visual': v:true, 'regtype': 'V'},
2775    \g:event)
2776  call feedkeys("\<C-V>y", 'x')
2777  call assert_equal(
2778    \{'regcontents': ['f'], 'inclusive': v:true, 'regname': '',  'operator': 'y', 'visual': v:true, 'regtype': "\x161"},
2779    \g:event)
2780  norm "xciwbar
2781  call assert_equal(
2782    \{'regcontents': ['foo'], 'inclusive': v:true, 'regname': 'x', 'operator': 'c', 'visual': v:false, 'regtype': 'v'},
2783    \g:event)
2784  norm "bdiw
2785  call assert_equal(
2786    \{'regcontents': ['bar'], 'inclusive': v:true, 'regname': 'b', 'operator': 'd', 'visual': v:false, 'regtype': 'v'},
2787    \g:event)
2788
2789  call assert_equal({}, v:event)
2790
2791  au! TextYankPost
2792  unlet g:event
2793  bwipe!
2794endfunc
2795
2796func Test_autocommand_all_events()
2797  call assert_fails('au * * bwipe', 'E1155:')
2798  call assert_fails('au * x bwipe', 'E1155:')
2799  call assert_fails('au! * x bwipe', 'E1155:')
2800endfunc
2801
2802func Test_autocmd_user()
2803  au User MyEvent let s:res = [expand("<afile>"), expand("<amatch>")]
2804  doautocmd User MyEvent
2805  call assert_equal(['MyEvent', 'MyEvent'], s:res)
2806  au! User
2807  unlet s:res
2808endfunc
2809
2810function s:Before_test_dirchanged()
2811  augroup test_dirchanged
2812    autocmd!
2813  augroup END
2814  let s:li = []
2815  let s:dir_this = getcwd()
2816  let s:dir_foo = s:dir_this . '/Xfoo'
2817  call mkdir(s:dir_foo)
2818  let s:dir_bar = s:dir_this . '/Xbar'
2819  call mkdir(s:dir_bar)
2820endfunc
2821
2822function s:After_test_dirchanged()
2823  call chdir(s:dir_this)
2824  call delete(s:dir_foo, 'd')
2825  call delete(s:dir_bar, 'd')
2826  augroup test_dirchanged
2827    autocmd!
2828  augroup END
2829endfunc
2830
2831function Test_dirchanged_global()
2832  call s:Before_test_dirchanged()
2833  autocmd test_dirchanged DirChangedPre global call add(s:li, expand("<amatch>") .. " pre cd " .. v:event.directory)
2834  autocmd test_dirchanged DirChanged global call add(s:li, "cd:")
2835  autocmd test_dirchanged DirChanged global call add(s:li, expand("<afile>"))
2836  call chdir(s:dir_foo)
2837  let expected = ["global pre cd " .. s:dir_foo, "cd:", s:dir_foo]
2838  call assert_equal(expected, s:li)
2839  call chdir(s:dir_foo)
2840  call assert_equal(expected, s:li)
2841  exe 'lcd ' .. fnameescape(s:dir_bar)
2842  call assert_equal(expected, s:li)
2843
2844  exe 'cd ' .. s:dir_foo
2845  exe 'cd ' .. s:dir_bar
2846  autocmd! test_dirchanged DirChanged global let g:result = expand("<afile>")
2847  cd -
2848  call assert_equal(s:dir_foo, substitute(g:result, '\\', '/', 'g'))
2849
2850  call s:After_test_dirchanged()
2851endfunc
2852
2853function Test_dirchanged_local()
2854  call s:Before_test_dirchanged()
2855  autocmd test_dirchanged DirChanged window call add(s:li, "lcd:")
2856  autocmd test_dirchanged DirChanged window call add(s:li, expand("<afile>"))
2857  call chdir(s:dir_foo)
2858  call assert_equal([], s:li)
2859  exe 'lcd ' .. fnameescape(s:dir_bar)
2860  call assert_equal(["lcd:", s:dir_bar], s:li)
2861  exe 'lcd ' .. fnameescape(s:dir_bar)
2862  call assert_equal(["lcd:", s:dir_bar], s:li)
2863  call s:After_test_dirchanged()
2864endfunc
2865
2866function Test_dirchanged_auto()
2867  CheckFunction test_autochdir
2868  CheckOption autochdir
2869  call s:Before_test_dirchanged()
2870  call test_autochdir()
2871  autocmd test_dirchanged DirChangedPre auto call add(s:li, "pre cd " .. v:event.directory)
2872  autocmd test_dirchanged DirChanged auto call add(s:li, "auto:")
2873  autocmd test_dirchanged DirChanged auto call add(s:li, expand("<afile>"))
2874  set acd
2875  cd ..
2876  call assert_equal([], s:li)
2877  exe 'edit ' . s:dir_foo . '/Xautofile'
2878  call assert_equal(s:dir_foo, getcwd())
2879  let expected = ["pre cd " .. s:dir_foo, "auto:", s:dir_foo]
2880  call assert_equal(expected, s:li)
2881  set noacd
2882  bwipe!
2883  call s:After_test_dirchanged()
2884endfunc
2885
2886" Test TextChangedI and TextChangedP
2887func Test_ChangedP()
2888  new
2889  call setline(1, ['foo', 'bar', 'foobar'])
2890  call Ntest_override("char_avail", 1)
2891  set complete=. completeopt=menuone
2892
2893  func! TextChangedAutocmd(char)
2894    let g:autocmd .= a:char
2895  endfunc
2896
2897  " TextChanged will not be triggered, only check that it isn't.
2898  au! TextChanged <buffer> :call TextChangedAutocmd('N')
2899  au! TextChangedI <buffer> :call TextChangedAutocmd('I')
2900  au! TextChangedP <buffer> :call TextChangedAutocmd('P')
2901
2902  call cursor(3, 1)
2903  let g:autocmd = ''
2904  call feedkeys("o\<esc>", 'tnix')
2905  call assert_equal('I', g:autocmd)
2906
2907  let g:autocmd = ''
2908  call feedkeys("Sf", 'tnix')
2909  call assert_equal('II', g:autocmd)
2910
2911  let g:autocmd = ''
2912  call feedkeys("Sf\<C-N>", 'tnix')
2913  call assert_equal('IIP', g:autocmd)
2914
2915  let g:autocmd = ''
2916  call feedkeys("Sf\<C-N>\<C-N>", 'tnix')
2917  call assert_equal('IIPP', g:autocmd)
2918
2919  let g:autocmd = ''
2920  call feedkeys("Sf\<C-N>\<C-N>\<C-N>", 'tnix')
2921  call assert_equal('IIPPP', g:autocmd)
2922
2923  let g:autocmd = ''
2924  call feedkeys("Sf\<C-N>\<C-N>\<C-N>\<C-N>", 'tnix')
2925  call assert_equal('IIPPPP', g:autocmd)
2926
2927  call assert_equal(['foo', 'bar', 'foobar', 'foo'], getline(1, '$'))
2928  " TODO: how should it handle completeopt=noinsert,noselect?
2929
2930  " CleanUp
2931  call Ntest_override("char_avail", 0)
2932  au! TextChanged
2933  au! TextChangedI
2934  au! TextChangedP
2935  delfu TextChangedAutocmd
2936  unlet! g:autocmd
2937  set complete&vim completeopt&vim
2938
2939  bw!
2940endfunc
2941
2942let g:setline_handled = v:false
2943func SetLineOne()
2944  if !g:setline_handled
2945    call setline(1, "(x)")
2946    let g:setline_handled = v:true
2947  endif
2948endfunc
2949
2950func Test_TextChangedI_with_setline()
2951  new
2952  call Ntest_override('char_avail', 1)
2953  autocmd TextChangedI <buffer> call SetLineOne()
2954  call feedkeys("i(\<CR>\<Esc>", 'tx')
2955  call assert_equal('(', getline(1))
2956  call assert_equal('x)', getline(2))
2957  undo
2958  call assert_equal('', getline(1))
2959  call assert_equal('', getline(2))
2960
2961  call Ntest_override('char_avail', 0)
2962  bwipe!
2963endfunc
2964
2965func Test_TextChanged_with_norm()
2966  " For unknown reason this fails on MS-Windows
2967  CheckNotMSWindows
2968  CheckFeature terminal
2969  let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile'], {'term_rows': 3})
2970  call assert_equal('running', term_getstatus(buf))
2971  call term_sendkeys(buf, ":let g:a=0\<cr>")
2972  call term_wait(buf, 50)
2973  call term_sendkeys(buf, ":au! TextChanged * :let g:a+=1\<cr>")
2974  call term_wait(buf, 50)
2975  call term_sendkeys(buf, ":norm! ia\<cr>")
2976  call term_wait(buf, 50)
2977  call term_sendkeys(buf, ":echo g:a\<cr>")
2978  call term_wait(buf, 50)
2979  call WaitForAssert({-> assert_match('^1.*$', term_getline(buf, 3))})
2980  bwipe!
2981endfunc
2982
2983func Test_Changed_FirstTime()
2984  CheckFeature terminal
2985  CheckNotGui
2986  " Starting a terminal to run Vim is always considered flaky.
2987  let g:test_is_flaky = 1
2988
2989  " Prepare file for TextChanged event.
2990  call writefile([''], 'Xchanged.txt', 'D')
2991  let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile'], {'term_rows': 3})
2992  call assert_equal('running', term_getstatus(buf))
2993  " Wait for the ruler (in the status line) to be shown.
2994  " In ConPTY, there is additional character which is drawn up to the width of
2995  " the screen.
2996  if has('conpty')
2997    call WaitForAssert({-> assert_match('\<All.*$', term_getline(buf, 3))})
2998  else
2999    call WaitForAssert({-> assert_match('\<All$', term_getline(buf, 3))})
3000  endif
3001  " It's only adding autocmd, so that no event occurs.
3002  call term_sendkeys(buf, ":au! TextChanged <buffer> call writefile(['No'], 'Xchanged.txt')\<cr>")
3003  call term_sendkeys(buf, "\<C-\\>\<C-N>:qa!\<cr>")
3004  call WaitForAssert({-> assert_equal('finished', term_getstatus(buf))})
3005  call assert_equal([''], readfile('Xchanged.txt'))
3006
3007  " clean up
3008  bwipe!
3009endfunc
3010
3011func Test_autocmd_nested()
3012  let g:did_nested = 0
3013  defer CleanUpTestAuGroup()
3014  augroup testing
3015    au WinNew * edit somefile
3016    au BufNew * let g:did_nested = 1
3017  augroup END
3018  split
3019  call assert_equal(0, g:did_nested)
3020  close
3021  bwipe! somefile
3022
3023  " old nested argument still works
3024  augroup testing
3025    au!
3026    au WinNew * nested edit somefile
3027    au BufNew * let g:did_nested = 1
3028  augroup END
3029  split
3030  call assert_equal(1, g:did_nested)
3031  close
3032  bwipe! somefile
3033
3034  " New ++nested argument works
3035  augroup Testing
3036    au!
3037    au WinNew * ++nested edit somefile
3038    au BufNew * let g:did_nested = 1
3039  augroup END
3040  split
3041  call assert_equal(1, g:did_nested)
3042  close
3043  bwipe! somefile
3044
3045  augroup Testing
3046    au!
3047  augroup END
3048
3049  call assert_fails('au WinNew * ++nested ++nested echo bad', 'E983:')
3050  call assert_fails('au WinNew * nested nested echo bad', 'E983:')
3051endfunc
3052
3053func Test_autocmd_nested_cursor_invalid()
3054  set laststatus=0
3055  copen
3056  cclose
3057  call setline(1, ['foo', 'bar', 'baz'])
3058  3
3059  augroup nested_inv
3060    autocmd User foo ++nested copen
3061    autocmd BufAdd * let &laststatus = 2 - &laststatus
3062  augroup END
3063  doautocmd User foo
3064
3065  augroup nested_inv
3066    au!
3067  augroup END
3068  set laststatus&
3069  cclose
3070  bwipe!
3071endfunc
3072
3073func Test_autocmd_nested_keeps_cursor_pos()
3074  enew
3075  call setline(1, 'foo')
3076  autocmd User foo ++nested normal! $a
3077  autocmd InsertLeave * :
3078  doautocmd User foo
3079  call assert_equal([0, 1, 3, 0], getpos('.'))
3080
3081  bwipe!
3082endfunc
3083
3084func Test_autocmd_nested_switch_window()
3085  " run this in a separate Vim so that SafeState works
3086  CheckRunVimInTerminal
3087  CheckScreendump
3088
3089  let lines =<< trim END
3090      vim9script
3091      ['()']->writefile('Xautofile')
3092      autocmd VimEnter * ++nested edit Xautofile | split
3093      autocmd BufReadPost * autocmd SafeState * ++once foldclosed('.')
3094      autocmd WinEnter * matchadd('ErrorMsg', 'pat')
3095  END
3096  call writefile(lines, 'Xautoscript', 'D')
3097  let buf = RunVimInTerminal('-S Xautoscript', {'rows': 10})
3098  call VerifyScreenDump(buf, 'Test_autocmd_nested_switch', {})
3099
3100  call StopVimInTerminal(buf)
3101  call delete('Xautofile')
3102endfunc
3103
3104func Test_autocmd_once()
3105  " Without ++once WinNew triggers twice
3106  let g:did_split = 0
3107  augroup Testing
3108    au WinNew * let g:did_split += 1
3109  augroup END
3110  split
3111  split
3112  call assert_equal(2, g:did_split)
3113  call assert_true(exists('#WinNew'))
3114  close
3115  close
3116
3117  " With ++once WinNew triggers once
3118  let g:did_split = 0
3119  augroup Testing
3120    au!
3121    au WinNew * ++once let g:did_split += 1
3122  augroup END
3123  split
3124  split
3125  call assert_equal(1, g:did_split)
3126  call assert_false(exists('#WinNew'))
3127  close
3128  close
3129
3130  call assert_fails('au WinNew * ++once ++once echo bad', 'E983:')
3131  call assert_false(exists('#WinNew'))
3132endfunc
3133
3134func Test_autocmd_dup_arg()
3135  " Duplicate ++once / ++nested, or the legacy "nested" used twice, must
3136  " error out *and* not create the autocommand.  Using an environment
3137  " variable in the pattern also exercises the error-exit path that frees
3138  " the expanded pattern (checked by the address/leak sanitizers).
3139  augroup XdupTest
3140    au!
3141  augroup END
3142  let $XAUTODIR = 'Xfoo'
3143
3144  " New behavior: duplicate ++once now aborts, the autocmd is not added
3145  call assert_fails('au XdupTest WinNew $XAUTODIR/* ++once ++once echo bad', 'E983:')
3146  call assert_false(exists('#XdupTest#WinNew'))
3147
3148  call assert_fails('au XdupTest WinNew $XAUTODIR/* ++nested ++nested echo bad', 'E983:')
3149  call assert_false(exists('#XdupTest#WinNew'))
3150
3151  call assert_fails('au XdupTest WinNew $XAUTODIR/* nested nested echo bad', 'E983:')
3152  call assert_false(exists('#XdupTest#WinNew'))
3153
3154  " "nested" without "++" is rejected in Vim9 script (also frees the pattern)
3155  "call assert_fails('vim9cmd au XdupTest WinNew $XAUTODIR/* nested echo bad', 'E1078:')
3156  call assert_false(exists('#XdupTest#WinNew'))
3157
3158  augroup XdupTest
3159    au!
3160  augroup END
3161  augroup! XdupTest
3162  let $XAUTODIR = ''
3163endfunc
3164
3165
3166func Test_autocmd_bufreadpre()
3167  new
3168  let b:bufreadpre = 1
3169  call append(0, range(100))
3170  w! XAutocmdBufReadPre.txt
3171  autocmd BufReadPre <buffer> :let b:bufreadpre += 1
3172  norm! 50gg
3173  sp
3174  norm! 100gg
3175  wincmd p
3176  let g:wsv1 = winsaveview()
3177  wincmd p
3178  let g:wsv2 = winsaveview()
3179  " triggers BufReadPre, should not move the cursor in either window
3180  " The topline may change one line in a large window.
3181  edit
3182  call assert_inrange(g:wsv2.topline - 1, g:wsv2.topline + 1, winsaveview().topline)
3183  call assert_equal(g:wsv2.lnum, winsaveview().lnum)
3184  call assert_equal(2, b:bufreadpre)
3185  wincmd p
3186  call assert_equal(g:wsv1.topline, winsaveview().topline)
3187  call assert_equal(g:wsv1.lnum, winsaveview().lnum)
3188  call assert_equal(2, b:bufreadpre)
3189  " Now set the cursor position in an BufReadPre autocommand
3190  " (even though the position will be invalid, this should make Vim reset the
3191  " cursor position in the other window.
3192  wincmd p
3193  1 " set cpo+=g
3194  " won't do anything, but try to set the cursor on an invalid lnum
3195  autocmd BufReadPre <buffer> :norm! 70gg
3196  " triggers BufReadPre, should not move the cursor in either window
3197  e
3198  call assert_equal(1, winsaveview().topline)
3199  call assert_equal(1, winsaveview().lnum)
3200  call assert_equal(3, b:bufreadpre)
3201  wincmd p
3202  call assert_equal(g:wsv1.topline, winsaveview().topline)
3203  call assert_equal(g:wsv1.lnum, winsaveview().lnum)
3204  call assert_equal(3, b:bufreadpre)
3205  close
3206  close
3207  call delete('XAutocmdBufReadPre.txt')
3208  set cpo-=g
3209endfunc
3210
3211" FileChangedShell tested in test_filechanged.vim
3212
3213" Tests for the following autocommands:
3214" - FileWritePre	writing a compressed file
3215" - FileReadPost	reading a compressed file
3216" - BufNewFile		reading a file template
3217" - BufReadPre		decompressing the file to be read
3218" - FilterReadPre	substituting characters in the temp file
3219" - FilterReadPost	substituting characters after filtering
3220" - FileReadPre		set options for decompression
3221" - FileReadPost	decompress the file
3222func Test_ReadWrite_Autocmds()
3223  " Run this test only on Unix-like systems and if gzip is available
3224  if !has('unix') || !executable("gzip")
3225    return
3226  endif
3227
3228  " Make $GZIP empty, "-v" would cause trouble.
3229  let $GZIP = ""
3230
3231  " Use a FileChangedShell autocommand to avoid a prompt for 'Xtestfile.gz'
3232  " being modified outside of Vim (noticed on Solaris).
3233  au FileChangedShell * echo 'caught FileChangedShell'
3234
3235  " Test for the FileReadPost, FileWritePre and FileWritePost autocmds
3236  augroup Test1
3237    au!
3238    au FileWritePre    *.gz   '[,']!gzip
3239    au FileWritePost   *.gz   undo
3240    au FileReadPost    *.gz   '[,']!gzip -d
3241  augroup END
3242
3243  new
3244  set bin
3245  call append(0, [
3246	      \ 'line 2	Abcdefghijklmnopqrstuvwxyz',
3247	      \ 'line 3	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3248	      \ 'line 4	Abcdefghijklmnopqrstuvwxyz',
3249	      \ 'line 5	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3250	      \ 'line 6	Abcdefghijklmnopqrstuvwxyz',
3251	      \ 'line 7	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3252	      \ 'line 8	Abcdefghijklmnopqrstuvwxyz',
3253	      \ 'line 9	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3254	      \ 'line 10 Abcdefghijklmnopqrstuvwxyz'
3255	      \ ])
3256  1,9write! Xtestfile.gz
3257  enew! | close
3258
3259  new
3260  " Read and decompress the testfile
3261  0read Xtestfile.gz
3262  call assert_equal([
3263	      \ 'line 2	Abcdefghijklmnopqrstuvwxyz',
3264	      \ 'line 3	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3265	      \ 'line 4	Abcdefghijklmnopqrstuvwxyz',
3266	      \ 'line 5	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3267	      \ 'line 6	Abcdefghijklmnopqrstuvwxyz',
3268	      \ 'line 7	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3269	      \ 'line 8	Abcdefghijklmnopqrstuvwxyz',
3270	      \ 'line 9	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3271	      \ 'line 10 Abcdefghijklmnopqrstuvwxyz'
3272	      \ ], getline(1, 9))
3273  enew! | close
3274
3275  augroup Test1
3276    au!
3277  augroup END
3278
3279  " Test for the FileAppendPre and FileAppendPost autocmds
3280  augroup Test2
3281    au!
3282    au BufNewFile      *.c    read Xtest.c
3283    au FileAppendPre   *.out  '[,']s/new/NEW/
3284    au FileAppendPost  *.out  !cat Xtest.c >> test.out
3285  augroup END
3286
3287  call writefile(['/*', ' * Here is a new .c file', ' */'], 'Xtest.c', 'D')
3288  new foo.c			" should load Xtest.c
3289  call assert_equal(['/*', ' * Here is a new .c file', ' */'], getline(2, 4))
3290  w! >> test.out		" append it to the output file
3291
3292  let contents = readfile('test.out')
3293  call assert_equal(' * Here is a NEW .c file', contents[2])
3294  call assert_equal(' * Here is a new .c file', contents[5])
3295
3296  call delete('test.out')
3297  enew! | close
3298  augroup Test2
3299    au!
3300  augroup END
3301
3302  " Test for the BufReadPre and BufReadPost autocmds
3303  augroup Test3
3304    au!
3305    " setup autocommands to decompress before reading and re-compress
3306    " afterwards
3307    au BufReadPre  *.gz  exe '!gzip -d ' . shellescape(expand("<afile>"))
3308    au BufReadPre  *.gz  call rename(expand("<afile>:r"), expand("<afile>"))
3309    au BufReadPost *.gz  call rename(expand("<afile>"), expand("<afile>:r"))
3310    au BufReadPost *.gz  exe '!gzip ' . shellescape(expand("<afile>:r"))
3311  augroup END
3312
3313  e! Xtestfile.gz		" Edit compressed file
3314  call assert_equal([
3315	      \ 'line 2	Abcdefghijklmnopqrstuvwxyz',
3316	      \ 'line 3	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3317	      \ 'line 4	Abcdefghijklmnopqrstuvwxyz',
3318	      \ 'line 5	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3319	      \ 'line 6	Abcdefghijklmnopqrstuvwxyz',
3320	      \ 'line 7	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3321	      \ 'line 8	Abcdefghijklmnopqrstuvwxyz',
3322	      \ 'line 9	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3323	      \ 'line 10 Abcdefghijklmnopqrstuvwxyz'
3324	      \ ], getline(1, 9))
3325
3326  w! >> test.out		" Append it to the output file
3327
3328  augroup Test3
3329    au!
3330  augroup END
3331
3332  " Test for the FilterReadPre and FilterReadPost autocmds.
3333  set shelltemp			" need temp files here
3334  augroup Test4
3335    au!
3336    au FilterReadPre   *.out  call rename(expand("<afile>"), expand("<afile>") . ".t")
3337    au FilterReadPre   *.out  exe 'silent !sed s/e/E/ ' . shellescape(expand("<afile>")) . ".t >" . shellescape(expand("<afile>"))
3338    au FilterReadPre   *.out  exe 'silent !rm ' . shellescape(expand("<afile>")) . '.t'
3339    au FilterReadPost  *.out  '[,']s/x/X/g
3340  augroup END
3341
3342  e! test.out			" Edit the output file
3343  1,$!cat
3344  call assert_equal([
3345	      \ 'linE 2	AbcdefghijklmnopqrstuvwXyz',
3346	      \ 'linE 3	XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
3347	      \ 'linE 4	AbcdefghijklmnopqrstuvwXyz',
3348	      \ 'linE 5	XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
3349	      \ 'linE 6	AbcdefghijklmnopqrstuvwXyz',
3350	      \ 'linE 7	XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
3351	      \ 'linE 8	AbcdefghijklmnopqrstuvwXyz',
3352	      \ 'linE 9	XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
3353	      \ 'linE 10 AbcdefghijklmnopqrstuvwXyz'
3354	      \ ], getline(1, 9))
3355  call assert_equal([
3356	      \ 'line 2	Abcdefghijklmnopqrstuvwxyz',
3357	      \ 'line 3	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3358	      \ 'line 4	Abcdefghijklmnopqrstuvwxyz',
3359	      \ 'line 5	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3360	      \ 'line 6	Abcdefghijklmnopqrstuvwxyz',
3361	      \ 'line 7	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3362	      \ 'line 8	Abcdefghijklmnopqrstuvwxyz',
3363	      \ 'line 9	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3364	      \ 'line 10 Abcdefghijklmnopqrstuvwxyz'
3365	      \ ], readfile('test.out'))
3366
3367  augroup Test4
3368    au!
3369  augroup END
3370  set shelltemp&vim
3371
3372  " Test for the FileReadPre and FileReadPost autocmds.
3373  augroup Test5
3374    au!
3375    au FileReadPre *.gz exe 'silent !gzip -d ' . shellescape(expand("<afile>"))
3376    au FileReadPre *.gz call rename(expand("<afile>:r"), expand("<afile>"))
3377    au FileReadPost *.gz '[,']s/l/L/
3378  augroup END
3379
3380  new
3381  0r Xtestfile.gz		" Read compressed file
3382  call assert_equal([
3383	      \ 'Line 2	Abcdefghijklmnopqrstuvwxyz',
3384	      \ 'Line 3	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3385	      \ 'Line 4	Abcdefghijklmnopqrstuvwxyz',
3386	      \ 'Line 5	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3387	      \ 'Line 6	Abcdefghijklmnopqrstuvwxyz',
3388	      \ 'Line 7	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3389	      \ 'Line 8	Abcdefghijklmnopqrstuvwxyz',
3390	      \ 'Line 9	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3391	      \ 'Line 10 Abcdefghijklmnopqrstuvwxyz'
3392	      \ ], getline(1, 9))
3393  call assert_equal([
3394	      \ 'line 2	Abcdefghijklmnopqrstuvwxyz',
3395	      \ 'line 3	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3396	      \ 'line 4	Abcdefghijklmnopqrstuvwxyz',
3397	      \ 'line 5	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3398	      \ 'line 6	Abcdefghijklmnopqrstuvwxyz',
3399	      \ 'line 7	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3400	      \ 'line 8	Abcdefghijklmnopqrstuvwxyz',
3401	      \ 'line 9	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
3402	      \ 'line 10 Abcdefghijklmnopqrstuvwxyz'
3403	      \ ], readfile('Xtestfile.gz'))
3404
3405  augroup Test5
3406    au!
3407  augroup END
3408
3409  au! FileChangedShell
3410  call delete('Xtestfile.gz')
3411  call delete('test.out')
3412endfunc
3413
3414func Test_throw_in_BufWritePre()
3415  new
3416  call setline(1, ['one', 'two', 'three'])
3417  call assert_false(filereadable('Xthefile'))
3418  augroup throwing
3419    au BufWritePre X* throw 'do not write'
3420  augroup END
3421  try
3422    w Xthefile
3423  catch
3424    let caught = 1
3425  endtry
3426  call assert_equal(1, caught)
3427  call assert_false(filereadable('Xthefile'))
3428
3429  bwipe!
3430  au! throwing
3431endfunc
3432
3433func Test_autocmd_in_try_block()
3434  call mkdir('Xintrydir', 'R')
3435  au BufEnter * let g:fname = expand('%')
3436  try
3437    edit Xintrydir/
3438  endtry
3439  call assert_match('Xintrydir', g:fname)
3440
3441  unlet g:fname
3442  au! BufEnter
3443endfunc
3444
3445func Test_autocmd_SafeState()
3446  CheckRunVimInTerminal
3447
3448  let lines =<< trim END
3449	let g:safe = 0
3450	let g:again = ''
3451	au SafeState * let g:safe += 1
3452	au SafeStateAgain * let g:again ..= 'x'
3453	func CallTimer()
3454	  call timer_start(10, {id -> execute('let g:again ..= "t"')})
3455	endfunc
3456  END
3457  call writefile(lines, 'XSafeState', 'D')
3458  let buf = RunVimInTerminal('-S XSafeState', #{rows: 6})
3459
3460  " Sometimes we loop to handle a K_IGNORE, SafeState may be triggered once or
3461  " more often.
3462  call term_sendkeys(buf, ":echo g:safe\<CR>")
3463  call WaitForAssert({-> assert_match('^\d ', term_getline(buf, 6))}, 1000)
3464
3465  " SafeStateAgain should be invoked at least three times
3466  call term_sendkeys(buf, ":echo g:again\<CR>")
3467  call WaitForAssert({-> assert_match('^xxx', term_getline(buf, 6))}, 1000)
3468
3469  call term_sendkeys(buf, ":let g:again = ''\<CR>:call CallTimer()\<CR>")
3470  call TermWait(buf, 50)
3471  call term_sendkeys(buf, ":\<CR>")
3472  call TermWait(buf, 50)
3473  call term_sendkeys(buf, ":echo g:again\<CR>")
3474  call WaitForAssert({-> assert_match('xtx', term_getline(buf, 6))}, 1000)
3475
3476  call StopVimInTerminal(buf)
3477endfunc
3478
3479func Test_autocmd_CmdWinEnter()
3480  CheckRunVimInTerminal
3481  " There is not cmdwin switch, so
3482  " test for cmdline_hist
3483  " (both are available with small builds)
3484  CheckFeature cmdline_hist
3485  let lines =<< trim END
3486    let b:dummy_var = 'This is a dummy'
3487    autocmd CmdWinEnter * quit
3488    let winnr = winnr('$')
3489  END
3490  let filename = 'XCmdWinEnter'
3491  call writefile(lines, filename)
3492  let buf = RunVimInTerminal('-S '.filename, #{rows: 6})
3493
3494  call term_sendkeys(buf, "q:")
3495  call TermWait(buf)
3496  call term_sendkeys(buf, ":echo b:dummy_var\<cr>")
3497  call WaitForAssert({-> assert_match('^This is a dummy', term_getline(buf, 6))}, 2000)
3498  call term_sendkeys(buf, ":echo &buftype\<cr>")
3499  call WaitForAssert({-> assert_notmatch('^nofile', term_getline(buf, 6))}, 1000)
3500  call term_sendkeys(buf, ":echo winnr\<cr>")
3501  call WaitForAssert({-> assert_match('^1', term_getline(buf, 6))}, 1000)
3502
3503  " clean up
3504  call StopVimInTerminal(buf)
3505  call delete(filename)
3506endfunc
3507
3508func Test_autocmd_was_using_freed_memory()
3509  CheckFeature quickfix
3510
3511  pedit xx
3512  n x
3513  augroup winenter
3514    au WinEnter * if winnr('$') > 2 | quit | endif
3515  augroup END
3516  " Nvim needs large 'winwidth' and 'nowinfixwidth' to crash
3517  set winwidth=99999 nowinfixwidth
3518  split
3519
3520  augroup winenter
3521    au! WinEnter
3522  augroup END
3523
3524  set winwidth& winfixwidth&
3525  bwipe xx
3526  bwipe x
3527  pclose
3528endfunc
3529
3530func Test_BufWrite_lockmarks()
3531  let g:test_is_flaky = 1
3532  edit! Xtest
3533  call setline(1, ['a', 'b', 'c', 'd'])
3534
3535  " :lockmarks preserves the marks
3536  call SetChangeMarks(2, 3)
3537  lockmarks write
3538  call assert_equal([2, 3], [line("'["), line("']")])
3539
3540  " *WritePre autocmds get the correct line range, but lockmarks preserves the
3541  " original values for the user
3542  augroup lockmarks
3543    au!
3544    au BufWritePre,FilterWritePre * call assert_equal([1, 4], [line("'["), line("']")])
3545    au FileWritePre * call assert_equal([3, 4], [line("'["), line("']")])
3546  augroup END
3547
3548  lockmarks write
3549  call assert_equal([2, 3], [line("'["), line("']")])
3550
3551  if executable('cat')
3552    lockmarks %!cat
3553    call assert_equal([2, 3], [line("'["), line("']")])
3554  endif
3555
3556  lockmarks 3,4write Xtest2
3557  call assert_equal([2, 3], [line("'["), line("']")])
3558
3559  au! lockmarks
3560  augroup! lockmarks
3561  call delete('Xtest')
3562  call delete('Xtest2')
3563endfunc
3564
3565func Test_FileType_spell()
3566  if !isdirectory('/tmp')
3567    throw "Skipped: requires /tmp directory"
3568  endif
3569
3570  " this was crashing with an invalid free()
3571  setglobal spellfile=/tmp/en.utf-8.add
3572  augroup crash
3573    autocmd!
3574    autocmd BufNewFile,BufReadPost crashfile setf somefiletype
3575    autocmd BufNewFile,BufReadPost crashfile set ft=anotherfiletype
3576    autocmd FileType anotherfiletype setlocal spell
3577  augroup END
3578  func! NoCrash() abort
3579    edit /tmp/crashfile
3580  endfunc
3581  call NoCrash()
3582
3583  au! crash
3584  setglobal spellfile=
3585endfunc
3586
3587" this was wiping out the current buffer and using freed memory
3588func Test_SpellFileMissing_bwipe()
3589  next 0
3590  au SpellFileMissing 0 bwipe
3591  call assert_fails('set spell spelllang=0', 'E937:')
3592
3593  au! SpellFileMissing
3594  set nospell spelllang=en
3595  bwipe
3596endfunc
3597
3598" Test closing a window or editing another buffer from a FileChangedRO handler
3599" in a readonly buffer
3600func Test_FileChangedRO_winclose()
3601  augroup FileChangedROTest
3602    au!
3603    autocmd FileChangedRO * quit
3604  augroup END
3605  new
3606  set readonly
3607  call assert_fails('normal i', 'E788:')
3608  close
3609  augroup! FileChangedROTest
3610
3611  augroup FileChangedROTest
3612    au!
3613    autocmd FileChangedRO * edit Xrofile
3614  augroup END
3615  new
3616  set readonly
3617  call assert_fails('normal i', 'E788:')
3618  close
3619  augroup! FileChangedROTest
3620endfunc
3621
3622func LogACmd()
3623  call add(g:logged, line('$'))
3624endfunc
3625
3626func Test_TermChanged()
3627  throw 'skipped: Nvim does not support TermChanged event'
3628  CheckNotGui
3629
3630  enew!
3631  tabnew
3632  call setline(1, ['a', 'b', 'c', 'd'])
3633  $
3634  au TermChanged * call LogACmd()
3635  let g:logged = []
3636  let term_save = &term
3637  set term=xterm
3638  call assert_equal([1, 4], g:logged)
3639
3640  au! TermChanged
3641  let &term = term_save
3642  bwipe!
3643endfunc
3644
3645" Test for FileReadCmd autocmd
3646func Test_autocmd_FileReadCmd()
3647  func ReadFileCmd()
3648    call append(line('$'), "v:cmdarg = " .. v:cmdarg)
3649  endfunc
3650  augroup FileReadCmdTest
3651    au!
3652    au FileReadCmd Xtest call ReadFileCmd()
3653  augroup END
3654
3655  new
3656  read ++bin Xtest
3657  read ++nobin Xtest
3658  read ++edit Xtest
3659  read ++bad=keep Xtest
3660  read ++bad=drop Xtest
3661  read ++bad=- Xtest
3662  read ++ff=unix Xtest
3663  read ++ff=dos Xtest
3664  read ++ff=mac Xtest
3665  read ++enc=utf-8 Xtest
3666
3667  call assert_equal(['',
3668        \ 'v:cmdarg =  ++bin',
3669        \ 'v:cmdarg =  ++nobin',
3670        \ 'v:cmdarg =  ++edit',
3671        \ 'v:cmdarg =  ++bad=keep',
3672        \ 'v:cmdarg =  ++bad=drop',
3673        \ 'v:cmdarg =  ++bad=-',
3674        \ 'v:cmdarg =  ++ff=unix',
3675        \ 'v:cmdarg =  ++ff=dos',
3676        \ 'v:cmdarg =  ++ff=mac',
3677        \ 'v:cmdarg =  ++enc=utf-8'], getline(1, '$'))
3678
3679  bwipe!
3680  augroup FileReadCmdTest
3681    au!
3682  augroup END
3683  delfunc ReadFileCmd
3684endfunc
3685
3686" Test for passing invalid arguments to autocmd
3687func Test_autocmd_invalid_args()
3688  " Additional character after * for event
3689  call assert_fails('autocmd *a Xinvfile set ff=unix', 'E215:')
3690  augroup Test
3691  augroup END
3692  " Invalid autocmd event
3693  call assert_fails('autocmd Bufabc Xinvfile set ft=vim', 'E216:')
3694  " Invalid autocmd event in a autocmd group
3695  call assert_fails('autocmd Test Bufabc Xinvfile set ft=vim', 'E216:')
3696  augroup! Test
3697  " Execute all autocmds
3698  call assert_fails('doautocmd * BufEnter', 'E217:')
3699  call assert_fails('augroup! x1a2b3', 'E367:')
3700  call assert_fails('autocmd BufNew <buffer=999> pwd', 'E680:')
3701  call assert_fails('autocmd BufNew \) set ff=unix', 'E55:')
3702endfunc
3703
3704" Test for deep nesting of autocmds
3705func Test_autocmd_deep_nesting()
3706  autocmd BufEnter Xdeepfile doautocmd BufEnter Xdeepfile
3707  call assert_fails('doautocmd BufEnter Xdeepfile', 'E218:')
3708  autocmd! BufEnter Xdeepfile
3709endfunc
3710
3711" Tests for SigUSR1 autocmd event, which is only available on posix systems.
3712func Test_autocmd_sigusr1()
3713  CheckUnix
3714
3715  let g:sigusr1_passed = 0
3716  au Signal SIGUSR1 let g:sigusr1_passed = 1
3717  call system('kill -s usr1 ' . getpid())
3718  call WaitForAssert({-> assert_true(g:sigusr1_passed)})
3719
3720  au! Signal
3721  unlet g:sigusr1_passed
3722endfunc
3723
3724" Test for BufReadPre autocmd deleting the file
3725func Test_BufReadPre_delfile()
3726  augroup TestAuCmd
3727    au!
3728    autocmd BufReadPre XbufreadPre call delete('XbufreadPre')
3729  augroup END
3730  call writefile([], 'XbufreadPre', 'D')
3731  call assert_fails('new XbufreadPre', 'E200:')
3732  call assert_equal('XbufreadPre', @%)
3733  call assert_equal(1, &readonly)
3734
3735  augroup TestAuCmd
3736    au!
3737  augroup END
3738  close!
3739endfunc
3740
3741" Test for BufReadPre autocmd changing the current buffer
3742func Test_BufReadPre_changebuf()
3743  augroup TestAuCmd
3744    au!
3745    autocmd BufReadPre Xchangebuf edit Xsomeotherfile
3746  augroup END
3747  call writefile([], 'Xchangebuf', 'D')
3748  call assert_fails('new Xchangebuf', 'E201:')
3749  call assert_equal('Xsomeotherfile', @%)
3750  call assert_equal(1, &readonly)
3751
3752  augroup TestAuCmd
3753    au!
3754  augroup END
3755  close!
3756endfunc
3757
3758" Test for BufWipeout autocmd changing the current buffer when reading a file
3759" in an empty buffer with 'f' flag in 'cpo'
3760func Test_BufDelete_changebuf()
3761  new
3762  augroup TestAuCmd
3763    au!
3764    autocmd BufWipeout * let bufnr = bufadd('somefile') | exe "b " .. bufnr
3765  augroup END
3766  let save_cpo = &cpo
3767  set cpo+=f
3768  call assert_fails('r Xfile', ['E812:', 'E484:'])
3769  call assert_equal('somefile', @%)
3770  let &cpo = save_cpo
3771  augroup TestAuCmd
3772    au!
3773  augroup END
3774  close!
3775endfunc
3776
3777" Test for the temporary internal window used to execute autocmds
3778func Test_autocmd_window()
3779  %bw!
3780  edit one.txt
3781  tabnew two.txt
3782  vnew three.txt
3783  tabnew four.txt
3784  tabprevious
3785  let g:blist = []
3786  augroup aucmd_win_test1
3787    au!
3788    au BufEnter * call add(g:blist, [expand('<afile>'),
3789          \ win_gettype(bufwinnr(expand('<afile>')))])
3790  augroup END
3791
3792  doautoall BufEnter
3793  call assert_equal([
3794        \ ['one.txt', 'autocmd'],
3795        \ ['two.txt', ''],
3796        \ ['four.txt', 'autocmd'],
3797        \ ['three.txt', ''],
3798        \ ], g:blist)
3799
3800  augroup aucmd_win_test1
3801    au!
3802  augroup END
3803  augroup! aucmd_win_test1
3804  %bw!
3805endfunc
3806
3807" Test for trying to close the temporary window used for executing an autocmd
3808func Test_close_autocmd_window()
3809  %bw!
3810  edit one.txt
3811  tabnew two.txt
3812  augroup aucmd_win_test2
3813    au!
3814    " Nvim makes aucmd_win the last window
3815    " au BufEnter * if expand('<afile>') == 'one.txt' | 1close | endif
3816    au BufEnter * if expand('<afile>') == 'one.txt' | close | endif
3817  augroup END
3818
3819  call assert_fails('doautoall BufEnter', 'E813:')
3820
3821  augroup aucmd_win_test2
3822    au!
3823  augroup END
3824  augroup! aucmd_win_test2
3825  %bw!
3826endfunc
3827
3828" Test for trying to close the tab that has the temporary window for exeucing
3829" an autocmd.
3830func Test_close_autocmd_tab()
3831  edit one.txt
3832  tabnew two.txt
3833   augroup aucmd_win_test
3834    au!
3835    au BufEnter * if expand('<afile>') == 'one.txt' | tabfirst | tabonly | endif
3836  augroup END
3837
3838  call assert_fails('doautoall BufEnter', 'E813:')
3839
3840  tabonly
3841  augroup aucmd_win_test
3842    au!
3843  augroup END
3844  augroup! aucmd_win_test
3845  %bwipe!
3846endfunc
3847
3848func Test_Visual_doautoall_redraw()
3849  call setline(1, ['a', 'b'])
3850  new
3851  wincmd p
3852  call feedkeys("G\<C-V>", 'txn')
3853  autocmd User Explode ++once redraw
3854  doautoall User Explode
3855  %bwipe!
3856endfunc
3857
3858func Test_get_Visual_selection_in_curbuf_autocmd()
3859  call Ntest_override('starting', 1)
3860  new
3861  autocmd OptionSet list let b:text = getregion(getpos('.'), getpos('v'))
3862  call setline(1, 'foo bar baz')
3863
3864  normal! gg0fbvtb
3865  setlocal list
3866  call assert_equal(['bar '], b:text)
3867  exe "normal! \<Esc>"
3868
3869  normal! v0
3870  call setbufvar('%', '&list', v:false)
3871  call assert_equal(['foo bar '], b:text)
3872  exe "normal! \<Esc>"
3873
3874  autocmd! OptionSet list
3875  bwipe!
3876  call Ntest_override('starting', 0)
3877endfunc
3878
3879" This was using freed memory.
3880func Test_BufNew_arglocal()
3881  arglocal
3882  au BufNew * arglocal
3883  call assert_fails('drop xx', 'E1156:')
3884
3885  au! BufNew
3886endfunc
3887
3888func Test_autocmd_closes_window()
3889  au BufNew,BufWinLeave * e %e
3890  file yyy
3891  au BufNew,BufWinLeave * ball
3892  n xxx
3893
3894  %bwipe
3895  au! BufNew
3896  au! BufWinLeave
3897endfunc
3898
3899func Test_autocmd_quit_psearch()
3900  sn aa bb
3901  augroup aucmd_win_test
3902    au!
3903    au BufEnter,BufLeave,BufNew,WinEnter,WinLeave,WinNew * if winnr('$') > 1 | q | endif
3904  augroup END
3905  ps /
3906
3907  augroup aucmd_win_test
3908    au!
3909  augroup END
3910  new
3911  pclose
3912endfunc
3913
3914" Fuzzer found some strange combination that caused a crash.
3915func Test_autocmd_normal_mess()
3916  " Uses `q/` (cmdwin) in autocmd; with non-blocking cmdwin (#40312) the
3917  " expected E1159 path now hits E1513 (winfixbuf) instead.
3918  throw 'Skipped: Nvim supports cmdwin freedom #40312'
3919  " For unknown reason this hangs on MS-Windows
3920  CheckNotMSWindows
3921
3922  augroup aucmd_normal_test
3923    au BufLeave,BufWinLeave,BufHidden,BufUnload,BufDelete,BufWipeout * norm 7q/qc
3924  augroup END
3925  " Nvim has removed :open
3926  " call assert_fails('o4', 'E1159:')
3927  call assert_fails('e4', 'E1159:')
3928  silent! H
3929  call assert_fails('e xx', 'E1159:')
3930  normal G
3931
3932  augroup aucmd_normal_test
3933    au!
3934  augroup END
3935endfunc
3936
3937func Test_autocmd_closing_cmdwin()
3938  throw 'Skipped: Nvim supports cmdwin freedom #40312'
3939  " For unknown reason this hangs on MS-Windows
3940  CheckNotMSWindows
3941
3942  au BufWinLeave * nested q
3943  call assert_fails("norm 7q?\n", 'E855:')
3944
3945  au! BufWinLeave
3946  new
3947  only
3948endfunc
3949
3950func Test_autocmd_vimgrep()
3951  augroup aucmd_vimgrep
3952    au QuickfixCmdPre,BufNew,BufReadCmd * sb
3953    " Nvim makes aucmd_win the last window
3954    " au QuickfixCmdPre,BufNew,BufReadCmd * q9
3955    au QuickfixCmdPre,BufNew,BufReadCmd * exe 'q' .. (winnr('$') - (win_gettype(winnr('$')) == 'autocmd'))
3956  augroup END
3957  call assert_fails('lv ?a? foo', 'E926:')
3958
3959  augroup aucmd_vimgrep
3960    au!
3961  augroup END
3962endfunc
3963
3964func Test_closing_autocmd_window()
3965  let lines =<< trim END
3966      edit Xa.txt
3967      tabnew Xb.txt
3968      autocmd BufEnter Xa.txt unhide 1
3969      doautoall BufEnter
3970  END
3971  call CheckScriptFailure(lines, 'E814:')
3972  au! BufEnter
3973  bwipe Xa.txt
3974  bwipe Xb.txt
3975endfunc
3976
3977func Test_switch_window_in_autocmd_window()
3978  edit Xa.txt
3979  tabnew Xb.txt
3980  autocmd BufEnter Xa.txt wincmd w
3981  doautoall BufEnter
3982  au! BufEnter
3983  bwipe Xa.txt
3984  call assert_false(bufexists('Xa.txt'))
3985  bwipe Xb.txt
3986  call assert_false(bufexists('Xb.txt'))
3987endfunc
3988
3989" Test that using the autocommand window doesn't change current directory.
3990func Test_autocmd_window_cwd()
3991  let saveddir = getcwd()
3992  call mkdir('Xcwd/a/b/c/d', 'pR')
3993
3994  new Xa.txt
3995  tabnew
3996  new Xb.txt
3997
3998  tabprev
3999  cd Xcwd
4000  call assert_match('/Xcwd$', getcwd())
4001  call assert_match('\[global\] .*/Xcwd$', trim(execute('verbose pwd')))
4002
4003  autocmd BufEnter Xb.txt lcd ./a/b/c/d
4004  doautoall BufEnter
4005  au! BufEnter
4006  call assert_match('/Xcwd$', getcwd())
4007  call assert_match('\[global\] .*/Xcwd$', trim(execute('verbose pwd')))
4008
4009  tabnext
4010  cd ./a
4011  tcd ./b
4012  lcd ./c
4013  call assert_match('/Xcwd/a/b/c$', getcwd())
4014  call assert_match('\[window\] .*/Xcwd/a/b/c$', trim(execute('verbose pwd')))
4015
4016  autocmd BufEnter Xa.txt call assert_match('Xcwd/a/b/c$', getcwd())
4017  doautoall BufEnter
4018  au! BufEnter
4019  call assert_match('/Xcwd/a/b/c$', getcwd())
4020  call assert_match('\[window\] .*/Xcwd/a/b/c$', trim(execute('verbose pwd')))
4021  bwipe!
4022  call assert_match('/Xcwd/a/b$', getcwd())
4023  call assert_match('\[tabpage\] .*/Xcwd/a/b$', trim(execute('verbose pwd')))
4024  bwipe!
4025  call assert_match('/Xcwd/a$', getcwd())
4026  call assert_match('\[global\] .*/Xcwd/a$', trim(execute('verbose pwd')))
4027  bwipe!
4028
4029  call chdir(saveddir)
4030endfunc
4031
4032func Test_bufwipeout_changes_window()
4033  " This should not crash, but we don't have any expectations about what
4034  " happens, changing window in BufWipeout has unpredictable results.
4035  tabedit
4036  let g:window_id = win_getid()
4037  topleft new
4038  setlocal bufhidden=wipe
4039  autocmd BufWipeout <buffer> call win_gotoid(g:window_id)
4040  tabprevious
4041  +tabclose
4042
4043  unlet g:window_id
4044  au! BufWipeout
4045  %bwipe!
4046endfunc
4047
4048func Test_autocmd_prevent_buf_wipe()
4049  " Xa must be the first buffer so that win_close_othertab() puts it in
4050  " another window, which causes wiping the buffer to fail.
4051  %bwipe!
4052
4053  file Xa
4054  call setline(1, 'foo')
4055  setlocal bufhidden=wipe
4056  tabnew Xb
4057  setlocal bufhidden=wipe
4058  autocmd BufUnload Xa ++once ++nested tabonly
4059  autocmd BufWinLeave Xb ++once tabnext
4060  tabfirst
4061
4062  edit! Xc
4063  call assert_equal('Xc', bufname('%'))
4064  tabnext
4065  call assert_equal('Xa', bufname('%'))
4066  call assert_equal("\n\"Xa\" --No lines in buffer--", execute('file'))
4067
4068  %bwipe!
4069endfunc
4070
4071func Test_v_event_readonly()
4072  autocmd CompleteChanged * let v:event.width = 0
4073  call assert_fails("normal! i\<C-X>\<C-V>", 'E46:')
4074  au! CompleteChanged
4075
4076  autocmd DirChangedPre * let v:event.directory = ''
4077  call assert_fails('cd .', 'E46:')
4078  au! DirChangedPre
4079
4080  autocmd ModeChanged * let v:event.new_mode = ''
4081  call assert_fails('normal! cc', 'E46:')
4082  au! ModeChanged
4083
4084  autocmd TextYankPost * let v:event.operator = ''
4085  call assert_fails('normal! yy', 'E46:')
4086  au! TextYankPost
4087endfunc
4088
4089" Test for ModeChanged pattern
4090func Test_mode_changes()
4091  let g:index = 0
4092  let g:mode_seq = ['n', 'i', 'n', 'v', 'V', 'i', 'ix', 'i', 'ic', 'i', 'n', 'no', 'noV', 'n', 'V', 'v', 's', 'n']
4093  func! TestMode()
4094    call assert_equal(g:mode_seq[g:index], get(v:event, "old_mode"))
4095    call assert_equal(g:mode_seq[g:index + 1], get(v:event, "new_mode"))
4096    call assert_equal(mode(1), get(v:event, "new_mode"))
4097    let g:index += 1
4098  endfunc
4099
4100  au ModeChanged * :call TestMode()
4101  let g:n_to_any = 0
4102  au ModeChanged n:* let g:n_to_any += 1
4103  call feedkeys("i\<esc>vVca\<CR>\<C-X>\<C-L>\<esc>ggdV\<MouseMove>G", 'tnix')
4104
4105  let g:V_to_v = 0
4106  au ModeChanged V:v let g:V_to_v += 1
4107  call feedkeys("Vv\<C-G>\<esc>", 'tnix')
4108  call assert_equal(len(filter(g:mode_seq[1:], {idx, val -> val == 'n'})), g:n_to_any)
4109  call assert_equal(1, g:V_to_v)
4110  call assert_equal(len(g:mode_seq) - 1, g:index)
4111
4112  let g:n_to_i = 0
4113  au ModeChanged n:i let g:n_to_i += 1
4114  let g:n_to_niI = 0
4115  au ModeChanged i:niI let g:n_to_niI += 1
4116  let g:niI_to_i = 0
4117  au ModeChanged niI:i let g:niI_to_i += 1
4118  let g:nany_to_i = 0
4119  au ModeChanged n*:i let g:nany_to_i += 1
4120  let g:i_to_n = 0
4121  au ModeChanged i:n let g:i_to_n += 1
4122  let g:nori_to_any = 0
4123  au ModeChanged [ni]:* let g:nori_to_any += 1
4124  let g:i_to_any = 0
4125  au ModeChanged i:* let g:i_to_any += 1
4126  let g:index = 0
4127  let g:mode_seq = ['n', 'i', 'niI', 'i', 'n']
4128  call feedkeys("a\<C-O>l\<esc>", 'tnix')
4129  call assert_equal(len(g:mode_seq) - 1, g:index)
4130  call assert_equal(1, g:n_to_i)
4131  call assert_equal(1, g:n_to_niI)
4132  call assert_equal(1, g:niI_to_i)
4133  call assert_equal(2, g:nany_to_i)
4134  call assert_equal(1, g:i_to_n)
4135  call assert_equal(2, g:i_to_any)
4136  call assert_equal(3, g:nori_to_any)
4137
4138  if has('terminal')
4139    let g:mode_seq += ['c', 'n', 't', 'nt', 'c', 'nt', 'n']
4140    call feedkeys(":term\<CR>\<C-W>N:bd!\<CR>", 'tnix')
4141    call assert_equal(len(g:mode_seq) - 1, g:index)
4142    call assert_equal(1, g:n_to_i)
4143    call assert_equal(1, g:n_to_niI)
4144    call assert_equal(1, g:niI_to_i)
4145    call assert_equal(2, g:nany_to_i)
4146    call assert_equal(1, g:i_to_n)
4147    call assert_equal(2, g:i_to_any)
4148    call assert_equal(5, g:nori_to_any)
4149  endif
4150
4151  let g:n_to_c = 0
4152  au ModeChanged n:c let g:n_to_c += 1
4153  let g:c_to_n = 0
4154  au ModeChanged c:n let g:c_to_n += 1
4155  " Nvim: Cannot test non-blocking cmdwin (#40312) using feedkeys() 'x' flag.
4156  "let g:mode_seq += ['c', 'n', 'c', 'n']
4157  "call feedkeys("q:\<C-C>\<Esc>", 'tnix')
4158  "call assert_equal(len(g:mode_seq) - 1, g:index)
4159  "call assert_equal(2, g:n_to_c)
4160  "call assert_equal(2, g:c_to_n)
4161
4162  let g:n_to_v = 0
4163  au ModeChanged n:v let g:n_to_v += 1
4164  let g:v_to_n = 0
4165  au ModeChanged v:n let g:v_to_n += 1
4166  let g:mode_seq += ['v', 'n']
4167  call feedkeys("v\<C-C>", 'tnix')
4168  call assert_equal(len(g:mode_seq) - 1, g:index)
4169  call assert_equal(1, g:n_to_v)
4170  call assert_equal(1, g:v_to_n)
4171
4172  let g:mode_seq += ['c', 'cr', 'c', 'cr', 'n']
4173  call feedkeys(":\<Insert>\<Insert>\<Insert>\<CR>", 'tnix')
4174  call assert_equal(len(g:mode_seq) - 1, g:index)
4175
4176  au! ModeChanged
4177  delfunc TestMode
4178  unlet! g:mode_seq
4179  unlet! g:index
4180  unlet! g:n_to_any
4181  unlet! g:V_to_v
4182  unlet! g:n_to_i
4183  unlet! g:n_to_niI
4184  unlet! g:niI_to_i
4185  unlet! g:nany_to_i
4186  unlet! g:i_to_n
4187  unlet! g:nori_to_any
4188  unlet! g:i_to_any
4189  unlet! g:n_to_c
4190  unlet! g:c_to_n
4191  unlet! g:n_to_v
4192  unlet! g:v_to_n
4193endfunc
4194
4195func Test_recursive_ModeChanged()
4196  au! ModeChanged * norm 0u
4197  sil! norm 
4198  au! ModeChanged
4199endfunc
4200
4201func Test_ModeChanged_starts_visual()
4202  " This was triggering ModeChanged before setting VIsual, causing a crash.
4203  au! ModeChanged * norm 0u
4204  sil! norm 
4205
4206  au! ModeChanged
4207endfunc
4208
4209func Test_noname_autocmd()
4210  augroup test_noname_autocmd_group
4211    autocmd!
4212    autocmd BufEnter * call add(s:li, ["BufEnter", expand("<afile>")])
4213    autocmd BufDelete * call add(s:li, ["BufDelete", expand("<afile>")])
4214    autocmd BufLeave * call add(s:li, ["BufLeave", expand("<afile>")])
4215    autocmd BufUnload * call add(s:li, ["BufUnload", expand("<afile>")])
4216    autocmd BufWipeout * call add(s:li, ["BufWipeout", expand("<afile>")])
4217  augroup END
4218
4219  let s:li = []
4220  edit foo
4221  call assert_equal([['BufUnload', ''], ['BufDelete', ''], ['BufWipeout', ''], ['BufEnter', 'foo']], s:li)
4222
4223  au! test_noname_autocmd_group
4224  augroup! test_noname_autocmd_group
4225endfunc
4226
4227func Test_autocmd_split_dummy()
4228  " Autocommand trying to split a window containing a dummy buffer.
4229  auto BufReadPre * exe "sbuf " .. expand("<abuf>")
4230  " Avoid the "W11" prompt
4231  au FileChangedShell * let v:fcs_choice = 'reload'
4232  func Xautocmd_changelist()
4233    cal writefile(['Xtestfile2:4:4'], 'Xerr')
4234    edit Xerr
4235    lex 'Xtestfile2:4:4'
4236  endfunc
4237  call Xautocmd_changelist()
4238  " Should get E86, but it doesn't always happen (timing?)
4239  silent! call Xautocmd_changelist()
4240
4241  au! BufReadPre
4242  au! FileChangedShell
4243  delfunc Xautocmd_changelist
4244  bwipe! Xerr
4245  call delete('Xerr')
4246endfunc
4247
4248" This was crashing because there was only one window to execute autocommands
4249" in.
4250func Test_autocmd_nested_setbufvar()
4251  CheckFeature python3
4252
4253  set hidden
4254  edit Xaaa
4255  edit Xbbb
4256  call setline(1, 'bar')
4257  enew
4258  au BufWriteCmd Xbbb ++nested call setbufvar('Xaaa', '&ft', 'foo') | bw! Xaaa
4259  au FileType foo call py3eval('vim.current.buffer.options["cindent"]')
4260  wall
4261
4262  au! BufWriteCmd
4263  au! FileType foo
4264  set nohidden
4265  call delete('Xaaa')
4266  call delete('Xbbb')
4267  %bwipe!
4268endfunc
4269
4270func SetupVimTest_shm()
4271  let g:bwe = []
4272  let g:brp = []
4273  set shortmess-=l
4274  messages clear
4275
4276  let dirname='XVimTestSHM'
4277  call mkdir(dirname, 'R')
4278  call writefile(['test'], dirname .. '/1')
4279  call writefile(['test'], dirname .. '/2')
4280  call writefile(['test'], dirname .. '/3')
4281
4282  augroup test
4283      autocmd!
4284      autocmd BufWinEnter * call add(g:bwe, $'BufWinEnter: {expand('<amatch>')}')
4285      autocmd BufReadPost * call add(g:brp,  $'BufReadPost: {expand('<amatch>')}')
4286  augroup END
4287
4288  call setqflist([
4289        \  {'filename': dirname .. '/1', 'lnum': 1, 'col': 1, 'text': 'test', 'vcol': 0},
4290        \  {'filename': dirname .. '/2', 'lnum': 1, 'col': 1, 'text': 'test', 'vcol': 0},
4291        \  {'filename': dirname .. '/3', 'lnum': 1, 'col': 1, 'text': 'test', 'vcol': 0}
4292        \  ])
4293  cdo! substitute/test/TEST
4294
4295  " clean up
4296  noa enew!
4297  set shortmess&vim
4298  augroup test
4299      autocmd!
4300  augroup END
4301  augroup! test
4302endfunc
4303
4304func Test_autocmd_shortmess()
4305  CheckNotMSWindows
4306
4307  call SetupVimTest_shm()
4308  let output = execute(':mess')->split('\n')
4309
4310  let info = copy(output)->filter({idx, val -> val =~# '\d of 3'} )
4311  let bytes = copy(output)->filter({idx, val -> val =~# 'bytes'} )
4312
4313  " We test the following here:
4314  " BufReadPost should have been triggered 3 times, once per file
4315  " BufWinEnter should have been triggered 3 times, once per file
4316  " FileInfoMessage should have been shown 3 times, regardless of shm option
4317  " "(x of 3)" message from :cnext has been shown 3 times
4318
4319  call assert_equal(3, g:brp->len())
4320  call assert_equal(3, g:bwe->len())
4321  call assert_equal(3, info->len())
4322  call assert_equal(3, bytes->len())
4323
4324  delfunc SetupVimTest_shm
4325endfunc
4326
4327func Test_autocmd_invalidates_undo_on_textchanged()
4328  CheckRunVimInTerminal
4329  let script =<< trim END
4330    set hidden
4331    " create quickfix list (at least 2 lines to move line)
4332    vimgrep /u/j %
4333
4334    " enter quickfix window
4335    cwindow
4336
4337    " set modifiable
4338    setlocal modifiable
4339
4340    " set autocmd to clear quickfix list
4341
4342    autocmd! TextChanged <buffer> call setqflist([])
4343    " move line
4344    move+1
4345  END
4346  call writefile(script, 'XTest_autocmd_invalidates_undo_on_textchanged', 'D')
4347  let buf = RunVimInTerminal('XTest_autocmd_invalidates_undo_on_textchanged', {'rows': 20})
4348  call term_sendkeys(buf, ":so %\<cr>")
4349  call term_sendkeys(buf, "G")
4350  call WaitForAssert({-> assert_match('^XTest_autocmd_invalidates_undo_on_textchanged\s*$', term_getline(buf, 20))}, 1000)
4351
4352  call StopVimInTerminal(buf)
4353endfunc
4354
4355func Test_autocmd_creates_new_window_on_bufleave()
4356  e a.txt
4357  e b.txt
4358  setlocal bufhidden=wipe
4359  autocmd BufLeave <buffer> diffsplit c.txt
4360  bn
4361  " curbuf set for the new split opened for c.txt, due to BufLeave
4362  call assert_equal(2, winnr('$'))
4363  call assert_equal('a.txt', bufname('%'))
4364  call assert_equal('b.txt', bufname('#'))
4365  %bw!
4366endfunc
4367
4368" Ensure `expected` was just recently written as a Vim session
4369func s:assert_session_path(expected)
4370  call assert_equal(a:expected, v:this_session)
4371endfunc
4372
4373" Check for `expected` after a session is written to-disk.
4374func s:watch_for_session_path(expected)
4375  execute 'autocmd SessionWritePost * ++once execute "call s:assert_session_path(\"'
4376        \ . a:expected
4377        \ . '\")"'
4378endfunc
4379
4380" Ensure v:this_session gets the full session path, if explicitly stated
4381func Test_explicit_session_absolute_path()
4382  %bwipeout!
4383
4384  let directory = getcwd()
4385
4386  let v:this_session = ""
4387  let name = "some_file.vim"
4388  let expected = fnamemodify(name, ":p")
4389  call s:watch_for_session_path(expected)
4390  execute "mksession! " .. expected
4391
4392  call delete(expected)
4393endfunc
4394
4395" Ensure v:this_session gets the full session path, if explicitly stated
4396func Test_explicit_session_relative_path()
4397  %bwipeout!
4398
4399  let directory = getcwd()
4400
4401  let v:this_session = ""
4402  let name = "some_file.vim"
4403  let expected = fnamemodify(name, ":p")
4404  call s:watch_for_session_path(expected)
4405  execute "mksession! " .. name
4406
4407  call delete(expected)
4408endfunc
4409
4410" Ensure v:this_session gets the full session path, if not specified
4411func Test_implicit_session()
4412  %bwipeout!
4413
4414  let directory = getcwd()
4415
4416  let v:this_session = ""
4417  let expected = fnamemodify("Session.vim", ":p")
4418  call s:watch_for_session_path(expected)
4419  mksession!
4420
4421  call delete(expected)
4422endfunc
4423
4424" Test TextChangedI and TextChanged
4425func Test_Changed_ChangedI()
4426  " Run this test in a terminal because it requires running the main loop.
4427  " Don't use CheckRunVimInTerminal as that will skip the test on Windows.
4428  CheckFeature terminal
4429  CheckNotGui
4430  " Starting a terminal to run Vim is always considered flaky.
4431  let g:test_is_flaky = 1
4432
4433  call writefile(['one', 'two', 'three'], 'XTextChangedI2', 'D')
4434  let before =<< trim END
4435      set ttimeout ttimeoutlen=10
4436      let [g:autocmd_n, g:autocmd_i] = ['','']
4437
4438      func TextChangedAutocmd(char)
4439        let g:autocmd_{tolower(a:char)} = a:char .. b:changedtick
4440        call writefile([$'{g:autocmd_n},{g:autocmd_i}'], 'XTextChangedI3')
4441      endfunc
4442
4443      au TextChanged  <buffer> :call TextChangedAutocmd('N')
4444      au TextChangedI <buffer> :call TextChangedAutocmd('I')
4445
4446      nnoremap <CR> o<Esc>
4447      autocmd SafeState * ++once call writefile([''], 'XTextChangedI3')
4448  END
4449
4450  call writefile(before, 'Xinit', 'D')
4451  let buf = term_start(
4452        \ GetVimCommandCleanTerm() .. '-n -S Xinit XTextChangedI2',
4453        \ {'term_rows': 10})
4454  call assert_equal('running', term_getstatus(buf))
4455  call WaitForAssert({-> assert_true(filereadable('XTextChangedI3'))})
4456  defer delete('XTextChangedI3')
4457  call WaitForAssert({-> assert_equal([''], readfile('XTextChangedI3'))})
4458
4459  " TextChanged should trigger if a mapping enters and leaves Insert mode.
4460  call term_sendkeys(buf, "\<CR>")
4461  call WaitForAssert({-> assert_equal('N4,', readfile('XTextChangedI3')->join("\n"))})
4462
4463  call term_sendkeys(buf, "i")
4464  call WaitForAssert({-> assert_match('^-- INSERT --', term_getline(buf, 10))})
4465  call WaitForAssert({-> assert_equal('N4,', readfile('XTextChangedI3')->join("\n"))})
4466  " TextChangedI should trigger if change is done in Insert mode.
4467  call term_sendkeys(buf, "f")
4468  call WaitForAssert({-> assert_equal('N4,I5', readfile('XTextChangedI3')->join("\n"))})
4469  call term_sendkeys(buf, "o")
4470  call WaitForAssert({-> assert_equal('N4,I6', readfile('XTextChangedI3')->join("\n"))})
4471  call term_sendkeys(buf, "o")
4472  call WaitForAssert({-> assert_equal('N4,I7', readfile('XTextChangedI3')->join("\n"))})
4473  " TextChanged shouldn't trigger when leaving Insert mode and TextChangedI
4474  " has been triggered.
4475  call term_sendkeys(buf, "\<Esc>")
4476  call WaitForAssert({-> assert_notmatch('^-- INSERT --', term_getline(buf, 10))})
4477  call WaitForAssert({-> assert_equal('N4,I7', readfile('XTextChangedI3')->join("\n"))})
4478
4479  " TextChanged should trigger if change is done in Normal mode.
4480  call term_sendkeys(buf, "yyp")
4481  call WaitForAssert({-> assert_equal('N8,I7', readfile('XTextChangedI3')->join("\n"))})
4482
4483  " TextChangedI shouldn't trigger if change isn't done in Insert mode.
4484  call term_sendkeys(buf, "i")
4485  call WaitForAssert({-> assert_match('^-- INSERT --', term_getline(buf, 10))})
4486  call WaitForAssert({-> assert_equal('N8,I7', readfile('XTextChangedI3')->join("\n"))})
4487  call term_sendkeys(buf, "\<Esc>")
4488  call WaitForAssert({-> assert_notmatch('^-- INSERT --', term_getline(buf, 10))})
4489  call WaitForAssert({-> assert_equal('N8,I7', readfile('XTextChangedI3')->join("\n"))})
4490
4491  " TextChangedI should trigger if change is a mix of Normal and Insert modes.
4492  func! s:validate_mixed_textchangedi(buf, keys)
4493    let buf = a:buf
4494    call term_sendkeys(buf, "ifoo")
4495    call WaitForAssert({-> assert_match('^-- INSERT --', term_getline(buf, 10))})
4496    call term_sendkeys(buf, "\<Esc>")
4497    call WaitForAssert({-> assert_notmatch('^-- INSERT --', term_getline(buf, 10))})
4498    call term_sendkeys(buf, ":let [g:autocmd_n, g:autocmd_i] = ['', '']\<CR>")
4499    call writefile([], 'XTextChangedI3')
4500    call term_sendkeys(buf, a:keys)
4501    call WaitForAssert({-> assert_match('^-- INSERT --', term_getline(buf, 10))})
4502    call WaitForAssert({-> assert_match('^,I\d\+', readfile('XTextChangedI3')->join("\n"))})
4503    call term_sendkeys(buf, "\<Esc>")
4504    call WaitForAssert({-> assert_notmatch('^-- INSERT --', term_getline(buf, 10))})
4505    call WaitForAssert({-> assert_match('^,I\d\+', readfile('XTextChangedI3')->join("\n"))})
4506  endfunc
4507
4508  call s:validate_mixed_textchangedi(buf, "o")
4509  call s:validate_mixed_textchangedi(buf, "O")
4510  call s:validate_mixed_textchangedi(buf, "ciw")
4511  call s:validate_mixed_textchangedi(buf, "cc")
4512  call s:validate_mixed_textchangedi(buf, "C")
4513  call s:validate_mixed_textchangedi(buf, "s")
4514  call s:validate_mixed_textchangedi(buf, "S")
4515
4516  " clean up
4517  bwipe!
4518endfunc
4519
4520" Test that filetype detection still works when SwapExists autocommand sets
4521" filetype in another buffer.
4522func Test_SwapExists_set_other_buf_filetype()
4523  let lines =<< trim END
4524    set nocompatible directory=.
4525    filetype on
4526
4527    let g:buf = bufnr()
4528    new
4529
4530    func SwapExists()
4531      let v:swapchoice = 'o'
4532      call setbufvar(g:buf, '&filetype', 'text')
4533    endfunc
4534
4535    func SafeState()
4536      edit <script>
4537      redir! > XftSwapExists.out
4538        set readonly? filetype?
4539      redir END
4540      qall!
4541    endfunc
4542
4543    autocmd SwapExists * ++nested call SwapExists()
4544    autocmd SafeState * ++nested ++once call SafeState()
4545  END
4546  call writefile(lines, 'XftSwapExists.vim', 'D')
4547
4548  new XftSwapExists.vim
4549  if RunVim('', '', ' -S XftSwapExists.vim')
4550    call assert_equal(
4551          \ ['', '  readonly', '  filetype=vim'],
4552          \ readfile('XftSwapExists.out'))
4553    call delete('XftSwapExists.out')
4554  endif
4555
4556  bwipe!
4557endfunc
4558
4559" Test that file is not marked as modified when SwapExists autocommand sets
4560" 'modified' in another buffer.
4561func Test_SwapExists_set_other_buf_modified()
4562  let lines =<< trim END
4563    set nocompatible directory=.
4564
4565    let g:buf = bufnr()
4566    new
4567
4568    func SwapExists()
4569      let v:swapchoice = 'o'
4570      call setbufvar(g:buf, '&modified', 1)
4571    endfunc
4572
4573    func SafeState()
4574      edit <script>
4575      redir! > XmodSwapExists.out
4576        set readonly? modified?
4577      redir END
4578      qall!
4579    endfunc
4580
4581    autocmd SwapExists * ++nested call SwapExists()
4582    autocmd SafeState * ++nested ++once call SafeState()
4583  END
4584  call writefile(lines, 'XmodSwapExists.vim', 'D')
4585
4586  new XmodSwapExists.vim
4587  if RunVim('', '', ' -S XmodSwapExists.vim')
4588    call assert_equal(
4589          \ ['', '  readonly', 'nomodified'],
4590          \ readfile('XmodSwapExists.out'))
4591    call delete('XmodSwapExists.out')
4592  endif
4593
4594  bwipe!
4595endfunc
4596
4597func Test_BufEnter_botline()
4598  set hidden
4599  call writefile(range(10), 'Xxx1', 'D')
4600  call writefile(range(20), 'Xxx2', 'D')
4601  edit Xxx1
4602  edit Xxx2
4603  au BufEnter Xxx1 call assert_true(line('w$') > 1)
4604  edit Xxx1
4605
4606  bwipe! Xxx1
4607  bwipe! Xxx2
4608  au! BufEnter Xxx1
4609  set hidden&vim
4610endfunc
4611
4612" those commands caused null pointer access, see #15464
4613func Test_WinNewPre_crash()
4614  defer CleanUpTestAuGroup()
4615  let _cmdheight=&cmdheight
4616  augroup testing
4617    au!
4618    autocmd WinNewPre * redraw
4619  augroup END
4620  tabnew
4621  tabclose
4622  augroup testing
4623    au!
4624    autocmd WinNewPre * wincmd t
4625  augroup END
4626  tabnew
4627  tabclose
4628  augroup testing
4629    au!
4630    autocmd WinNewPre * wincmd b
4631  augroup END
4632  tabnew
4633  tabclose
4634  augroup testing
4635    au!
4636    autocmd WinNewPre * set cmdheight+=1
4637  augroup END
4638  tabnew
4639  tabclose
4640  let &cmdheight=_cmdheight
4641endfunc
4642
4643
4644" This was using freed memory
4645func Test_autocmd_BufWinLeave_with_vsp()
4646  new
4647  let fname = 'XXXBufWinLeaveUAF.txt'
4648  let dummy = 'XXXDummy.txt'
4649  call writefile([], fname)
4650  call writefile([], dummy)
4651  defer delete(fname)
4652  defer delete(dummy)
4653  exe "e " fname
4654  vsp
4655  augroup testing
4656    exe 'au BufWinLeave' fname 'e' dummy
4657          \ '| call assert_fails(''vsp' fname ''', ''E1546:'')'
4658  augroup END
4659  bw
4660  call CleanUpTestAuGroup()
4661  exe "bw! " .. dummy
4662endfunc
4663
4664func Test_autocmd_BufWinLeave_with_vsp2()
4665  edit Xfoo
4666  split Xbar
4667  split
4668  let s:fired = 0
4669  augroup testing
4670    autocmd!
4671    autocmd BufWinLeave Xfoo ++once ++nested
4672          \ execute 'autocmd WinEnter * ++once let s:fired = 1'
4673          \  .. '| call assert_equal(3, win_findbuf(bufnr(''Xbar''))->len())'
4674          \  .. '| quit'
4675          \| call assert_fails('vsplit Xfoo', 'E1546:')
4676  augroup END
4677  bw Xfoo
4678  call assert_equal(1, s:fired)
4679  " After 9.1.0764, Xbar's b_nwindows would be 0 if autocmds closed the new
4680  " split before E1546, causing it to be unloaded despite being in a window.
4681  call assert_equal(0, bufexists('Xfoo'))
4682  call assert_equal(1, win_findbuf(bufnr('Xbar'))->len())
4683  call assert_equal(1, bufloaded('Xbar'))
4684
4685  call CleanUpTestAuGroup()
4686  unlet! s:fired
4687  %bw!
4688endfunc
4689
4690func Test_OptionSet_cmdheight()
4691  set mouse=a laststatus=2
4692  au OptionSet cmdheight :let &l:ch = v:option_new
4693
4694  resize -1
4695  call assert_equal(2, &l:ch)
4696  resize +1
4697  call assert_equal(1, &l:ch)
4698
4699  call Ntest_setmouse(&lines - 1, 1)
4700  call feedkeys("\<LeftMouse>", 'xt')
4701  call Ntest_setmouse(&lines - 2, 1)
4702  call feedkeys("\<LeftDrag>", 'xt')
4703  call assert_equal(2, &l:ch)
4704  call feedkeys("\<LeftRelease>", 'xt')
4705
4706  tabnew | resize +1
4707  call assert_equal(1, &l:ch)
4708  tabfirst
4709  call assert_equal(2, &l:ch)
4710
4711  tabonly
4712  set cmdheight& mouse& laststatus&
4713endfunc
4714
4715func Test_eventignorewin()
4716  defer CleanUpTestAuGroup()
4717  augroup testing
4718    au WinEnter * :call add(g:evs, ["WinEnter", expand("<afile>")])
4719    au WinLeave * :call add(g:evs, ["WinLeave", expand("<afile>")])
4720    au BufWinEnter * :call add(g:evs, ["BufWinEnter", expand("<afile>")])
4721  augroup END
4722
4723  let g:evs = []
4724  set eventignorewin=WinLeave,WinEnter
4725  split foo
4726  call assert_equal([['BufWinEnter', 'foo']], g:evs)
4727  set eventignorewin=all
4728  edit bar
4729  call assert_equal([['BufWinEnter', 'foo']], g:evs)
4730  set eventignorewin=
4731  wincmd w
4732  call assert_equal([['BufWinEnter', 'foo'], ['WinLeave', 'bar']], g:evs)
4733
4734  only!
4735  %bwipe!
4736  set eventignorewin&
4737  unlet g:evs
4738endfunc
4739
4740func Test_WinScrolled_Resized_eiw()
4741  CheckRunVimInTerminal
4742
4743  let lines =<< trim END
4744    call setline(1, ['foo']->repeat(32))
4745    set eventignorewin=WinScrolled,WinResized
4746    split
4747    let [g:afile,g:resized,g:scrolled] = ['none',0,0]
4748    au WinScrolled * let [g:afile,g:scrolled] = [expand('<afile>'),g:scrolled+1]
4749    au WinResized * let [g:afile,g:resized] = [expand('<afile>'),g:resized+1]
4750  END
4751  call writefile(lines, 'Xtest_winscrolled_eiw', 'D')
4752  let buf = RunVimInTerminal('-S Xtest_winscrolled_eiw', {'rows': 10})
4753
4754  " Both windows are ignoring resize events
4755  call term_sendkeys(buf, "\<C-W>-")
4756  call TermWait(buf)
4757  call term_sendkeys(buf, ":echo g:afile g:resized g:scrolled\<CR>")
4758  call WaitForAssert({-> assert_equal('none 0 0', term_getline(buf, 10))}, 1000)
4759
4760  " And scroll events
4761  call term_sendkeys(buf, "Ggg")
4762  call TermWait(buf)
4763  call term_sendkeys(buf, ":echo g:afile g:resized g:scrolled\<CR>")
4764  call WaitForAssert({-> assert_equal('none 0 0', term_getline(buf, 10))}, 1000)
4765
4766  " Un-ignore events in second window, make first window current and resize
4767  call term_sendkeys(buf, ":set eventignorewin=\<CR>\<C-W>w\<C-W>+")
4768  call TermWait(buf)
4769  call term_sendkeys(buf, ":echo win_getid() g:afile g:resized g:scrolled\<CR>")
4770  call WaitForAssert({-> assert_equal('1000 1001 1 1', term_getline(buf, 10))}, 1000)
4771
4772  call StopVimInTerminal(buf)
4773endfunc
4774
4775" Test that TabClosedPre and TabClosed are triggered when closing a tab.
4776func Test_autocmd_TabClosedPre()
4777  augroup testing
4778    au TabClosedPre * call add(g:tabpagenr_pre, t:testvar)
4779    au TabClosed * call add(g:tabpagenr_post, t:testvar)
4780  augroup END
4781
4782  " Test 'tabclose' triggering
4783  let g:tabpagenr_pre = []
4784  let g:tabpagenr_post = []
4785  let t:testvar = 1
4786  tabnew
4787  let t:testvar = 2
4788  tabnew
4789  let t:testvar = 3
4790  tabnew
4791  let t:testvar = 4
4792  tabnext
4793  tabclose
4794  tabclose
4795  tabclose
4796  call assert_equal([1, 2, 3], g:tabpagenr_pre)
4797  call assert_equal([2, 3, 4], g:tabpagenr_post)
4798
4799  " Test 'tabclose {count}' triggering
4800  let g:tabpagenr_pre = []
4801  let g:tabpagenr_post = []
4802  let t:testvar = 1
4803  tabnew
4804  let t:testvar = 2
4805  tabnew
4806  let t:testvar = 3
4807  tabclose 2
4808  tabclose 2
4809  call assert_equal([2, 3], g:tabpagenr_pre)
4810  call assert_equal([3, 1], g:tabpagenr_post)
4811
4812  " Test 'tabonly' triggering
4813  let g:tabpagenr_pre = []
4814  let g:tabpagenr_post = []
4815  let t:testvar = 1
4816  tabnew
4817  let t:testvar = 2
4818  tabonly
4819  call assert_equal([1], g:tabpagenr_pre)
4820  call assert_equal([2], g:tabpagenr_post)
4821
4822  " Test 'q' and 'close' triggering (closing the last window in a tab)
4823  let g:tabpagenr_pre = []
4824  let g:tabpagenr_post = []
4825  split
4826  let t:testvar = 1
4827  tabnew
4828  let t:testvar = 2
4829  split
4830  vsplit
4831  tabnew
4832  let t:testvar = 3
4833  tabnext
4834  only
4835  quit
4836  quit
4837  close
4838  close
4839  call assert_equal([1, 2], g:tabpagenr_pre)
4840  call assert_equal([2, 3], g:tabpagenr_post)
4841
4842  " Test failing to close tab page
4843  let g:tabpagenr_pre = []
4844  let g:tabpagenr_post = []
4845  let t:testvar = 1
4846  call setline(1, 'foo')
4847  setlocal bufhidden=wipe
4848  tabnew
4849  let t:testvar = 2
4850  tabnew
4851  let t:testvar = 3
4852  call setline(1, 'bar')
4853  setlocal bufhidden=wipe
4854  tabnew
4855  let t:testvar = 4
4856  call setline(1, 'baz')
4857  setlocal bufhidden=wipe
4858  new
4859  call assert_fails('tabclose', 'E445:')
4860  call assert_equal([4], g:tabpagenr_pre)
4861  call assert_equal([], g:tabpagenr_post)
4862  " :tabclose! after failed :tabclose should trigger TabClosedPre again.
4863  tabclose!
4864  call assert_equal([4, 4], g:tabpagenr_pre)
4865  call assert_equal([3], g:tabpagenr_post)
4866  call assert_fails('tabclose', 'E37:')
4867  call assert_equal([4, 4, 3], g:tabpagenr_pre)
4868  call assert_equal([3], g:tabpagenr_post)
4869  " The same for :close! if the tab page only has one window.
4870  close!
4871  call assert_equal([4, 4, 3, 3], g:tabpagenr_pre)
4872  call assert_equal([3, 2], g:tabpagenr_post)
4873  " Also test with :close! after failed :tabonly.
4874  call assert_fails('tabonly', 'E37:')
4875  call assert_equal([4, 4, 3, 3, 1], g:tabpagenr_pre)
4876  call assert_equal([3, 2], g:tabpagenr_post)
4877  tabprevious | close!
4878  call assert_equal([4, 4, 3, 3, 1, 1], g:tabpagenr_pre)
4879  call assert_equal([3, 2, 2], g:tabpagenr_post)
4880  %bwipe!
4881
4882  " Test closing another tab page in BufWinLeave
4883  let g:tabpagenr_pre = []
4884  let g:tabpagenr_post = []
4885  split
4886  let t:testvar = 1
4887  tabnew
4888  let t:testvar = 2
4889  tabnew Xsomebuf
4890  let t:testvar = 3
4891  new
4892  autocmd BufWinLeave Xsomebuf ++once ++nested tabclose 1
4893  tabclose
4894  " TabClosedPre should not be triggered for tab page 3 twice.
4895  call assert_equal([3, 1], g:tabpagenr_pre)
4896  " When tab page 1 was closed, tab page 3 was still the current tab page.
4897  call assert_equal([3, 2], g:tabpagenr_post)
4898  %bwipe!
4899
4900  func ClearAutocmdAndCreateTabs()
4901    au! TabClosedPre
4902    bw!
4903    e Z
4904    tabonly
4905    tabnew A
4906    tabnew B
4907    tabnew C
4908  endfunc
4909
4910  func GetTabs()
4911    redir => tabsout
4912      tabs
4913    redir END
4914    let tabsout = substitute(tabsout, '\n', '', 'g')
4915    let tabsout = substitute(tabsout, 'Tab page ', '', 'g')
4916    let tabsout = substitute(tabsout, '#', '', 'g')  " Nvim: remove '#'
4917    let tabsout = substitute(tabsout, ' ', '', 'g')
4918    return tabsout
4919  endfunc
4920
4921  call CleanUpTestAuGroup()
4922
4923  " Close tab in TabClosedPre autocmd
4924  call ClearAutocmdAndCreateTabs()
4925  au TabClosedPre * tabclose
4926  call assert_fails('tabclose', 'E1312:')
4927  call ClearAutocmdAndCreateTabs()
4928  au TabClosedPre * tabclose
4929  call assert_fails('tabclose 2', 'E1312:')
4930  call ClearAutocmdAndCreateTabs()
4931  au TabClosedPre * tabclose 1
4932  call assert_fails('tabclose', 'E1312:')
4933
4934  " Close other (all) tabs in TabClosedPre autocmd
4935  call ClearAutocmdAndCreateTabs()
4936  au TabClosedPre * tabonly
4937  call assert_fails('tabclose', 'E1312:')
4938  call ClearAutocmdAndCreateTabs()
4939  au TabClosedPre * tabonly
4940  call assert_fails('tabclose 2', 'E1312:')
4941  call ClearAutocmdAndCreateTabs()
4942  au TabClosedPre * tabclose 4
4943  call assert_fails('tabclose 2', 'E1312:')
4944
4945  " Open new tabs in TabClosedPre autocmd
4946  call ClearAutocmdAndCreateTabs()
4947  au TabClosedPre * tabnew D
4948  call assert_fails('tabclose', 'E1312:')
4949  call ClearAutocmdAndCreateTabs()
4950  au TabClosedPre * tabnew D
4951  call assert_fails('tabclose 1', 'E1312:')
4952
4953  " Moving the tab page in TabClosedPre autocmd
4954  call ClearAutocmdAndCreateTabs()
4955  au TabClosedPre * tabmove 0
4956  tabclose
4957  call assert_equal('1>Z2A3B', GetTabs())
4958  call ClearAutocmdAndCreateTabs()
4959  au TabClosedPre * tabmove 0
4960  tabclose 1
4961  call assert_equal('1A2B3>C', GetTabs())
4962  tabonly
4963  call assert_equal('1>C', GetTabs())
4964
4965  " Switching tab page in TabClosedPre autocmd
4966  call ClearAutocmdAndCreateTabs()
4967  au TabClosedPre * tabnext | e Y
4968  tabclose
4969  call assert_equal('1Y2A3>B', GetTabs())
4970  call ClearAutocmdAndCreateTabs()
4971  au TabClosedPre * tabnext | e Y
4972  tabclose 1
4973  call assert_equal('1Y2B3>C', GetTabs())
4974  tabonly
4975  call assert_equal('1>Y', GetTabs())
4976
4977  " Create new windows in TabClosedPre autocmd
4978  call ClearAutocmdAndCreateTabs()
4979  au TabClosedPre * split | e X| vsplit | e Y | split | e Z
4980  call assert_fails('tabclose', 'E242:')
4981  call ClearAutocmdAndCreateTabs()
4982  au TabClosedPre * new X | new Y | new Z
4983  call assert_fails('tabclose 1', 'E242:')
4984
4985  " Test directly closing the tab page with ':tabclose'
4986  au!
4987  tabonly
4988  bw!
4989  e Z
4990  au TabClosedPre * mksession!
4991  tabnew A
4992  sp
4993  tabclose
4994  source Session.vim
4995  call assert_equal('1Z2>AA', GetTabs())
4996
4997  " Test directly closing the tab page with ':tabonly'
4998  " Z is closed before A. Hence A overwrites the session.
4999  au!
5000  tabonly
5001  bw!
5002  e Z
5003  au TabClosedPre * mksession!
5004  tabnew A
5005  tabnew B
5006  tabonly
5007  source Session.vim
5008  call assert_equal('1>A2B', GetTabs())
5009
5010  " Clean up
5011  call delete('Session.vim')
5012  au!
5013  only
5014  tabonly
5015  bw!
5016  delfunc ClearAutocmdAndCreateTabs
5017  delfunc GetTabs
5018endfunc
5019
5020" This used to cause heap-use-after-free.
5021func Run_test_TabClosedPre_wipe_buffer(split_cmds)
5022  file Xa
5023  exe a:split_cmds
5024  autocmd TabClosedPre * ++once tabnext | bwipe! Xa
5025  " Closing window inside TabClosedPre is not allowed.
5026  call assert_fails('tabonly', 'E1312:')
5027
5028  %bwipe!
5029endfunc
5030
5031func Test_TabClosedPre_wipe_buffer()
5032  " Test with Xa only in other tab pages.
5033  call Run_test_TabClosedPre_wipe_buffer('split | tab split | tabnew Xb')
5034  " Test with Xa in both current and other tab pages.
5035  call Run_test_TabClosedPre_wipe_buffer('split | tab split | new Xb')
5036endfunc
5037
5038func Test_TabClosedPre_mouse()
5039  func MyTabline()
5040    let cnt = tabpagenr('$')
5041    return range(1, cnt)->mapnew({_, n -> $'%{n}X|Close{n}|%X'})->join('')
5042  endfunc
5043
5044  let save_mouse = &mouse
5045  if has('gui')
5046    set guioptions-=e
5047  endif
5048  set mouse=a tabline=%!MyTabline()
5049
5050  func OpenTwoTabPages()
5051    %bwipe!
5052    file Xa | split | split
5053    let g:Xa_bufnr = bufnr()
5054    tabnew Xb | split
5055    let g:Xb_bufnr = bufnr()
5056    redraw!
5057    call assert_match('^|Close1||Close2| *$', Screenline(1))
5058    call assert_equal(2, tabpagenr('$'))
5059  endfunc
5060
5061  autocmd! TabClosedPre
5062  call OpenTwoTabPages()
5063  let g:autocmd_bufnrs = []
5064  autocmd TabClosedPre * let g:autocmd_bufnrs += [tabpagebuflist()]
5065  call Ntest_setmouse(1, 2)
5066  call feedkeys("\<LeftMouse>\<LeftRelease>", 'tx')
5067  call assert_equal(1, tabpagenr('$'))
5068  call assert_equal([[g:Xa_bufnr]->repeat(3)], g:autocmd_bufnrs)
5069  call assert_equal([g:Xb_bufnr]->repeat(2), tabpagebuflist())
5070
5071  call OpenTwoTabPages()
5072  let g:autocmd_bufnrs = []
5073  autocmd TabClosedPre * call feedkeys("\<LeftRelease>\<LeftMouse>", 'tx')
5074  call Ntest_setmouse(1, 2)
5075  " Closing tab page inside TabClosedPre is not allowed.
5076  call assert_fails('call feedkeys("\<LeftMouse>", "tx")', 'E1312:')
5077  call feedkeys("\<LeftRelease>", 'tx')
5078
5079  autocmd! TabClosedPre
5080  call OpenTwoTabPages()
5081  let g:autocmd_bufnrs = []
5082  autocmd TabClosedPre * let g:autocmd_bufnrs += [tabpagebuflist()]
5083  call Ntest_setmouse(1, 10)
5084  call feedkeys("\<LeftMouse>\<LeftRelease>", 'tx')
5085  call assert_equal(1, tabpagenr('$'))
5086  call assert_equal([[g:Xb_bufnr]->repeat(2)], g:autocmd_bufnrs)
5087  call assert_equal([g:Xa_bufnr]->repeat(3), tabpagebuflist())
5088
5089  call OpenTwoTabPages()
5090  let g:autocmd_bufnrs = []
5091  autocmd TabClosedPre * call feedkeys("\<LeftRelease>\<LeftMouse>", 'tx')
5092  call Ntest_setmouse(1, 10)
5093  " Closing tab page inside TabClosedPre is not allowed.
5094  call assert_fails('call feedkeys("\<LeftMouse>", "tx")', 'E1312:')
5095  call feedkeys("\<LeftRelease>", 'tx')
5096
5097  autocmd! TabClosedPre
5098  %bwipe!
5099  unlet g:Xa_bufnr g:Xb_bufnr g:autocmd_bufnrs
5100  let &mouse = save_mouse
5101  set tabline& guioptions&
5102  delfunc MyTabline
5103  delfunc OpenTwoTabPages
5104endfunc
5105
5106func Test_eventignorewin_non_current()
5107  defer CleanUpTestAuGroup()
5108  let s:triggered = ''
5109  augroup testing
5110    " Will set <abuf> to the buffer of the closing window.
5111    autocmd WinClosed * let s:triggered = 'WinClosed'
5112  augroup END
5113  let initial_win = win_getid()
5114
5115  new
5116  let new_buf = bufnr()
5117  " Only set for one of the windows into the new buffer.
5118  setlocal eventignorewin=all
5119  split
5120  setlocal eventignorewin=
5121  let close_winnr = winnr()
5122
5123  " Return to the window where the buffer is non-current. WinClosed should
5124  " trigger as not all windows into new_buf have 'eventignorewin' set for it.
5125  call win_gotoid(initial_win)
5126  call assert_notequal(new_buf, bufnr())
5127  execute close_winnr 'close'
5128  call assert_equal('WinClosed', s:triggered)
5129
5130  wincmd w
5131  call assert_equal(new_buf, bufnr())
5132  tab split
5133  setlocal eventignorewin=
5134  let close_winnr = win_getid()
5135
5136  " Ensure that new_buf's window in the other tabpage with 'eventignorewin'
5137  " unset allows WinClosed to run when new_buf is non-current.
5138  call win_gotoid(initial_win)
5139  call assert_notequal(new_buf, bufnr())
5140  let s:triggered = ''
5141  only!
5142  call assert_equal('WinClosed', s:triggered)
5143  call assert_equal(1, win_findbuf(new_buf)->len())
5144
5145  " Create an only window to new_buf with 'eventignorewin' set.
5146  tabonly!
5147  execute new_buf 'sbuffer'
5148  setlocal eventignorewin=all
5149  wincmd p
5150  call assert_equal(1, win_findbuf(new_buf)->len())
5151  call assert_notequal(new_buf, bufnr())
5152
5153  " Closing a window unrelated to new_buf should not block WinClosed.
5154  split
5155  let s:triggered = ''
5156  close
5157  call assert_equal('WinClosed', s:triggered)
5158  call assert_equal(1, win_findbuf(new_buf)->len())
5159
5160  " Check WinClosed is blocked when we close the only window to new_buf (that
5161  " has 'eventignorewin' set) while new_buf is non-current.
5162  call assert_notequal(new_buf, bufnr())
5163  let s:triggered = ''
5164  only!
5165  call assert_equal('', s:triggered)
5166  call assert_equal(0, win_findbuf(new_buf)->len())
5167
5168  augroup testing
5169    autocmd!
5170    autocmd BufNew * ++once let s:triggered = 'BufNew'
5171  augroup END
5172
5173  " Buffer not shown in a window, 'eventignorewin' should not block (and
5174  " can't even be set for it anyway in this case).
5175  badd foo
5176  call assert_equal('BufNew', s:triggered)
5177
5178  unlet! s:triggered
5179  %bw!
5180endfunc
5181
5182func Test_reuse_curbuf_leak()
5183  new bar
5184  let s:bar_buf = bufnr()
5185  augroup testing
5186    autocmd!
5187    autocmd BufDelete * ++once let s:triggered = 1 | execute s:bar_buf 'buffer'
5188  augroup END
5189  enew
5190  let empty_buf = bufnr()
5191
5192  " Old curbuf should be reused, firing BufDelete. As BufDelete changes curbuf,
5193  " reusing the buffer would fail and leak the ffname.
5194  edit foo
5195  call assert_equal(1, s:triggered)
5196  " Wasn't reused because the buffer changed, but buffer "foo" is still created.
5197  call assert_equal(1, bufexists(empty_buf))
5198  call assert_notequal(empty_buf, bufnr())
5199  call assert_equal('foo', bufname())
5200  call assert_equal('bar', bufname(s:bar_buf))
5201
5202  unlet! s:bar_buf s:triggered
5203  call CleanUpTestAuGroup()
5204  %bw!
5205endfunc
5206
5207func Test_reuse_curbuf_switch()
5208  edit asdf
5209  let s:asdf_win = win_getid()
5210  new
5211  let other_buf = bufnr()
5212  let other_win = win_getid()
5213  augroup testing
5214    autocmd!
5215    autocmd BufUnload * ++once let s:triggered = 1
5216          \| call assert_fails('split', 'E1159:')
5217          \| call win_gotoid(s:asdf_win)
5218  augroup END
5219
5220  " Check BufUnload changing curbuf does not cause buflist_new to create a new
5221  " buffer while leaving "other_buf" unloaded in a window.
5222  enew
5223  call assert_equal(1, s:triggered)
5224  call assert_equal(other_buf, bufnr())
5225  call assert_equal(other_win, win_getid())
5226  call assert_equal(1, win_findbuf(other_buf)->len())
5227  call assert_equal(1, bufloaded(other_buf))
5228
5229  unlet! s:asdf_win s:triggered
5230  call CleanUpTestAuGroup()
5231  %bw!
5232endfunc
5233
5234func Test_eventignore_subtract()
5235  set eventignore=all,-WinEnter
5236  augroup testing
5237    autocmd!
5238    autocmd WinEnter * ++once let s:triggered = 1
5239  augroup END
5240
5241  new
5242  call assert_equal(1, s:triggered)
5243
5244  set eventignore&
5245  unlet! s:triggered
5246  call CleanUpTestAuGroup()
5247  %bw!
5248endfunc
5249
5250func Test_win_tabclose_autocmd()
5251
5252  defer CleanUpTestAuGroup()
5253  new
5254  augroup testing
5255    au WinClosed * wincmd p
5256  augroup END
5257
5258  tabnew
5259  new
5260  new
5261
5262  call assert_equal(2, tabpagenr('$'))
5263  try
5264    tabclose
5265  catch
5266    " should not happen
5267    call assert_report("closing tabpage failed")
5268  endtry
5269  call assert_equal(1, tabpagenr('$'))
5270  bw!
5271endfunc
5272
5273func Test_buffer_b_nwindows()
5274  " In these cases, b_nwindows of the Xbars was 1 despite being in no windows.
5275  " Would cause weird failures in other tests, as they would be un-deletable.
5276  edit Xfoo1
5277  augroup testing
5278    autocmd!
5279    autocmd BufUnload * ++once edit Xbar1
5280  augroup END
5281  bdelete
5282  call assert_equal([], win_findbuf(bufnr('Xfoo1')))
5283  call assert_equal([], win_findbuf(bufnr('Xbar1')))
5284  call assert_equal(1, bufexists('Xfoo1'))
5285  call assert_equal(1, bufexists('Xbar1'))
5286  %bw!
5287  call assert_equal(0, bufexists('Xfoo1'))
5288  call assert_equal(0, bufexists('Xbar1'))
5289
5290  split Xbar2
5291  enew
5292  augroup testing
5293    autocmd!
5294    autocmd BufWinLeave * ++once buffer Xbar2
5295  augroup END
5296  quit
5297  call assert_equal([], win_findbuf(bufnr('Xbar2')))
5298  call assert_equal(1, bufexists('Xbar2'))
5299  %bw!
5300  call assert_equal(0, bufexists('Xbar2'))
5301
5302  edit Xbar3
5303  enew
5304  setlocal bufhidden=hide
5305  let s:win = win_getid()
5306  tabnew
5307  augroup testing
5308    autocmd!
5309    autocmd BufHidden * ++once call win_execute(s:win, 'buffer Xbar3')
5310  augroup END
5311  tabonly
5312  call assert_equal([], win_findbuf(bufnr('Xbar3')))
5313  call assert_equal(1, bufexists('Xbar3'))
5314  %bw!
5315  call assert_equal(0, bufexists('Xbar3'))
5316  unlet! s:win
5317
5318  edit Xbar4
5319  split Xfoo4
5320  augroup testing
5321    autocmd!
5322    autocmd BufWinLeave * ++once call assert_equal('Xfoo4', bufname())
5323          \| edit Xbar4
5324  augroup END
5325  edit Xbar4
5326  call assert_equal(0, bufloaded('Xfoo4'))
5327  call assert_equal(1, bufexists('Xfoo4'))
5328  " After 8.2.2354, Xfoo4 wrongly had b_nwindows of 1, so couldn't be wiped.
5329  call assert_equal([], win_findbuf('Xfoo4'))
5330  %bw!
5331  call assert_equal(0, bufexists('Xfoo4'))
5332
5333  call CleanUpTestAuGroup()
5334  %bw!
5335endfunc
5336
5337" Test that an autocmd triggered by v:swapchoice == 'q' that switches buffers
5338" doesn't cause b_nwindows to be wrong.
5339func Test_SwapExists_b_nwindows()
5340  let lines =<< trim END
5341    set nocompatible directory=.
5342
5343    let g:buf = bufnr()
5344    new
5345
5346    func SwapExists()
5347      let v:swapchoice = 'q'
5348      autocmd BufWinLeave * ++nested ++once buffer Xfoo
5349    endfunc
5350
5351    func SafeState()
5352      edit Xfoo
5353      edit <script>
5354      %bw!
5355      call writefile([bufexists('Xfoo')], 'XnwindowsSwapExists.out')
5356      qall!
5357    endfunc
5358
5359    autocmd SwapExists * ++nested ++once call SwapExists()
5360    autocmd SafeState * ++nested ++once call SafeState()
5361  END
5362  call writefile(lines, 'XnwindowsSwapExists.vim', 'D')
5363
5364  new XnwindowsSwapExists.vim
5365  if RunVim('', '', ' -S XnwindowsSwapExists.vim')
5366    call assert_equal(['0'], readfile('XnwindowsSwapExists.out'))
5367    call delete('XnwindowsSwapExists.out')
5368  endif
5369
5370  %bw!
5371endfunc
5372
5373func Test_TextPutX()
5374  enew!
5375
5376  let g:pre_event = []
5377  let g:post_event = []
5378  au TextPutPre * let g:pre_event = copy(v:event)
5379  au TextPutPost * let g:post_event = copy(v:event)
5380
5381  call setreg('a', ['foo'], 'v')
5382  norm "ap
5383  call assert_equal(
5384        \ #{regcontents: ['foo'], regname: 'a', operator: 'p',
5385        \ visual: v:false, regtype: 'v'},
5386        \ g:pre_event)
5387  call assert_equal(g:pre_event, g:post_event)
5388
5389  call setreg('', ['hello'], 'V')
5390  norm P
5391  call assert_equal(
5392        \ #{regcontents: ['hello'], regname: '',  operator: 'P',
5393        \ visual: v:false, regtype: 'V'},
5394        \ g:pre_event)
5395  call assert_equal(g:pre_event, g:post_event)
5396
5397  call setreg('', ['maybe', 'true'], 'V')
5398  norm Vp
5399  call assert_equal(
5400        \ #{regcontents: ['maybe', 'true'], regname: '',  operator: 'P',
5401        \ regtype: 'V', visual: v:true},
5402        \ g:pre_event)
5403  call assert_equal(g:pre_event, g:post_event)
5404  call assert_equal({}, v:event)
5405
5406  call feedkeys("iinserted text\<CR>below\<Esc>", 'x')
5407  norm ".p
5408  call assert_equal(
5409        \ #{regcontents: ["inserted text\nbelow"], regname: '.',
5410        \ operator: 'p', regtype: 'v', visual: v:false},
5411        \ g:pre_event)
5412  call assert_equal(g:pre_event, g:post_event)
5413
5414  call feedkeys("\"=201\<CR>p", 'x')
5415  call assert_equal(
5416        \ #{regcontents: ["201"], regname: '=',
5417        \ operator: 'p', regtype: 'v', visual: v:false},
5418        \ g:pre_event)
5419  call assert_equal(g:pre_event, g:post_event)
5420
5421  vsplit some.txt
5422  wincmd l
5423  norm "#p
5424  call assert_equal(
5425        \ #{regcontents: ["some.txt"], regname: '#',
5426        \ operator: 'p', regtype: 'v', visual: v:false},
5427        \ g:pre_event)
5428  call assert_equal(g:pre_event, g:post_event)
5429  wincmd h
5430  bw!
5431
5432  if has('clipboard_working')
5433    let @+ = 'clipboard'
5434
5435    norm "+p
5436    call assert_equal(
5437          \ #{regcontents: ["clipboard"], regname: '+',
5438          \ operator: 'p', regtype: 'v', visual: v:false},
5439          \ g:pre_event)
5440    call assert_equal(g:pre_event, g:post_event)
5441  endif
5442
5443  %delete " Clear buffer
5444
5445  au! TextPutPre
5446  au! TextPutPost
5447  let g:pre_event = []
5448  let g:post_event = []
5449
5450  au TextPutPre * call setreg(v:event['regname'],
5451        \ getreg('', 0, v:true) + ['!']) " Unnamed register should be same as regname
5452
5453  call setreg('', ['hello', 'world'])
5454  norm p
5455  call assert_equal(['', 'hello', 'world', '!'], getline(1, '$'))
5456
5457  au! TextPutPre
5458
5459  " Test that special registers cannot be modified
5460  %delete
5461  au TextPutPre * call setreg('=', '"modified"') | let g:pre_event = copy(v:event)
5462
5463  " Set up the expression register to evaluate to a known value.
5464  call feedkeys("\"=\"original\"\<CR>p", 'x')
5465
5466  " The original value is what got put, not the modified one.
5467  call assert_equal(['original'], getline(1, '$'))
5468
5469  " v:event still reports the original value.
5470  call assert_equal(['original'], g:pre_event['regcontents'])
5471
5472  au! TextPutPre
5473  let g:pre_event = []
5474
5475  for round in range(2)
5476    " Recursive ". register calls have the same contents for post and pre.
5477    au TextPutPre * put . | let g:pre_event = copy(v:event)
5478    au TextPutPost * let g:post_event = copy(v:event)
5479
5480    call feedkeys("iinserted\<Esc>", 'x')
5481    norm! ".p
5482
5483    call assert_equal(
5484          \ #{regcontents: ["inserted"], regname: '.',
5485          \ operator: 'p', regtype: 'v', visual: v:false},
5486          \ g:pre_event)
5487    call assert_equal(g:pre_event, g:post_event)
5488
5489    au! TextPutPre
5490    au! TextPutPost
5491
5492    " Pasting ". register without TextPutPre/TextPutPost autocommands should
5493    " not interfere with these autocommands in the next round.
5494    norm! ".p
5495  endfor
5496
5497  unlet g:post_event
5498  unlet g:pre_event
5499  bwipe!
5500endfunc
5501
5502" Test that attempting to put text in normal mode terminal buffer does not
5503" result in a crash. This only happens when terminal is only window in tabpage
5504" it seems.
5505func Test_TextPutPost_term_norm()
5506  CheckFeature terminal
5507
5508  tabnew
5509  term ++curwin
5510
5511  let bnr = bufnr('$')
5512  call WaitForAssert({-> assert_equal('running', term_getstatus(bnr))})
5513
5514  call feedkeys("\<C-\>\<C-N>", 'xt')
5515  call WaitForAssert({-> assert_equal('running,normal', term_getstatus(bnr))})
5516
5517  let err = 0
5518
5519  try
5520    call feedkeys("p", 'xt')
5521  catch /^Vim\%((\S\+)\)\=:E21:/
5522    let err = 1
5523  endtry
5524
5525  call assert_true(err)
5526
5527  unlet err
5528  bwipe!
5529endfunc
5530
5531" vim: shiftwidth=2 sts=2 expandtab