robin/laufey

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

Justin M. KeyesMerge #41065 from justinmk/optionfunc4836ecad1f

master
203.2 KiB7179 linesraw
1" Test for the quickfix feature.
2
3source check.vim
4source vim9.vim
5CheckFeature quickfix
6
7source screendump.vim
8
9set encoding=utf-8
10
11func s:setup_commands(cchar)
12  if a:cchar == 'c'
13    command! -nargs=* -bang Xlist <mods>clist<bang> <args>
14    command! -nargs=* Xgetexpr <mods>cgetexpr <args>
15    command! -nargs=* Xaddexpr <mods>caddexpr <args>
16    command! -nargs=* -count Xolder <mods><count>colder <args>
17    command! -nargs=* Xnewer <mods>cnewer <args>
18    command! -nargs=* Xopen <mods> copen <args>
19    command! -nargs=* Xwindow <mods>cwindow <args>
20    command! -nargs=* Xbottom <mods>cbottom <args>
21    command! -nargs=* Xclose <mods>cclose <args>
22    command! -nargs=* -bang Xfile <mods>cfile<bang> <args>
23    command! -nargs=* Xgetfile <mods>cgetfile <args>
24    command! -nargs=* Xaddfile <mods>caddfile <args>
25    command! -nargs=* -bang Xbuffer <mods>cbuffer<bang> <args>
26    command! -nargs=* Xgetbuffer <mods>cgetbuffer <args>
27    command! -nargs=* Xaddbuffer <mods>caddbuffer <args>
28    command! -nargs=* Xrewind <mods>crewind <args>
29    command! -count -nargs=* -bang Xnext <mods><count>cnext<bang> <args>
30    command! -count -nargs=* -bang Xprev <mods><count>cprev<bang> <args>
31    command! -nargs=* -bang Xfirst <mods>cfirst<bang> <args>
32    command! -nargs=* -bang Xlast <mods>clast<bang> <args>
33    command! -count -nargs=* -bang Xnfile <mods><count>cnfile<bang> <args>
34    command! -nargs=* -bang Xpfile <mods>cpfile<bang> <args>
35    command! -nargs=* Xexpr <mods>cexpr <args>
36    command! -count=999 -nargs=* Xvimgrep <mods> <count>vimgrep <args>
37    command! -nargs=* Xvimgrepadd <mods> vimgrepadd <args>
38    command! -nargs=* Xgrep <mods> grep <args>
39    command! -nargs=* Xgrepadd <mods> grepadd <args>
40    command! -nargs=* Xhelpgrep helpgrep <args>
41    command! -nargs=0 -count Xcc <count>cc
42    command! -count=1 -nargs=0 Xbelow <mods><count>cbelow
43    command! -count=1 -nargs=0 Xabove <mods><count>cabove
44    command! -count=1 -nargs=0 Xbefore <mods><count>cbefore
45    command! -count=1 -nargs=0 Xafter <mods><count>cafter
46    command! -nargs=1 Xsethist <mods>set chistory=<args>
47    command! -nargs=0 Xsethistdefault <mods>set chistory&
48    let g:Xgetlist = function('getqflist')
49    let g:Xsetlist = function('setqflist')
50    call setqflist([], 'f')
51  else
52    command! -nargs=* -bang Xlist <mods>llist<bang> <args>
53    command! -nargs=* Xgetexpr <mods>lgetexpr <args>
54    command! -nargs=* Xaddexpr <mods>laddexpr <args>
55    command! -nargs=* -count Xolder <mods><count>lolder <args>
56    command! -nargs=* Xnewer <mods>lnewer <args>
57    command! -nargs=* Xopen <mods> lopen <args>
58    command! -nargs=* Xwindow <mods>lwindow <args>
59    command! -nargs=* Xbottom <mods>lbottom <args>
60    command! -nargs=* Xclose <mods>lclose <args>
61    command! -nargs=* -bang Xfile <mods>lfile<bang> <args>
62    command! -nargs=* Xgetfile <mods>lgetfile <args>
63    command! -nargs=* Xaddfile <mods>laddfile <args>
64    command! -nargs=* -bang Xbuffer <mods>lbuffer<bang> <args>
65    command! -nargs=* Xgetbuffer <mods>lgetbuffer <args>
66    command! -nargs=* Xaddbuffer <mods>laddbuffer <args>
67    command! -nargs=* Xrewind <mods>lrewind <args>
68    command! -count -nargs=* -bang Xnext <mods><count>lnext<bang> <args>
69    command! -count -nargs=* -bang Xprev <mods><count>lprev<bang> <args>
70    command! -nargs=* -bang Xfirst <mods>lfirst<bang> <args>
71    command! -nargs=* -bang Xlast <mods>llast<bang> <args>
72    command! -count -nargs=* -bang Xnfile <mods><count>lnfile<bang> <args>
73    command! -nargs=* -bang Xpfile <mods>lpfile<bang> <args>
74    command! -nargs=* Xexpr <mods>lexpr <args>
75    command! -count=999 -nargs=* Xvimgrep <mods> <count>lvimgrep <args>
76    command! -nargs=* Xvimgrepadd <mods> lvimgrepadd <args>
77    command! -nargs=* Xgrep <mods> lgrep <args>
78    command! -nargs=* Xgrepadd <mods> lgrepadd <args>
79    command! -nargs=* Xhelpgrep lhelpgrep <args>
80    command! -nargs=0 -count Xcc <count>ll
81    command! -count=1 -nargs=0 Xbelow <mods><count>lbelow
82    command! -count=1 -nargs=0 Xabove <mods><count>labove
83    command! -count=1 -nargs=0 Xbefore <mods><count>lbefore
84    command! -count=1 -nargs=0 Xafter <mods><count>lafter
85    command! -nargs=1 Xsethist <mods>set lhistory=<args>
86    command! -nargs=1 Xsetlocalhist <mods>setlocal lhistory=<args>
87    command! -nargs=0 Xsethistdefault <mods>set lhistory&
88    let g:Xgetlist = function('getloclist', [0])
89    let g:Xsetlist = function('setloclist', [0])
90    call setloclist(0, [], 'f')
91  endif
92endfunc
93
94" This must be run before any error lists are created.
95func Test_AA_cc_no_errors()
96  call assert_fails('cc', 'E42:')
97  call assert_fails('ll', 'E42:')
98endfunc
99
100" Tests for the :clist and :llist commands
101func XlistTests(cchar)
102  call s:setup_commands(a:cchar)
103
104  if a:cchar == 'l'
105      call assert_fails('llist', 'E776:')
106  endif
107  " With an empty list, command should return error
108  Xgetexpr []
109  silent! Xlist
110  call assert_true(v:errmsg ==# 'E42: No Errors')
111
112  " Populate the list and then try
113  let lines =<< trim END
114    non-error 1
115    Xtestfile1:1:3:Line1
116    non-error 2
117    Xtestfile2:2:2:Line2
118    non-error| 3
119    Xtestfile3:3:1:Line3
120  END
121  Xgetexpr lines
122
123  " List only valid entries
124  let l = split(execute('Xlist', ''), "\n")
125  call assert_equal([' 2 Xtestfile1:1 col 3: Line1',
126		   \ ' 4 Xtestfile2:2 col 2: Line2',
127		   \ ' 6 Xtestfile3:3 col 1: Line3'], l)
128
129  " List all the entries
130  let l = split(execute('Xlist!', ''), "\n")
131  call assert_equal([' 1: non-error 1', ' 2 Xtestfile1:1 col 3: Line1',
132		   \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2',
133		   \ ' 5: non-error| 3', ' 6 Xtestfile3:3 col 1: Line3'], l)
134
135  " List a range of errors
136  let l = split(execute('Xlist 3,6', ''), "\n")
137  call assert_equal([' 4 Xtestfile2:2 col 2: Line2',
138		   \ ' 6 Xtestfile3:3 col 1: Line3'], l)
139
140  let l = split(execute('Xlist! 3,4', ''), "\n")
141  call assert_equal([' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2'], l)
142
143  let l = split(execute('Xlist -6,-4', ''), "\n")
144  call assert_equal([' 2 Xtestfile1:1 col 3: Line1'], l)
145
146  let l = split(execute('Xlist! -5,-3', ''), "\n")
147  call assert_equal([' 2 Xtestfile1:1 col 3: Line1',
148		   \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2'], l)
149
150  " Test for '+'
151  let l = split(execute('Xlist! +2', ''), "\n")
152  call assert_equal([' 2 Xtestfile1:1 col 3: Line1',
153		   \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2'], l)
154
155  " Ranged entries
156  call g:Xsetlist([{'lnum':10,'text':'Line1'},
157	      \ {'lnum':20,'col':10,'text':'Line2'},
158	      \ {'lnum':30,'col':15,'end_col':20,'text':'Line3'},
159	      \ {'lnum':40,'end_lnum':45,'text':'Line4'},
160	      \ {'lnum':50,'end_lnum':55,'col':15,'text':'Line5'},
161	      \ {'lnum':60,'end_lnum':65,'col':25,'end_col':35,'text':'Line6'}])
162  let l = split(execute('Xlist', ""), "\n")
163  call assert_equal([' 1:10: Line1',
164	      \ ' 2:20 col 10: Line2',
165	      \ ' 3:30 col 15-20: Line3',
166	      \ ' 4:40-45: Line4',
167	      \ ' 5:50-55 col 15: Line5',
168	      \ ' 6:60-65 col 25-35: Line6'], l)
169
170  " Different types of errors
171  call g:Xsetlist([{'lnum':10,'col':5,'type':'W', 'text':'Warning','nr':11},
172	      \ {'lnum':20,'col':10,'type':'e','text':'Error','nr':22},
173	      \ {'lnum':30,'col':15,'type':'i','text':'Info','nr':33},
174	      \ {'lnum':40,'col':20,'type':'x', 'text':'Other','nr':44},
175	      \ {'lnum':50,'col':25,'type':"\<C-A>",'text':'one','nr':55},
176	      \ {'lnum':0,'type':'e','text':'Check type field is output even when lnum==0. ("error" was not output by v9.0.0736.)','nr':66}])
177  let l = split(execute('Xlist', ""), "\n")
178  call assert_equal([' 1:10 col 5 warning  11: Warning',
179	      \ ' 2:20 col 10 error  22: Error',
180	      \ ' 3:30 col 15 info  33: Info',
181	      \ ' 4:40 col 20 x  44: Other',
182	      \ ' 5:50 col 25  55: one',
183              \ ' 6 error  66: Check type field is output even when lnum==0. ("error" was not output by v9.0.0736.)'], l)
184
185  " Test for module names, one needs to explicitly set `'valid':v:true` so
186  call g:Xsetlist([
187	\ {'lnum':10,'col':5,'type':'W','module':'Data.Text','text':'ModuleWarning','nr':11,'valid':v:true},
188	\ {'lnum':20,'col':10,'type':'W','module':'Data.Text','filename':'Data/Text.hs','text':'ModuleWarning','nr':22,'valid':v:true},
189	\ {'lnum':30,'col':15,'type':'W','filename':'Data/Text.hs','text':'FileWarning','nr':33,'valid':v:true}])
190  let l = split(execute('Xlist', ""), "\n")
191  call assert_equal([' 1 Data.Text:10 col 5 warning  11: ModuleWarning',
192	\ ' 2 Data.Text:20 col 10 warning  22: ModuleWarning',
193	\ ' 3 Data/Text.hs:30 col 15 warning  33: FileWarning'], l)
194
195  " Very long line should be displayed.
196  let text = 'Line' .. repeat('1234567890', 130)
197  let lines = ['Xtestfile9:2:9:' .. text]
198  Xgetexpr lines
199
200  let l = split(execute('Xlist', ''), "\n")
201  call assert_equal([' 1 Xtestfile9:2 col 9: ' .. text] , l)
202
203  " For help entries in the quickfix list, only the filename without directory
204  " should be displayed
205  Xhelpgrep setqflist()
206  let l = split(execute('Xlist 1', ''), "\n")
207  call assert_match('^ 1 [^\\/]\{-}:', l[0])
208
209  " Error cases
210  call assert_fails('Xlist abc', 'E488:')
211endfunc
212
213func Test_clist()
214  call XlistTests('c')
215  call XlistTests('l')
216endfunc
217
218" Tests for the :colder, :cnewer, :lolder and :lnewer commands
219" Note that this test assumes that a quickfix/location list is
220" already set by the caller.
221func XageTests(cchar)
222  call s:setup_commands(a:cchar)
223
224  if a:cchar == 'l'
225    " No location list for the current window
226    call assert_fails('lolder', 'E776:')
227    call assert_fails('lnewer', 'E776:')
228  endif
229
230  let list = [{'bufnr': bufnr('%'), 'lnum': 1}]
231  call g:Xsetlist(list)
232
233  " Jumping to a non existent list should return error
234  silent! Xolder 99
235  call assert_true(v:errmsg ==# 'E380: At bottom of quickfix stack')
236
237  silent! Xnewer 99
238  call assert_true(v:errmsg ==# 'E381: At top of quickfix stack')
239
240  " Add three quickfix/location lists
241  Xgetexpr ['Xtestfile1:1:3:Line1']
242  Xgetexpr ['Xtestfile2:2:2:Line2']
243  Xgetexpr ['Xtestfile3:3:1:Line3']
244
245  " Go back two lists
246  Xolder
247  let l = g:Xgetlist()
248  call assert_equal('Line2', l[0].text)
249
250  " Go forward two lists
251  Xnewer
252  let l = g:Xgetlist()
253  call assert_equal('Line3', l[0].text)
254
255  " Test for the optional count argument
256  Xolder 2
257  let l = g:Xgetlist()
258  call assert_equal('Line1', l[0].text)
259
260  Xnewer 2
261  let l = g:Xgetlist()
262  call assert_equal('Line3', l[0].text)
263endfunc
264
265func Test_cage()
266  call XageTests('c')
267  call XageTests('l')
268endfunc
269
270" Tests for the :cwindow, :lwindow :cclose, :lclose, :copen and :lopen
271" commands
272func XwindowTests(cchar)
273  call s:setup_commands(a:cchar)
274
275  " Opening the location list window without any errors should fail
276  if a:cchar == 'l'
277      call assert_fails('lopen', 'E776:')
278      call assert_fails('lwindow', 'E776:')
279  endif
280
281  " Create a list with no valid entries
282  Xgetexpr ['non-error 1', 'non-error 2', 'non-error 3']
283
284  " Quickfix/Location window should not open with no valid errors
285  Xwindow
286  call assert_true(winnr('$') == 1)
287
288  " Create a list with valid entries
289  let lines =<< trim END
290    Xtestfile1:1:3:Line1
291    Xtestfile2:2:2:Line2
292    Xtestfile3:3:1:Line3
293  END
294  Xgetexpr lines
295
296  " Open the window
297  Xwindow
298  call assert_true(winnr('$') == 2 && winnr() == 2 &&
299	\ getline('.') ==# 'Xtestfile1|1 col 3| Line1')
300  redraw!
301
302  " Close the window
303  Xclose
304  call assert_true(winnr('$') == 1)
305
306  " Create a list with no valid entries
307  Xgetexpr ['non-error 1', 'non-error 2', 'non-error 3']
308
309  " Open the window
310  Xopen 5
311  call assert_true(winnr('$') == 2 && getline('.') ==# '|| non-error 1'
312		      \  && winheight(0) == 5)
313
314  " Opening the window again, should move the cursor to that window
315  wincmd t
316  Xopen 7
317  call assert_true(winnr('$') == 2 && winnr() == 2 &&
318	\ winheight(0) == 7 &&
319	\ getline('.') ==# '|| non-error 1')
320
321  " :cnext in quickfix window should move to the next entry
322  Xnext
323  call assert_equal(2, g:Xgetlist({'idx' : 0}).idx)
324
325  " Calling cwindow should close the quickfix window with no valid errors
326  Xwindow
327  call assert_true(winnr('$') == 1)
328
329  " Specifying the width should adjust the width for a vertically split
330  " quickfix window.
331  vert Xopen
332  call assert_equal(10, winwidth(0))
333  vert Xopen 12
334  call assert_equal(12, winwidth(0))
335  Xclose
336
337  " Horizontally or vertically splitting the quickfix window should create a
338  " normal window/buffer
339  Xopen
340  wincmd s
341  call assert_equal(0, getwininfo(win_getid())[0].quickfix)
342  call assert_equal(0, getwininfo(win_getid())[0].loclist)
343  call assert_notequal('quickfix', &buftype)
344  close
345  Xopen
346  wincmd v
347  call assert_equal(0, getwininfo(win_getid())[0].quickfix)
348  call assert_equal(0, getwininfo(win_getid())[0].loclist)
349  call assert_notequal('quickfix', &buftype)
350  close
351  Xopen
352  Xclose
353
354  if a:cchar == 'c'
355      " Opening the quickfix window in multiple tab pages should reuse the
356      " quickfix buffer
357      let lines =<< trim END
358        Xtestfile1:1:3:Line1
359        Xtestfile2:2:2:Line2
360        Xtestfile3:3:1:Line3
361      END
362      Xgetexpr lines
363      Xopen
364      let qfbufnum = bufnr('%')
365      tabnew
366      Xopen
367      call assert_equal(qfbufnum, bufnr('%'))
368      new | only | tabonly
369  endif
370endfunc
371
372func Test_cwindow()
373  call XwindowTests('c')
374  call XwindowTests('l')
375endfunc
376
377func Test_copenHeight()
378  copen
379  wincmd H
380  let height = winheight(0)
381  copen 10
382  call assert_equal(height, winheight(0))
383  quit
384endfunc
385
386func Test_copenHeight_tabline()
387  set tabline=foo showtabline=2
388  copen
389  wincmd H
390  let height = winheight(0)
391  copen 10
392  call assert_equal(height, winheight(0))
393  quit
394  set tabline& showtabline&
395endfunc
396
397" Tests for the :cfile, :lfile, :caddfile, :laddfile, :cgetfile and :lgetfile
398" commands.
399func XfileTests(cchar)
400  call s:setup_commands(a:cchar)
401
402  let lines =<< trim END
403    Xtestfile1:700:10:Line 700
404    Xtestfile2:800:15:Line 800
405  END
406  call writefile(lines, 'Xqftestfile1')
407
408  enew!
409  Xfile Xqftestfile1
410  let l = g:Xgetlist()
411  call assert_true(len(l) == 2 &&
412	\ l[0].lnum == 700 && l[0].col == 10 && l[0].text ==# 'Line 700' &&
413	\ l[1].lnum == 800 && l[1].col == 15 && l[1].text ==# 'Line 800')
414
415  " Test with a non existent file
416  call assert_fails('Xfile non_existent_file', 'E40')
417
418  " Run cfile/lfile from a modified buffer
419  enew!
420  silent! put ='Quickfix'
421  silent! Xfile Xqftestfile1
422  call assert_true(v:errmsg ==# 'E37: No write since last change (add ! to override)')
423
424  call writefile(['Xtestfile3:900:30:Line 900'], 'Xqftestfile1')
425  Xaddfile Xqftestfile1
426  let l = g:Xgetlist()
427  call assert_true(len(l) == 3 &&
428	\ l[2].lnum == 900 && l[2].col == 30 && l[2].text ==# 'Line 900')
429
430  let lines =<< trim END
431    Xtestfile1:222:77:Line 222
432    Xtestfile2:333:88:Line 333
433  END
434  call writefile(lines, 'Xqftestfile1')
435
436  enew!
437  Xgetfile Xqftestfile1
438  let l = g:Xgetlist()
439  call assert_true(len(l) == 2 &&
440	\ l[0].lnum == 222 && l[0].col == 77 && l[0].text ==# 'Line 222' &&
441	\ l[1].lnum == 333 && l[1].col == 88 && l[1].text ==# 'Line 333')
442
443  " Test for a file with a long line and without a newline at the end
444  let text = repeat('x', 1024)
445  let t = 'a.txt:18:' . text
446  call writefile([t], 'Xqftestfile1', 'b')
447  silent! Xfile Xqftestfile1
448  call assert_equal(text, g:Xgetlist()[0].text)
449
450  call delete('Xqftestfile1')
451endfunc
452
453func Test_cfile()
454  call XfileTests('c')
455  call XfileTests('l')
456endfunc
457
458" Tests for the :cbuffer, :lbuffer, :caddbuffer, :laddbuffer, :cgetbuffer and
459" :lgetbuffer commands.
460func XbufferTests(cchar)
461  call s:setup_commands(a:cchar)
462
463  enew!
464  let lines =<< trim END
465    Xtestfile7:700:10:Line 700
466    Xtestfile8:800:15:Line 800
467  END
468  silent! call setline(1, lines)
469  Xbuffer!
470  let l = g:Xgetlist()
471  call assert_true(len(l) == 2 &&
472	\ l[0].lnum == 700 && l[0].col == 10 && l[0].text ==# 'Line 700' &&
473	\ l[1].lnum == 800 && l[1].col == 15 && l[1].text ==# 'Line 800')
474
475  enew!
476  let lines =<< trim END
477    Xtestfile9:900:55:Line 900
478    Xtestfile10:950:66:Line 950
479  END
480  silent! call setline(1, lines)
481  Xgetbuffer
482  let l = g:Xgetlist()
483  call assert_true(len(l) == 2 &&
484	\ l[0].lnum == 900 && l[0].col == 55 && l[0].text ==# 'Line 900' &&
485	\ l[1].lnum == 950 && l[1].col == 66 && l[1].text ==# 'Line 950')
486
487  enew!
488  let lines =<< trim END
489    Xtestfile11:700:20:Line 700
490    Xtestfile12:750:25:Line 750
491  END
492  silent! call setline(1, lines)
493  Xaddbuffer
494  let l = g:Xgetlist()
495  call assert_true(len(l) == 4 &&
496	\ l[1].lnum == 950 && l[1].col == 66 && l[1].text ==# 'Line 950' &&
497	\ l[2].lnum == 700 && l[2].col == 20 && l[2].text ==# 'Line 700' &&
498	\ l[3].lnum == 750 && l[3].col == 25 && l[3].text ==# 'Line 750')
499  enew!
500
501  " Check for invalid buffer
502  call assert_fails('Xbuffer 199', 'E474:')
503
504  " Check for unloaded buffer
505  edit Xtestfile1
506  let bnr = bufnr('%')
507  enew!
508  call assert_fails('Xbuffer ' . bnr, 'E681:')
509
510  " Check for invalid range
511  " Using Xbuffer will not run the range check in the cbuffer/lbuffer
512  " commands. So directly call the commands.
513  if (a:cchar == 'c')
514      call assert_fails('900,999cbuffer', 'E16:')
515  else
516      call assert_fails('900,999lbuffer', 'E16:')
517  endif
518endfunc
519
520func Test_cbuffer()
521  call XbufferTests('c')
522  call XbufferTests('l')
523endfunc
524
525func XexprTests(cchar)
526  call s:setup_commands(a:cchar)
527
528  call assert_fails('Xexpr 10', 'E777:')
529endfunc
530
531func Test_cexpr()
532  call XexprTests('c')
533  call XexprTests('l')
534endfunc
535
536" Tests for :cnext, :cprev, :cfirst, :clast commands
537func Xtest_browse(cchar)
538  call s:setup_commands(a:cchar)
539
540  call g:Xsetlist([], 'f')
541  " Jumping to first or next location list entry without any error should
542  " result in failure
543  if a:cchar == 'c'
544    let err = 'E42:'
545    let cmd = '$cc'
546  else
547    let err = 'E776:'
548    let cmd = '$ll'
549  endif
550  call assert_fails('Xnext', err)
551  call assert_fails('Xprev', err)
552  call assert_fails('Xnfile', err)
553  call assert_fails('Xpfile', err)
554  call assert_fails(cmd, err)
555
556  Xexpr ''
557  call assert_fails(cmd, 'E42:')
558
559  call s:create_test_file('Xqftestfile1')
560  call s:create_test_file('Xqftestfile2')
561
562  let lines =<< trim END
563    Xqftestfile1:5:Line5
564    Xqftestfile1:6:Line6
565    Xqftestfile2:10:Line10
566    Xqftestfile2:11:Line11
567    RegularLine1
568    RegularLine2
569  END
570  Xgetexpr lines
571
572  Xfirst
573  call assert_fails('-5Xcc', 'E16:')
574  call assert_fails('Xprev', 'E553')
575  call assert_fails('Xpfile', 'E553')
576  Xnfile
577  call assert_equal('Xqftestfile2', @%)
578  call assert_equal(10, line('.'))
579  Xpfile
580  call assert_equal('Xqftestfile1', @%)
581  call assert_equal(6, line('.'))
582  5Xcc
583  call assert_equal(5, g:Xgetlist({'idx':0}).idx)
584  2Xcc
585  call assert_equal(2, g:Xgetlist({'idx':0}).idx)
586  if a:cchar == 'c'
587    cc
588  else
589    ll
590  endif
591  call assert_equal(2, g:Xgetlist({'idx':0}).idx)
592  10Xcc
593  call assert_equal(6, g:Xgetlist({'idx':0}).idx)
594  Xlast
595  Xprev
596  call assert_equal('Xqftestfile2', @%)
597  call assert_equal(11, line('.'))
598  call assert_fails('Xnext', 'E553')
599  call assert_fails('Xnfile', 'E553')
600  " To process the range using quickfix list entries, directly use the
601  " quickfix commands (don't use the user defined commands)
602  if a:cchar == 'c'
603    $cc
604  else
605    $ll
606  endif
607  call assert_equal(6, g:Xgetlist({'idx':0}).idx)
608  Xrewind
609  call assert_equal('Xqftestfile1', @%)
610  call assert_equal(5, line('.'))
611
612  10Xnext
613  call assert_equal('Xqftestfile2', @%)
614  call assert_equal(11, line('.'))
615  10Xprev
616  call assert_equal('Xqftestfile1', @%)
617  call assert_equal(5, line('.'))
618
619  " Jumping to an error from the error window using cc command
620  let lines =<< trim END
621    Xqftestfile1:5:Line5
622    Xqftestfile1:6:Line6
623    Xqftestfile2:10:Line10
624    Xqftestfile2:11:Line11
625  END
626  Xgetexpr lines
627  Xopen
628  10Xcc
629  call assert_equal(11, line('.'))
630  call assert_equal('Xqftestfile2', @%)
631  Xopen
632  call cursor(2, 1)
633  if a:cchar == 'c'
634    .cc
635  else
636    .ll
637  endif
638  call assert_equal(6, line('.'))
639  call assert_equal('Xqftestfile1', @%)
640
641  " Jumping to an error from the error window (when only the error window is
642  " present)
643  Xopen | only
644  Xlast 1
645  call assert_equal(5, line('.'))
646  call assert_equal('Xqftestfile1', @%)
647
648  Xexpr ""
649  call assert_fails('Xnext', 'E42:')
650
651  call delete('Xqftestfile1')
652  call delete('Xqftestfile2')
653
654  " Should be able to use next/prev with invalid entries
655  Xexpr ""
656  call assert_equal(0, g:Xgetlist({'idx' : 0}).idx)
657  call assert_equal(0, g:Xgetlist({'size' : 0}).size)
658  Xaddexpr ['foo', 'bar', 'baz', 'quux', 'sh|moo']
659  call assert_equal(5, g:Xgetlist({'size' : 0}).size)
660  Xlast
661  call assert_equal(5, g:Xgetlist({'idx' : 0}).idx)
662  Xfirst
663  call assert_equal(1, g:Xgetlist({'idx' : 0}).idx)
664  2Xnext
665  call assert_equal(3, g:Xgetlist({'idx' : 0}).idx)
666endfunc
667
668func Test_browse()
669  call Xtest_browse('c')
670  call Xtest_browse('l')
671endfunc
672
673" Test for memory allocation failures
674func Xnomem_tests(cchar)
675  call s:setup_commands(a:cchar)
676
677  call test_alloc_fail(GetAllocId('qf_dirname_start'), 0, 0)
678  call assert_fails('Xvimgrep vim runtest.vim', 'E342:')
679
680  call test_alloc_fail(GetAllocId('qf_dirname_now'), 0, 0)
681  call assert_fails('Xvimgrep vim runtest.vim', 'E342:')
682
683  call test_alloc_fail(GetAllocId('qf_namebuf'), 0, 0)
684  call assert_fails('Xfile runtest.vim', 'E342:')
685
686  call test_alloc_fail(GetAllocId('qf_errmsg'), 0, 0)
687  call assert_fails('Xfile runtest.vim', 'E342:')
688
689  call test_alloc_fail(GetAllocId('qf_pattern'), 0, 0)
690  call assert_fails('Xfile runtest.vim', 'E342:')
691
692  call test_alloc_fail(GetAllocId('qf_efm_fmtstr'), 0, 0)
693  set efm=%f
694  call assert_fails('Xexpr ["Xfile1"]', 'E342:')
695  set efm&
696
697  call test_alloc_fail(GetAllocId('qf_efm_fmtpart'), 0, 0)
698  set efm=%f:%l:%m,%f-%l-%m
699  call assert_fails('Xaddexpr ["Xfile2", "Xfile3"]', 'E342:')
700  set efm&
701
702  call test_alloc_fail(GetAllocId('qf_title'), 0, 0)
703  call assert_fails('Xexpr ""', 'E342:')
704  call assert_equal('', g:Xgetlist({'all': 1}).title)
705
706  call test_alloc_fail(GetAllocId('qf_mef_name'), 0, 0)
707  set makeef=Xtmp##.err
708  call assert_fails('Xgrep needle haystack', 'E342:')
709  set makeef&
710
711  call test_alloc_fail(GetAllocId('qf_qfline'), 0, 0)
712  call assert_fails('Xexpr "Xfile1:10:Line10"', 'E342:')
713
714  if a:cchar == 'l'
715    for id in ['qf_qfline', 'qf_qfinfo']
716      lgetexpr ["Xfile1:10:L10", "Xfile2:20:L20"]
717      call test_alloc_fail(GetAllocId(id), 0, 0)
718      call assert_fails('new', 'E342:')
719      call assert_equal(2, winnr('$'))
720      call assert_equal([], getloclist(0))
721      %bw!
722    endfor
723  endif
724
725  call test_alloc_fail(GetAllocId('qf_qfline'), 0, 0)
726  try
727    call assert_fails('Xvimgrep vim runtest.vim', 'E342:')
728  catch /^Vim:Interrupt$/
729  endtry
730
731  call test_alloc_fail(GetAllocId('qf_qfline'), 0, 0)
732  try
733    call assert_fails('Xvimgrep /vim/f runtest.vim', 'E342:')
734  catch /^Vim:Interrupt$/
735  endtry
736
737  let l = getqflist({"lines": ["Xfile1:10:L10"]})
738  call test_alloc_fail(GetAllocId('qf_qfline'), 0, 0)
739  call assert_fails('call g:Xsetlist(l.items)', 'E342:')
740
741  call test_alloc_fail(GetAllocId('qf_qfline'), 0, 0)
742  try
743    call assert_fails('Xhelpgrep quickfix', 'E342:')
744  catch /^Vim:Interrupt$/
745  endtry
746
747  call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
748  call assert_fails('let l = g:Xgetlist({"lines": ["Xfile1:10:L10"]})', 'E342:')
749  call assert_equal(#{items: []}, l)
750
751  if a:cchar == 'l'
752    call setqflist([], 'f')
753    call setloclist(0, [], 'f')
754    call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
755    call assert_fails('lhelpgrep quickfix', 'E342:')
756    call assert_equal([], getloclist(0))
757
758    call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
759    call assert_fails('lvimgrep vim runtest.vim', 'E342:')
760
761    let l = getqflist({"lines": ["Xfile1:10:L10"]})
762    call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
763    call assert_fails('call setloclist(0, l.items)', 'E342:')
764
765    call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
766    call assert_fails('lbuffer', 'E342:')
767
768    call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
769    call assert_fails('lexpr ["Xfile1:10:L10", "Xfile2:20:L20"]', 'E342:')
770
771    call test_alloc_fail(GetAllocId('qf_qfinfo'), 0, 0)
772    call assert_fails('lfile runtest.vim', 'E342:')
773  endif
774
775  call test_alloc_fail(GetAllocId('qf_dirstack'), 0, 0)
776  set efm=%DEntering\ dir\ %f,%f:%l:%m
777  call assert_fails('Xexpr ["Entering dir abc", "abc.txt:1:Hello world"]', 'E342:')
778  set efm&
779
780  call test_alloc_fail(GetAllocId('qf_dirstack'), 0, 0)
781  set efm=%+P[%f],(%l)%m
782  call assert_fails('Xexpr ["[runtest.vim]", "(1)Hello"]', 'E342:')
783  set efm&
784
785  call test_alloc_fail(GetAllocId('qf_multiline_pfx'), 0, 0)
786  set efm=%EError,%Cline\ %l,%Z%m
787  call assert_fails('Xexpr ["Error", "line 1", "msg"]', 'E342:')
788  set efm&
789
790  call test_alloc_fail(GetAllocId('qf_makecmd'), 0, 0)
791  call assert_fails('Xgrep vim runtest.vim', 'E342:')
792
793  call test_alloc_fail(GetAllocId('qf_linebuf'), 0, 0)
794  call assert_fails('Xexpr repeat("a", 8192)', 'E342:')
795
796  call test_alloc_fail(GetAllocId('qf_linebuf'), 0, 0)
797  call assert_fails('Xexpr [repeat("a", 8192)]', 'E342:')
798
799  new
800  call setline(1, repeat('a', 8192))
801  call test_alloc_fail(GetAllocId('qf_linebuf'), 0, 0)
802  call assert_fails('Xbuffer', 'E342:')
803  %bw!
804
805  call writefile([repeat('a', 8192)], 'Xtest')
806  call test_alloc_fail(GetAllocId('qf_linebuf'), 0, 0)
807  call assert_fails('Xfile Xtest', 'E342:')
808  call delete('Xtest')
809endfunc
810
811func Test_nomem()
812  throw 'Skipped: Nvim does not support test_alloc_fail()'
813  call Xnomem_tests('c')
814  call Xnomem_tests('l')
815endfunc
816
817func s:test_xhelpgrep(cchar)
818  call s:setup_commands(a:cchar)
819  Xhelpgrep quickfix
820  Xopen
821  if a:cchar == 'c'
822    let title_text = ':helpgrep quickfix'
823  else
824    let title_text = ':lhelpgrep quickfix'
825  endif
826  call assert_true(w:quickfix_title =~ title_text, w:quickfix_title)
827
828  " Jumping to a help topic should open the help window
829  only
830  Xnext
831  call assert_true(&buftype == 'help')
832  call assert_true(winnr('$') == 2)
833  " Jumping to the next match should reuse the help window
834  Xnext
835  call assert_true(&buftype == 'help')
836  call assert_true(winnr() == 1)
837  call assert_true(winnr('$') == 2)
838  " Jumping to the next match from the quickfix window should reuse the help
839  " window
840  Xopen
841  Xnext
842  call assert_true(&buftype == 'help')
843  call assert_true(winnr() == 1)
844  call assert_true(winnr('$') == 2)
845  call assert_match('|\d\+ col \d\+-\d\+|', getbufline(winbufnr(2), 1)[0])
846
847  " This wipes out the buffer, make sure that doesn't cause trouble.
848  Xclose
849
850  " When the current window is vertically split, jumping to a help match
851  " should open the help window at the top.
852  only | enew
853  let w1 = win_getid()
854  vert new
855  let w2 = win_getid()
856  Xnext
857  let w3 = win_getid()
858  call assert_true(&buftype == 'help')
859  call assert_true(winnr() == 1)
860  " See jump_to_help_window() for details
861  let w2_width = winwidth(w2)
862  if w2_width != &columns && w2_width < 80
863    call assert_equal(['col', [['leaf', w3],
864          \ ['row', [['leaf', w2], ['leaf', w1]]]]], winlayout())
865  else
866    call assert_equal(['row', [['col', [['leaf', w3], ['leaf', w2]]],
867          \ ['leaf', w1]]] , winlayout())
868  endif
869
870  new | only
871  set buftype=help
872  set modified
873  call assert_fails('Xnext', 'E37:')
874  set nomodified
875  new | only
876
877  if a:cchar == 'l'
878      " When a help window is present, running :lhelpgrep should reuse the
879      " help window and not the current window
880      new | only
881      call g:Xsetlist([], 'f')
882      help index.txt
883      wincmd w
884      lhelpgrep quickfix
885      call assert_equal(1, winnr())
886      call assert_notequal([], getloclist(1))
887      call assert_equal([], getloclist(2))
888  endif
889
890  new | only
891
892  " Search for non existing help string
893  call assert_fails('Xhelpgrep a1b2c3', 'E480:')
894  " Invalid regular expression
895  call assert_fails('Xhelpgrep \@<!', 'E866:')
896endfunc
897
898func Test_helpgrep()
899  call s:test_xhelpgrep('c')
900  helpclose
901  call s:test_xhelpgrep('l')
902endfunc
903
904" When running the :helpgrep command, if an autocmd modifies the 'cpoptions'
905" value, then Vim crashes. (issue fixed by 7.2b-004 and 8.2.4453)
906func Test_helpgrep_restore_cpo_aucmd()
907  let save_cpo = &cpo
908  augroup QF_Test
909    au!
910    autocmd BufNew * set cpo=acd
911  augroup END
912
913  helpgrep quickfix
914  call assert_equal('acd', &cpo)
915  %bw!
916
917  set cpo&vim
918  augroup QF_Test
919    au!
920    autocmd BufReadPost * set cpo=
921  augroup END
922
923  helpgrep buffer
924  call assert_equal('', &cpo)
925
926  augroup QF_Test
927    au!
928  augroup END
929  %bw!
930  let &cpo = save_cpo
931endfunc
932
933func Test_errortitle()
934  augroup QfBufWinEnter
935    au!
936    au BufWinEnter * :let g:a=get(w:, 'quickfix_title', 'NONE')
937  augroup END
938  copen
939  let a=[{'lnum': 308, 'bufnr': bufnr(''), 'col': 58, 'valid': 1, 'vcol': 0, 'nr': 0, 'type': '', 'pattern': '', 'text': '    au BufWinEnter * :let g:a=get(w:, ''quickfix_title'', ''NONE'')'}]
940  call setqflist(a)
941  call assert_equal(':setqflist()', g:a)
942  augroup QfBufWinEnter
943    au!
944  augroup END
945  augroup! QfBufWinEnter
946endfunc
947
948func Test_vimgreptitle()
949  augroup QfBufWinEnter
950    au!
951    au BufWinEnter * :let g:a=get(w:, 'quickfix_title', 'NONE')
952  augroup END
953  try
954    vimgrep /pattern/j file
955  catch /E480/
956  endtry
957  copen
958  call assert_equal(':    vimgrep /pattern/j file', g:a)
959  augroup QfBufWinEnter
960    au!
961  augroup END
962  augroup! QfBufWinEnter
963endfunc
964
965func Test_bufwinenter_once()
966  augroup QfBufWinEnter
967    au!
968    au BufWinEnter * let g:got_afile ..= 'got ' .. expand('<afile>')
969  augroup END
970  let g:got_afile = ''
971  copen
972  call assert_equal('got quickfix', g:got_afile)
973
974  cclose
975  unlet g:got_afile
976  augroup QfBufWinEnter
977    au!
978  augroup END
979  augroup! QfBufWinEnter
980endfunc
981
982func XqfTitleTests(cchar)
983  call s:setup_commands(a:cchar)
984
985  Xgetexpr ['file:1:1:message']
986  let l = g:Xgetlist()
987  if a:cchar == 'c'
988    call setqflist(l, 'r')
989  else
990    call setloclist(0, l, 'r')
991  endif
992
993  Xopen
994  if a:cchar == 'c'
995    let title = ':setqflist()'
996  else
997    let title = ':setloclist()'
998  endif
999  call assert_equal(title, w:quickfix_title)
1000  Xclose
1001endfunc
1002
1003" Tests for quickfix window's title
1004func Test_qf_title()
1005  call XqfTitleTests('c')
1006  call XqfTitleTests('l')
1007endfunc
1008
1009" Tests for 'errorformat'
1010func Test_efm()
1011  let save_efm = &efm
1012  set efm=%EEEE%m,%WWWW%m,%+CCCC%.%#,%-GGGG%.%#
1013  cgetexpr ['WWWW', 'EEEE', 'CCCC']
1014  let l = strtrans(string(map(getqflist(), '[v:val.text, v:val.valid]')))
1015  call assert_equal("[['W', 1], ['E^@CCCC', 1]]", l)
1016  cgetexpr ['WWWW', 'GGGG', 'EEEE', 'CCCC']
1017  let l = strtrans(string(map(getqflist(), '[v:val.text, v:val.valid]')))
1018  call assert_equal("[['W', 1], ['E^@CCCC', 1]]", l)
1019  cgetexpr ['WWWW', 'GGGG', 'ZZZZ', 'EEEE', 'CCCC', 'YYYY']
1020  let l = strtrans(string(map(getqflist(), '[v:val.text, v:val.valid]')))
1021  call assert_equal("[['W', 1], ['ZZZZ', 0], ['E^@CCCC', 1], ['YYYY', 0]]", l)
1022  let &efm = save_efm
1023endfunc
1024
1025" This will test for problems in quickfix:
1026" A. incorrectly copying location lists which caused the location list to show
1027"    a different name than the file that was actually being displayed.
1028" B. not reusing the window for which the location list window is opened but
1029"    instead creating new windows.
1030" C. make sure that the location list window is not reused instead of the
1031"    window it belongs to.
1032"
1033" Set up the test environment:
1034func ReadTestProtocol(name)
1035  let base = substitute(a:name, '\v^test://(.*)%(\.[^.]+)?', '\1', '')
1036  let word = substitute(base, '\v(.*)\..*', '\1', '')
1037
1038  setl modifiable
1039  setl noreadonly
1040  setl noswapfile
1041  setl bufhidden=delete
1042  %del _
1043  " For problem 2:
1044  " 'buftype' has to be set to reproduce the constant opening of new windows
1045  setl buftype=nofile
1046
1047  call setline(1, word)
1048
1049  setl nomodified
1050  setl nomodifiable
1051  setl readonly
1052  exe 'doautocmd BufRead ' . substitute(a:name, '\v^test://(.*)', '\1', '')
1053endfunc
1054
1055func Test_locationlist()
1056  enew
1057
1058  augroup testgroup
1059    au!
1060    autocmd BufReadCmd test://* call ReadTestProtocol(expand("<amatch>"))
1061  augroup END
1062
1063  let words = [ "foo", "bar", "baz", "quux", "shmoo", "spam", "eggs" ]
1064
1065  let qflist = []
1066  for word in words
1067    call add(qflist, {'filename': 'test://' . word . '.txt', 'text': 'file ' . word . '.txt', })
1068    " NOTE: problem 1:
1069    " intentionally not setting 'lnum' so that the quickfix entries are not
1070    " valid
1071    eval qflist->setloclist(0, ' ')
1072  endfor
1073
1074  " Test A
1075  lrewind
1076  enew
1077  lopen
1078  4lnext
1079  vert split
1080  wincmd L
1081  lopen
1082  wincmd p
1083  lnext
1084  let fileName = expand("%")
1085  wincmd p
1086  let locationListFileName = substitute(getline(line('.')), '\([^|]*\)|.*', '\1', '')
1087  let fileName = substitute(fileName, '\\', '/', 'g')
1088  let locationListFileName = substitute(locationListFileName, '\\', '/', 'g')
1089  call assert_equal("test://bar.txt", fileName)
1090  call assert_equal("test://bar.txt", locationListFileName)
1091
1092  wincmd n | only
1093
1094  " Test B:
1095  lrewind
1096  lopen
1097  2
1098  exe "normal \<CR>"
1099  wincmd p
1100  3
1101  exe "normal \<CR>"
1102  wincmd p
1103  4
1104  exe "normal \<CR>"
1105  call assert_equal(2, winnr('$'))
1106  wincmd n | only
1107
1108  " Test C:
1109  lrewind
1110  lopen
1111  " Let's move the location list window to the top to check whether it (the
1112  " first window found) will be reused when we try to open new windows:
1113  wincmd K
1114  2
1115  exe "normal \<CR>"
1116  wincmd p
1117  3
1118  exe "normal \<CR>"
1119  wincmd p
1120  4
1121  exe "normal \<CR>"
1122  1wincmd w
1123  call assert_equal('quickfix', &buftype)
1124  2wincmd w
1125  let bufferName = expand("%")
1126  let bufferName = substitute(bufferName, '\\', '/', 'g')
1127  call assert_equal('test://quux.txt', bufferName)
1128
1129  wincmd n | only
1130
1131  augroup! testgroup
1132endfunc
1133
1134func Test_locationlist_curwin_was_closed()
1135  augroup testgroup
1136    au!
1137    autocmd BufReadCmd test_curwin.txt call R(expand("<amatch>"))
1138  augroup END
1139
1140  func! R(n)
1141    quit
1142  endfunc
1143
1144  new
1145  let q = []
1146  call add(q, {'filename': 'test_curwin.txt' })
1147  call setloclist(0, q)
1148  call assert_fails('lrewind', 'E924:')
1149
1150  augroup! testgroup
1151  delfunc R
1152endfunc
1153
1154func Test_locationlist_cross_tab_jump()
1155  call writefile(['loclistfoo'], 'loclistfoo')
1156  call writefile(['loclistbar'], 'loclistbar')
1157  set switchbuf=usetab
1158
1159  edit loclistfoo
1160  tabedit loclistbar
1161  silent lgrep loclistfoo loclist*
1162  call assert_equal(1, tabpagenr())
1163
1164  enew | only | tabonly
1165  set switchbuf&vim
1166  call delete('loclistfoo')
1167  call delete('loclistbar')
1168endfunc
1169
1170" More tests for 'errorformat'
1171func Test_efm1()
1172  " The 'errorformat' setting is different on non-Unix systems.
1173  " This test works only on Unix-like systems.
1174  CheckUnix
1175
1176  let l =<< trim [DATA]
1177    "Xtestfile", line 4.12: 1506-045 (S) Undeclared identifier fd_set.
1178    "Xtestfile", line 6 col 19; this is an error
1179    gcc -c -DHAVE_CONFIsing-prototypes -I/usr/X11R6/include  version.c
1180    Xtestfile:9: parse error before `asd'
1181    make: *** [src/vim/testdir/Makefile:100: test_quickfix] Error 1
1182    in file "Xtestfile" linenr 10: there is an error
1183
1184    2 returned
1185    "Xtestfile", line 11 col 1; this is an error
1186    "Xtestfile", line 12 col 2; this is another error
1187    "Xtestfile", line 14:10; this is an error in column 10
1188    =Xtestfile=, line 15:10; this is another error, but in vcol 10 this time
1189    "Xtestfile", linenr 16: yet another problem
1190    Error in "Xtestfile" at line 17:
1191    x should be a dot
1192	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 17
1193                ^
1194    Error in "Xtestfile" at line 18:
1195    x should be a dot
1196	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 18
1197    .............^
1198    Error in "Xtestfile" at line 19:
1199    x should be a dot
1200	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 19
1201    --------------^
1202    Error in "Xtestfile" at line 20:
1203    x should be a dot
1204	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 20
1205	       ^
1206
1207    Does anyone know what is the problem and how to correction it?
1208    "Xtestfile", line 21 col 9: What is the title of the quickfix window?
1209    "Xtestfile", line 22 col 9: What is the title of the quickfix window?
1210  [DATA]
1211
1212  call writefile(l, 'Xerrorfile1')
1213  call writefile(l[:-2], 'Xerrorfile2')
1214
1215  let m =<< [DATA]
1216	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  2
1217	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  3
1218	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  4
1219	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  5
1220	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  6
1221	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  7
1222	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  8
1223	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line  9
1224	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 10
1225	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 11
1226	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 12
1227	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 13
1228	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 14
1229	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 15
1230	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 16
1231	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 17
1232	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 18
1233	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 19
1234	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 20
1235	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 21
1236	xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    line 22
1237[DATA]
1238  call writefile(m, 'Xtestfile')
1239
1240  let save_efm = &efm
1241  set efm+==%f=\\,\ line\ %l%*\\D%v%*[^\ ]\ %m
1242  set efm^=%AError\ in\ \"%f\"\ at\ line\ %l:,%Z%p^,%C%m
1243
1244  exe 'cf Xerrorfile2'
1245  clast
1246  copen
1247  call assert_equal(':cf Xerrorfile2', w:quickfix_title)
1248  wincmd p
1249
1250  exe 'cf Xerrorfile1'
1251  call assert_equal([4, 12], [line('.'), col('.')])
1252  cn
1253  call assert_equal([6, 19], [line('.'), col('.')])
1254  cn
1255  call assert_equal([9, 2], [line('.'), col('.')])
1256  cn
1257  call assert_equal([10, 2], [line('.'), col('.')])
1258  cn
1259  call assert_equal([11, 1], [line('.'), col('.')])
1260  cn
1261  call assert_equal([12, 2], [line('.'), col('.')])
1262  cn
1263  call assert_equal([14, 10], [line('.'), col('.')])
1264  cn
1265  call assert_equal([15, 3, 10], [line('.'), col('.'), virtcol('.')])
1266  cn
1267  call assert_equal([16, 2], [line('.'), col('.')])
1268  cn
1269  call assert_equal([17, 6], [line('.'), col('.')])
1270  cn
1271  call assert_equal([18, 7], [line('.'), col('.')])
1272  cn
1273  call assert_equal([19, 8], [line('.'), col('.')])
1274  cn
1275  call assert_equal([20, 9], [line('.'), col('.')])
1276  clast
1277  cprev
1278  cprev
1279  wincmd w
1280  call assert_equal(':cf Xerrorfile1', w:quickfix_title)
1281  wincmd p
1282
1283  let &efm = save_efm
1284  call delete('Xerrorfile1')
1285  call delete('Xerrorfile2')
1286  call delete('Xtestfile')
1287endfunc
1288
1289" Test for quickfix directory stack support
1290func s:dir_stack_tests(cchar)
1291  call s:setup_commands(a:cchar)
1292
1293  let save_efm=&efm
1294  set efm=%DEntering\ dir\ '%f',%f:%l:%m,%XLeaving\ dir\ '%f'
1295
1296  let lines =<< trim END
1297    Entering dir 'dir1/a'
1298    habits2.txt:1:Nine Healthy Habits
1299    Entering dir 'b'
1300    habits3.txt:2:0 Hours of television
1301    habits2.txt:7:5 Small meals
1302    Entering dir 'dir1/c'
1303    habits4.txt:3:1 Hour of exercise
1304    Leaving dir 'dir1/c'
1305    Leaving dir 'dir1/a'
1306    habits1.txt:4:2 Liters of water
1307    Entering dir 'dir2'
1308    habits5.txt:5:3 Cups of hot green tea
1309    Leaving dir 'dir2'
1310  END
1311
1312  Xexpr ""
1313  for l in lines
1314      Xaddexpr l
1315  endfor
1316
1317  let qf = g:Xgetlist()
1318
1319  call assert_equal('dir1/a/habits2.txt', bufname(qf[1].bufnr))
1320  call assert_equal(1, qf[1].lnum)
1321  call assert_equal('dir1/a/b/habits3.txt', bufname(qf[3].bufnr))
1322  call assert_equal(2, qf[3].lnum)
1323  call assert_equal('dir1/a/habits2.txt', bufname(qf[4].bufnr))
1324  call assert_equal(7, qf[4].lnum)
1325  call assert_equal('dir1/c/habits4.txt', bufname(qf[6].bufnr))
1326  call assert_equal(3, qf[6].lnum)
1327  call assert_equal('habits1.txt', bufname(qf[9].bufnr))
1328  call assert_equal(4, qf[9].lnum)
1329  call assert_equal('dir2/habits5.txt', bufname(qf[11].bufnr))
1330  call assert_equal(5, qf[11].lnum)
1331
1332  let &efm=save_efm
1333endfunc
1334
1335" Tests for %D and %X errorformat options
1336func Test_efm_dirstack()
1337  " Create the directory stack and files
1338  call mkdir('dir1')
1339  call mkdir('dir1/a')
1340  call mkdir('dir1/a/b')
1341  call mkdir('dir1/c')
1342  call mkdir('dir2')
1343
1344  let lines =<< trim END
1345    Nine Healthy Habits
1346    0 Hours of television
1347    1 Hour of exercise
1348    2 Liters of water
1349    3 Cups of hot green tea
1350    4 Short mental breaks
1351    5 Small meals
1352    6 AM wake up time
1353    7 Minutes of laughter
1354    8 Hours of sleep (at least)
1355    9 PM end of the day and off to bed
1356  END
1357  call writefile(lines, 'habits1.txt')
1358  call writefile(lines, 'dir1/a/habits2.txt')
1359  call writefile(lines, 'dir1/a/b/habits3.txt')
1360  call writefile(lines, 'dir1/c/habits4.txt')
1361  call writefile(lines, 'dir2/habits5.txt')
1362
1363  call s:dir_stack_tests('c')
1364  call s:dir_stack_tests('l')
1365
1366  call delete('dir1', 'rf')
1367  call delete('dir2', 'rf')
1368  call delete('habits1.txt')
1369endfunc
1370
1371" Test for resync after continuing an ignored message
1372func Xefm_ignore_continuations(cchar)
1373  call s:setup_commands(a:cchar)
1374
1375  let save_efm = &efm
1376
1377  let &efm =
1378	\ '%Eerror %m %l,' .
1379	\ '%-Wignored %m %l,' .
1380	\ '%+Cmore ignored %m %l,' .
1381	\ '%Zignored end'
1382  let lines =<< trim END
1383    ignored warning 1
1384    more ignored continuation 2
1385    ignored end
1386    error resync 4
1387  END
1388  Xgetexpr lines
1389  let l = map(g:Xgetlist(), '[v:val.text, v:val.valid, v:val.lnum, v:val.type]')
1390  call assert_equal([['resync', 1, 4, 'E']], l)
1391
1392  let &efm = save_efm
1393endfunc
1394
1395func Test_efm_ignore_continuations()
1396  call Xefm_ignore_continuations('c')
1397  call Xefm_ignore_continuations('l')
1398endfunc
1399
1400" Tests for invalid error format specifies
1401func Xinvalid_efm_Tests(cchar)
1402  call s:setup_commands(a:cchar)
1403
1404  let save_efm = &efm
1405
1406  set efm=%f:%l:%m,%f:%f:%l:%m
1407  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E372:')
1408
1409  set efm=%f:%l:%m,%f:%l:%r:%m
1410  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E373:')
1411
1412  set efm=%f:%l:%m,%O:%f:%l:%m
1413  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E373:')
1414
1415  set efm=%f:%l:%m,%f:%l:%*[^a-z
1416  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E374:')
1417
1418  set efm=%f:%l:%m,%f:%l:%*c
1419  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E375:')
1420
1421  set efm=%f:%l:%m,%L%M%N
1422  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E376:')
1423
1424  set efm=%f:%l:%m,%f:%l:%m:%R
1425  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E377:')
1426
1427  " Invalid regular expression
1428  set efm=%\\%%k
1429  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E867:')
1430
1431  set efm=
1432  call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E378:')
1433
1434  " Empty directory name. When there is an error in parsing new entries, make
1435  " sure the previous quickfix list is made the current list.
1436  set efm&
1437  cexpr ["one", "two"]
1438  let qf_id = getqflist(#{id: 0}).id
1439  set efm=%DEntering\ dir\ abc,%f:%l:%m
1440  call assert_fails('Xexpr ["Entering dir abc", "abc.txt:1:Hello world"]', 'E379:')
1441  call assert_equal(qf_id, getqflist(#{id: 0}).id)
1442
1443  let &efm = save_efm
1444endfunc
1445
1446func Test_invalid_efm()
1447  call Xinvalid_efm_Tests('c')
1448  call Xinvalid_efm_Tests('l')
1449endfunc
1450
1451" TODO:
1452" Add tests for the following formats in 'errorformat'
1453"	%r  %O
1454func Test_efm2()
1455  let save_efm = &efm
1456
1457  " Test for %s format in efm
1458  set efm=%f:%s
1459  cexpr 'Xtestfile:Line search text'
1460  let l = getqflist()
1461  call assert_equal('^\VLine search text\$', l[0].pattern)
1462  call assert_equal(0, l[0].lnum)
1463
1464  let l = split(execute('clist', ''), "\n")
1465  call assert_equal([' 1 Xtestfile:^\VLine search text\$:  '], l)
1466
1467  " Test for a long line
1468  cexpr 'Xtestfile:' . repeat('a', 1026)
1469  let l = getqflist()
1470  call assert_equal('^\V' . repeat('a', 1019) . '\$', l[0].pattern)
1471
1472  " Test for %P, %Q and %t format specifiers
1473  let lines =<< trim [DATA]
1474    [Xtestfile1]
1475    (1,17)  error: ';' missing
1476    (21,2)  warning: variable 'z' not defined
1477    (67,3)  error: end of file found before string ended
1478    --
1479
1480    [Xtestfile2]
1481    --
1482
1483    [Xtestfile3]
1484    NEW compiler v1.1
1485    (2,2)   warning: variable 'x' not defined
1486    (67,3)  warning: 's' already defined
1487    --
1488  [DATA]
1489
1490  set efm=%+P[%f]%r,(%l\\,%c)%*[\ ]%t%*[^:]:\ %m,%+Q--%r
1491  " To exercise the push/pop file functionality in quickfix, the test files
1492  " need to be created.
1493  call writefile(['Line1'], 'Xtestfile1')
1494  call writefile(['Line2'], 'Xtestfile2')
1495  call writefile(['Line3'], 'Xtestfile3')
1496  cexpr ""
1497  for l in lines
1498      caddexpr l
1499  endfor
1500  let l = getqflist()
1501  call assert_equal(12, len(l))
1502  call assert_equal(21, l[2].lnum)
1503  call assert_equal(2, l[2].col)
1504  call assert_equal('w', l[2].type)
1505  call assert_equal('e', l[3].type)
1506  call delete('Xtestfile1')
1507  call delete('Xtestfile2')
1508  call delete('Xtestfile3')
1509
1510  " Test for %P, %Q with non-existing files
1511  cexpr lines
1512  let l = getqflist()
1513  call assert_equal(14, len(l))
1514  call assert_equal('[Xtestfile1]', l[0].text)
1515  call assert_equal('[Xtestfile2]', l[6].text)
1516  call assert_equal('[Xtestfile3]', l[9].text)
1517
1518  " Tests for %E, %C and %Z format specifiers
1519  let lines =<< trim [DATA]
1520    Error 275
1521    line 42
1522    column 3
1523    ' ' expected after '--'
1524  [DATA]
1525
1526  set efm=%EError\ %n,%Cline\ %l,%Ccolumn\ %c,%Z%m
1527  cgetexpr lines
1528  let l = getqflist()
1529  call assert_equal(275, l[0].nr)
1530  call assert_equal(42, l[0].lnum)
1531  call assert_equal(3, l[0].col)
1532  call assert_equal('E', l[0].type)
1533  call assert_equal("\n' ' expected after '--'", l[0].text)
1534
1535  " Test for %>
1536  let lines =<< trim [DATA]
1537    Error in line 147 of foo.c:
1538    unknown variable 'i'
1539  [DATA]
1540
1541  set efm=unknown\ variable\ %m,%E%>Error\ in\ line\ %l\ of\ %f:,%Z%m
1542  cgetexpr lines
1543  let l = getqflist()
1544  call assert_equal(147, l[0].lnum)
1545  call assert_equal('E', l[0].type)
1546  call assert_equal("\nunknown variable 'i'", l[0].text)
1547
1548  " Test for %A, %C and other formats
1549  let lines =<< trim [DATA]
1550    ==============================================================
1551    FAIL: testGetTypeIdCachesResult (dbfacadeTest.DjsDBFacadeTest)
1552    --------------------------------------------------------------
1553    Traceback (most recent call last):
1554      File "unittests/dbfacadeTest.py", line 89, in testFoo
1555        self.assertEquals(34, dtid)
1556      File "/usr/lib/python2.2/unittest.py", line 286, in
1557     failUnlessEqual
1558        raise self.failureException, \\
1559    W:AssertionError: 34 != 33
1560
1561    --------------------------------------------------------------
1562    Ran 27 tests in 0.063s
1563  [DATA]
1564
1565  set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%t:%m
1566  cgetexpr lines
1567  let l = getqflist()
1568  call assert_equal(8, len(l))
1569  call assert_equal(89, l[4].lnum)
1570  call assert_equal(1, l[4].valid)
1571  call assert_equal('unittests/dbfacadeTest.py', bufname(l[4].bufnr))
1572  call assert_equal('W', l[4].type)
1573
1574  " Test for %o
1575  set efm=%f(%o):%l\ %m
1576  cgetexpr ['Xotestfile(Language.PureScript.Types):20 Error']
1577  call writefile(['Line1'], 'Xotestfile')
1578  let l = getqflist()
1579  call assert_equal(1, len(l), string(l))
1580  call assert_equal('Language.PureScript.Types', l[0].module)
1581  copen
1582  call assert_equal('Language.PureScript.Types|20| Error', getline(1))
1583  call feedkeys("\<CR>", 'xn')
1584  call assert_equal('Xotestfile', expand('%:t'))
1585  cclose
1586  bd
1587  call delete("Xotestfile")
1588
1589  " Test for a long module name
1590  cexpr 'Xtest(' . repeat('m', 1026) . '):15 message'
1591  let l = getqflist()
1592  " call assert_equal(repeat('m', 1024), l[0].module)
1593  call assert_equal(repeat('m', 1023), l[0].module)
1594  call assert_equal(15, l[0].lnum)
1595  call assert_equal('message', l[0].text)
1596
1597  " The following sequence of commands used to crash Vim
1598  set efm=%W%m
1599  cgetexpr ['msg1']
1600  let l = getqflist()
1601  call assert_equal(1, len(l), string(l))
1602  call assert_equal('msg1', l[0].text)
1603  set efm=%C%m
1604  lexpr 'msg2'
1605  let l = getloclist(0)
1606  call assert_equal(1, len(l), string(l))
1607  call assert_equal('msg2', l[0].text)
1608  lopen
1609  call setqflist([], 'r')
1610  caddbuf
1611  let l = getqflist()
1612  call assert_equal(1, len(l), string(l))
1613  call assert_equal('|| msg2', l[0].text)
1614
1615  " When matching error lines, case should be ignored. Test for this.
1616  set noignorecase
1617  let l=getqflist({'lines' : ['Xtest:FOO10:Line 20'], 'efm':'%f:foo%l:%m'})
1618  call assert_equal(10, l.items[0].lnum)
1619  call assert_equal('Line 20', l.items[0].text)
1620  set ignorecase&
1621
1622  new | only
1623  let &efm = save_efm
1624endfunc
1625
1626" Test for '%t' (error type) field in 'efm'
1627func Test_efm_error_type()
1628  let save_efm = &efm
1629
1630  " error type
1631  set efm=%f:%l:%t:%m
1632  let lines =<< trim END
1633    Xfile1:10:E:msg1
1634    Xfile1:20:W:msg2
1635    Xfile1:30:I:msg3
1636    Xfile1:40:N:msg4
1637    Xfile1:50:R:msg5
1638  END
1639  cexpr lines
1640  let output = split(execute('clist'), "\n")
1641  call assert_equal([
1642        \ ' 1 Xfile1:10 error: msg1',
1643        \ ' 2 Xfile1:20 warning: msg2',
1644        \ ' 3 Xfile1:30 info: msg3',
1645        \ ' 4 Xfile1:40 note: msg4',
1646        \ ' 5 Xfile1:50 R: msg5'], output)
1647
1648  " error type and a error number
1649  set efm=%f:%l:%t:%n:%m
1650  let lines =<< trim END
1651    Xfile1:10:E:2:msg1
1652    Xfile1:20:W:4:msg2
1653    Xfile1:30:I:6:msg3
1654    Xfile1:40:N:8:msg4
1655    Xfile1:50:R:3:msg5
1656  END
1657  cexpr lines
1658  let output = split(execute('clist'), "\n")
1659  call assert_equal([
1660        \ ' 1 Xfile1:10 error   2: msg1',
1661        \ ' 2 Xfile1:20 warning   4: msg2',
1662        \ ' 3 Xfile1:30 info   6: msg3',
1663        \ ' 4 Xfile1:40 note   8: msg4',
1664        \ ' 5 Xfile1:50 R   3: msg5'], output)
1665  let &efm = save_efm
1666endfunc
1667
1668" Test for end_lnum ('%e') and end_col ('%k') fields in 'efm'
1669func Test_efm_end_lnum_col()
1670  let save_efm = &efm
1671
1672  " single line
1673  set efm=%f:%l-%e:%c-%k:%t:%m
1674  cexpr ["Xfile1:10-20:1-2:E:msg1", "Xfile1:20-30:2-3:W:msg2",]
1675  let output = split(execute('clist'), "\n")
1676  call assert_equal([
1677        \ ' 1 Xfile1:10-20 col 1-2 error: msg1',
1678        \ ' 2 Xfile1:20-30 col 2-3 warning: msg2'], output)
1679
1680  " multiple lines
1681  set efm=%A%n)%m,%Z%f:%l-%e:%c-%k
1682  let lines =<< trim END
1683    1)msg1
1684    Xfile1:14-24:1-2
1685    2)msg2
1686    Xfile1:24-34:3-4
1687  END
1688  cexpr lines
1689  let output = split(execute('clist'), "\n")
1690  call assert_equal([
1691        \ ' 1 Xfile1:14-24 col 1-2 error   1: msg1',
1692        \ ' 2 Xfile1:24-34 col 3-4 error   2: msg2'], output)
1693  let &efm = save_efm
1694endfunc
1695
1696func XquickfixChangedByAutocmd(cchar)
1697  call s:setup_commands(a:cchar)
1698  if a:cchar == 'c'
1699    let ErrorNr = 'E925'
1700    func! ReadFunc()
1701      colder
1702      cgetexpr []
1703    endfunc
1704  else
1705    let ErrorNr = 'E926'
1706    func! ReadFunc()
1707      lolder
1708      lgetexpr []
1709    endfunc
1710  endif
1711
1712  augroup QF_Test
1713    au!
1714    autocmd BufReadCmd test_changed.txt call ReadFunc()
1715  augroup END
1716
1717  new | only
1718  let words = [ "a", "b" ]
1719  let qflist = []
1720  for word in words
1721    call add(qflist, {'filename': 'test_changed.txt'})
1722    call g:Xsetlist(qflist, ' ')
1723  endfor
1724  call assert_fails('Xrewind', ErrorNr . ':')
1725
1726  augroup QF_Test
1727    au!
1728  augroup END
1729
1730  if a:cchar == 'c'
1731    cexpr ["Xtest1:1:Line"]
1732    cwindow
1733    only
1734    augroup QF_Test
1735      au!
1736      autocmd WinEnter * call setqflist([], 'f')
1737    augroup END
1738    call assert_fails('exe "normal \<CR>"', 'E925:')
1739    augroup QF_Test
1740      au!
1741    augroup END
1742  endif
1743  %bw!
1744endfunc
1745
1746func Test_quickfix_was_changed_by_autocmd()
1747  call XquickfixChangedByAutocmd('c')
1748  call XquickfixChangedByAutocmd('l')
1749endfunc
1750
1751func Test_setloclist_in_autocommand()
1752  call writefile(['test1', 'test2'], 'Xfile')
1753  edit Xfile
1754  let s:bufnr = bufnr()
1755  call setloclist(1,
1756        \ [{'bufnr' : s:bufnr, 'lnum' : 1, 'text' : 'test1'},
1757        \  {'bufnr' : s:bufnr, 'lnum' : 2, 'text' : 'test2'}])
1758
1759  augroup Test_LocList
1760    au!
1761    autocmd BufEnter * call setloclist(1,
1762          \ [{'bufnr' : s:bufnr, 'lnum' : 1, 'text' : 'test1'},
1763          \  {'bufnr' : s:bufnr, 'lnum' : 2, 'text' : 'test2'}], 'r')
1764  augroup END
1765
1766  lopen
1767  call assert_fails('exe "normal j\<CR>"', 'E926:')
1768
1769  augroup Test_LocList
1770    au!
1771  augroup END
1772  call delete('Xfile')
1773endfunc
1774
1775func Test_caddbuffer_to_empty()
1776  helpgr quickfix
1777  call setqflist([], 'r')
1778  cad
1779  try
1780    cn
1781  catch
1782    " number of matches is unknown
1783    call assert_true(v:exception =~ 'E553:')
1784  endtry
1785  quit!
1786endfunc
1787
1788func Test_cgetexpr_works()
1789  " this must not crash Vim
1790  cgetexpr [$x]
1791  lgetexpr [$x]
1792endfunc
1793
1794" Tests for the setqflist() and setloclist() functions
1795func SetXlistTests(cchar, bnum)
1796  call s:setup_commands(a:cchar)
1797
1798  call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 1},
1799        \  {'bufnr': a:bnum, 'lnum': 2, 'end_lnum': 3, 'col': 4, 'end_col': 5, 'user_data': {'6': [7, 8]}}])
1800  let l = g:Xgetlist()
1801  call assert_equal(2, len(l))
1802  call assert_equal(2, l[1].lnum)
1803  call assert_equal(3, l[1].end_lnum)
1804  call assert_equal(4, l[1].col)
1805  call assert_equal(5, l[1].end_col)
1806  call assert_equal({'6': [7, 8]}, l[1].user_data)
1807
1808  " Test that user_data is garbage collected
1809  call g:Xsetlist([{'user_data': ['high', 5]},
1810        \  {'user_data': {'this': [7, 'eight'], 'is': ['a', 'dictionary']}}])
1811  call test_garbagecollect_now()
1812  let l = g:Xgetlist()
1813  call assert_equal(2, len(l))
1814  call assert_equal(['high', 5], l[0].user_data)
1815  call assert_equal({'this': [7, 'eight'], 'is': ['a', 'dictionary']}, l[1].user_data)
1816
1817  Xnext
1818  call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 3}], 'a')
1819  let l = g:Xgetlist()
1820  call assert_equal(3, len(l))
1821  Xnext
1822  call assert_equal(3, line('.'))
1823
1824  " Appending entries to the list should not change the cursor position
1825  " in the quickfix window
1826  Xwindow
1827  1
1828  call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 4},
1829	      \  {'bufnr': a:bnum, 'lnum': 5}], 'a')
1830  call assert_equal(1, line('.'))
1831  close
1832
1833  call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 3},
1834	      \  {'bufnr': a:bnum, 'lnum': 4},
1835	      \  {'bufnr': a:bnum, 'lnum': 5}], 'r')
1836  let l = g:Xgetlist()
1837  call assert_equal(3, len(l))
1838  call assert_equal(5, l[2].lnum)
1839
1840  call g:Xsetlist([])
1841  let l = g:Xgetlist()
1842  call assert_equal(0, len(l))
1843
1844  " Tests for setting the 'valid' flag
1845  call g:Xsetlist([{'bufnr':a:bnum, 'lnum':4, 'valid':0}])
1846  Xwindow
1847  call assert_equal(1, winnr('$'))
1848  let l = g:Xgetlist()
1849  call g:Xsetlist(l)
1850  call assert_equal(0, g:Xgetlist()[0].valid)
1851  " Adding a non-valid entry should not mark the list as having valid entries
1852  call g:Xsetlist([{'bufnr':a:bnum, 'lnum':5, 'valid':0}], 'a')
1853  Xwindow
1854  call assert_equal(1, winnr('$'))
1855
1856  " :cnext/:cprev should still work even with invalid entries in the list
1857  let l = [{'bufnr' : a:bnum, 'lnum' : 1, 'text' : '1', 'valid' : 0},
1858	      \ {'bufnr' : a:bnum, 'lnum' : 2, 'text' : '2', 'valid' : 0}]
1859  call g:Xsetlist(l)
1860  Xnext
1861  call assert_equal(2, g:Xgetlist({'idx' : 0}).idx)
1862  Xprev
1863  call assert_equal(1, g:Xgetlist({'idx' : 0}).idx)
1864  " :cnext/:cprev should still work after appending invalid entries to an
1865  " empty list
1866  call g:Xsetlist([])
1867  call g:Xsetlist(l, 'a')
1868  Xnext
1869  call assert_equal(2, g:Xgetlist({'idx' : 0}).idx)
1870  Xprev
1871  call assert_equal(1, g:Xgetlist({'idx' : 0}).idx)
1872
1873  call g:Xsetlist([{'text':'Text1', 'valid':1}])
1874  Xwindow
1875  call assert_equal(2, winnr('$'))
1876  Xclose
1877  let save_efm = &efm
1878  set efm=%m
1879  Xgetexpr 'TestMessage'
1880  let l = g:Xgetlist()
1881  call g:Xsetlist(l)
1882  call assert_equal(1, g:Xgetlist()[0].valid)
1883  let &efm = save_efm
1884
1885  " Error cases:
1886  " Refer to a non-existing buffer and pass a non-dictionary type
1887  call assert_fails("call g:Xsetlist([{'bufnr':998, 'lnum':4}," .
1888	      \ " {'bufnr':999, 'lnum':5}])", 'E92:')
1889  call g:Xsetlist([[1, 2,3]])
1890  call assert_equal(0, len(g:Xgetlist()))
1891  call assert_fails('call g:Xsetlist([], [])', 'E928:')
1892  call g:Xsetlist([v:_null_dict])
1893  call assert_equal([], g:Xgetlist())
1894endfunc
1895
1896func Test_setqflist()
1897  new Xtestfile | only
1898  let bnum = bufnr('%')
1899  call setline(1, range(1,5))
1900
1901  call SetXlistTests('c', bnum)
1902  call SetXlistTests('l', bnum)
1903
1904  enew!
1905  call delete('Xtestfile')
1906endfunc
1907
1908func Xlist_empty_middle(cchar)
1909  call s:setup_commands(a:cchar)
1910
1911  " create three quickfix lists
1912  let @/ = 'Test_'
1913  Xvimgrep // test_quickfix.vim
1914  let testlen = len(g:Xgetlist())
1915  call assert_true(testlen > 0)
1916  Xvimgrep empty test_quickfix.vim
1917  call assert_true(len(g:Xgetlist()) > 0)
1918  Xvimgrep matches test_quickfix.vim
1919  let matchlen = len(g:Xgetlist())
1920  call assert_true(matchlen > 0)
1921  Xolder
1922  " make the middle list empty
1923  call g:Xsetlist([], 'r')
1924  call assert_true(len(g:Xgetlist()) == 0)
1925  Xolder
1926  call assert_equal(testlen, len(g:Xgetlist()))
1927  Xnewer
1928  Xnewer
1929  call assert_equal(matchlen, len(g:Xgetlist()))
1930endfunc
1931
1932func Test_setqflist_empty_middle()
1933  call Xlist_empty_middle('c')
1934  call Xlist_empty_middle('l')
1935endfunc
1936
1937func Xlist_empty_older(cchar)
1938  call s:setup_commands(a:cchar)
1939
1940  " create three quickfix lists
1941  Xvimgrep one test_quickfix.vim
1942  let onelen = len(g:Xgetlist())
1943  call assert_true(onelen > 0)
1944  Xvimgrep two test_quickfix.vim
1945  let twolen = len(g:Xgetlist())
1946  call assert_true(twolen > 0)
1947  Xvimgrep three test_quickfix.vim
1948  let threelen = len(g:Xgetlist())
1949  call assert_true(threelen > 0)
1950  Xolder 2
1951  " make the first list empty, check the others didn't change
1952  call g:Xsetlist([], 'r')
1953  call assert_true(len(g:Xgetlist()) == 0)
1954  Xnewer
1955  call assert_equal(twolen, len(g:Xgetlist()))
1956  Xnewer
1957  call assert_equal(threelen, len(g:Xgetlist()))
1958endfunc
1959
1960func Test_setqflist_empty_older()
1961  call Xlist_empty_older('c')
1962  call Xlist_empty_older('l')
1963endfunc
1964
1965func XquickfixSetListWithAct(cchar)
1966  call s:setup_commands(a:cchar)
1967
1968  let list1 = [{'filename': 'fnameA', 'text': 'A'},
1969          \    {'filename': 'fnameB', 'text': 'B'}]
1970  let list2 = [{'filename': 'fnameC', 'text': 'C'},
1971          \    {'filename': 'fnameD', 'text': 'D'},
1972          \    {'filename': 'fnameE', 'text': 'E'}]
1973
1974  " {action} is unspecified.  Same as specifying ' '.
1975  new | only
1976  silent! Xnewer 99
1977  call g:Xsetlist(list1)
1978  call g:Xsetlist(list2)
1979  let li = g:Xgetlist()
1980  call assert_equal(3, len(li))
1981  call assert_equal('C', li[0]['text'])
1982  call assert_equal('D', li[1]['text'])
1983  call assert_equal('E', li[2]['text'])
1984  silent! Xolder
1985  let li = g:Xgetlist()
1986  call assert_equal(2, len(li))
1987  call assert_equal('A', li[0]['text'])
1988  call assert_equal('B', li[1]['text'])
1989
1990  " {action} is specified ' '.
1991  new | only
1992  silent! Xnewer 99
1993  call g:Xsetlist(list1)
1994  call g:Xsetlist(list2, ' ')
1995  let li = g:Xgetlist()
1996  call assert_equal(3, len(li))
1997  call assert_equal('C', li[0]['text'])
1998  call assert_equal('D', li[1]['text'])
1999  call assert_equal('E', li[2]['text'])
2000  silent! Xolder
2001  let li = g:Xgetlist()
2002  call assert_equal(2, len(li))
2003  call assert_equal('A', li[0]['text'])
2004  call assert_equal('B', li[1]['text'])
2005
2006  " {action} is specified 'a'.
2007  new | only
2008  silent! Xnewer 99
2009  call g:Xsetlist(list1)
2010  call g:Xsetlist(list2, 'a')
2011  let li = g:Xgetlist()
2012  call assert_equal(5, len(li))
2013  call assert_equal('A', li[0]['text'])
2014  call assert_equal('B', li[1]['text'])
2015  call assert_equal('C', li[2]['text'])
2016  call assert_equal('D', li[3]['text'])
2017  call assert_equal('E', li[4]['text'])
2018
2019  " {action} is specified 'r'.
2020  new | only
2021  silent! Xnewer 99
2022  call g:Xsetlist(list1)
2023  call g:Xsetlist(list2, 'r')
2024  let li = g:Xgetlist()
2025  call assert_equal(3, len(li))
2026  call assert_equal('C', li[0]['text'])
2027  call assert_equal('D', li[1]['text'])
2028  call assert_equal('E', li[2]['text'])
2029
2030  " Test for wrong value.
2031  new | only
2032  call assert_fails("call g:Xsetlist(0)", 'E714:')
2033  call assert_fails("call g:Xsetlist(list1, '')", 'E927:')
2034  call assert_fails("call g:Xsetlist(list1, 'aa')", 'E927:')
2035  call assert_fails("call g:Xsetlist(list1, ' a')", 'E927:')
2036  call assert_fails("call g:Xsetlist(list1, 0)", 'E928:')
2037endfunc
2038
2039func Test_setqflist_invalid_nr()
2040  " The following command used to crash Vim
2041  eval []->setqflist(' ', {'nr' : $XXX_DOES_NOT_EXIST})
2042endfunc
2043
2044func Test_setqflist_user_sets_buftype()
2045  call setqflist([{'text': 'foo'}, {'text': 'bar'}])
2046  set buftype=quickfix
2047  call setqflist([], 'a')
2048  enew
2049endfunc
2050
2051func Test_quickfix_set_list_with_act()
2052  call XquickfixSetListWithAct('c')
2053  call XquickfixSetListWithAct('l')
2054endfunc
2055
2056func XLongLinesTests(cchar)
2057  let l = g:Xgetlist()
2058
2059  call assert_equal(4, len(l))
2060  call assert_equal(1, l[0].lnum)
2061  call assert_equal(1, l[0].col)
2062  call assert_equal(1975, len(l[0].text))
2063  call assert_equal(2, l[1].lnum)
2064  call assert_equal(1, l[1].col)
2065  call assert_equal(4070, len(l[1].text))
2066  call assert_equal(3, l[2].lnum)
2067  call assert_equal(1, l[2].col)
2068  call assert_equal(4070, len(l[2].text))
2069  call assert_equal(4, l[3].lnum)
2070  call assert_equal(1, l[3].col)
2071  call assert_equal(10, len(l[3].text))
2072
2073  call g:Xsetlist([], 'r')
2074endfunc
2075
2076func s:long_lines_tests(cchar)
2077  call s:setup_commands(a:cchar)
2078
2079  let testfile = 'samples/quickfix.txt'
2080
2081  " file
2082  exe 'Xgetfile' testfile
2083  call XLongLinesTests(a:cchar)
2084
2085  " list
2086  Xexpr readfile(testfile)
2087  call XLongLinesTests(a:cchar)
2088
2089  " string
2090  Xexpr join(readfile(testfile), "\n")
2091  call XLongLinesTests(a:cchar)
2092
2093  " buffer
2094  exe 'edit' testfile
2095  exe 'Xbuffer' bufnr('%')
2096  call XLongLinesTests(a:cchar)
2097endfunc
2098
2099func Test_long_lines()
2100  call s:long_lines_tests('c')
2101  call s:long_lines_tests('l')
2102endfunc
2103
2104func Test_cgetfile_on_long_lines()
2105  " Problematic values if the line is longer than 4096 bytes.  Then 1024 bytes
2106  " are read at a time.
2107  for len in [4078, 4079, 4080, 5102, 5103, 5104, 6126, 6127, 6128, 7150, 7151, 7152]
2108    let lines =<< trim END
2109      /tmp/file1:1:1:aaa
2110      /tmp/file2:1:1:%s
2111      /tmp/file3:1:1:bbb
2112      /tmp/file4:1:1:ccc
2113    END
2114    let lines[1] = substitute(lines[1], '%s', repeat('x', len), '')
2115    call writefile(lines, 'Xcqetfile.txt')
2116    cgetfile Xcqetfile.txt
2117    call assert_equal(4, getqflist(#{size: v:true}).size, 'with length ' .. len)
2118  endfor
2119  call delete('Xcqetfile.txt')
2120endfunc
2121
2122func s:create_test_file(filename)
2123  let l = []
2124  for i in range(1, 20)
2125      call add(l, 'Line' . i)
2126  endfor
2127  call writefile(l, a:filename)
2128endfunc
2129
2130func Test_switchbuf()
2131  call s:create_test_file('Xqftestfile1')
2132  call s:create_test_file('Xqftestfile2')
2133  call s:create_test_file('Xqftestfile3')
2134
2135  new | only
2136  edit Xqftestfile1
2137  let file1_winid = win_getid()
2138  new Xqftestfile2
2139  let file2_winid = win_getid()
2140  let lines =<< trim END
2141    Xqftestfile1:5:Line5
2142    Xqftestfile1:6:Line6
2143    Xqftestfile2:10:Line10
2144    Xqftestfile2:11:Line11
2145    Xqftestfile3:15:Line15
2146    Xqftestfile3:16:Line16
2147  END
2148  cgetexpr lines
2149
2150  new
2151  let winid = win_getid()
2152  cfirst | cnext
2153  call assert_equal(winid, win_getid())
2154  2cnext
2155  call assert_equal(winid, win_getid())
2156  2cnext
2157  call assert_equal(winid, win_getid())
2158
2159  " Test for 'switchbuf' set to search for files in windows in the current
2160  " tabpage and jump to an existing window (if present)
2161  set switchbuf=useopen
2162  enew
2163  cfirst | cnext
2164  call assert_equal(file1_winid, win_getid())
2165  2cnext
2166  call assert_equal(file2_winid, win_getid())
2167  2cnext
2168  call assert_equal(file2_winid, win_getid())
2169
2170  " Test for 'switchbuf' set to search for files in tabpages and jump to an
2171  " existing tabpage (if present)
2172  enew | only
2173  set switchbuf=usetab
2174  tabedit Xqftestfile1
2175  tabedit Xqftestfile2
2176  tabedit Xqftestfile3
2177  tabfirst
2178  cfirst | cnext
2179  call assert_equal(2, tabpagenr())
2180  2cnext
2181  call assert_equal(3, tabpagenr())
2182  6cnext
2183  call assert_equal(4, tabpagenr())
2184  2cpfile
2185  call assert_equal(2, tabpagenr())
2186  2cnfile
2187  call assert_equal(4, tabpagenr())
2188  tabfirst | tabonly | enew
2189
2190  " Test for 'switchbuf' set to open a new window for every file
2191  set switchbuf=split
2192  cfirst | cnext
2193  call assert_equal(1, winnr('$'))
2194  cnext | cnext
2195  call assert_equal(2, winnr('$'))
2196  cnext | cnext
2197  call assert_equal(3, winnr('$'))
2198
2199  " Test for 'switchbuf' set to open a new tabpage for every file
2200  set switchbuf=newtab
2201  enew | only
2202  cfirst | cnext
2203  call assert_equal(1, tabpagenr('$'))
2204  cnext | cnext
2205  call assert_equal(2, tabpagenr('$'))
2206  cnext | cnext
2207  call assert_equal(3, tabpagenr('$'))
2208  tabfirst | enew | tabonly | only
2209
2210  set switchbuf=uselast
2211  split
2212  let last_winid = win_getid()
2213  copen
2214  exe "normal 1G\<CR>"
2215  call assert_equal(last_winid, win_getid())
2216  enew | only
2217
2218  " With an empty 'switchbuf', jumping to a quickfix entry should open the
2219  " file in an existing window (if present)
2220  set switchbuf=
2221  edit Xqftestfile1
2222  let file1_winid = win_getid()
2223  new Xqftestfile2
2224  let file2_winid = win_getid()
2225  copen
2226  exe "normal 1G\<CR>"
2227  call assert_equal(file1_winid, win_getid())
2228  copen
2229  exe "normal 3G\<CR>"
2230  call assert_equal(file2_winid, win_getid())
2231  copen | only
2232  exe "normal 5G\<CR>"
2233  call assert_equal(2, winnr('$'))
2234  call assert_equal(1, bufwinnr('Xqftestfile3'))
2235
2236  " If only quickfix window is open in the current tabpage, jumping to an
2237  " entry with 'switchbuf' set to 'usetab' should search in other tabpages.
2238  enew | only
2239  set switchbuf=usetab
2240  tabedit Xqftestfile1
2241  tabedit Xqftestfile2
2242  tabedit Xqftestfile3
2243  tabfirst
2244  copen | only
2245  clast
2246  call assert_equal(4, tabpagenr())
2247  tabfirst | tabonly | enew | only
2248
2249  " Jumping to a file that is not present in any of the tabpages and the
2250  " current tabpage doesn't have any usable windows, should open it in a new
2251  " window in the current tabpage.
2252  copen | only
2253  cfirst
2254  call assert_equal(1, tabpagenr())
2255  call assert_equal('Xqftestfile1', @%)
2256
2257  " If opening a file changes 'switchbuf', then the new value should be
2258  " retained.
2259  set modeline&vim
2260  call writefile(["vim: switchbuf=split"], 'Xqftestfile1')
2261  enew | only
2262  set switchbuf&vim
2263  cexpr "Xqftestfile1:1:10"
2264  call assert_equal('split', &switchbuf)
2265  call writefile(["vim: switchbuf=usetab"], 'Xqftestfile1')
2266  enew | only
2267  set switchbuf=useopen
2268  cexpr "Xqftestfile1:1:10"
2269  call assert_equal('usetab', &switchbuf)
2270  call writefile(["vim: switchbuf&vim"], 'Xqftestfile1')
2271  enew | only
2272  set switchbuf=useopen
2273  cexpr "Xqftestfile1:1:10"
2274  call assert_equal('uselast', &switchbuf)
2275
2276  call delete('Xqftestfile1')
2277  call delete('Xqftestfile2')
2278  call delete('Xqftestfile3')
2279  set switchbuf&vim
2280
2281  enew | only
2282endfunc
2283
2284func Xadjust_qflnum(cchar)
2285  call s:setup_commands(a:cchar)
2286
2287  enew | only
2288
2289  let fname = 'Xqftestfile' . a:cchar
2290  call s:create_test_file(fname)
2291  exe 'edit ' . fname
2292
2293  Xgetexpr [fname . ':5:Line5',
2294	      \ fname . ':10:Line10',
2295	      \ fname . ':15:Line15',
2296	      \ fname . ':20:Line20']
2297
2298  6,14delete
2299  call append(6, ['Buffer', 'Window'])
2300
2301  let l = g:Xgetlist()
2302  call assert_equal(5, l[0].lnum)
2303  call assert_equal(6, l[2].lnum)
2304  call assert_equal(13, l[3].lnum)
2305
2306  " If a file doesn't have any quickfix entries, then deleting lines in the
2307  " file should not update the quickfix list
2308  call g:Xsetlist([], 'f')
2309  1,2delete
2310  call assert_equal([], g:Xgetlist())
2311
2312  enew!
2313  call delete(fname)
2314endfunc
2315
2316func Test_adjust_lnum()
2317  call setloclist(0, [])
2318  call Xadjust_qflnum('c')
2319  call setqflist([])
2320  call Xadjust_qflnum('l')
2321endfunc
2322
2323func Xqf_undo_after_delete(cchar)
2324  call s:setup_commands(a:cchar)
2325
2326  enew | only
2327
2328  let fname = 'Xqfundofile' . a:cchar
2329  call s:create_test_file(fname)
2330  exe 'edit ' . fname
2331
2332  Xgetexpr [fname . ':5:Line5',
2333	      \ fname . ':10:Line10',
2334	      \ fname . ':15:Line15']
2335
2336  " Delete the line of the second error and undo the deletion.
2337  10delete
2338  let l = g:Xgetlist()
2339  call assert_equal(5, l[0].lnum)
2340  call assert_equal(10, l[1].lnum)
2341  call assert_equal(14, l[2].lnum)
2342
2343  undo
2344  call assert_equal('Line10', getline(10))
2345  let l = g:Xgetlist()
2346  call assert_equal(5, l[0].lnum)
2347  call assert_equal(10, l[1].lnum)
2348  call assert_equal(15, l[2].lnum)
2349
2350  " Redo and undo again to make sure the line number does not drift.
2351  redo
2352  call assert_equal(14, g:Xgetlist()[2].lnum)
2353  undo
2354  let l = g:Xgetlist()
2355  call assert_equal(10, l[1].lnum)
2356  call assert_equal(15, l[2].lnum)
2357
2358  call g:Xsetlist([], 'f')
2359  enew!
2360  call delete(fname)
2361endfunc
2362
2363func Test_qf_undo_after_delete()
2364  call setloclist(0, [])
2365  call Xqf_undo_after_delete('c')
2366  call setqflist([])
2367  call Xqf_undo_after_delete('l')
2368endfunc
2369
2370" Tests for the :grep/:lgrep and :grepadd/:lgrepadd commands
2371func s:test_xgrep(cchar)
2372  call s:setup_commands(a:cchar)
2373
2374  " The following lines are used for the grep test. Don't remove.
2375  " Grep_Test_Text: Match 1
2376  " Grep_Test_Text: Match 2
2377  " GrepAdd_Test_Text: Match 1
2378  " GrepAdd_Test_Text: Match 2
2379  enew! | only
2380  set makeef&vim
2381  silent Xgrep Grep_Test_Text: test_quickfix.vim
2382  call assert_true(len(g:Xgetlist()) == 5)
2383  Xopen
2384  call assert_true(w:quickfix_title =~ '^:grep')
2385  Xclose
2386  enew
2387  set makeef=Temp_File_##
2388  silent Xgrepadd GrepAdd_Test_Text: test_quickfix.vim
2389  call assert_true(len(g:Xgetlist()) == 9)
2390
2391  " Try with 'grepprg' set to 'internal'
2392  set grepprg=internal
2393  silent Xgrep Grep_Test_Text: test_quickfix.vim
2394  silent Xgrepadd GrepAdd_Test_Text: test_quickfix.vim
2395  call assert_true(len(g:Xgetlist()) == 9)
2396  set grepprg&vim
2397
2398  call writefile(['Vim'], 'XtestTempFile')
2399  set makeef=XtestTempFile
2400  silent Xgrep Grep_Test_Text: test_quickfix.vim
2401  call assert_equal(5, len(g:Xgetlist()))
2402  call assert_false(filereadable('XtestTempFile'))
2403  set makeef&vim
2404endfunc
2405
2406func Test_grep()
2407  " The grepprg may not be set on non-Unix systems
2408  CheckUnix
2409
2410  call s:test_xgrep('c')
2411  call s:test_xgrep('l')
2412endfunc
2413
2414func Test_local_grepformat()
2415  let save_grepformat = &grepformat
2416  set grepformat=%f:%l:%m
2417  " The following line are used for the local grep test. Don't remove.
2418  " UNIQUEPREFIX:2:3: Local grepformat test
2419  new
2420  setlocal grepformat=UNIQUEPREFIX:%c:%n:%m
2421  call assert_equal('UNIQUEPREFIX:%c:%n:%m', &l:grepformat)
2422  call assert_equal('%f:%l:%m', &g:grepformat)
2423
2424  set grepprg=internal
2425  silent grep "^[[:space:]]*\" UNIQUEPREFIX:" test_quickfix.vim
2426  call assert_equal(1, len(getqflist()))
2427  set grepprg&vim
2428
2429  bwipe!
2430  let &grepformat = save_grepformat
2431endfunc
2432
2433func Test_two_windows()
2434  " Use one 'errorformat' for two windows.  Add an expression to each of them,
2435  " make sure they each keep their own state.
2436  set efm=%DEntering\ dir\ '%f',%f:%l:%m,%XLeaving\ dir\ '%f'
2437  call mkdir('Xone/a', 'p')
2438  call mkdir('Xtwo/a', 'p')
2439  let lines = ['1', '2', 'one one one', '4', 'two two two', '6', '7']
2440  call writefile(lines, 'Xone/a/one.txt')
2441  call writefile(lines, 'Xtwo/a/two.txt')
2442
2443  new one
2444  let one_id = win_getid()
2445  lexpr ""
2446  new two
2447  let two_id = win_getid()
2448  lexpr ""
2449
2450  laddexpr "Entering dir 'Xtwo/a'"
2451  call win_gotoid(one_id)
2452  laddexpr "Entering dir 'Xone/a'"
2453  call win_gotoid(two_id)
2454  laddexpr 'two.txt:5:two two two'
2455  call win_gotoid(one_id)
2456  laddexpr 'one.txt:3:one one one'
2457
2458  let loc_one = getloclist(one_id)
2459  call assert_equal('Xone/a/one.txt', bufname(loc_one[1].bufnr))
2460  call assert_equal(3, loc_one[1].lnum)
2461
2462  let loc_two = getloclist(two_id)
2463  call assert_equal('Xtwo/a/two.txt', bufname(loc_two[1].bufnr))
2464  call assert_equal(5, loc_two[1].lnum)
2465
2466  call win_gotoid(one_id)
2467  bwipe!
2468  call win_gotoid(two_id)
2469  bwipe!
2470  call delete('Xone', 'rf')
2471  call delete('Xtwo', 'rf')
2472endfunc
2473
2474func XbottomTests(cchar)
2475  call s:setup_commands(a:cchar)
2476
2477  " Calling lbottom without any errors should fail
2478  if a:cchar == 'l'
2479      call assert_fails('lbottom', 'E776:')
2480  endif
2481
2482  call g:Xsetlist([{'filename': 'foo', 'lnum': 42}])
2483  Xopen
2484  let wid = win_getid()
2485  call assert_equal(1, line('.'))
2486  wincmd w
2487  call g:Xsetlist([{'filename': 'var', 'lnum': 24}], 'a')
2488  Xbottom
2489  call win_gotoid(wid)
2490  call assert_equal(2, line('.'))
2491  Xclose
2492endfunc
2493
2494" Tests for the :cbottom and :lbottom commands
2495func Test_cbottom()
2496  call XbottomTests('c')
2497  call XbottomTests('l')
2498endfunc
2499
2500func HistoryTest(cchar)
2501  call s:setup_commands(a:cchar)
2502
2503  " clear all lists after the first one, then replace the first one.
2504  call g:Xsetlist([])
2505  call assert_fails('Xolder 99', 'E380:')
2506  let entry = {'filename': 'foo', 'lnum': 42}
2507  call g:Xsetlist([entry], 'r')
2508  call g:Xsetlist([entry, entry])
2509  call g:Xsetlist([entry, entry, entry])
2510  let res = split(execute(a:cchar . 'hist'), "\n")
2511  call assert_equal(3, len(res))
2512  let common = 'errors     :set' . (a:cchar == 'c' ? 'qf' : 'loc') . 'list()'
2513  call assert_equal('  error list 1 of 3; 1 ' . common, res[0])
2514  call assert_equal('  error list 2 of 3; 2 ' . common, res[1])
2515  call assert_equal('> error list 3 of 3; 3 ' . common, res[2])
2516
2517  " Test for changing the quickfix lists
2518  call assert_equal(3, g:Xgetlist({'nr' : 0}).nr)
2519  exe '1' . a:cchar . 'hist'
2520  call assert_equal(1, g:Xgetlist({'nr' : 0}).nr)
2521  exe '3' . a:cchar . 'hist'
2522  call assert_equal(3, g:Xgetlist({'nr' : 0}).nr)
2523  call assert_fails('-2' . a:cchar . 'hist', 'E16:')
2524  call assert_fails('4' . a:cchar . 'hist', 'E16:')
2525
2526  call g:Xsetlist([], 'f')
2527  let l = split(execute(a:cchar . 'hist'), "\n")
2528  call assert_equal('No entries', l[0])
2529  if a:cchar == 'c'
2530    call assert_fails('4chist', 'E16:')
2531  else
2532    call assert_fails('4lhist', 'E776:')
2533  endif
2534
2535  " An empty list should still show the stack history
2536  call g:Xsetlist([])
2537  let res = split(execute(a:cchar . 'hist'), "\n")
2538  call assert_equal('> error list 1 of 1; 0 ' . common, res[0])
2539
2540  call g:Xsetlist([], 'f')
2541endfunc
2542
2543func Test_history()
2544  call HistoryTest('c')
2545  call HistoryTest('l')
2546endfunc
2547
2548func Test_duplicate_buf()
2549  " make sure we can get the highest buffer number
2550  edit DoesNotExist
2551  edit DoesNotExist2
2552  let last_buffer = bufnr("$")
2553
2554  " make sure only one buffer is created
2555  call writefile(['this one', 'that one'], 'Xgrepthis')
2556  vimgrep one Xgrepthis
2557  vimgrep one Xgrepthis
2558  call assert_equal(last_buffer + 1, bufnr("$"))
2559
2560  call delete('Xgrepthis')
2561endfunc
2562
2563" Quickfix/Location list set/get properties tests
2564func Xproperty_tests(cchar)
2565  call s:setup_commands(a:cchar)
2566
2567  " Error cases
2568  call assert_fails('call g:Xgetlist(99)', 'E715:')
2569  call assert_fails('call g:Xsetlist(99)', 'E714:')
2570  call assert_fails('call g:Xsetlist([], "a", [])', 'E715:')
2571
2572  " Set and get the title
2573  call g:Xsetlist([])
2574  Xopen
2575  wincmd p
2576  call g:Xsetlist([{'filename':'foo', 'lnum':27}])
2577  let s = g:Xsetlist([], 'a', {'title' : 'Sample'})
2578  call assert_equal(0, s)
2579  let d = g:Xgetlist({"title":1})
2580  call assert_equal('Sample', d.title)
2581  " Try setting title to a non-string value
2582  call assert_equal(-1, g:Xsetlist([], 'a', {'title' : ['Test']}))
2583  call assert_equal('Sample', g:Xgetlist({"title":1}).title)
2584
2585  Xopen
2586  call assert_equal('Sample', w:quickfix_title)
2587  Xclose
2588
2589  " Tests for action argument
2590  silent! Xolder 999
2591  let qfnr = g:Xgetlist({'all':1}).nr
2592  call g:Xsetlist([], 'r', {'title' : 'N1'})
2593  call assert_equal('N1', g:Xgetlist({'all':1}).title)
2594  call g:Xsetlist([], ' ', {'title' : 'N2'})
2595  call assert_equal(qfnr + 1, g:Xgetlist({'all':1}).nr)
2596
2597  let res = g:Xgetlist({'nr': 0})
2598  call assert_equal(qfnr + 1, res.nr)
2599  call assert_equal(['nr'], keys(res))
2600
2601  call g:Xsetlist([], ' ', {'title' : 'N3'})
2602  call assert_equal('N2', g:Xgetlist({'nr':2, 'title':1}).title)
2603
2604  " Changing the title of an earlier quickfix list
2605  call g:Xsetlist([], 'r', {'title' : 'NewTitle', 'nr' : 2})
2606  call assert_equal('NewTitle', g:Xgetlist({'nr':2, 'title':1}).title)
2607
2608  " Changing the title of an invalid quickfix list
2609  call assert_equal(-1, g:Xsetlist([], ' ',
2610        \ {'title' : 'SomeTitle', 'nr' : 99}))
2611  call assert_equal(-1, g:Xsetlist([], ' ',
2612        \ {'title' : 'SomeTitle', 'nr' : 'abc'}))
2613
2614  if a:cchar == 'c'
2615    copen
2616    call assert_equal({'winid':win_getid()}, getqflist({'winid':1}))
2617    cclose
2618  endif
2619
2620  " Invalid arguments
2621  call assert_fails('call g:Xgetlist([])', 'E715')
2622  call assert_fails('call g:Xsetlist([], "a", [])', 'E715')
2623  let s = g:Xsetlist([], 'a', {'abc':1})
2624  call assert_equal(-1, s)
2625
2626  call assert_equal({}, g:Xgetlist({'abc':1}))
2627  call assert_equal('', g:Xgetlist({'nr':99, 'title':1}).title)
2628  call assert_equal('', g:Xgetlist({'nr':[], 'title':1}).title)
2629
2630  if a:cchar == 'l'
2631    call assert_equal({}, getloclist(99, {'title': 1}))
2632  endif
2633
2634  " Context related tests
2635  let s = g:Xsetlist([], 'a', {'context':[1,2,3]})
2636  call assert_equal(0, s)
2637  call test_garbagecollect_now()
2638  let d = g:Xgetlist({'context':1})
2639  call assert_equal([1,2,3], d.context)
2640  call g:Xsetlist([], 'a', {'context':{'color':'green'}})
2641  let d = g:Xgetlist({'context':1})
2642  call assert_equal({'color':'green'}, d.context)
2643  call g:Xsetlist([], 'a', {'context':"Context info"})
2644  let d = g:Xgetlist({'context':1})
2645  call assert_equal("Context info", d.context)
2646  call g:Xsetlist([], 'a', {'context':246})
2647  let d = g:Xgetlist({'context':1})
2648  call assert_equal(246, d.context)
2649  " set other Vim data types as context
2650  call g:Xsetlist([], 'a', {'context' : v:_null_blob})
2651  if has('channel')
2652    call g:Xsetlist([], 'a', {'context' : test_null_channel()})
2653  endif
2654  if has('job')
2655    call g:Xsetlist([], 'a', {'context' : test_null_job()})
2656  endif
2657  " Nvim doesn't have null functions
2658  " call g:Xsetlist([], 'a', {'context' : test_null_function()})
2659  " Nvim doesn't have null partials
2660  " call g:Xsetlist([], 'a', {'context' : test_null_partial()})
2661  call g:Xsetlist([], 'a', {'context' : ''})
2662  call test_garbagecollect_now()
2663  if a:cchar == 'l'
2664    " Test for copying context across two different location lists
2665    new | only
2666    let w1_id = win_getid()
2667    let l = [1]
2668    call setloclist(0, [], 'a', {'context':l})
2669    new
2670    let w2_id = win_getid()
2671    call add(l, 2)
2672    call assert_equal([1, 2], getloclist(w1_id, {'context':1}).context)
2673    call assert_equal([1, 2], getloclist(w2_id, {'context':1}).context)
2674    unlet! l
2675    call assert_equal([1, 2], getloclist(w2_id, {'context':1}).context)
2676    only
2677    call setloclist(0, [], 'f')
2678    call assert_equal('', getloclist(0, {'context':1}).context)
2679  endif
2680
2681  " Test for changing the context of previous quickfix lists
2682  call g:Xsetlist([], 'f')
2683  Xexpr "One"
2684  Xexpr "Two"
2685  Xexpr "Three"
2686  call g:Xsetlist([], 'r', {'context' : [1], 'nr' : 1})
2687  call g:Xsetlist([], 'a', {'context' : [2], 'nr' : 2})
2688  " Also, check for setting the context using quickfix list number zero.
2689  call g:Xsetlist([], 'r', {'context' : [3], 'nr' : 0})
2690  call test_garbagecollect_now()
2691  let l = g:Xgetlist({'nr' : 1, 'context' : 1})
2692  call assert_equal([1], l.context)
2693  let l = g:Xgetlist({'nr' : 2, 'context' : 1})
2694  call assert_equal([2], l.context)
2695  let l = g:Xgetlist({'nr' : 3, 'context' : 1})
2696  call assert_equal([3], l.context)
2697
2698  " Test for changing the context through reference and for garbage
2699  " collection of quickfix context
2700  let l = ["red"]
2701  call g:Xsetlist([], ' ', {'context' : l})
2702  call add(l, "blue")
2703  let x = g:Xgetlist({'context' : 1})
2704  call add(x.context, "green")
2705  call assert_equal(["red", "blue", "green"], l)
2706  call assert_equal(["red", "blue", "green"], x.context)
2707  unlet l
2708  call test_garbagecollect_now()
2709  let m = g:Xgetlist({'context' : 1})
2710  call assert_equal(["red", "blue", "green"], m.context)
2711
2712  " Test for setting/getting items
2713  Xexpr ""
2714  let qfprev = g:Xgetlist({'nr':0})
2715  let s = g:Xsetlist([], ' ', {'title':'Green',
2716        \ 'items' : [{'filename':'F1', 'lnum':10}]})
2717  call assert_equal(0, s)
2718  let qfcur = g:Xgetlist({'nr':0})
2719  call assert_true(qfcur.nr == qfprev.nr + 1)
2720  let l = g:Xgetlist({'items':1})
2721  call assert_equal('F1', bufname(l.items[0].bufnr))
2722  call assert_equal(10, l.items[0].lnum)
2723  call g:Xsetlist([], 'a', {'items' : [{'filename':'F2', 'lnum':20},
2724        \  {'filename':'F2', 'lnum':30}]})
2725  let l = g:Xgetlist({'items':1})
2726  call assert_equal('F2', bufname(l.items[2].bufnr))
2727  call assert_equal(30, l.items[2].lnum)
2728  call g:Xsetlist([], 'r', {'items' : [{'filename':'F3', 'lnum':40}]})
2729  let l = g:Xgetlist({'items':1})
2730  call assert_equal('F3', bufname(l.items[0].bufnr))
2731  call assert_equal(40, l.items[0].lnum)
2732  call g:Xsetlist([], 'r', {'items' : []})
2733  let l = g:Xgetlist({'items':1})
2734  call assert_equal(0, len(l.items))
2735
2736  call g:Xsetlist([], 'r', {'title' : 'TestTitle'})
2737  call g:Xsetlist([], 'r', {'items' : [{'filename' : 'F1', 'lnum' : 10, 'text' : 'L10'}]})
2738  call g:Xsetlist([], 'r', {'items' : [{'filename' : 'F1', 'lnum' : 10, 'text' : 'L10'}]})
2739  call assert_equal('TestTitle', g:Xgetlist({'title' : 1}).title)
2740
2741  " Test for getting id of window associated with a location list window
2742  if a:cchar == 'l'
2743    only
2744    call assert_equal(0, g:Xgetlist({'all' : 1}).filewinid)
2745    let wid = win_getid()
2746    Xopen
2747    call assert_equal(wid, g:Xgetlist({'filewinid' : 1}).filewinid)
2748    wincmd w
2749    call assert_equal(0, g:Xgetlist({'filewinid' : 1}).filewinid)
2750    only
2751  endif
2752
2753  " The following used to crash Vim with address sanitizer
2754  call g:Xsetlist([], 'f')
2755  call g:Xsetlist([], 'a', {'items' : [{'filename':'F1', 'lnum':10}]})
2756  call assert_equal(10, g:Xgetlist({'items':1}).items[0].lnum)
2757
2758  " Try setting the items using a string
2759  call assert_equal(-1, g:Xsetlist([], ' ', {'items' : 'Test'}))
2760
2761  " Save and restore the quickfix stack
2762  call g:Xsetlist([], 'f')
2763  call assert_equal(0, g:Xgetlist({'nr':'$'}).nr)
2764  Xexpr "File1:10:Line1"
2765  Xexpr "File2:20:Line2"
2766  Xexpr "File3:30:Line3"
2767  let last_qf = g:Xgetlist({'nr':'$'}).nr
2768  call assert_equal(3, last_qf)
2769  let qstack = []
2770  for i in range(1, last_qf)
2771    let qstack = add(qstack, g:Xgetlist({'nr':i, 'all':1}))
2772  endfor
2773  call g:Xsetlist([], 'f')
2774  for i in range(len(qstack))
2775    call g:Xsetlist([], ' ', qstack[i])
2776  endfor
2777  call assert_equal(3, g:Xgetlist({'nr':'$'}).nr)
2778  call assert_equal(10, g:Xgetlist({'nr':1, 'items':1}).items[0].lnum)
2779  call assert_equal(20, g:Xgetlist({'nr':2, 'items':1}).items[0].lnum)
2780  call assert_equal(30, g:Xgetlist({'nr':3, 'items':1}).items[0].lnum)
2781  call g:Xsetlist([], 'f')
2782
2783  " Swap two quickfix lists
2784  Xexpr "File1:10:Line10"
2785  Xexpr "File2:20:Line20"
2786  Xexpr "File3:30:Line30"
2787  call g:Xsetlist([], 'r', {'nr':1,'title':'Colors','context':['Colors']})
2788  call g:Xsetlist([], 'r', {'nr':2,'title':'Fruits','context':['Fruits']})
2789  let l1=g:Xgetlist({'nr':1,'all':1})
2790  let l2=g:Xgetlist({'nr':2,'all':1})
2791  let save_id = l1.id
2792  let l1.id=l2.id
2793  let l2.id=save_id
2794  call g:Xsetlist([], 'r', l1)
2795  call g:Xsetlist([], 'r', l2)
2796  let newl1=g:Xgetlist({'nr':1,'all':1})
2797  let newl2=g:Xgetlist({'nr':2,'all':1})
2798  call assert_equal('Fruits', newl1.title)
2799  call assert_equal(['Fruits'], newl1.context)
2800  call assert_equal('Line20', newl1.items[0].text)
2801  call assert_equal('Colors', newl2.title)
2802  call assert_equal(['Colors'], newl2.context)
2803  call assert_equal('Line10', newl2.items[0].text)
2804  call g:Xsetlist([], 'f')
2805
2806  " Cannot specify both a non-empty list argument and a dict argument
2807  call assert_fails("call g:Xsetlist([{}], ' ', {})", 'E475:')
2808endfunc
2809
2810func Test_qf_property()
2811  call Xproperty_tests('c')
2812  call Xproperty_tests('l')
2813endfunc
2814
2815" Test for setting the current index in the location/quickfix list
2816func Xtest_setqfidx(cchar)
2817  call s:setup_commands(a:cchar)
2818
2819  Xgetexpr "F1:10:1:Line1\nF2:20:2:Line2\nF3:30:3:Line3"
2820  Xgetexpr "F4:10:1:Line1\nF5:20:2:Line2\nF6:30:3:Line3"
2821  Xgetexpr "F7:10:1:Line1\nF8:20:2:Line2\nF9:30:3:Line3"
2822
2823  call g:Xsetlist([], 'a', {'nr' : 3, 'idx' : 2})
2824  call g:Xsetlist([], 'a', {'nr' : 2, 'idx' : 2})
2825  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 3})
2826  Xolder 2
2827  Xopen
2828  call assert_equal(3, line('.'))
2829  Xnewer
2830  call assert_equal(2, line('.'))
2831  Xnewer
2832  call assert_equal(2, line('.'))
2833  " Update the current index with the quickfix window open
2834  wincmd w
2835  call g:Xsetlist([], 'a', {'nr' : 3, 'idx' : 3})
2836  Xopen
2837  call assert_equal(3, line('.'))
2838  Xclose
2839
2840  " Set the current index to the last entry
2841  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : '$'})
2842  call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx)
2843  " A large value should set the index to the last index
2844  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 1})
2845  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 999})
2846  call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx)
2847  " Invalid index values
2848  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : -1})
2849  call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx)
2850  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 0})
2851  call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx)
2852  call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 'xx'})
2853  call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx)
2854  call assert_fails("call g:Xsetlist([], 'a', {'nr':1, 'idx':[]})", 'E745:')
2855
2856  call g:Xsetlist([], 'f')
2857  new | only
2858endfunc
2859
2860func Test_setqfidx()
2861  call Xtest_setqfidx('c')
2862  call Xtest_setqfidx('l')
2863endfunc
2864
2865" Tests for the QuickFixCmdPre/QuickFixCmdPost autocommands
2866func QfAutoCmdHandler(loc, cmd)
2867  call add(g:acmds, a:loc . a:cmd)
2868endfunc
2869
2870func Test_Autocmd()
2871  autocmd QuickFixCmdPre * call QfAutoCmdHandler('pre', expand('<amatch>'))
2872  autocmd QuickFixCmdPost * call QfAutoCmdHandler('post', expand('<amatch>'))
2873
2874  let g:acmds = []
2875  cexpr "F1:10:Line 10"
2876  caddexpr "F1:20:Line 20"
2877  cgetexpr "F1:30:Line 30"
2878  cexpr ""
2879  caddexpr ""
2880  cgetexpr ""
2881  silent! cexpr non_existing_func()
2882  silent! caddexpr non_existing_func()
2883  silent! cgetexpr non_existing_func()
2884  let l =<< trim END
2885    precexpr
2886    postcexpr
2887    precaddexpr
2888    postcaddexpr
2889    precgetexpr
2890    postcgetexpr
2891    precexpr
2892    postcexpr
2893    precaddexpr
2894    postcaddexpr
2895    precgetexpr
2896    postcgetexpr
2897    precexpr
2898    precaddexpr
2899    precgetexpr
2900  END
2901  call assert_equal(l, g:acmds)
2902
2903  let g:acmds = []
2904  enew! | call append(0, "F2:10:Line 10")
2905  cbuffer!
2906  enew! | call append(0, "F2:20:Line 20")
2907  cgetbuffer
2908  enew! | call append(0, "F2:30:Line 30")
2909  caddbuffer
2910  new
2911  let bnum = bufnr('%')
2912  bunload
2913  exe 'silent! cbuffer! ' . bnum
2914  exe 'silent! cgetbuffer ' . bnum
2915  exe 'silent! caddbuffer ' . bnum
2916  enew!
2917  let l =<< trim END
2918    precbuffer
2919    postcbuffer
2920    precgetbuffer
2921    postcgetbuffer
2922    precaddbuffer
2923    postcaddbuffer
2924    precbuffer
2925    precgetbuffer
2926    precaddbuffer
2927  END
2928  call assert_equal(l, g:acmds)
2929
2930  call writefile(['Xtest:1:Line1'], 'Xtest')
2931  call writefile([], 'Xempty')
2932  let g:acmds = []
2933  cfile Xtest
2934  caddfile Xtest
2935  cgetfile Xtest
2936  cfile Xempty
2937  caddfile Xempty
2938  cgetfile Xempty
2939  silent! cfile do_not_exist
2940  silent! caddfile do_not_exist
2941  silent! cgetfile do_not_exist
2942  let l =<< trim END
2943    precfile
2944    postcfile
2945    precaddfile
2946    postcaddfile
2947    precgetfile
2948    postcgetfile
2949    precfile
2950    postcfile
2951    precaddfile
2952    postcaddfile
2953    precgetfile
2954    postcgetfile
2955    precfile
2956    postcfile
2957    precaddfile
2958    postcaddfile
2959    precgetfile
2960    postcgetfile
2961  END
2962  call assert_equal(l, g:acmds)
2963
2964  let g:acmds = []
2965  helpgrep quickfix
2966  silent! helpgrep non_existing_help_topic
2967  vimgrep test Xtest
2968  vimgrepadd test Xtest
2969  silent! vimgrep non_existing_test Xtest
2970  silent! vimgrepadd non_existing_test Xtest
2971  set makeprg=
2972  silent! make
2973  set makeprg&
2974  let l =<< trim END
2975    prehelpgrep
2976    posthelpgrep
2977    prehelpgrep
2978    posthelpgrep
2979    previmgrep
2980    postvimgrep
2981    previmgrepadd
2982    postvimgrepadd
2983    previmgrep
2984    postvimgrep
2985    previmgrepadd
2986    postvimgrepadd
2987    premake
2988    postmake
2989  END
2990  call assert_equal(l, g:acmds)
2991
2992  if has('unix')
2993    " Run this test only on Unix-like systems. The grepprg may not be set on
2994    " non-Unix systems.
2995    " The following lines are used for the grep test. Don't remove.
2996    " Grep_Autocmd_Text: Match 1
2997    " GrepAdd_Autocmd_Text: Match 2
2998    let g:acmds = []
2999    silent grep Grep_Autocmd_Text test_quickfix.vim
3000    silent grepadd GrepAdd_Autocmd_Text test_quickfix.vim
3001    silent grep abc123def Xtest
3002    silent grepadd abc123def Xtest
3003    set grepprg=internal
3004    silent grep Grep_Autocmd_Text test_quickfix.vim
3005    silent grepadd GrepAdd_Autocmd_Text test_quickfix.vim
3006    silent lgrep Grep_Autocmd_Text test_quickfix.vim
3007    silent lgrepadd GrepAdd_Autocmd_Text test_quickfix.vim
3008    set grepprg&vim
3009    let l =<< trim END
3010      pregrep
3011      postgrep
3012      pregrepadd
3013      postgrepadd
3014      pregrep
3015      postgrep
3016      pregrepadd
3017      postgrepadd
3018      pregrep
3019      postgrep
3020      pregrepadd
3021      postgrepadd
3022      prelgrep
3023      postlgrep
3024      prelgrepadd
3025      postlgrepadd
3026    END
3027    call assert_equal(l, g:acmds)
3028  endif
3029
3030  call delete('Xtest')
3031  call delete('Xempty')
3032  au! QuickFixCmdPre
3033  au! QuickFixCmdPost
3034endfunc
3035
3036func Test_Autocmd_Exception()
3037  set efm=%m
3038  lgetexpr '?'
3039
3040  try
3041    call DoesNotExit()
3042  catch
3043    lgetexpr '1'
3044  finally
3045    lgetexpr '1'
3046  endtry
3047
3048  call assert_equal('1', getloclist(0)[0].text)
3049
3050  set efm&vim
3051endfunc
3052
3053func Test_caddbuffer_wrong()
3054  " This used to cause a memory access in freed memory.
3055  let save_efm = &efm
3056  set efm=%EEEE%m,%WWWW,%+CCCC%>%#,%GGGG%.#
3057  cgetexpr ['WWWW', 'EEEE', 'CCCC']
3058  let &efm = save_efm
3059  caddbuffer
3060  bwipe!
3061endfunc
3062
3063func Test_caddexpr_wrong()
3064  " This used to cause a memory access in freed memory.
3065  cbuffer
3066  cbuffer
3067  copen
3068  let save_efm = &efm
3069  set efm=%
3070  call assert_fails('caddexpr ""', 'E376:')
3071  let &efm = save_efm
3072endfunc
3073
3074func Test_dirstack_cleanup()
3075  " This used to cause a memory access in freed memory.
3076  let save_efm = &efm
3077  lexpr '0'
3078  lopen
3079  fun X(c)
3080    let save_efm=&efm
3081    set efm=%D%f
3082    if a:c == 'c'
3083      caddexpr '::'
3084    else
3085      laddexpr ':0:0'
3086    endif
3087    let &efm=save_efm
3088  endfun
3089  call X('c')
3090  call X('l')
3091  call setqflist([], 'r')
3092  caddbuffer
3093  let &efm = save_efm
3094endfunc
3095
3096" Tests for jumping to entries from the location list window and quickfix
3097" window
3098func Test_cwindow_jump()
3099  set efm=%f%%%l%%%m
3100  lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"]
3101  lopen | only
3102  lfirst
3103  call assert_true(winnr('$') == 2)
3104  call assert_true(winnr() == 1)
3105  " Location list for the new window should be set
3106  call assert_true(getloclist(0)[2].text == 'Line 30')
3107
3108  " Open a scratch buffer
3109  " Open a new window and create a location list
3110  " Open the location list window and close the other window
3111  " Jump to an entry.
3112  " Should create a new window and jump to the entry. The scratch buffer
3113  " should not be used.
3114  enew | only
3115  set buftype=nofile
3116  below new
3117  lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"]
3118  lopen
3119  2wincmd c
3120  lnext
3121  call assert_true(winnr('$') == 3)
3122  call assert_true(winnr() == 2)
3123
3124  " Open two windows with two different location lists
3125  " Open the location list window and close the previous window
3126  " Jump to an entry in the location list window
3127  " Should open the file in the first window and not set the location list.
3128  enew | only
3129  lgetexpr ["F1%5%Line 5"]
3130  below new
3131  lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"]
3132  lopen
3133  2wincmd c
3134  lnext
3135  call assert_true(winnr() == 1)
3136  call assert_true(getloclist(0)[0].text == 'Line 5')
3137
3138  enew | only
3139  cgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"]
3140  copen
3141  cnext
3142  call assert_true(winnr('$') == 2)
3143  call assert_true(winnr() == 1)
3144
3145  " open the quickfix buffer in two windows and jump to an entry. Should open
3146  " the file in the first quickfix window.
3147  enew | only
3148  copen
3149  let bnum = bufnr('')
3150  exe 'sbuffer ' . bnum
3151  wincmd b
3152  cfirst
3153  call assert_equal(2, winnr())
3154  call assert_equal('F1', @%)
3155  enew | only
3156  exe 'sb' bnum
3157  exe 'botright sb' bnum
3158  wincmd t
3159  clast
3160  call assert_equal(2, winnr())
3161  call assert_equal('quickfix', getwinvar(1, '&buftype'))
3162  call assert_equal('quickfix', getwinvar(3, '&buftype'))
3163
3164  " Jumping to a file from the location list window should find a usable
3165  " window by wrapping around the window list.
3166  enew | only
3167  call setloclist(0, [], 'f')
3168  new | new
3169  lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"]
3170  lopen
3171  1close
3172  call assert_equal(0, getloclist(3, {'id' : 0}).id)
3173  lnext
3174  call assert_equal(3, winnr())
3175  call assert_equal(getloclist(1, {'id' : 0}).id, getloclist(3, {'id' : 0}).id)
3176
3177  enew | only
3178  set efm&vim
3179endfunc
3180
3181func Test_cwindow_highlight()
3182  CheckScreendump
3183
3184  let lines =<< trim END
3185    call setline(1, ['some', 'text', 'with', 'matches'])
3186    write XCwindow
3187    vimgrep e XCwindow
3188    redraw
3189    cwindow 4
3190  END
3191  call writefile(lines, 'XtestCwindow')
3192  let buf = RunVimInTerminal('-S XtestCwindow', #{rows: 12})
3193  call VerifyScreenDump(buf, 'Test_quickfix_cwindow_1', {})
3194
3195  call term_sendkeys(buf, ":cnext\<CR>")
3196  call VerifyScreenDump(buf, 'Test_quickfix_cwindow_2', {})
3197
3198  " clean up
3199  call StopVimInTerminal(buf)
3200  call delete('XtestCwindow')
3201  call delete('XCwindow')
3202endfunc
3203
3204func XvimgrepTests(cchar)
3205  call s:setup_commands(a:cchar)
3206
3207  let lines =<< trim END
3208    Editor:VIM vim
3209    Editor:Emacs EmAcS
3210    Editor:Notepad NOTEPAD
3211  END
3212  call writefile(lines, 'Xtestfile1')
3213  call writefile(['Linux', 'macOS', 'MS-Windows'], 'Xtestfile2')
3214
3215  " Error cases
3216  call assert_fails('Xvimgrep /abc *', 'E682:')
3217
3218  let @/=''
3219  call assert_fails('Xvimgrep // *', 'E35:')
3220
3221  call assert_fails('Xvimgrep abc', 'E683:')
3222  call assert_fails('Xvimgrep a1b2c3 Xtestfile1', 'E480:')
3223  call assert_fails('Xvimgrep pat Xa1b2c3', 'E480:')
3224
3225  Xexpr ""
3226  Xvimgrepadd Notepad Xtestfile1
3227  Xvimgrepadd macOS Xtestfile2
3228  let l = g:Xgetlist()
3229  call assert_equal(2, len(l))
3230  call assert_equal('Editor:Notepad NOTEPAD', l[0].text)
3231
3232  10Xvimgrep #\cvim#g Xtestfile?
3233  let l = g:Xgetlist()
3234  call assert_equal(2, len(l))
3235  call assert_equal(8, l[0].col)
3236  call assert_equal(11, l[0].end_col)
3237  call assert_equal(12, l[1].col)
3238  call assert_equal(15, l[1].end_col)
3239
3240  1Xvimgrep ?Editor? Xtestfile*
3241  let l = g:Xgetlist()
3242  call assert_equal(1, len(l))
3243  call assert_equal('Editor:VIM vim', l[0].text)
3244
3245  edit +3 Xtestfile2
3246  Xvimgrep +\cemacs+j Xtestfile1
3247  let l = g:Xgetlist()
3248  call assert_equal('Xtestfile2', @%)
3249  call assert_equal('Editor:Emacs EmAcS', l[0].text)
3250
3251  " Test for unloading a buffer after vimgrep searched the buffer
3252  %bwipe
3253  Xvimgrep /Editor/j Xtestfile*
3254  call assert_equal(0, getbufinfo('Xtestfile1')[0].loaded)
3255  call assert_equal([], getbufinfo('Xtestfile2'))
3256
3257  " Test for opening the dummy buffer used by vimgrep in a window. The new
3258  " window should be closed
3259  %bw!
3260  augroup QF_Test
3261    au!
3262    autocmd BufReadPre * exe "sb " .. expand("<abuf>")
3263  augroup END
3264  call assert_fails("Xvimgrep /sublime/ Xtestfile1", 'E480:')
3265  call assert_equal(1, winnr('$'))
3266  augroup QF_Test
3267    au!
3268  augroup END
3269
3270  call delete('Xtestfile1')
3271  call delete('Xtestfile2')
3272endfunc
3273
3274" Tests for the :vimgrep command
3275func Test_vimgrep()
3276  call XvimgrepTests('c')
3277  call XvimgrepTests('l')
3278endfunc
3279
3280func Test_vimgrep_wildcards_expanded_once()
3281  new X[id-01] file.txt
3282  call setline(1, 'some text to search for')
3283  vimgrep text %
3284  bwipe!
3285endfunc
3286
3287" Test for incsearch highlighting of the :vimgrep pattern
3288" This test used to cause "E315: ml_get: invalid lnum" errors.
3289func Test_vimgrep_incsearch()
3290  enew
3291  set incsearch
3292  call Ntest_override("char_avail", 1)
3293
3294  call feedkeys(":2vimgrep assert test_quickfix.vim test_cdo.vim\<CR>", "ntx")
3295  let l = getqflist()
3296  call assert_equal(2, len(l))
3297
3298  call Ntest_override("ALL", 0)
3299  set noincsearch
3300endfunc
3301
3302" Test vimgrep with the last search pattern not set
3303func Test_vimgrep_with_no_last_search_pat()
3304  let lines =<< trim [SCRIPT]
3305    call assert_fails('vimgrep // *', 'E35:')
3306    call writefile(v:errors, 'Xresult')
3307    qall!
3308  [SCRIPT]
3309  call writefile(lines, 'Xscript')
3310  if RunVim([], [], '--clean -S Xscript')
3311    call assert_equal([], readfile('Xresult'))
3312  endif
3313  call delete('Xscript')
3314  call delete('Xresult')
3315endfunc
3316
3317" Test vimgrep without swap file
3318func Test_vimgrep_without_swap_file()
3319  let lines =<< trim [SCRIPT]
3320    vimgrep grep test_c*
3321    call writefile(['done'], 'Xresult')
3322    qall!
3323  [SCRIPT]
3324  call writefile(lines, 'Xscript')
3325  if RunVim([], [], '--clean -n -S Xscript Xscript')
3326    call assert_equal(['done'], readfile('Xresult'))
3327  endif
3328  call delete('Xscript')
3329  call delete('Xresult')
3330endfunc
3331
3332func Test_vimgrep_existing_swapfile()
3333  call writefile(['match apple with apple'], 'Xapple')
3334  call writefile(['swapfile'], '.Xapple.swp')
3335  let g:foundSwap = 0
3336  let g:ignoreSwapExists = 1
3337  augroup grep
3338    au SwapExists * let foundSwap = 1 | let v:swapchoice = 'e'
3339  augroup END
3340  vimgrep apple Xapple
3341  call assert_equal(1, g:foundSwap)
3342  call assert_match('.Xapple.swo', swapname(''))
3343
3344  call delete('Xapple')
3345  call delete('.Xapple.swp')
3346  augroup grep
3347    au! SwapExists
3348  augroup END
3349  unlet g:ignoreSwapExists
3350endfunc
3351
3352func XfreeTests(cchar)
3353  call s:setup_commands(a:cchar)
3354
3355  enew | only
3356
3357  " Deleting the quickfix stack should work even When the current list is
3358  " somewhere in the middle of the stack
3359  Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15']
3360  Xexpr ['Xfile2:20:20:Line 20', 'Xfile2:25:25:Line 25']
3361  Xexpr ['Xfile3:30:30:Line 30', 'Xfile3:35:35:Line 35']
3362  Xolder
3363  call g:Xsetlist([], 'f')
3364  call assert_equal(0, len(g:Xgetlist()))
3365
3366  " After deleting the stack, adding a new list should create a stack with a
3367  " single list.
3368  Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15']
3369  call assert_equal(1, g:Xgetlist({'all':1}).nr)
3370
3371  " Deleting the stack from a quickfix window should update/clear the
3372  " quickfix/location list window.
3373  Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15']
3374  Xexpr ['Xfile2:20:20:Line 20', 'Xfile2:25:25:Line 25']
3375  Xexpr ['Xfile3:30:30:Line 30', 'Xfile3:35:35:Line 35']
3376  Xolder
3377  Xwindow
3378  call g:Xsetlist([], 'f')
3379  call assert_equal(2, winnr('$'))
3380  call assert_equal(1, line('$'))
3381  Xclose
3382
3383  " Deleting the stack from a non-quickfix window should update/clear the
3384  " quickfix/location list window.
3385  Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15']
3386  Xexpr ['Xfile2:20:20:Line 20', 'Xfile2:25:25:Line 25']
3387  Xexpr ['Xfile3:30:30:Line 30', 'Xfile3:35:35:Line 35']
3388  Xolder
3389  Xwindow
3390  wincmd p
3391  call g:Xsetlist([], 'f')
3392  call assert_equal(0, len(g:Xgetlist()))
3393  wincmd p
3394  call assert_equal(2, winnr('$'))
3395  call assert_equal(1, line('$'))
3396
3397  " After deleting the location list stack, if the location list window is
3398  " opened, then a new location list should be created. So opening the
3399  " location list window again should not create a new window.
3400  if a:cchar == 'l'
3401      lexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15']
3402      wincmd p
3403      lopen
3404      call assert_equal(2, winnr('$'))
3405  endif
3406  Xclose
3407endfunc
3408
3409" Tests for the quickfix free functionality
3410func Test_qf_free()
3411  call XfreeTests('c')
3412  call XfreeTests('l')
3413endfunc
3414
3415" Test for buffer overflow when parsing lines and adding new entries to
3416" the quickfix list.
3417func Test_bufoverflow()
3418  set efm=%f:%l:%m
3419  cgetexpr ['File1:100:' . repeat('x', 1025)]
3420
3421  set efm=%+GCompiler:\ %.%#,%f:%l:%m
3422  cgetexpr ['Compiler: ' . repeat('a', 1015), 'File1:10:Hello World']
3423
3424  set efm=%DEntering\ directory\ %f,%f:%l:%m
3425  let lines =<< trim eval END
3426    Entering directory $"{repeat('a', 1006)}"
3427    File1:10:Hello World
3428  END
3429  cgetexpr lines
3430  set efm&vim
3431endfunc
3432
3433" Tests for getting the quickfix stack size
3434func XsizeTests(cchar)
3435  call s:setup_commands(a:cchar)
3436
3437  call g:Xsetlist([], 'f')
3438  call assert_equal(0, g:Xgetlist({'nr':'$'}).nr)
3439  call assert_equal('', g:Xgetlist({'nr':'$', 'all':1}).title)
3440  call assert_equal(0, g:Xgetlist({'nr':0}).nr)
3441
3442  Xexpr "File1:10:Line1"
3443  Xexpr "File2:20:Line2"
3444  Xexpr "File3:30:Line3"
3445  Xolder | Xolder
3446  call assert_equal(3, g:Xgetlist({'nr':'$'}).nr)
3447  call g:Xsetlist([], 'f')
3448
3449  Xexpr "File1:10:Line1"
3450  Xexpr "File2:20:Line2"
3451  Xexpr "File3:30:Line3"
3452  Xolder | Xolder
3453  call g:Xsetlist([], 'a', {'nr':'$', 'title':'Compiler'})
3454  call assert_equal('Compiler', g:Xgetlist({'nr':3, 'all':1}).title)
3455endfunc
3456
3457func Test_Qf_Size()
3458  call XsizeTests('c')
3459  call XsizeTests('l')
3460endfunc
3461
3462func Test_cclose_from_copen()
3463    augroup QF_Test
3464	au!
3465        au FileType qf :call assert_fails(':cclose', 'E788')
3466    augroup END
3467    copen
3468    augroup QF_Test
3469	au!
3470    augroup END
3471    augroup! QF_Test
3472endfunc
3473
3474func Test_cclose_in_autocmd()
3475  " Problem is only triggered if "starting" is zero, so that the OptionSet
3476  " event will be triggered.
3477  call Ntest_override('starting', 1)
3478  augroup QF_Test
3479    au!
3480    au FileType qf :call assert_fails(':cclose', 'E788')
3481  augroup END
3482  copen
3483  augroup QF_Test
3484    au!
3485  augroup END
3486  augroup! QF_Test
3487  call Ntest_override('starting', 0)
3488endfunc
3489
3490" Check that ":file" without an argument is possible even when "curbuf->b_ro_locked"
3491" is set.
3492func Test_file_from_copen()
3493  " Works without argument.
3494  augroup QF_Test
3495    au!
3496    au FileType qf file
3497  augroup END
3498  copen
3499
3500  augroup QF_Test
3501    au!
3502  augroup END
3503  cclose
3504
3505  " Fails with argument.
3506  augroup QF_Test
3507    au!
3508    au FileType qf call assert_fails(':file foo', 'E788')
3509  augroup END
3510  copen
3511  augroup QF_Test
3512    au!
3513  augroup END
3514  cclose
3515
3516  augroup! QF_Test
3517endfunc
3518
3519func Test_resize_from_copen()
3520  augroup QF_Test
3521    au!
3522    au FileType qf resize 5
3523  augroup END
3524  try
3525    " This should succeed without any exception.  No other buffers are
3526    " involved in the autocmd.
3527    copen
3528  finally
3529    augroup QF_Test
3530      au!
3531    augroup END
3532    augroup! QF_Test
3533  endtry
3534endfunc
3535
3536func Test_filetype_autocmd()
3537  " this changes the location list while it is in use to fill a buffer
3538  lexpr ''
3539  lopen
3540  augroup FT_loclist
3541    au FileType * call setloclist(0, [], 'f')
3542  augroup END
3543  silent! lolder
3544  lexpr ''
3545
3546  augroup FT_loclist
3547    au! FileType
3548  augroup END
3549endfunc
3550
3551func Test_vimgrep_with_textlock()
3552  new
3553
3554  " Simple way to execute something with "textlock" set.
3555  " Check that vimgrep without jumping can be executed.
3556  au InsertCharPre * vimgrep /RunTheTest/j runtest.vim
3557  normal ax
3558  let qflist = getqflist()
3559  call assert_true(len(qflist) > 0)
3560  call assert_match('RunTheTest', qflist[0].text)
3561  call setqflist([], 'r')
3562  au! InsertCharPre
3563
3564  " Check that vimgrepadd without jumping can be executed.
3565  au InsertCharPre * vimgrepadd /RunTheTest/j runtest.vim
3566  normal ax
3567  let qflist = getqflist()
3568  call assert_true(len(qflist) > 0)
3569  call assert_match('RunTheTest', qflist[0].text)
3570  call setqflist([], 'r')
3571  au! InsertCharPre
3572
3573  " Check that lvimgrep without jumping can be executed.
3574  au InsertCharPre * lvimgrep /RunTheTest/j runtest.vim
3575  normal ax
3576  let qflist = getloclist(0)
3577  call assert_true(len(qflist) > 0)
3578  call assert_match('RunTheTest', qflist[0].text)
3579  call setloclist(0, [], 'r')
3580  au! InsertCharPre
3581
3582  " Check that lvimgrepadd without jumping can be executed.
3583  au InsertCharPre * lvimgrepadd /RunTheTest/j runtest.vim
3584  normal ax
3585  let qflist = getloclist(0)
3586  call assert_true(len(qflist) > 0)
3587  call assert_match('RunTheTest', qflist[0].text)
3588  call setloclist(0, [], 'r')
3589  au! InsertCharPre
3590
3591  " trying to jump will give an error
3592  au InsertCharPre * vimgrep /RunTheTest/ runtest.vim
3593  call assert_fails('normal ax', 'E565:')
3594  au! InsertCharPre
3595
3596  au InsertCharPre * vimgrepadd /RunTheTest/ runtest.vim
3597  call assert_fails('normal ax', 'E565:')
3598  au! InsertCharPre
3599
3600  au InsertCharPre * lvimgrep /RunTheTest/ runtest.vim
3601  call assert_fails('normal ax', 'E565:')
3602  au! InsertCharPre
3603
3604  au InsertCharPre * lvimgrepadd /RunTheTest/ runtest.vim
3605  call assert_fails('normal ax', 'E565:')
3606  au! InsertCharPre
3607
3608  bwipe!
3609endfunc
3610
3611" Tests for the quickfix buffer b:changedtick variable
3612func Xchangedtick_tests(cchar)
3613  call s:setup_commands(a:cchar)
3614
3615  new | only
3616
3617  Xexpr "" | Xexpr "" | Xexpr ""
3618
3619  Xopen
3620  Xolder
3621  Xolder
3622  Xaddexpr "F1:10:Line10"
3623  Xaddexpr "F2:20:Line20"
3624  call g:Xsetlist([{"filename":"F3", "lnum":30, "text":"Line30"}], 'a')
3625  call g:Xsetlist([], 'f')
3626  call assert_equal(8, getbufvar('%', 'changedtick'))
3627  Xclose
3628endfunc
3629
3630func Test_changedtick()
3631  call Xchangedtick_tests('c')
3632  call Xchangedtick_tests('l')
3633endfunc
3634
3635" Tests for parsing an expression using setqflist()
3636func Xsetexpr_tests(cchar)
3637  call s:setup_commands(a:cchar)
3638
3639  let t = ["File1:10:Line10", "File1:20:Line20"]
3640  call g:Xsetlist([], ' ', {'lines' : t})
3641  call g:Xsetlist([], 'a', {'lines' : ["File1:30:Line30"]})
3642
3643  let l = g:Xgetlist()
3644  call assert_equal(3, len(l))
3645  call assert_equal(20, l[1].lnum)
3646  call assert_equal('Line30', l[2].text)
3647  call g:Xsetlist([], 'r', {'lines' : ["File2:5:Line5"]})
3648  let l = g:Xgetlist()
3649  call assert_equal(1, len(l))
3650  call assert_equal('Line5', l[0].text)
3651  call assert_equal(-1, g:Xsetlist([], 'a', {'lines' : 10}))
3652  call assert_equal(-1, g:Xsetlist([], 'a', {'lines' : "F1:10:L10"}))
3653
3654  call g:Xsetlist([], 'f')
3655  " Add entries to multiple lists
3656  call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["File1:10:Line10"]})
3657  call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["File2:20:Line20"]})
3658  call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["File1:15:Line15"]})
3659  call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["File2:25:Line25"]})
3660  call assert_equal('Line15', g:Xgetlist({'nr':1, 'items':1}).items[1].text)
3661  call assert_equal('Line25', g:Xgetlist({'nr':2, 'items':1}).items[1].text)
3662
3663  " Adding entries using a custom efm
3664  set efm&
3665  call g:Xsetlist([], ' ', {'efm' : '%f#%l#%m',
3666				\ 'lines' : ["F1#10#L10", "F2#20#L20"]})
3667  call assert_equal(20, g:Xgetlist({'items':1}).items[1].lnum)
3668  call g:Xsetlist([], 'a', {'efm' : '%f#%l#%m', 'lines' : ["F3:30:L30"]})
3669  call assert_equal('F3:30:L30', g:Xgetlist({'items':1}).items[2].text)
3670  call assert_equal(20, g:Xgetlist({'items':1}).items[1].lnum)
3671  call assert_equal(-1, g:Xsetlist([], 'a', {'efm' : [],
3672				\ 'lines' : ['F1:10:L10']}))
3673endfunc
3674
3675func Test_setexpr()
3676  call Xsetexpr_tests('c')
3677  call Xsetexpr_tests('l')
3678endfunc
3679
3680" Tests for per quickfix/location list directory stack
3681func Xmultidirstack_tests(cchar)
3682  call s:setup_commands(a:cchar)
3683
3684  call g:Xsetlist([], 'f')
3685  Xexpr "" | Xexpr ""
3686
3687  call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["Entering dir 'Xone/a'"]})
3688  call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["Entering dir 'Xtwo/a'"]})
3689  call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["one.txt:3:one one one"]})
3690  call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["two.txt:5:two two two"]})
3691
3692  let l1 = g:Xgetlist({'nr':1, 'items':1})
3693  let l2 = g:Xgetlist({'nr':2, 'items':1})
3694  call assert_equal('Xone/a/one.txt', bufname(l1.items[1].bufnr))
3695  call assert_equal(3, l1.items[1].lnum)
3696  call assert_equal('Xtwo/a/two.txt', bufname(l2.items[1].bufnr))
3697  call assert_equal(5, l2.items[1].lnum)
3698endfunc
3699
3700func Test_multidirstack()
3701  call mkdir('Xone/a', 'p')
3702  call mkdir('Xtwo/a', 'p')
3703  let lines = ['1', '2', 'one one one', '4', 'two two two', '6', '7']
3704  call writefile(lines, 'Xone/a/one.txt')
3705  call writefile(lines, 'Xtwo/a/two.txt')
3706  let save_efm = &efm
3707  set efm=%DEntering\ dir\ '%f',%f:%l:%m,%XLeaving\ dir\ '%f'
3708
3709  call Xmultidirstack_tests('c')
3710  call Xmultidirstack_tests('l')
3711
3712  let &efm = save_efm
3713  call delete('Xone', 'rf')
3714  call delete('Xtwo', 'rf')
3715endfunc
3716
3717" Tests for per quickfix/location list file stack
3718func Xmultifilestack_tests(cchar)
3719  call s:setup_commands(a:cchar)
3720
3721  call g:Xsetlist([], 'f')
3722  Xexpr "" | Xexpr ""
3723
3724  call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["[one.txt]"]})
3725  call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["[two.txt]"]})
3726  call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["(3,5) one one one"]})
3727  call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["(5,9) two two two"]})
3728
3729  let l1 = g:Xgetlist({'nr':1, 'items':1})
3730  let l2 = g:Xgetlist({'nr':2, 'items':1})
3731  call assert_equal('one.txt', bufname(l1.items[1].bufnr))
3732  call assert_equal(3, l1.items[1].lnum)
3733  call assert_equal('two.txt', bufname(l2.items[1].bufnr))
3734  call assert_equal(5, l2.items[1].lnum)
3735
3736  " Test for start of a new error line in the same line where a previous
3737  " error line ends with a file stack.
3738  let efm_val = 'Error\ l%l\ in\ %f,'
3739  let efm_val .= '%-P%>(%f%r,Error\ l%l\ in\ %m,%-Q)%r'
3740  let lines =<< trim END
3741    (one.txt
3742    Error l4 in one.txt
3743    ) (two.txt
3744    Error l6 in two.txt
3745    )
3746    Error l8 in one.txt
3747  END
3748  let l = g:Xgetlist({'lines': lines, 'efm' : efm_val})
3749  call assert_equal(3, len(l.items))
3750  call assert_equal('one.txt', bufname(l.items[0].bufnr))
3751  call assert_equal(4, l.items[0].lnum)
3752  call assert_equal('one.txt', l.items[0].text)
3753  call assert_equal('two.txt', bufname(l.items[1].bufnr))
3754  call assert_equal(6, l.items[1].lnum)
3755  call assert_equal('two.txt', l.items[1].text)
3756  call assert_equal('one.txt', bufname(l.items[2].bufnr))
3757  call assert_equal(8, l.items[2].lnum)
3758  call assert_equal('', l.items[2].text)
3759endfunc
3760
3761func Test_multifilestack()
3762  let lines = ['1', '2', 'one one one', '4', 'two two two', '6', '7']
3763  call writefile(lines, 'one.txt')
3764  call writefile(lines, 'two.txt')
3765  let save_efm = &efm
3766  set efm=%+P[%f],(%l\\,%c)\ %m,%-Q
3767
3768  call Xmultifilestack_tests('c')
3769  call Xmultifilestack_tests('l')
3770
3771  let &efm = save_efm
3772  call delete('one.txt')
3773  call delete('two.txt')
3774endfunc
3775
3776" Tests for per buffer 'efm' setting
3777func Test_perbuf_efm()
3778  call writefile(["File1-10-Line10"], 'one.txt')
3779  call writefile(["File2#20#Line20"], 'two.txt')
3780  set efm=%f#%l#%m
3781  new | only
3782  new
3783  setlocal efm=%f-%l-%m
3784  cfile one.txt
3785  wincmd w
3786  caddfile two.txt
3787
3788  let l = getqflist()
3789  call assert_equal(10, l[0].lnum)
3790  call assert_equal('Line20', l[1].text)
3791
3792  set efm&
3793  new | only
3794  call delete('one.txt')
3795  call delete('two.txt')
3796endfunc
3797
3798" Open multiple help windows using ":lhelpgrep
3799" This test used to crash Vim
3800func Test_Multi_LL_Help()
3801  new | only
3802  lhelpgrep window
3803  lopen
3804  e#
3805  lhelpgrep buffer
3806  call assert_equal(3, winnr('$'))
3807  call assert_true(len(getloclist(1)) != 0)
3808  call assert_true(len(getloclist(2)) != 0)
3809  new | only
3810endfunc
3811
3812" Tests for adding new quickfix lists using setqflist()
3813func XaddQf_tests(cchar)
3814  call s:setup_commands(a:cchar)
3815
3816  " Create a new list using ' ' for action
3817  call g:Xsetlist([], 'f')
3818  call g:Xsetlist([], ' ', {'title' : 'Test1'})
3819  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3820  call assert_equal(1, l.nr)
3821  call assert_equal('Test1', l.title)
3822
3823  " Create a new list using ' ' for action and '$' for 'nr'
3824  call g:Xsetlist([], 'f')
3825  call g:Xsetlist([], ' ', {'title' : 'Test2', 'nr' : '$'})
3826  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3827  call assert_equal(1, l.nr)
3828  call assert_equal('Test2', l.title)
3829
3830  " Create a new list using 'a' for action
3831  call g:Xsetlist([], 'f')
3832  call g:Xsetlist([], 'a', {'title' : 'Test3'})
3833  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3834  call assert_equal(1, l.nr)
3835  call assert_equal('Test3', l.title)
3836
3837  " Create a new list using 'a' for action and '$' for 'nr'
3838  call g:Xsetlist([], 'f')
3839  call g:Xsetlist([], 'a', {'title' : 'Test3', 'nr' : '$'})
3840  call g:Xsetlist([], 'a', {'title' : 'Test4'})
3841  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3842  call assert_equal(1, l.nr)
3843  call assert_equal('Test4', l.title)
3844
3845  " Adding a quickfix list should remove all the lists following the current
3846  " list.
3847  Xexpr "" | Xexpr "" | Xexpr ""
3848  silent! 10Xolder
3849  call g:Xsetlist([], ' ', {'title' : 'Test5'})
3850  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3851  call assert_equal(2, l.nr)
3852  call assert_equal('Test5', l.title)
3853
3854  " Add a quickfix list using '$' as the list number.
3855  let lastqf = g:Xgetlist({'nr':'$'}).nr
3856  silent! 99Xolder
3857  call g:Xsetlist([], ' ', {'nr' : '$', 'title' : 'Test6'})
3858  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3859  call assert_equal(lastqf + 1, l.nr)
3860  call assert_equal('Test6', l.title)
3861
3862  " Add a quickfix list using 'nr' set to one more than the quickfix
3863  " list size.
3864  let lastqf = g:Xgetlist({'nr':'$'}).nr
3865  silent! 99Xolder
3866  call g:Xsetlist([], ' ', {'nr' : lastqf + 1, 'title' : 'Test7'})
3867  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3868  call assert_equal(lastqf + 1, l.nr)
3869  call assert_equal('Test7', l.title)
3870
3871  " Add a quickfix list to a stack with 10 lists using 'nr' set to '$'
3872  exe repeat('Xexpr "" |', 9) . 'Xexpr ""'
3873  silent! 99Xolder
3874  call g:Xsetlist([], ' ', {'nr' : '$', 'title' : 'Test8'})
3875  let l = g:Xgetlist({'nr' : '$', 'all' : 1})
3876  call assert_equal(10, l.nr)
3877  call assert_equal('Test8', l.title)
3878
3879  " Add a quickfix list using 'nr' set to a value greater than 10
3880  call assert_equal(-1, g:Xsetlist([], ' ', {'nr' : 12, 'title' : 'Test9'}))
3881
3882  " Try adding a quickfix list with 'nr' set to a value greater than the
3883  " quickfix list size but less than 10.
3884  call g:Xsetlist([], 'f')
3885  Xexpr "" | Xexpr "" | Xexpr ""
3886  silent! 99Xolder
3887  call assert_equal(-1, g:Xsetlist([], ' ', {'nr' : 8, 'title' : 'Test10'}))
3888
3889  " Add a quickfix list using 'nr' set to a some string or list
3890  call assert_equal(-1, g:Xsetlist([], ' ', {'nr' : [1,2], 'title' : 'Test11'}))
3891endfunc
3892
3893func Test_add_qf()
3894  call XaddQf_tests('c')
3895  call XaddQf_tests('l')
3896endfunc
3897
3898" Test for getting the quickfix list items from some text without modifying
3899" the quickfix stack
3900func XgetListFromLines(cchar)
3901  call s:setup_commands(a:cchar)
3902  call g:Xsetlist([], 'f')
3903
3904  let l = g:Xgetlist({'lines' : ["File2:20:Line20", "File2:30:Line30"]}).items
3905  call assert_equal(2, len(l))
3906  call assert_equal(30, l[1].lnum)
3907
3908  call assert_equal({}, g:Xgetlist({'lines' : 10}))
3909  call assert_equal({}, g:Xgetlist({'lines' : 'File1:10:Line10'}))
3910  call assert_equal([], g:Xgetlist({'lines' : []}).items)
3911  call assert_equal([], g:Xgetlist({'lines' : [10, 20]}).items)
3912
3913  " Parse text using a custom efm
3914  set efm&
3915  let l = g:Xgetlist({'lines':['File3#30#Line30'], 'efm' : '%f#%l#%m'}).items
3916  call assert_equal('Line30', l[0].text)
3917  let l = g:Xgetlist({'lines':['File3:30:Line30'], 'efm' : '%f-%l-%m'}).items
3918  call assert_equal('File3:30:Line30', l[0].text)
3919  let l = g:Xgetlist({'lines':['File3:30:Line30'], 'efm' : [1,2]})
3920  call assert_equal({}, l)
3921  call assert_fails("call g:Xgetlist({'lines':['abc'], 'efm':'%2'})", 'E376:')
3922  call assert_fails("call g:Xgetlist({'lines':['abc'], 'efm':''})", 'E378:')
3923
3924  " Make sure that the quickfix stack is not modified
3925  call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
3926endfunc
3927
3928func Test_get_list_from_lines()
3929  call XgetListFromLines('c')
3930  call XgetListFromLines('l')
3931endfunc
3932
3933" Tests for the quickfix list id
3934func Xqfid_tests(cchar)
3935  call s:setup_commands(a:cchar)
3936
3937  call g:Xsetlist([], 'f')
3938  call assert_equal(0, g:Xgetlist({'id':0}).id)
3939  Xexpr ''
3940  let start_id = g:Xgetlist({'id' : 0}).id
3941  Xexpr '' | Xexpr ''
3942  Xolder
3943  call assert_equal(start_id, g:Xgetlist({'id':0, 'nr':1}).id)
3944  call assert_equal(start_id + 1, g:Xgetlist({'id':0, 'nr':0}).id)
3945  call assert_equal(start_id + 2, g:Xgetlist({'id':0, 'nr':'$'}).id)
3946  call assert_equal(0, g:Xgetlist({'id':0, 'nr':99}).id)
3947  call assert_equal(2, g:Xgetlist({'id':start_id + 1, 'nr':0}).nr)
3948  call assert_equal(0, g:Xgetlist({'id':99, 'nr':0}).id)
3949  call assert_equal(0, g:Xgetlist({'id':"abc", 'nr':0}).id)
3950
3951  call g:Xsetlist([], 'a', {'id':start_id, 'context':[1,2]})
3952  call assert_equal([1,2], g:Xgetlist({'nr':1, 'context':1}).context)
3953  call g:Xsetlist([], 'a', {'id':start_id+1, 'lines':['F1:10:L10']})
3954  call assert_equal('L10', g:Xgetlist({'nr':2, 'items':1}).items[0].text)
3955  call assert_equal(-1, g:Xsetlist([], 'a', {'id':999, 'title':'Vim'}))
3956  call assert_equal(-1, g:Xsetlist([], 'a', {'id':'abc', 'title':'Vim'}))
3957
3958  let qfid = g:Xgetlist({'id':0, 'nr':0})
3959  call g:Xsetlist([], 'f')
3960  call assert_equal(0, g:Xgetlist({'id':qfid, 'nr':0}).id)
3961endfunc
3962
3963func Test_qf_id()
3964  call Xqfid_tests('c')
3965  call Xqfid_tests('l')
3966endfunc
3967
3968func Xqfjump_tests(cchar)
3969  call s:setup_commands(a:cchar)
3970
3971  call writefile(["Line1\tFoo", "Line2"], 'F1')
3972  call writefile(["Line1\tBar", "Line2"], 'F2')
3973  call writefile(["Line1\tBaz", "Line2"], 'F3')
3974
3975  call g:Xsetlist([], 'f')
3976
3977  " Tests for
3978  "   Jumping to a line using a pattern
3979  "   Jumping to a column greater than the last column in a line
3980  "   Jumping to a line greater than the last line in the file
3981  let l = []
3982  for i in range(1, 7)
3983    call add(l, {})
3984  endfor
3985  let l[0].filename='F1'
3986  let l[0].pattern='Line1'
3987  let l[1].filename='F2'
3988  let l[1].pattern='Line1'
3989  let l[2].filename='F3'
3990  let l[2].pattern='Line1'
3991  let l[3].filename='F3'
3992  let l[3].lnum=1
3993  let l[3].col=9
3994  let l[3].vcol=1
3995  let l[4].filename='F3'
3996  let l[4].lnum=99
3997  let l[5].filename='F3'
3998  let l[5].lnum=1
3999  let l[5].col=99
4000  let l[5].vcol=1
4001  let l[6].filename='F3'
4002  let l[6].pattern='abcxyz'
4003
4004  call g:Xsetlist([], ' ', {'items' : l})
4005  Xopen | only
4006  2Xnext
4007  call assert_equal(3, g:Xgetlist({'idx' : 0}).idx)
4008  call assert_equal('F3', @%)
4009  Xnext
4010  call assert_equal(7, col('.'))
4011  Xnext
4012  call assert_equal(2, line('.'))
4013  Xnext
4014  call assert_equal(9, col('.'))
4015  2
4016  Xnext
4017  call assert_equal(2, line('.'))
4018
4019  if a:cchar == 'l'
4020    " When jumping to a location list entry in the location list window and
4021    " no usable windows are available, then a new window should be opened.
4022    enew! | new | only
4023    call g:Xsetlist([], 'f')
4024    setlocal buftype=nofile
4025    new
4026    let lines =<< trim END
4027      F1:1:1:Line1
4028      F1:2:2:Line2
4029      F2:1:1:Line1
4030      F2:2:2:Line2
4031      F3:1:1:Line1
4032      F3:2:2:Line2
4033    END
4034    call g:Xsetlist([], ' ', {'lines': lines})
4035    Xopen
4036    let winid = win_getid()
4037    wincmd p
4038    close
4039    call win_gotoid(winid)
4040    Xnext
4041    call assert_equal(3, winnr('$'))
4042    call assert_equal(1, winnr())
4043    call assert_equal(2, line('.'))
4044
4045    " When jumping to an entry in the location list window and the window
4046    " associated with the location list is not present and a window containing
4047    " the file is already present, then that window should be used.
4048    close
4049    belowright new
4050    call g:Xsetlist([], 'f')
4051    edit F3
4052    call win_gotoid(winid)
4053    Xlast
4054    call assert_equal(3, winnr())
4055    call assert_equal(6, g:Xgetlist({'size' : 1}).size)
4056    call assert_equal(winid, g:Xgetlist({'winid' : 1}).winid)
4057  endif
4058
4059  " Cleanup
4060  enew!
4061  new | only
4062
4063  call delete('F1')
4064  call delete('F2')
4065  call delete('F3')
4066endfunc
4067
4068func Test_qfjump()
4069  call Xqfjump_tests('c')
4070  call Xqfjump_tests('l')
4071endfunc
4072
4073" Tests for the getqflist() and getloclist() functions when the list is not
4074" present or is empty
4075func Xgetlist_empty_tests(cchar)
4076  call s:setup_commands(a:cchar)
4077
4078  " Empty quickfix stack
4079  call g:Xsetlist([], 'f')
4080  call assert_equal('', g:Xgetlist({'context' : 0}).context)
4081  call assert_equal(0, g:Xgetlist({'id' : 0}).id)
4082  call assert_equal(0, g:Xgetlist({'idx' : 0}).idx)
4083  call assert_equal([], g:Xgetlist({'items' : 0}).items)
4084  call assert_equal(0, g:Xgetlist({'nr' : 0}).nr)
4085  call assert_equal(0, g:Xgetlist({'size' : 0}).size)
4086  call assert_equal('', g:Xgetlist({'title' : 0}).title)
4087  call assert_equal(0, g:Xgetlist({'winid' : 0}).winid)
4088  call assert_equal(0, g:Xgetlist({'changedtick' : 0}).changedtick)
4089  if a:cchar == 'c'
4090    call assert_equal({'context' : '', 'id' : 0, 'idx' : 0,
4091		  \ 'items' : [], 'nr' : 0, 'size' : 0, 'qfbufnr' : 0,
4092		  \ 'title' : '', 'winid' : 0, 'changedtick': 0,
4093                  \ 'quickfixtextfunc' : ''}, g:Xgetlist({'all' : 0}))
4094  else
4095    call assert_equal({'context' : '', 'id' : 0, 'idx' : 0,
4096		\ 'items' : [], 'nr' : 0, 'size' : 0, 'title' : '',
4097		\ 'winid' : 0, 'changedtick': 0, 'filewinid' : 0,
4098		\ 'qfbufnr' : 0, 'quickfixtextfunc' : ''},
4099		\ g:Xgetlist({'all' : 0}))
4100  endif
4101
4102  " Quickfix window with empty stack
4103  silent! Xopen
4104  let qfwinid = (a:cchar == 'c') ? win_getid() : 0
4105  let qfbufnr = (a:cchar == 'c') ? bufnr('') : 0
4106  call assert_equal(qfwinid, g:Xgetlist({'winid' : 0}).winid)
4107  Xclose
4108
4109  " Empty quickfix list
4110  Xexpr ""
4111  call assert_equal('', g:Xgetlist({'context' : 0}).context)
4112  call assert_notequal(0, g:Xgetlist({'id' : 0}).id)
4113  call assert_equal(0, g:Xgetlist({'idx' : 0}).idx)
4114  call assert_equal([], g:Xgetlist({'items' : 0}).items)
4115  call assert_notequal(0, g:Xgetlist({'nr' : 0}).nr)
4116  call assert_equal(0, g:Xgetlist({'size' : 0}).size)
4117  call assert_notequal('', g:Xgetlist({'title' : 0}).title)
4118  call assert_equal(0, g:Xgetlist({'winid' : 0}).winid)
4119  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
4120
4121  let qfid = g:Xgetlist({'id' : 0}).id
4122  call g:Xsetlist([], 'f')
4123
4124  " Non-existing quickfix identifier
4125  call assert_equal('', g:Xgetlist({'id' : qfid, 'context' : 0}).context)
4126  call assert_equal(0, g:Xgetlist({'id' : qfid}).id)
4127  call assert_equal(0, g:Xgetlist({'id' : qfid, 'idx' : 0}).idx)
4128  call assert_equal([], g:Xgetlist({'id' : qfid, 'items' : 0}).items)
4129  call assert_equal(0, g:Xgetlist({'id' : qfid, 'nr' : 0}).nr)
4130  call assert_equal(0, g:Xgetlist({'id' : qfid, 'size' : 0}).size)
4131  call assert_equal('', g:Xgetlist({'id' : qfid, 'title' : 0}).title)
4132  call assert_equal(0, g:Xgetlist({'id' : qfid, 'winid' : 0}).winid)
4133  call assert_equal(0, g:Xgetlist({'id' : qfid, 'changedtick' : 0}).changedtick)
4134  if a:cchar == 'c'
4135    call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
4136		\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
4137		\ 'qfbufnr' : qfbufnr, 'quickfixtextfunc' : '',
4138		\ 'changedtick' : 0}, g:Xgetlist({'id' : qfid, 'all' : 0}))
4139  else
4140    call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
4141		\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
4142		\ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0,
4143                \ 'quickfixtextfunc' : ''},
4144		\ g:Xgetlist({'id' : qfid, 'all' : 0}))
4145  endif
4146
4147  " Non-existing quickfix list number
4148  call assert_equal('', g:Xgetlist({'nr' : 5, 'context' : 0}).context)
4149  call assert_equal(0, g:Xgetlist({'nr' : 5}).nr)
4150  call assert_equal(0, g:Xgetlist({'nr' : 5, 'idx' : 0}).idx)
4151  call assert_equal([], g:Xgetlist({'nr' : 5, 'items' : 0}).items)
4152  call assert_equal(0, g:Xgetlist({'nr' : 5, 'id' : 0}).id)
4153  call assert_equal(0, g:Xgetlist({'nr' : 5, 'size' : 0}).size)
4154  call assert_equal('', g:Xgetlist({'nr' : 5, 'title' : 0}).title)
4155  call assert_equal(0, g:Xgetlist({'nr' : 5, 'winid' : 0}).winid)
4156  call assert_equal(0, g:Xgetlist({'nr' : 5, 'changedtick' : 0}).changedtick)
4157  if a:cchar == 'c'
4158    call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
4159		\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
4160		\ 'changedtick' : 0, 'qfbufnr' : qfbufnr,
4161                \ 'quickfixtextfunc' : ''}, g:Xgetlist({'nr' : 5, 'all' : 0}))
4162  else
4163    call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
4164		\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
4165		\ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0,
4166                \ 'quickfixtextfunc' : ''}, g:Xgetlist({'nr' : 5, 'all' : 0}))
4167  endif
4168endfunc
4169
4170func Test_empty_list_quickfixtextfunc()
4171  " This was crashing.  Can only reproduce by running it in a separate Vim
4172  " instance.
4173  let lines =<< trim END
4174      func s:Func(o)
4175              cgetexpr '0'
4176      endfunc
4177      cope
4178      let &quickfixtextfunc = 's:Func'
4179      cgetfile [ex
4180  END
4181  call writefile(lines, 'Xquickfixtextfunc')
4182  call RunVim([], [], '-e -s -S Xquickfixtextfunc -c qa')
4183  call delete('Xquickfixtextfunc')
4184endfunc
4185
4186func Test_getqflist()
4187  call Xgetlist_empty_tests('c')
4188  call Xgetlist_empty_tests('l')
4189endfunc
4190
4191func Test_getqflist_invalid_nr()
4192  " The following commands used to crash Vim
4193  cexpr ""
4194  call getqflist({'nr' : $XXX_DOES_NOT_EXIST_XXX})
4195
4196  " Cleanup
4197  call setqflist([], 'r')
4198endfunc
4199
4200" Tests for the quickfix/location list changedtick
4201func Xqftick_tests(cchar)
4202  call s:setup_commands(a:cchar)
4203
4204  call g:Xsetlist([], 'f')
4205
4206  Xexpr "F1:10:Line10"
4207  let qfid = g:Xgetlist({'id' : 0}).id
4208  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
4209  Xaddexpr "F2:20:Line20\nF2:21:Line21"
4210  call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick)
4211  call g:Xsetlist([], 'a', {'lines' : ["F3:30:Line30", "F3:31:Line31"]})
4212  call assert_equal(3, g:Xgetlist({'changedtick' : 0}).changedtick)
4213  call g:Xsetlist([], 'r', {'lines' : ["F4:40:Line40"]})
4214  call assert_equal(4, g:Xgetlist({'changedtick' : 0}).changedtick)
4215  call g:Xsetlist([], 'a', {'title' : 'New Title'})
4216  call assert_equal(5, g:Xgetlist({'changedtick' : 0}).changedtick)
4217
4218  enew!
4219  call append(0, ["F5:50:L50", "F6:60:L60"])
4220  Xaddbuffer
4221  call assert_equal(6, g:Xgetlist({'changedtick' : 0}).changedtick)
4222  enew!
4223
4224  call g:Xsetlist([], 'a', {'context' : {'bus' : 'pci'}})
4225  call assert_equal(7, g:Xgetlist({'changedtick' : 0}).changedtick)
4226  call g:Xsetlist([{'filename' : 'F7', 'lnum' : 10, 'text' : 'L7'},
4227	      \ {'filename' : 'F7', 'lnum' : 11, 'text' : 'L11'}], 'a')
4228  call assert_equal(8, g:Xgetlist({'changedtick' : 0}).changedtick)
4229  call g:Xsetlist([{'filename' : 'F7', 'lnum' : 10, 'text' : 'L7'},
4230	      \ {'filename' : 'F7', 'lnum' : 11, 'text' : 'L11'}], ' ')
4231  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
4232  call g:Xsetlist([{'filename' : 'F7', 'lnum' : 10, 'text' : 'L7'},
4233	      \ {'filename' : 'F7', 'lnum' : 11, 'text' : 'L11'}], 'r')
4234  call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick)
4235
4236  if isdirectory("Xone")
4237    call delete("Xone", 'rf')
4238  endif
4239  call writefile(["F8:80:L80", "F8:81:L81"], "Xone")
4240  Xfile Xone
4241  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
4242  Xaddfile Xone
4243  call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick)
4244
4245  " Test case for updating a non-current quickfix list
4246  call g:Xsetlist([], 'f')
4247  Xexpr "F1:1:L1"
4248  Xexpr "F2:2:L2"
4249  call g:Xsetlist([], 'a', {'nr' : 1, "lines" : ["F10:10:L10"]})
4250  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
4251  call assert_equal(2, g:Xgetlist({'nr' : 1, 'changedtick' : 0}).changedtick)
4252
4253  call delete("Xone")
4254endfunc
4255
4256func Test_qf_tick()
4257  call Xqftick_tests('c')
4258  call Xqftick_tests('l')
4259endfunc
4260
4261" Test helpgrep with lang specifier
4262func Xtest_helpgrep_with_lang_specifier(cchar)
4263  call s:setup_commands(a:cchar)
4264  Xhelpgrep Vim@en
4265  call assert_equal('help', &filetype)
4266  call assert_notequal(0, g:Xgetlist({'nr' : '$'}).nr)
4267  new | only
4268endfunc
4269
4270func Test_helpgrep_with_lang_specifier()
4271  call Xtest_helpgrep_with_lang_specifier('c')
4272  call Xtest_helpgrep_with_lang_specifier('l')
4273endfunc
4274
4275" The following test used to crash Vim.
4276" Open the location list window and close the regular window associated with
4277" the location list. When the garbage collection runs now, it incorrectly
4278" marks the location list context as not in use and frees the context.
4279func Test_ll_window_ctx()
4280  call setloclist(0, [], 'f')
4281  call setloclist(0, [], 'a', {'context' : []})
4282  lopen | only
4283  call test_garbagecollect_now()
4284  echo getloclist(0, {'context' : 1}).context
4285  enew | only
4286endfunc
4287
4288" Similar to the problem above, but for user data.
4289func Test_ll_window_user_data()
4290  call setloclist(0, [#{bufnr: bufnr(), user_data: {}}])
4291  lopen
4292  wincmd t
4293  close
4294  call test_garbagecollect_now()
4295  call feedkeys("\<CR>", 'tx')
4296  call test_garbagecollect_now()
4297  %bwipe!
4298endfunc
4299
4300" The following test used to crash vim
4301func Test_lfile_crash()
4302  sp Xtest
4303  au QuickFixCmdPre * bw
4304  call assert_fails('lfile', 'E40:')
4305  au! QuickFixCmdPre
4306endfunc
4307
4308" The following test used to crash vim
4309func Test_lbuffer_crash()
4310  sv Xtest
4311  augroup QF_Test
4312    au!
4313    au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * bw
4314  augroup END
4315  lbuffer
4316  augroup QF_Test
4317    au!
4318  augroup END
4319endfunc
4320
4321" The following test used to crash vim
4322func Test_lexpr_crash()
4323  augroup QF_Test
4324    au!
4325    au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * call setloclist(0, [], 'f')
4326  augroup END
4327  lexpr ""
4328  augroup QF_Test
4329    au!
4330  augroup END
4331
4332  enew | only
4333  augroup QF_Test
4334    au!
4335    au BufNew * call setloclist(0, [], 'f')
4336  augroup END
4337  lexpr 'x:1:x'
4338  augroup QF_Test
4339    au!
4340  augroup END
4341
4342  enew | only
4343  lexpr ''
4344  lopen
4345  augroup QF_Test
4346    au!
4347    au FileType * call setloclist(0, [], 'f')
4348  augroup END
4349  lexpr ''
4350  augroup QF_Test
4351    au!
4352  augroup END
4353endfunc
4354
4355" The following test used to crash Vim
4356func Test_lvimgrep_crash()
4357  " this leaves a swapfile .test_quickfix.vim.swp around, why?
4358  sv Xtest
4359  augroup QF_Test
4360    au!
4361    au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * call setloclist(0, [], 'f')
4362  augroup END
4363  lvimgrep quickfix test_quickfix.vim
4364  augroup QF_Test
4365    au!
4366  augroup END
4367
4368  new | only
4369  augroup QF_Test
4370    au!
4371    au BufEnter * call setloclist(0, [], 'r')
4372  augroup END
4373  call assert_fails('lvimgrep Test_lvimgrep_crash *', 'E926:')
4374  augroup QF_Test
4375    au!
4376  augroup END
4377
4378  enew | only
4379endfunc
4380
4381func Test_lvimgrep_crash2()
4382  au BufNewFile x sfind
4383  call assert_fails('lvimgrep x x', 'E471:')
4384  call assert_fails('lvimgrep x x x', 'E471:')
4385
4386  au! BufNewFile
4387endfunc
4388
4389" Test for the position of the quickfix and location list window
4390func Test_qfwin_pos()
4391  " Open two windows
4392  new | only
4393  new
4394  cexpr ['F1:10:L10']
4395  copen
4396  " Quickfix window should be the bottom most window
4397  call assert_equal(3, winnr())
4398  close
4399  " Open at the very top
4400  wincmd t
4401  topleft copen
4402  call assert_equal(1, winnr())
4403  close
4404  " open left of the current window
4405  wincmd t
4406  below new
4407  leftabove copen
4408  call assert_equal(2, winnr())
4409  close
4410  " open right of the current window
4411  rightbelow copen
4412  call assert_equal(3, winnr())
4413  close
4414endfunc
4415
4416" Tests for quickfix/location lists changed by autocommands when
4417" :vimgrep/:lvimgrep commands are running.
4418func Test_vimgrep_autocmd()
4419  call setqflist([], 'f')
4420  call writefile(['stars'], 'Xtest1.txt', 'D')
4421  call writefile(['stars'], 'Xtest2.txt', 'D')
4422
4423  " Test 1:
4424  " When searching for a pattern using :vimgrep, if the quickfix list is
4425  " changed by an autocmd, the results should be added to the correct quickfix
4426  " list.
4427  autocmd BufRead Xtest2.txt cexpr '' | cexpr ''
4428  silent vimgrep stars Xtest*.txt
4429  call assert_equal(1, getqflist({'nr' : 0}).nr)
4430  call assert_equal(3, getqflist({'nr' : '$'}).nr)
4431  call assert_equal('Xtest2.txt', bufname(getqflist()[1].bufnr))
4432  au! BufRead Xtest2.txt
4433
4434  " Test 2:
4435  " When searching for a pattern using :vimgrep, if the quickfix list is
4436  " freed, then a error should be given.
4437  silent! %bwipe!
4438  call setqflist([], 'f')
4439  autocmd BufRead Xtest2.txt for i in range(10) | cexpr '' | endfor
4440  call assert_fails('vimgrep stars Xtest*.txt', 'E925:')
4441  au! BufRead Xtest2.txt
4442
4443  " Test 3:
4444  " When searching for a pattern using :lvimgrep, if the location list is
4445  " freed, then the command should error out.
4446  silent! %bwipe!
4447  let g:save_winid = win_getid()
4448  autocmd BufRead Xtest2.txt call setloclist(g:save_winid, [], 'f')
4449  call assert_fails('lvimgrep stars Xtest*.txt', 'E926:')
4450  au! BufRead Xtest2.txt
4451  " cleanup the swap files
4452  bw! Xtest2.txt Xtest1.txt
4453
4454  call setqflist([], 'f')
4455endfunc
4456
4457" Test for an autocmd changing the current directory when running vimgrep
4458func Xvimgrep_autocmd_cd(cchar)
4459  call s:setup_commands(a:cchar)
4460
4461  %bwipe
4462  let save_cwd = getcwd()
4463
4464  augroup QF_Test
4465    au!
4466    autocmd BufRead * silent cd %:p:h
4467  augroup END
4468
4469  10Xvimgrep /vim/ Xdir/**
4470  let l = g:Xgetlist()
4471  call assert_equal('f1.txt', bufname(l[0].bufnr))
4472  call assert_equal('f2.txt', fnamemodify(bufname(l[2].bufnr), ':t'))
4473
4474  augroup QF_Test
4475    au!
4476  augroup END
4477
4478  exe 'cd ' . save_cwd
4479endfunc
4480
4481func Test_vimgrep_autocmd_cd()
4482  call mkdir('Xdir/a', 'p')
4483  call mkdir('Xdir/b', 'p')
4484  call writefile(['a_L1_vim', 'a_L2_vim'], 'Xdir/a/f1.txt')
4485  call writefile(['b_L1_vim', 'b_L2_vim'], 'Xdir/b/f2.txt')
4486  call Xvimgrep_autocmd_cd('c')
4487  call Xvimgrep_autocmd_cd('l')
4488  %bwipe
4489  call delete('Xdir', 'rf')
4490endfunc
4491
4492" The following test used to crash Vim
4493func Test_lhelpgrep_autocmd()
4494  lhelpgrep quickfix
4495  augroup QF_Test
4496    au!
4497    autocmd QuickFixCmdPost * call setloclist(0, [], 'f')
4498  augroup END
4499  lhelpgrep buffer
4500  call assert_equal('help', &filetype)
4501  call assert_equal(0, getloclist(0, {'nr' : '$'}).nr)
4502  lhelpgrep tabpage
4503  call assert_equal('help', &filetype)
4504  call assert_equal(1, getloclist(0, {'nr' : '$'}).nr)
4505  augroup QF_Test
4506    au!
4507  augroup END
4508
4509  new | only
4510  augroup QF_Test
4511    au!
4512    au BufEnter * call setqflist([], 'f')
4513  augroup END
4514  call assert_fails('helpgrep quickfix', 'E925:')
4515  " run the test with a help window already open
4516  help
4517  wincmd w
4518  call assert_fails('helpgrep quickfix', 'E925:')
4519  augroup QF_Test
4520    au!
4521  augroup END
4522
4523  new | only
4524  augroup QF_Test
4525    au!
4526    au BufEnter * call setqflist([], 'r')
4527  augroup END
4528  call assert_fails('helpgrep quickfix', 'E925:')
4529  augroup QF_Test
4530    au!
4531  augroup END
4532
4533  new | only
4534  augroup QF_Test
4535    au!
4536    au BufEnter * call setloclist(0, [], 'r')
4537  augroup END
4538  call assert_fails('lhelpgrep quickfix', 'E926:')
4539  augroup QF_Test
4540    au!
4541  augroup END
4542
4543  " Replace the contents of a help window location list when it is still in
4544  " use.
4545  new | only
4546  lhelpgrep quickfix
4547  wincmd w
4548  augroup QF_Test
4549    au!
4550    autocmd WinEnter * call setloclist(0, [], 'r')
4551  augroup END
4552  call assert_fails('lhelpgrep win_getid', 'E926:')
4553  augroup QF_Test
4554    au!
4555  augroup END
4556
4557  %bw!
4558endfunc
4559
4560" The following test used to crash Vim
4561func Test_lhelpgrep_autocmd_free_loclist()
4562  %bw!
4563  lhelpgrep quickfix
4564  wincmd w
4565  augroup QF_Test
4566    au!
4567    autocmd WinEnter * call setloclist(0, [], 'f')
4568  augroup END
4569  lhelpgrep win_getid
4570  wincmd w
4571  wincmd w
4572  wincmd w
4573  augroup QF_Test
4574    au!
4575  augroup END
4576  %bw!
4577endfunc
4578
4579" Test for shortening/simplifying the file name when opening the
4580" quickfix window or when displaying the quickfix list
4581func Test_shorten_fname()
4582  CheckUnix
4583  %bwipe
4584  " Create a quickfix list with an absolute path filename
4585  let fname = getcwd() . '/test_quickfix.vim'
4586  call setqflist([], ' ', {'lines':[fname . ":20:Line20"], 'efm':'%f:%l:%m'})
4587  call assert_equal(fname, bufname('test_quickfix.vim'))
4588  " Opening the quickfix window should simplify the file path
4589  cwindow
4590  call assert_equal('test_quickfix.vim', bufname('test_quickfix.vim'))
4591  cclose
4592  %bwipe
4593  " Create a quickfix list with an absolute path filename
4594  call setqflist([], ' ', {'lines':[fname . ":20:Line20"], 'efm':'%f:%l:%m'})
4595  call assert_equal(fname, bufname('test_quickfix.vim'))
4596  " Displaying the quickfix list should simplify the file path
4597  silent! clist
4598  call assert_equal('test_quickfix.vim', bufname('test_quickfix.vim'))
4599  " Add a few entries for the same file with different paths and check whether
4600  " the buffer name is shortened
4601  %bwipe
4602  call setqflist([], 'f')
4603  call setqflist([{'filename' : 'test_quickfix.vim', 'lnum' : 10},
4604        \ {'filename' : '../testdir/test_quickfix.vim', 'lnum' : 20},
4605        \ {'filename' : fname, 'lnum' : 30}], ' ')
4606  copen
4607  call assert_equal(['test_quickfix.vim|10| ',
4608        \ 'test_quickfix.vim|20| ',
4609        \ 'test_quickfix.vim|30| '], getline(1, '$'))
4610  cclose
4611endfunc
4612
4613" Quickfix title tests
4614" In the below tests, 'exe "cmd"' is used to invoke the quickfix commands.
4615" Otherwise due to indentation, the title is set with spaces at the beginning
4616" of the command.
4617func Test_qftitle()
4618  call writefile(["F1:1:Line1"], 'Xerr')
4619
4620  " :cexpr
4621  exe "cexpr readfile('Xerr')"
4622  call assert_equal(":cexpr readfile('Xerr')", getqflist({'title' : 1}).title)
4623
4624  " :cgetexpr
4625  exe "cgetexpr readfile('Xerr')"
4626  call assert_equal(":cgetexpr readfile('Xerr')",
4627					\ getqflist({'title' : 1}).title)
4628
4629  " :caddexpr
4630  call setqflist([], 'f')
4631  exe "caddexpr readfile('Xerr')"
4632  call assert_equal(":caddexpr readfile('Xerr')",
4633					\ getqflist({'title' : 1}).title)
4634
4635  " :cbuffer
4636  new Xerr
4637  exe "cbuffer"
4638  call assert_equal(':cbuffer (Xerr)', getqflist({'title' : 1}).title)
4639
4640  " :cgetbuffer
4641  edit Xerr
4642  exe "cgetbuffer"
4643  call assert_equal(':cgetbuffer (Xerr)', getqflist({'title' : 1}).title)
4644
4645  " :caddbuffer
4646  call setqflist([], 'f')
4647  edit Xerr
4648  exe "caddbuffer"
4649  call assert_equal(':caddbuffer (Xerr)', getqflist({'title' : 1}).title)
4650
4651  " :cfile
4652  exe "cfile Xerr"
4653  call assert_equal(':cfile Xerr', getqflist({'title' : 1}).title)
4654
4655  " :cgetfile
4656  exe "cgetfile Xerr"
4657  call assert_equal(':cgetfile Xerr', getqflist({'title' : 1}).title)
4658
4659  " :caddfile
4660  call setqflist([], 'f')
4661  exe "caddfile Xerr"
4662  call assert_equal(':caddfile Xerr', getqflist({'title' : 1}).title)
4663
4664  " :grep
4665  set grepprg=internal
4666  exe "grep F1 Xerr"
4667  call assert_equal(':grep F1 Xerr', getqflist({'title' : 1}).title)
4668
4669  " :grepadd
4670  call setqflist([], 'f')
4671  exe "grepadd F1 Xerr"
4672  call assert_equal(':grepadd F1 Xerr', getqflist({'title' : 1}).title)
4673  set grepprg&vim
4674
4675  " :vimgrep
4676  exe "vimgrep F1 Xerr"
4677  call assert_equal(':vimgrep F1 Xerr', getqflist({'title' : 1}).title)
4678
4679  " :vimgrepadd
4680  call setqflist([], 'f')
4681  exe "vimgrepadd F1 Xerr"
4682  call assert_equal(':vimgrepadd F1 Xerr', getqflist({'title' : 1}).title)
4683
4684  call setqflist(['F1:10:L10'], ' ')
4685  call assert_equal(':setqflist()', getqflist({'title' : 1}).title)
4686
4687  call setqflist([], 'f')
4688  call setqflist(['F1:10:L10'], 'a')
4689  call assert_equal(':setqflist()', getqflist({'title' : 1}).title)
4690
4691  call setqflist([], 'f')
4692  call setqflist(['F1:10:L10'], 'r')
4693  call assert_equal(':setqflist()', getqflist({'title' : 1}).title)
4694
4695  close
4696  call delete('Xerr')
4697
4698  call setqflist([], ' ', {'title' : 'Errors'})
4699  copen
4700  call assert_equal('Errors', w:quickfix_title)
4701  call setqflist([], 'r', {'items' : [{'filename' : 'a.c', 'lnum' : 10}]})
4702  call assert_equal('Errors', w:quickfix_title)
4703  cclose
4704
4705  " Switching to another quickfix list in one tab page should update the
4706  " quickfix window title and statusline in all the other tab pages also
4707  call setqflist([], 'f')
4708  %bw!
4709  cgetexpr ['file_one:1:1: error in the first quickfix list']
4710  call setqflist([], 'a', {'title': 'first quickfix list'})
4711  cgetexpr ['file_two:2:1: error in the second quickfix list']
4712  call setqflist([], 'a', {'title': 'second quickfix list'})
4713  copen
4714  wincmd t
4715  tabnew two
4716  copen
4717  wincmd t
4718  colder
4719  call assert_equal('first quickfix list', gettabwinvar(1, 2, 'quickfix_title'))
4720  call assert_equal('first quickfix list', gettabwinvar(2, 2, 'quickfix_title'))
4721  call assert_equal(1, tabpagewinnr(1))
4722  call assert_equal(1, tabpagewinnr(2))
4723  tabnew
4724  call setqflist([], 'a', {'title': 'new quickfix title'})
4725  call assert_equal('new quickfix title', gettabwinvar(1, 2, 'quickfix_title'))
4726  call assert_equal('new quickfix title', gettabwinvar(2, 2, 'quickfix_title'))
4727  %bw!
4728endfunc
4729
4730func Test_lbuffer_with_bwipe()
4731  new
4732  new
4733  augroup nasty
4734    au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * bwipe
4735  augroup END
4736  lbuffer
4737  augroup nasty
4738    au!
4739  augroup END
4740endfunc
4741
4742" Test for an autocmd freeing the quickfix/location list when cexpr/lexpr is
4743" running
4744func Xexpr_acmd_freelist(cchar)
4745  call s:setup_commands(a:cchar)
4746
4747  " This was using freed memory (but with what events?)
4748  augroup nasty
4749    au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * call g:Xsetlist([], 'f')
4750  augroup END
4751  Xexpr "x"
4752  augroup nasty
4753    au!
4754  augroup END
4755endfunc
4756
4757func Test_cexpr_acmd_freelist()
4758  call Xexpr_acmd_freelist('c')
4759  call Xexpr_acmd_freelist('l')
4760endfunc
4761
4762" Test for commands that create a new quickfix/location list and jump to the
4763" first error automatically.
4764func Xjumpto_first_error_test(cchar)
4765  call s:setup_commands(a:cchar)
4766
4767  call s:create_test_file('Xtestfile1')
4768  call s:create_test_file('Xtestfile2')
4769  let l = ['Xtestfile1:2:Line2', 'Xtestfile2:4:Line4']
4770
4771  " Test for cexpr/lexpr
4772  enew
4773  Xexpr l
4774  call assert_equal('Xtestfile1', @%)
4775  call assert_equal(2, line('.'))
4776
4777  " Test for cfile/lfile
4778  enew
4779  call writefile(l, 'Xerr')
4780  Xfile Xerr
4781  call assert_equal('Xtestfile1', @%)
4782  call assert_equal(2, line('.'))
4783
4784  " Test for cbuffer/lbuffer
4785  edit Xerr
4786  Xbuffer
4787  call assert_equal('Xtestfile1', @%)
4788  call assert_equal(2, line('.'))
4789
4790  call delete('Xerr')
4791  call delete('Xtestfile1')
4792  call delete('Xtestfile2')
4793endfunc
4794
4795func Test_jumpto_first_error()
4796  call Xjumpto_first_error_test('c')
4797  call Xjumpto_first_error_test('l')
4798endfunc
4799
4800" Test for a quickfix autocmd changing the quickfix/location list before
4801" jumping to the first error in the new list.
4802func Xautocmd_changelist(cchar)
4803  call s:setup_commands(a:cchar)
4804
4805  " Test for cfile/lfile
4806  call s:create_test_file('Xtestfile1')
4807  call s:create_test_file('Xtestfile2')
4808  Xexpr 'Xtestfile1:2:Line2'
4809  autocmd QuickFixCmdPost * Xolder
4810  call writefile(['Xtestfile2:4:Line4'], 'Xerr')
4811  Xfile Xerr
4812  call assert_equal('Xtestfile2', @%)
4813  call assert_equal(4, line('.'))
4814  autocmd! QuickFixCmdPost
4815
4816  " Test for cbuffer/lbuffer
4817  call g:Xsetlist([], 'f')
4818  Xexpr 'Xtestfile1:2:Line2'
4819  autocmd QuickFixCmdPost * Xolder
4820  call writefile(['Xtestfile2:4:Line4'], 'Xerr')
4821  edit Xerr
4822  Xbuffer
4823  call assert_equal('Xtestfile2', @%)
4824  call assert_equal(4, line('.'))
4825  autocmd! QuickFixCmdPost
4826
4827  " Test for cexpr/lexpr
4828  call g:Xsetlist([], 'f')
4829  Xexpr 'Xtestfile1:2:Line2'
4830  autocmd QuickFixCmdPost * Xolder
4831  Xexpr 'Xtestfile2:4:Line4'
4832  call assert_equal('Xtestfile2', @%)
4833  call assert_equal(4, line('.'))
4834  autocmd! QuickFixCmdPost
4835
4836  " The grepprg may not be set on non-Unix systems
4837  if has('unix')
4838    " Test for grep/lgrep
4839    call g:Xsetlist([], 'f')
4840    Xexpr 'Xtestfile1:2:Line2'
4841    autocmd QuickFixCmdPost * Xolder
4842    silent Xgrep Line5 Xtestfile2
4843    call assert_equal('Xtestfile2', @%)
4844    call assert_equal(5, line('.'))
4845    autocmd! QuickFixCmdPost
4846  endif
4847
4848  " Test for vimgrep/lvimgrep
4849  call g:Xsetlist([], 'f')
4850  Xexpr 'Xtestfile1:2:Line2'
4851  autocmd QuickFixCmdPost * Xolder
4852  silent Xvimgrep Line5 Xtestfile2
4853  call assert_equal('Xtestfile2', @%)
4854  call assert_equal(5, line('.'))
4855  autocmd! QuickFixCmdPost
4856
4857  " Test for autocommands clearing the quickfix list before jumping to the
4858  " first error. This should not result in an error
4859  autocmd QuickFixCmdPost * call g:Xsetlist([], 'r')
4860  let v:errmsg = ''
4861  " Test for cfile/lfile
4862  Xfile Xerr
4863  call assert_true(v:errmsg !~# 'E42:')
4864  " Test for cbuffer/lbuffer
4865  edit Xerr
4866  Xbuffer
4867  call assert_true(v:errmsg !~# 'E42:')
4868  " Test for cexpr/lexpr
4869  Xexpr 'Xtestfile2:4:Line4'
4870  call assert_true(v:errmsg !~# 'E42:')
4871  " Test for grep/lgrep
4872  " The grepprg may not be set on non-Unix systems
4873  if has('unix')
4874    silent Xgrep Line5 Xtestfile2
4875    call assert_true(v:errmsg !~# 'E42:')
4876  endif
4877  " Test for vimgrep/lvimgrep
4878  call assert_fails('silent Xvimgrep Line5 Xtestfile2', 'E480:')
4879  autocmd! QuickFixCmdPost
4880
4881  call delete('Xerr')
4882  call delete('Xtestfile1')
4883  call delete('Xtestfile2')
4884endfunc
4885
4886func Test_autocmd_changelist()
4887  call Xautocmd_changelist('c')
4888  call Xautocmd_changelist('l')
4889endfunc
4890
4891" Tests for the ':filter /pat/ clist' command
4892func Test_filter_clist()
4893  cexpr ['Xfile1:10:10:Line 10', 'Xfile2:15:15:Line 15']
4894  call assert_equal([' 2 Xfile2:15 col 15: Line 15'],
4895			\ split(execute('filter /Line 15/ clist'), "\n"))
4896  call assert_equal([' 1 Xfile1:10 col 10: Line 10'],
4897			\ split(execute('filter /Xfile1/ clist'), "\n"))
4898  call assert_equal([], split(execute('filter /abc/ clist'), "\n"))
4899
4900  call setqflist([{'module' : 'abc', 'pattern' : 'pat1'},
4901			\ {'module' : 'pqr', 'pattern' : 'pat2'}], ' ')
4902  call assert_equal([' 2 pqr:pat2:  '],
4903			\ split(execute('filter /pqr/ clist'), "\n"))
4904  call assert_equal([' 1 abc:pat1:  '],
4905			\ split(execute('filter /pat1/ clist'), "\n"))
4906endfunc
4907
4908" Tests for the "CTRL-W <CR>" command.
4909func Xview_result_split_tests(cchar)
4910  call s:setup_commands(a:cchar)
4911
4912  " Test that "CTRL-W <CR>" in a qf/ll window fails with empty list.
4913  call g:Xsetlist([])
4914  Xopen
4915  let l:win_count = winnr('$')
4916  call assert_fails('execute "normal! \<C-W>\<CR>"', 'E42')
4917  call assert_equal(l:win_count, winnr('$'))
4918  Xclose
4919endfunc
4920
4921func Test_view_result_split()
4922  call Xview_result_split_tests('c')
4923  call Xview_result_split_tests('l')
4924endfunc
4925
4926" Test that :cc sets curswant
4927func Test_curswant()
4928  helpgrep quickfix
4929  normal! llll
4930  1cc
4931  call assert_equal(getcurpos()[4], virtcol('.'))
4932  cclose | helpclose
4933endfunc
4934
4935" Test for opening a file from the quickfix window using CTRL-W <Enter>
4936" doesn't leave an empty buffer around.
4937func Test_splitview()
4938  call s:create_test_file('Xtestfile1')
4939  call s:create_test_file('Xtestfile2')
4940  new | only
4941  let last_bufnr = bufnr('Test_sv_1', 1)
4942  let l = ['Xtestfile1:2:Line2', 'Xtestfile2:4:Line4']
4943  cgetexpr l
4944  copen
4945  let numbufs = len(getbufinfo())
4946  exe "normal \<C-W>\<CR>"
4947  copen
4948  exe "normal j\<C-W>\<CR>"
4949  " Make sure new empty buffers are not created
4950  call assert_equal(numbufs, len(getbufinfo()))
4951  " Creating a new buffer should use the next available buffer number
4952  call assert_equal(last_bufnr + 4, bufnr("Test_sv_2", 1))
4953  bwipe Test_sv_1
4954  bwipe Test_sv_2
4955  new | only
4956
4957  " When split opening files from location list window, make sure that two
4958  " windows doesn't refer to the same location list
4959  lgetexpr l
4960  let locid = getloclist(0, {'id' : 0}).id
4961  lopen
4962  exe "normal \<C-W>\<CR>"
4963  call assert_notequal(locid, getloclist(0, {'id' : 0}).id)
4964  call assert_equal(0, getloclist(0, {'winid' : 0}).winid)
4965  new | only
4966
4967  " When split opening files from a helpgrep location list window, a new help
4968  " window should be opened with a copy of the location list.
4969  lhelpgrep window
4970  let locid = getloclist(0, {'id' : 0}).id
4971  lwindow
4972  exe "normal j\<C-W>\<CR>"
4973  call assert_notequal(locid, getloclist(0, {'id' : 0}).id)
4974  call assert_equal(0, getloclist(0, {'winid' : 0}).winid)
4975  new | only
4976
4977  " Using :split or :vsplit from a quickfix window should behave like a :new
4978  " or a :vnew command
4979  copen
4980  split
4981  call assert_equal(3, winnr('$'))
4982  let l = getwininfo()
4983  call assert_equal([0, 0, 1], [l[0].quickfix, l[1].quickfix, l[2].quickfix])
4984  close
4985  copen
4986  vsplit
4987  let l = getwininfo()
4988  call assert_equal([0, 0, 1], [l[0].quickfix, l[1].quickfix, l[2].quickfix])
4989  new | only
4990
4991  call delete('Xtestfile1')
4992  call delete('Xtestfile2')
4993endfunc
4994
4995" Test for parsing entries using visual screen column
4996func Test_viscol()
4997  enew
4998  call writefile(["Col1\tCol2\tCol3"], 'Xfile1', 'D')
4999  edit Xfile1
5000
5001  " Use byte offset for column number
5002  set efm&
5003  cexpr "Xfile1:1:5:XX\nXfile1:1:9:YY\nXfile1:1:20:ZZ"
5004  call assert_equal([5, 8], [col('.'), virtcol('.')])
5005  cnext
5006  call assert_equal([9, 12], [col('.'), virtcol('.')])
5007  cnext
5008  call assert_equal([14, 20], [col('.'), virtcol('.')])
5009
5010  " Use screen column offset for column number
5011  set efm=%f:%l:%v:%m
5012  cexpr "Xfile1:1:8:XX\nXfile1:1:12:YY\nXfile1:1:20:ZZ"
5013  call assert_equal([5, 8], [col('.'), virtcol('.')])
5014  cnext
5015  call assert_equal([9, 12], [col('.'), virtcol('.')])
5016  cnext
5017  call assert_equal([14, 20], [col('.'), virtcol('.')])
5018  cexpr "Xfile1:1:6:XX\nXfile1:1:15:YY\nXfile1:1:24:ZZ"
5019  call assert_equal([5, 8], [col('.'), virtcol('.')])
5020  cnext
5021  call assert_equal([10, 16], [col('.'), virtcol('.')])
5022  cnext
5023  call assert_equal([14, 20], [col('.'), virtcol('.')])
5024
5025  enew
5026  call writefile(["Col1\täü\töß\tCol4"], 'Xfile1')
5027
5028  " Use byte offset for column number
5029  set efm&
5030  cexpr "Xfile1:1:8:XX\nXfile1:1:11:YY\nXfile1:1:16:ZZ"
5031  call assert_equal([8, 10], [col('.'), virtcol('.')])
5032  cnext
5033  call assert_equal([11, 17], [col('.'), virtcol('.')])
5034  cnext
5035  call assert_equal([16, 25], [col('.'), virtcol('.')])
5036
5037  " Use screen column offset for column number
5038  set efm=%f:%l:%v:%m
5039  cexpr "Xfile1:1:10:XX\nXfile1:1:17:YY\nXfile1:1:25:ZZ"
5040  call assert_equal([8, 10], [col('.'), virtcol('.')])
5041  cnext
5042  call assert_equal([11, 17], [col('.'), virtcol('.')])
5043  cnext
5044  call assert_equal([16, 25], [col('.'), virtcol('.')])
5045
5046  " Use screen column number with a multi-line error message
5047  enew
5048  call writefile(["à test"], 'Xfile1')
5049  set efm=%E===\ %f\ ===,%C%l:%v,%Z%m
5050  cexpr ["=== Xfile1 ===", "1:3", "errormsg"]
5051  call assert_equal('Xfile1', @%)
5052  call assert_equal([0, 1, 4, 0], getpos('.'))
5053
5054  " Repeat previous test with byte offset %c: ensure that fix to issue #7145
5055  " does not break this
5056  set efm=%E===\ %f\ ===,%C%l:%c,%Z%m
5057  cexpr ["=== Xfile1 ===", "1:3", "errormsg"]
5058  call assert_equal('Xfile1', @%)
5059  call assert_equal([0, 1, 3, 0], getpos('.'))
5060
5061  enew | only
5062  set efm&
5063endfunc
5064
5065" Test that '%v' is not affected by 'tabstop': a <tab> is always counted as
5066" 8 screen columns, matching the column numbers reported by compilers.
5067func Test_viscol_tabstop()
5068  enew
5069  call writefile(["\tABCDEFGH"], 'Xfile1', 'D')
5070  edit Xfile1
5071  set efm=%f:%l:%v:%m
5072
5073  " gcc reports column 9 for 'A' (the <tab> expands to 8 columns).  The jump
5074  " must land on 'A' (byte 2) for any 'tabstop' value.
5075  for ts in [8, 4, 2, 13]
5076    exe 'setlocal tabstop=' .. ts
5077    cexpr "Xfile1:1:9:XX"
5078    call assert_equal(2, col('.'), 'tabstop=' .. ts)
5079  endfor
5080
5081  " A multi-byte character after the tab: 'ä' is 2 bytes but 1 screen cell,
5082  " so screen column 10 is the next character 'b' (byte 4).
5083  call writefile(["\täbc"], 'Xfile1')
5084  edit! Xfile1
5085  setlocal tabstop=4
5086  cexpr "Xfile1:1:10:XX"
5087  call assert_equal(4, col('.'))
5088
5089  enew | only
5090  set efm&
5091endfunc
5092
5093" Test for the quickfix window buffer
5094func Xqfbuf_test(cchar)
5095  call s:setup_commands(a:cchar)
5096
5097  " Quickfix buffer should be reused across closing and opening a quickfix
5098  " window
5099  Xexpr "F1:10:Line10"
5100  Xopen
5101  let qfbnum = bufnr('')
5102  Xclose
5103  " Even after the quickfix window is closed, the buffer should be loaded
5104  call assert_true(bufloaded(qfbnum))
5105  call assert_true(qfbnum, g:Xgetlist({'qfbufnr' : 0}).qfbufnr)
5106  Xopen
5107  " Buffer should be reused when opening the window again
5108  call assert_equal(qfbnum, bufnr(''))
5109  Xclose
5110
5111  " When quickfix buffer is wiped out, getqflist() should return 0
5112  %bw!
5113  Xexpr ""
5114  Xopen
5115  bw!
5116  call assert_equal(0, g:Xgetlist({'qfbufnr': 0}).qfbufnr)
5117
5118  if a:cchar == 'l'
5119    %bwipe
5120    " For a location list, when both the file window and the location list
5121    " window for the list are closed, then the buffer should be freed.
5122    new | only
5123    lexpr "F1:10:Line10"
5124    let wid = win_getid()
5125    lopen
5126    let qfbnum = bufnr('')
5127    call assert_match(qfbnum . ' %a-  "\[Location List]"', execute('ls'))
5128    close
5129    " When the location list window is closed, the buffer name should not
5130    " change to 'Quickfix List'
5131    call assert_match(qfbnum . 'u h-  "\[Location List]"', execute('ls!'))
5132    call assert_true(bufloaded(qfbnum))
5133
5134    " After deleting a location list buffer using ":bdelete", opening the
5135    " location list window should mark the buffer as a location list buffer.
5136    exe "bdelete " . qfbnum
5137    lopen
5138    call assert_equal("quickfix", &buftype)
5139    call assert_equal(1, getwininfo(win_getid(winnr()))[0].loclist)
5140    call assert_equal(wid, getloclist(0, {'filewinid' : 0}).filewinid)
5141    call assert_false(&swapfile)
5142    lclose
5143
5144    " When the location list is cleared for the window, the buffer should be
5145    " removed
5146    call setloclist(0, [], 'f')
5147    call assert_false(bufexists(qfbnum))
5148    call assert_equal(0, getloclist(0, {'qfbufnr' : 0}).qfbufnr)
5149
5150    " When the location list is freed with the location list window open, the
5151    " location list buffer should not be lost. It should be reused when the
5152    " location list is again populated.
5153    lexpr "F1:10:Line10"
5154    lopen
5155    let wid = win_getid()
5156    let qfbnum = bufnr('')
5157    wincmd p
5158    call setloclist(0, [], 'f')
5159    lexpr "F1:10:Line10"
5160    lopen
5161    call assert_equal(wid, win_getid())
5162    call assert_equal(qfbnum, bufnr(''))
5163    lclose
5164
5165    " When the window with the location list is closed, the buffer should be
5166    " removed
5167    new | only
5168    call assert_false(bufexists(qfbnum))
5169  endif
5170endfunc
5171
5172func Test_qfbuf()
5173  call Xqfbuf_test('c')
5174  call Xqfbuf_test('l')
5175endfunc
5176
5177" If there is an autocmd to use only one window, then opening the location
5178" list window used to crash Vim.
5179func Test_winonly_autocmd()
5180  call s:create_test_file('Xtest1')
5181  " Autocmd to show only one Vim window at a time
5182  autocmd WinEnter * only
5183  new
5184  " Load the location list
5185  lexpr "Xtest1:5:Line5\nXtest1:10:Line10\nXtest1:15:Line15"
5186  let loclistid = getloclist(0, {'id' : 0}).id
5187  " Open the location list window. Only this window will be shown and the file
5188  " window is closed.
5189  lopen
5190  call assert_equal(loclistid, getloclist(0, {'id' : 0}).id)
5191  " Jump to an entry in the location list and make sure that the cursor is
5192  " positioned correctly.
5193  ll 3
5194  call assert_equal(loclistid, getloclist(0, {'id' : 0}).id)
5195  call assert_equal('Xtest1', @%)
5196  call assert_equal(15, line('.'))
5197  " Cleanup
5198  autocmd! WinEnter
5199  new | only
5200  call delete('Xtest1')
5201endfunc
5202
5203" Test to make sure that an empty quickfix buffer is not reused for loading
5204" a normal buffer.
5205func Test_empty_qfbuf()
5206  enew | only
5207  call writefile(["Test"], 'Xfile1')
5208  call setqflist([], 'f')
5209  copen | only
5210  let qfbuf = bufnr('')
5211  edit Xfile1
5212  call assert_notequal(qfbuf, bufnr(''))
5213  enew
5214  call delete('Xfile1')
5215endfunc
5216
5217" Test for the :cbelow, :cabove, :lbelow and :labove commands.
5218" And for the :cafter, :cbefore, :lafter and :lbefore commands.
5219func Xtest_below(cchar)
5220  call s:setup_commands(a:cchar)
5221
5222  " No quickfix/location list
5223  call assert_fails('Xbelow', 'E42:')
5224  call assert_fails('Xabove', 'E42:')
5225  call assert_fails('Xbefore', 'E42:')
5226  call assert_fails('Xafter', 'E42:')
5227
5228  " Empty quickfix/location list
5229  call g:Xsetlist([])
5230  call assert_fails('Xbelow', 'E42:')
5231  call assert_fails('Xabove', 'E42:')
5232  call assert_fails('Xbefore', 'E42:')
5233  call assert_fails('Xafter', 'E42:')
5234
5235  call s:create_test_file('X1')
5236  call s:create_test_file('X2')
5237  call s:create_test_file('X3')
5238  call s:create_test_file('X4')
5239
5240  " Invalid entries
5241  edit X1
5242  call g:Xsetlist(["E1", "E2"])
5243  call assert_fails('Xbelow', 'E42:')
5244  call assert_fails('Xabove', 'E42:')
5245  call assert_fails('3Xbelow', 'E42:')
5246  call assert_fails('4Xabove', 'E42:')
5247  call assert_fails('Xbefore', 'E42:')
5248  call assert_fails('Xafter', 'E42:')
5249  call assert_fails('3Xbefore', 'E42:')
5250  call assert_fails('4Xafter', 'E42:')
5251
5252  " Test the commands with various arguments
5253  Xexpr ["X1:5:3:L5", "X2:5:2:L5", "X2:10:3:L10", "X2:15:4:L15", "X3:3:5:L3"]
5254  edit +7 X2
5255  Xabove
5256  call assert_equal(['X2', 5], [@%, line('.')])
5257  call assert_fails('Xabove', 'E553:')
5258  normal 7G
5259  Xbefore
5260  call assert_equal(['X2', 5, 2], [@%, line('.'), col('.')])
5261  call assert_fails('Xbefore', 'E553:')
5262
5263  normal 2j
5264  Xbelow
5265  call assert_equal(['X2', 10], [@%, line('.')])
5266  normal 7G
5267  Xafter
5268  call assert_equal(['X2', 10, 3], [@%, line('.'), col('.')])
5269
5270  " Last error in this file
5271  Xbelow 99
5272  call assert_equal(['X2', 15], [@%, line('.')])
5273  call assert_fails('Xbelow', 'E553:')
5274  normal gg
5275  Xafter 99
5276  call assert_equal(['X2', 15, 4], [@%, line('.'), col('.')])
5277  call assert_fails('Xafter', 'E553:')
5278
5279  " First error in this file
5280  Xabove 99
5281  call assert_equal(['X2', 5], [@%, line('.')])
5282  call assert_fails('Xabove', 'E553:')
5283  normal G
5284  Xbefore 99
5285  call assert_equal(['X2', 5, 2], [@%, line('.'), col('.')])
5286  call assert_fails('Xbefore', 'E553:')
5287
5288  normal gg
5289  Xbelow 2
5290  call assert_equal(['X2', 10], [@%, line('.')])
5291  normal gg
5292  Xafter 2
5293  call assert_equal(['X2', 10, 3], [@%, line('.'), col('.')])
5294
5295  normal G
5296  Xabove 2
5297  call assert_equal(['X2', 10], [@%, line('.')])
5298  normal G
5299  Xbefore 2
5300  call assert_equal(['X2', 10, 3], [@%, line('.'), col('.')])
5301
5302  edit X4
5303  call assert_fails('Xabove', 'E42:')
5304  call assert_fails('Xbelow', 'E42:')
5305  call assert_fails('Xbefore', 'E42:')
5306  call assert_fails('Xafter', 'E42:')
5307  if a:cchar == 'l'
5308    " If a buffer has location list entries from some other window but not
5309    " from the current window, then the commands should fail.
5310    edit X1 | split | call setloclist(0, [], 'f')
5311    call assert_fails('Xabove', 'E776:')
5312    call assert_fails('Xbelow', 'E776:')
5313    call assert_fails('Xbefore', 'E776:')
5314    call assert_fails('Xafter', 'E776:')
5315    close
5316  endif
5317
5318  " Test for lines with multiple quickfix entries
5319  let lines =<< trim END
5320    X1:5:L5
5321    X2:5:1:L5_1
5322    X2:5:2:L5_2
5323    X2:5:3:L5_3
5324    X2:10:1:L10_1
5325    X2:10:2:L10_2
5326    X2:10:3:L10_3
5327    X2:15:1:L15_1
5328    X2:15:2:L15_2
5329    X2:15:3:L15_3
5330    X3:3:L3
5331  END
5332  Xexpr lines
5333  edit +1 X2
5334  Xbelow 2
5335  call assert_equal(['X2', 10, 1], [@%, line('.'), col('.')])
5336  normal 1G
5337  Xafter 2
5338  call assert_equal(['X2', 5, 2], [@%, line('.'), col('.')])
5339
5340  normal gg
5341  Xbelow 99
5342  call assert_equal(['X2', 15, 1], [@%, line('.'), col('.')])
5343  normal gg
5344  Xafter 99
5345  call assert_equal(['X2', 15, 3], [@%, line('.'), col('.')])
5346
5347  normal G
5348  Xabove 2
5349  call assert_equal(['X2', 10, 1], [@%, line('.'), col('.')])
5350  normal G
5351  Xbefore 2
5352  call assert_equal(['X2', 15, 2], [@%, line('.'), col('.')])
5353
5354  normal G
5355  Xabove 99
5356  call assert_equal(['X2', 5, 1], [@%, line('.'), col('.')])
5357  normal G
5358  Xbefore 99
5359  call assert_equal(['X2', 5, 1], [@%, line('.'), col('.')])
5360
5361  normal 10G
5362  Xabove
5363  call assert_equal(['X2', 5, 1], [@%, line('.'), col('.')])
5364  normal 10G$
5365  2Xbefore
5366  call assert_equal(['X2', 10, 2], [@%, line('.'), col('.')])
5367
5368  normal 10G
5369  Xbelow
5370  call assert_equal(['X2', 15, 1], [@%, line('.'), col('.')])
5371  normal 9G
5372  5Xafter
5373  call assert_equal(['X2', 15, 2], [@%, line('.'), col('.')])
5374
5375  " Invalid range
5376  if a:cchar == 'c'
5377    call assert_fails('-2cbelow', 'E16:')
5378    call assert_fails('-2cafter', 'E16:')
5379  else
5380    call assert_fails('-2lbelow', 'E16:')
5381    call assert_fails('-2lafter', 'E16:')
5382  endif
5383
5384  call delete('X1')
5385  call delete('X2')
5386  call delete('X3')
5387  call delete('X4')
5388endfunc
5389
5390func Test_cbelow()
5391  call Xtest_below('c')
5392  call Xtest_below('l')
5393endfunc
5394
5395func Test_quickfix_count()
5396  let commands =<< trim END
5397    cNext
5398    cNfile
5399    cabove
5400    cbelow
5401    cfirst
5402    clast
5403    cnewer
5404    cnext
5405    cnfile
5406    colder
5407    cprevious
5408    crewind
5409    lNext
5410    lNfile
5411    labove
5412    lbelow
5413    lfirst
5414    llast
5415    lnewer
5416    lnext
5417    lnfile
5418    lolder
5419    lprevious
5420    lrewind
5421  END
5422  for cmd in commands
5423    call assert_fails('-1' .. cmd, 'E16:')
5424    call assert_fails('.' .. cmd, 'E16:')
5425    call assert_fails('%' .. cmd, 'E16:')
5426    call assert_fails('$' .. cmd, 'E16:')
5427  endfor
5428endfunc
5429
5430" Test for aborting quickfix commands using QuickFixCmdPre
5431func Xtest_qfcmd_abort(cchar)
5432  call s:setup_commands(a:cchar)
5433
5434  call g:Xsetlist([], 'f')
5435
5436  " cexpr/lexpr
5437  let e = ''
5438  try
5439    Xexpr ["F1:10:Line10", "F2:20:Line20"]
5440  catch /.*/
5441    let e = v:exception
5442  endtry
5443  call assert_equal('AbortCmd', e)
5444  call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
5445
5446  " cfile/lfile
5447  call writefile(["F1:10:Line10", "F2:20:Line20"], 'Xfile1')
5448  let e = ''
5449  try
5450    Xfile Xfile1
5451  catch /.*/
5452    let e = v:exception
5453  endtry
5454  call assert_equal('AbortCmd', e)
5455  call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
5456  call delete('Xfile1')
5457
5458  " cgetbuffer/lgetbuffer
5459  enew!
5460  call append(0, ["F1:10:Line10", "F2:20:Line20"])
5461  let e = ''
5462  try
5463    Xgetbuffer
5464  catch /.*/
5465    let e = v:exception
5466  endtry
5467  call assert_equal('AbortCmd', e)
5468  call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
5469  enew!
5470
5471  " vimgrep/lvimgrep
5472  let e = ''
5473  try
5474    Xvimgrep /func/ test_quickfix.vim
5475  catch /.*/
5476    let e = v:exception
5477  endtry
5478  call assert_equal('AbortCmd', e)
5479  call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
5480
5481  " helpgrep/lhelpgrep
5482  let e = ''
5483  try
5484    Xhelpgrep quickfix
5485  catch /.*/
5486    let e = v:exception
5487  endtry
5488  call assert_equal('AbortCmd', e)
5489  call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
5490
5491  " grep/lgrep
5492  if has('unix')
5493    let e = ''
5494    try
5495      silent Xgrep func test_quickfix.vim
5496    catch /.*/
5497      let e = v:exception
5498    endtry
5499    call assert_equal('AbortCmd', e)
5500    call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr)
5501  endif
5502endfunc
5503
5504func Test_qfcmd_abort()
5505  augroup QF_Test
5506    au!
5507    autocmd  QuickFixCmdPre * throw "AbortCmd"
5508  augroup END
5509
5510  call Xtest_qfcmd_abort('c')
5511  call Xtest_qfcmd_abort('l')
5512
5513  augroup QF_Test
5514    au!
5515  augroup END
5516endfunc
5517
5518" Test for using a file in one of the parent directories.
5519func Test_search_in_dirstack()
5520  call mkdir('Xtestdir/a/b/c', 'p')
5521  let save_cwd = getcwd()
5522  call writefile(["X1_L1", "X1_L2"], 'Xtestdir/Xfile1')
5523  call writefile(["X2_L1", "X2_L2"], 'Xtestdir/a/Xfile2')
5524  call writefile(["X3_L1", "X3_L2"], 'Xtestdir/a/b/Xfile3')
5525  call writefile(["X4_L1", "X4_L2"], 'Xtestdir/a/b/c/Xfile4')
5526
5527  let lines = "Entering dir Xtestdir\n" .
5528	      \ "Entering dir a\n" .
5529	      \ "Entering dir b\n" .
5530	      \ "Xfile2:2:X2_L2\n" .
5531	      \ "Leaving dir a\n" .
5532	      \ "Xfile1:2:X1_L2\n" .
5533	      \ "Xfile3:1:X3_L1\n" .
5534	      \ "Entering dir c\n" .
5535	      \ "Xfile4:2:X4_L2\n" .
5536	      \ "Leaving dir c\n"
5537  set efm=%DEntering\ dir\ %f,%XLeaving\ dir\ %f,%f:%l:%m
5538  cexpr lines .. "Leaving dir Xtestdir|\n" | let next = 1
5539  call assert_equal(11, getqflist({'size' : 0}).size)
5540  call assert_equal(4, getqflist({'idx' : 0}).idx)
5541  call assert_equal('X2_L2', getline('.'))
5542  call assert_equal(1, next)
5543  cnext
5544  call assert_equal(6, getqflist({'idx' : 0}).idx)
5545  call assert_equal('X1_L2', getline('.'))
5546  cnext
5547  call assert_equal(7, getqflist({'idx' : 0}).idx)
5548  call assert_equal(1, line('$'))
5549  call assert_equal('', getline(1))
5550  cnext
5551  call assert_equal(9, getqflist({'idx' : 0}).idx)
5552  call assert_equal(1, line('$'))
5553  call assert_equal('', getline(1))
5554
5555  set efm&
5556  exe 'cd ' . save_cwd
5557  call delete('Xtestdir', 'rf')
5558endfunc
5559
5560" Test for :cquit
5561func Test_cquit()
5562  " Exit Vim with a non-zero value
5563  if RunVim([], ["cquit 7"], '')
5564    call assert_equal(7, v:shell_error)
5565  endif
5566
5567  if RunVim([], ["50cquit"], '')
5568    call assert_equal(50, v:shell_error)
5569  endif
5570
5571  " Exit Vim with default value
5572  if RunVim([], ["cquit"], '')
5573    call assert_equal(1, v:shell_error)
5574  endif
5575
5576  " Exit Vim with zero value
5577  if RunVim([], ["cquit 0"], '')
5578    call assert_equal(0, v:shell_error)
5579  endif
5580
5581  " Exit Vim with negative value
5582  call assert_fails('-3cquit', 'E16:')
5583endfunc
5584
5585" Test for getting a specific item from a quickfix list
5586func Xtest_getqflist_by_idx(cchar)
5587  call s:setup_commands(a:cchar)
5588  " Empty list
5589  call assert_equal([], g:Xgetlist({'idx' : 1, 'items' : 0}).items)
5590  Xexpr ['F1:10:L10', 'F1:20:L20']
5591  let l = g:Xgetlist({'idx' : 2, 'items' : 0}).items
5592  call assert_equal(bufnr('F1'), l[0].bufnr)
5593  call assert_equal(20, l[0].lnum)
5594  call assert_equal('L20', l[0].text)
5595  call assert_equal([], g:Xgetlist({'idx' : -1, 'items' : 0}).items)
5596  call assert_equal([], g:Xgetlist({'idx' : 3, 'items' : 0}).items)
5597  call assert_equal({}, g:Xgetlist(#{idx: "abc"}))
5598  %bwipe!
5599endfunc
5600
5601func Test_getqflist_by_idx()
5602  call Xtest_getqflist_by_idx('c')
5603  call Xtest_getqflist_by_idx('l')
5604endfunc
5605
5606" Test for the 'quickfixtextfunc' setting
5607func Tqfexpr(info)
5608  if a:info.quickfix
5609    let qfl = getqflist({'id' : a:info.id, 'items' : 1}).items
5610  else
5611    let qfl = getloclist(a:info.winid, {'id' : a:info.id, 'items' : 1}).items
5612  endif
5613
5614  let l = []
5615  for idx in range(a:info.start_idx - 1, a:info.end_idx - 1)
5616    let e = qfl[idx]
5617    let s = ''
5618    if e.bufnr != 0
5619      let bname = bufname(e.bufnr)
5620      let s ..= fnamemodify(bname, ':.')
5621    endif
5622    let s ..= '-'
5623    let s ..= 'L' .. string(e.lnum) .. 'C' .. string(e.col) .. '-'
5624    let s ..= e.text
5625    call add(l, s)
5626  endfor
5627
5628  return l
5629endfunc
5630
5631func Xtest_qftextfunc(cchar)
5632  call s:setup_commands(a:cchar)
5633
5634  set efm=%f:%l:%c:%m
5635  set quickfixtextfunc=Tqfexpr
5636  call assert_equal('Tqfexpr', &quickfixtextfunc)
5637  call assert_equal('',
5638        \ g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc)
5639  call g:Xsetlist([
5640        \ { 'filename': 'F1', 'lnum': 10, 'col': 2,
5641        \   'end_col': 7, 'text': 'green'},
5642        \ { 'filename': 'F1', 'lnum': 20, 'end_lnum': 25, 'col': 4,
5643        \   'end_col': 8, 'text': 'blue'},
5644        \ ])
5645
5646  Xwindow
5647  call assert_equal('F1-L10C2-green', getline(1))
5648  call assert_equal('F1-L20C4-blue', getline(2))
5649  Xclose
5650  set quickfixtextfunc&vim
5651  Xwindow
5652  call assert_equal('F1|10 col 2-7| green', getline(1))
5653  call assert_equal('F1|20-25 col 4-8| blue', getline(2))
5654  Xclose
5655
5656  set efm=%f:%l:%c:%m
5657  set quickfixtextfunc=Tqfexpr
5658  " Update the list with only the cwindow
5659  Xwindow
5660  only
5661  call g:Xsetlist([
5662        \ { 'filename': 'F2', 'lnum': 20, 'col': 2,
5663        \   'end_col': 7, 'text': 'red'}
5664        \ ])
5665  call assert_equal(['F2-L20C2-red'], getline(1, '$'))
5666  new
5667  Xclose
5668  set efm&
5669  set quickfixtextfunc&
5670
5671  " Test for per list 'quickfixtextfunc' setting
5672  func PerQfText(info)
5673    if a:info.quickfix
5674      let qfl = getqflist({'id' : a:info.id, 'items' : 1}).items
5675    else
5676      let qfl = getloclist(a:info.winid, {'id' : a:info.id, 'items' : 1}).items
5677    endif
5678    if empty(qfl)
5679      return []
5680    endif
5681    let l = []
5682    for idx in range(a:info.start_idx - 1, a:info.end_idx - 1)
5683      call add(l, 'Line ' .. qfl[idx].lnum .. ', Col ' .. qfl[idx].col)
5684    endfor
5685    return l
5686  endfunc
5687  set quickfixtextfunc=Tqfexpr
5688  call g:Xsetlist([], ' ', {'quickfixtextfunc' : "PerQfText"})
5689  Xaddexpr ['F1:10:2:green', 'F1:20:4:blue']
5690  Xwindow
5691  call assert_equal('Line 10, Col 2', getline(1))
5692  call assert_equal('Line 20, Col 4', getline(2))
5693  Xclose
5694  call assert_equal(function('PerQfText'),
5695        \ g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc)
5696  " Add entries to the list when the quickfix buffer is hidden
5697  Xaddexpr ['F1:30:6:red']
5698  Xwindow
5699  call assert_equal('Line 30, Col 6', getline(3))
5700  Xclose
5701  call g:Xsetlist([], 'r', {'quickfixtextfunc' : ''})
5702  call assert_equal('', g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc)
5703  set quickfixtextfunc&
5704  delfunc PerQfText
5705
5706  " Non-existing function
5707  set quickfixtextfunc=Tabc
5708  call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:')
5709  call assert_fails("Xwindow", 'E117:')
5710  Xclose
5711  set quickfixtextfunc&
5712
5713  " set option to a non-function
5714  set quickfixtextfunc=[10,\ 20]
5715  call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:')
5716  call assert_fails("Xwindow", 'E117:')
5717  Xclose
5718  set quickfixtextfunc&
5719
5720  " set option to a function with different set of arguments
5721  func Xqftext(a, b, c)
5722    return a:a .. a:b .. a:c
5723  endfunc
5724  set quickfixtextfunc=Xqftext
5725  call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E119:')
5726  call assert_fails("Xwindow", 'E119:')
5727  Xclose
5728
5729  " set option to a function that returns a list with non-strings
5730  func Xqftext2(d)
5731    return ['one', [], 'two']
5732  endfunc
5733  set quickfixtextfunc=Xqftext2
5734  call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue', 'F1:30:6:red']",
5735                                                                  \ 'E730:')
5736  call assert_fails('Xwindow', 'E730:')
5737  call assert_equal(['one', 'F1|20 col 4| blue', 'F1|30 col 6| red'],
5738        \ getline(1, '$'))
5739  Xclose
5740
5741  set quickfixtextfunc&
5742  delfunc Xqftext
5743  delfunc Xqftext2
5744
5745  " set the global option to a lambda function
5746  set quickfixtextfunc={d\ ->\ map(g:Xgetlist({'id'\ :\ d.id,\ 'items'\ :\ 1}).items[d.start_idx-1:d.end_idx-1],\ 'v:val.text')}
5747  Xexpr ['F1:10:2:green', 'F1:20:4:blue']
5748  Xwindow
5749  call assert_equal(['green', 'blue'], getline(1, '$'))
5750  Xclose
5751  " A callback option stores the resolved funcref, so a lambda reads back as its <lambda> handle
5752  " (consistent with the per-list 'quickfixtextfunc' below).
5753  call assert_match("function('<lambda>\\d\\+')", &quickfixtextfunc)
5754  set quickfixtextfunc&
5755
5756  " use a lambda function that returns an empty list
5757  set quickfixtextfunc={d\ ->\ []}
5758  Xexpr ['F1:10:2:green', 'F1:20:4:blue']
5759  Xwindow
5760  call assert_equal(['F1|10 col 2| green', 'F1|20 col 4| blue'],
5761        \ getline(1, '$'))
5762  Xclose
5763  set quickfixtextfunc&
5764
5765  " use a lambda function that returns a list with empty strings
5766  set quickfixtextfunc={d\ ->\ ['',\ '']}
5767  Xexpr ['F1:10:2:green', 'F1:20:4:blue']
5768  Xwindow
5769  call assert_equal(['F1|10 col 2| green', 'F1|20 col 4| blue'],
5770        \ getline(1, '$'))
5771  Xclose
5772  set quickfixtextfunc&
5773
5774  " set the per-quickfix list text function to a lambda function
5775  call g:Xsetlist([], ' ',
5776        \ {'quickfixtextfunc' :
5777        \   {d -> map(g:Xgetlist({'id' : d.id, 'items' : 1}).items[d.start_idx-1:d.end_idx-1],
5778        \ "'Line ' .. v:val.lnum .. ', Col ' .. v:val.col")}})
5779  Xaddexpr ['F1:10:2:green', 'F1:20:4:blue']
5780  Xwindow
5781  call assert_equal('Line 10, Col 2', getline(1))
5782  call assert_equal('Line 20, Col 4', getline(2))
5783  Xclose
5784  call assert_match("function('<lambda>\\d\\+')", string(g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc))
5785  call g:Xsetlist([], 'f')
5786endfunc
5787
5788func Test_qftextfunc()
5789  call Xtest_qftextfunc('c')
5790  call Xtest_qftextfunc('l')
5791endfunc
5792
5793func Test_qftextfunc_callback()
5794  let lines =<< trim END
5795    set efm=%f:%l:%c:%m
5796
5797    #" Test for using a function name
5798    LET &qftf = 'g:Tqfexpr'
5799    cexpr "F0:0:0:L0"
5800    copen
5801    call assert_equal('F0-L0C0-L0', getline(1))
5802    cclose
5803
5804    #" Test for using a function()
5805    set qftf=function('g:Tqfexpr')
5806    cexpr "F1:1:1:L1"
5807    copen
5808    call assert_equal('F1-L1C1-L1', getline(1))
5809    cclose
5810
5811    #" Using a funcref variable to set 'quickfixtextfunc'
5812    VAR Fn = function('g:Tqfexpr')
5813    LET &qftf = Fn
5814    cexpr "F2:2:2:L2"
5815    copen
5816    call assert_equal('F2-L2C2-L2', getline(1))
5817    cclose
5818
5819    #" Using string(funcref_variable) to set 'quickfixtextfunc'
5820    LET Fn = function('g:Tqfexpr')
5821    LET &qftf = string(Fn)
5822    cexpr "F3:3:3:L3"
5823    copen
5824    call assert_equal('F3-L3C3-L3', getline(1))
5825    cclose
5826
5827    #" Test for using a funcref()
5828    set qftf=funcref('g:Tqfexpr')
5829    cexpr "F4:4:4:L4"
5830    copen
5831    call assert_equal('F4-L4C4-L4', getline(1))
5832    cclose
5833
5834    #" Using a funcref variable to set 'quickfixtextfunc'
5835    LET Fn = funcref('g:Tqfexpr')
5836    LET &qftf = Fn
5837    cexpr "F5:5:5:L5"
5838    copen
5839    call assert_equal('F5-L5C5-L5', getline(1))
5840    cclose
5841
5842    #" Using a string(funcref_variable) to set 'quickfixtextfunc'
5843    LET Fn = funcref('g:Tqfexpr')
5844    LET &qftf = string(Fn)
5845    cexpr "F5:5:5:L5"
5846    copen
5847    call assert_equal('F5-L5C5-L5', getline(1))
5848    cclose
5849
5850    #" Test for using a lambda function with set
5851    VAR optval = "LSTART a LMIDDLE Tqfexpr(a) LEND"
5852    LET optval = substitute(optval, ' ', '\\ ', 'g')
5853    exe "set qftf=" .. optval
5854    cexpr "F6:6:6:L6"
5855    copen
5856    call assert_equal('F6-L6C6-L6', getline(1))
5857    cclose
5858
5859    #" Set 'quickfixtextfunc' to a lambda expression
5860    LET &qftf = LSTART a LMIDDLE Tqfexpr(a) LEND
5861    cexpr "F7:7:7:L7"
5862    copen
5863    call assert_equal('F7-L7C7-L7', getline(1))
5864    cclose
5865
5866    #" Set 'quickfixtextfunc' to string(lambda_expression)
5867    LET &qftf = "LSTART a LMIDDLE Tqfexpr(a) LEND"
5868    cexpr "F8:8:8:L8"
5869    copen
5870    call assert_equal('F8-L8C8-L8', getline(1))
5871    cclose
5872
5873    #" Set 'quickfixtextfunc' to a variable with a lambda expression
5874    VAR Lambda = LSTART a LMIDDLE Tqfexpr(a) LEND
5875    LET &qftf = Lambda
5876    cexpr "F9:9:9:L9"
5877    copen
5878    call assert_equal('F9-L9C9-L9', getline(1))
5879    cclose
5880
5881    #" Set 'quickfixtextfunc' to a string(variable with a lambda expression)
5882    LET Lambda = LSTART a LMIDDLE Tqfexpr(a) LEND
5883    LET &qftf = string(Lambda)
5884    cexpr "F9:9:9:L9"
5885    copen
5886    call assert_equal('F9-L9C9-L9', getline(1))
5887    cclose
5888  END
5889  call CheckLegacyAndVim9Success(lines)
5890
5891  " Test for using a script-local function name
5892  func s:TqfFunc2(info)
5893    let g:TqfFunc2Args = [a:info.start_idx, a:info.end_idx]
5894    return ''
5895  endfunc
5896  let g:TqfFunc2Args = []
5897  set quickfixtextfunc=s:TqfFunc2
5898  cexpr "F10:10:10:L10"
5899  cclose
5900  call assert_equal([1, 1], g:TqfFunc2Args)
5901
5902  let &quickfixtextfunc = 's:TqfFunc2'
5903  cexpr "F11:11:11:L11"
5904  cclose
5905  call assert_equal([1, 1], g:TqfFunc2Args)
5906  delfunc s:TqfFunc2
5907
5908  " set 'quickfixtextfunc' to a partial with dict. This used to cause a crash.
5909  func SetQftfFunc()
5910    let params = {'qftf': function('g:DictQftfFunc')}
5911    let &quickfixtextfunc = params.qftf
5912  endfunc
5913  func g:DictQftfFunc(_) dict
5914  endfunc
5915  call SetQftfFunc()
5916  new
5917  call SetQftfFunc()
5918  bw
5919  call test_garbagecollect_now()
5920  new
5921  set qftf=
5922  wincmd w
5923  set qftf=
5924  :%bw!
5925
5926  " set per-quickfix list 'quickfixtextfunc' to a partial with dict. This used
5927  " to cause a crash.
5928  let &qftf = ''
5929  func SetLocalQftfFunc()
5930    let params = {'qftf': function('g:DictQftfFunc')}
5931    call setqflist([], 'a', {'quickfixtextfunc' : params.qftf})
5932  endfunc
5933  call SetLocalQftfFunc()
5934  call test_garbagecollect_now()
5935  call setqflist([], 'a', {'quickfixtextfunc' : ''})
5936  delfunc g:DictQftfFunc
5937  delfunc SetQftfFunc
5938  delfunc SetLocalQftfFunc
5939  set efm&
5940endfunc
5941
5942" Test for updating a location list for some other window and check that
5943" 'qftextfunc' uses the correct location list.
5944func Test_qftextfunc_other_loclist()
5945  %bw!
5946  call setloclist(0, [], 'f')
5947
5948  " create a window and a location list for it and open the location list
5949  " window
5950  lexpr ['F1:10:12:one', 'F1:20:14:two']
5951  let w1_id = win_getid()
5952  call setloclist(0, [], ' ',
5953        \ {'lines': ['F1:10:12:one', 'F1:20:14:two'],
5954        \  'quickfixtextfunc':
5955        \    {d -> map(getloclist(d.winid, {'id' : d.id,
5956        \                'items' : 1}).items[d.start_idx-1:d.end_idx-1],
5957        \          "'Line ' .. v:val.lnum .. ', Col ' .. v:val.col")}})
5958  lwindow
5959  let w2_id = win_getid()
5960
5961  " create another window and a location list for it and open the location
5962  " list window
5963  topleft new
5964  let w3_id = win_getid()
5965  call setloclist(0, [], ' ',
5966        \ {'lines': ['F2:30:32:eleven', 'F2:40:34:twelve'],
5967        \  'quickfixtextfunc':
5968        \    {d -> map(getloclist(d.winid, {'id' : d.id,
5969        \                'items' : 1}).items[d.start_idx-1:d.end_idx-1],
5970        \          "'Ligne ' .. v:val.lnum .. ', Colonne ' .. v:val.col")}})
5971  lwindow
5972  let w4_id = win_getid()
5973
5974  topleft new
5975  lexpr ['F3:50:52:green', 'F3:60:54:blue']
5976  let w5_id = win_getid()
5977
5978  " change the location list for some other window
5979  call setloclist(0, [], 'r', {'lines': ['F3:55:56:aaa', 'F3:57:58:bbb']})
5980  call setloclist(w1_id, [], 'r', {'lines': ['F1:62:63:bbb', 'F1:64:65:ccc']})
5981  call setloclist(w3_id, [], 'r', {'lines': ['F2:76:77:ddd', 'F2:78:79:eee']})
5982  call assert_equal(['Line 62, Col 63', 'Line 64, Col 65'],
5983        \ getbufline(winbufnr(w2_id), 1, '$'))
5984  call assert_equal(['Ligne 76, Colonne 77', 'Ligne 78, Colonne 79'],
5985        \ getbufline(winbufnr(w4_id), 1, '$'))
5986  call setloclist(w2_id, [], 'r', {'lines': ['F1:32:33:fff', 'F1:34:35:ggg']})
5987  call setloclist(w4_id, [], 'r', {'lines': ['F2:46:47:hhh', 'F2:48:49:jjj']})
5988  call assert_equal(['Line 32, Col 33', 'Line 34, Col 35'],
5989        \ getbufline(winbufnr(w2_id), 1, '$'))
5990  call assert_equal(['Ligne 46, Colonne 47', 'Ligne 48, Colonne 49'],
5991        \ getbufline(winbufnr(w4_id), 1, '$'))
5992
5993  call win_gotoid(w5_id)
5994  lwindow
5995  call assert_equal(['F3|55 col 56| aaa', 'F3|57 col 58| bbb'],
5996        \ getline(1, '$'))
5997  %bw!
5998endfunc
5999
6000" Running :lhelpgrep command more than once in a help window, doesn't jump to
6001" the help topic
6002func Test_lhelpgrep_from_help_window()
6003  call mkdir('Xtestdir/doc', 'p')
6004  call writefile(['window'], 'Xtestdir/doc/a.txt')
6005  call writefile(['buffer'], 'Xtestdir/doc/b.txt')
6006  let save_rtp = &rtp
6007  let &rtp = 'Xtestdir'
6008  lhelpgrep window
6009  lhelpgrep buffer
6010  call assert_equal('b.txt', fnamemodify(@%, ":p:t"))
6011  lhelpgrep window
6012  call assert_equal('a.txt', fnamemodify(@%, ":p:t"))
6013  let &rtp = save_rtp
6014  call delete('Xtestdir', 'rf')
6015  new | only!
6016endfunc
6017
6018" Test for the crash fixed by 7.3.715
6019func Test_setloclist_crash()
6020  %bw!
6021  let g:BufNum = bufnr()
6022  augroup QF_Test
6023    au!
6024    au BufUnload * call setloclist(0, [{'bufnr':g:BufNum, 'lnum':1, 'col':1, 'text': 'tango down'}])
6025  augroup END
6026
6027  try
6028    lvimgrep /.*/ *.mak
6029  catch /E926:/
6030  endtry
6031  call assert_equal('tango down', getloclist(0, {'items' : 0}).items[0].text)
6032  call assert_equal(1, getloclist(0, {'size' : 0}).size)
6033
6034  augroup QF_Test
6035    au!
6036  augroup END
6037  unlet g:BufNum
6038  %bw!
6039endfunc
6040
6041" Test for adding an invalid entry with the quickfix window open and making
6042" sure that the window contents are not changed
6043func Test_add_invalid_entry_with_qf_window()
6044  call setqflist([], 'f')
6045  cexpr "Xfile1:10:aa"
6046  copen
6047  call setqflist(['bb'], 'a')
6048  call assert_equal(1, line('$'))
6049  call assert_equal(['Xfile1|10| aa'], getline(1, '$'))
6050  call assert_equal([{'lnum': 10                    , 'end_lnum': 0    , 'bufnr': bufnr('Xfile1') , 'col': 0   , 'end_col': 0    , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6051
6052  call setqflist([{'lnum': 10                                          , 'bufnr': bufnr('Xfile1') , 'col': 0                     , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6053  call assert_equal(1                               , line('$'))
6054  call assert_equal(['Xfile1|10| aa']               , getline(1        , '$'))
6055  call assert_equal([{'lnum': 10                    , 'end_lnum': 0    , 'bufnr': bufnr('Xfile1') , 'col': 0   , 'end_col': 0    , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6056
6057  call setqflist([{'lnum': 10                       , 'end_lnum': 0    , 'bufnr': bufnr('Xfile1') , 'col': 0   , 'end_col': 0    , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6058  call assert_equal(1                               , line('$'))
6059  call assert_equal(['Xfile1|10| aa']               , getline(1        , '$'))
6060  call assert_equal([{'lnum': 10                    , 'end_lnum': 0    , 'bufnr': bufnr('Xfile1') , 'col': 0   , 'end_col': 0    , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6061
6062  call setqflist([{'lnum': 10                       , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 0   , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6063  call assert_equal(1                               , line('$'))
6064  call assert_equal(['Xfile1|10| aa']               , getline(1        , '$'))
6065  call assert_equal([{'lnum': 10                    , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 0   , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6066
6067  call setqflist([{'lnum': 10                       , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 0    , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6068  call assert_equal(1                               , line('$'))
6069  call assert_equal(['Xfile1|10 col 666| aa']       , getline(1        , '$'))
6070  call assert_equal([{'lnum': 10                    , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 0    , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6071
6072  call setqflist([{'lnum': 10                       , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6073  call assert_equal(1                               , line('$'))
6074  call assert_equal(['Xfile1|10 col 666| aa']       , getline(1        , '$'))
6075  call assert_equal([{'lnum': 10                    , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6076
6077  call setqflist([{'lnum': 10                       , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222  , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6078  call assert_equal(1                               , line('$'))
6079  call assert_equal(['Xfile1|10 col 666-222| aa']   , getline(1        , '$'))
6080  call assert_equal([{'lnum': 10                    , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222  , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6081
6082  call setqflist([{'lnum': 10                       , 'end_lnum': 6 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222  , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r')
6083  call assert_equal(1                               , line('$'))
6084  call assert_equal(['Xfile1|10-6 col 666-222| aa'] , getline(1        , '$'))
6085  call assert_equal([{'lnum': 10                    , 'end_lnum': 6 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222  , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist())
6086  cclose
6087endfunc
6088
6089" Test for very weird problem: autocommand causes a failure, resulting opening
6090" the quickfix window to fail. This still splits the window, but otherwise
6091" should not mess up buffers.
6092func Test_quickfix_window_fails_to_open()
6093  CheckScreendump
6094
6095  let lines =<< trim END
6096      anything
6097      try
6098        anything
6099      endtry
6100  END
6101  call writefile(lines, 'XquickfixFails')
6102
6103  let lines =<< trim END
6104      split XquickfixFails
6105      silent vimgrep anything %
6106      normal o
6107      au BufLeave * ++once source XquickfixFails
6108      " This will trigger the autocommand, which causes an error, what follows
6109      " is aborted but the window was already split.
6110      silent! cwindow
6111  END
6112  call writefile(lines, 'XtestWinFails')
6113  let buf = RunVimInTerminal('-S XtestWinFails', #{rows: 13})
6114  call VerifyScreenDump(buf, 'Test_quickfix_window_fails', {})
6115
6116  " clean up
6117  call term_sendkeys(buf, ":bwipe!\<CR>")
6118  call term_wait(buf)
6119  call StopVimInTerminal(buf)
6120  call delete('XtestWinFails')
6121  call delete('XquickfixFails')
6122endfunc
6123
6124" Test for updating the quickfix buffer whenever the associated quickfix list
6125" is changed.
6126func Xqfbuf_update(cchar)
6127  call s:setup_commands(a:cchar)
6128
6129  Xexpr "F1:1:line1"
6130  Xopen
6131  call assert_equal(['F1|1| line1'], getline(1, '$'))
6132  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
6133
6134  " Test setqflist() using the 'lines' key in 'what'
6135  " add a new entry
6136  call g:Xsetlist([], 'a', {'lines' : ['F2:2: line2']})
6137  call assert_equal(['F1|1| line1', 'F2|2| line2'], getline(1, '$'))
6138  call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick)
6139  " replace all the entries with a single entry
6140  call g:Xsetlist([], 'r', {'lines' : ['F3:3: line3']})
6141  call assert_equal(['F3|3| line3'], getline(1, '$'))
6142  call assert_equal(3, g:Xgetlist({'changedtick' : 0}).changedtick)
6143  " remove all the entries
6144  call g:Xsetlist([], 'r', {'lines' : []})
6145  call assert_equal([''], getline(1, '$'))
6146  call assert_equal(4, g:Xgetlist({'changedtick' : 0}).changedtick)
6147  " add a new list
6148  call g:Xsetlist([], ' ', {'lines' : ['F4:4: line4']})
6149  call assert_equal(['F4|4| line4'], getline(1, '$'))
6150  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
6151
6152  " Test setqflist() using the 'items' key in 'what'
6153  " add a new entry
6154  call g:Xsetlist([], 'a', {'items' : [{'filename' : 'F5', 'lnum' : 5, 'text' : 'line5'}]})
6155  call assert_equal(['F4|4| line4', 'F5|5| line5'], getline(1, '$'))
6156  call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick)
6157  " replace all the entries with a single entry
6158  call g:Xsetlist([], 'r', {'items' : [{'filename' : 'F6', 'lnum' : 6, 'text' : 'line6'}]})
6159  call assert_equal(['F6|6| line6'], getline(1, '$'))
6160  call assert_equal(3, g:Xgetlist({'changedtick' : 0}).changedtick)
6161  " remove all the entries
6162  call g:Xsetlist([], 'r', {'items' : []})
6163  call assert_equal([''], getline(1, '$'))
6164  call assert_equal(4, g:Xgetlist({'changedtick' : 0}).changedtick)
6165  " add a new list
6166  call g:Xsetlist([], ' ', {'items' : [{'filename' : 'F7', 'lnum' : 7, 'text' : 'line7'}]})
6167  call assert_equal(['F7|7| line7'], getline(1, '$'))
6168  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
6169
6170  call g:Xsetlist([], ' ', {})
6171  call assert_equal([''], getline(1, '$'))
6172  call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick)
6173
6174  Xclose
6175endfunc
6176
6177func Test_qfbuf_update()
6178  call Xqfbuf_update('c')
6179  call Xqfbuf_update('l')
6180endfunc
6181
6182func Test_vimgrep_noswapfile()
6183  set noswapfile
6184  call writefile(['one', 'two', 'three'], 'Xgreppie')
6185  vimgrep two Xgreppie
6186  call assert_equal('two', getline('.'))
6187
6188  call delete('Xgreppie')
6189  set swapfile
6190endfunc
6191
6192" Test for the :vimgrep 'f' flag (fuzzy match)
6193func Xvimgrep_fuzzy_match(cchar)
6194  call s:setup_commands(a:cchar)
6195
6196  Xvimgrep /three one/f Xfile*
6197  let l = g:Xgetlist()
6198  call assert_equal(2, len(l))
6199  call assert_equal(['Xfile1', 1, 9, 'one two three'],
6200        \ [bufname(l[0].bufnr), l[0].lnum, l[0].col, l[0].text])
6201  call assert_equal(['Xfile2', 2, 1, 'three one two'],
6202        \ [bufname(l[1].bufnr), l[1].lnum, l[1].col, l[1].text])
6203
6204  Xvimgrep /the/f Xfile*
6205  let l = g:Xgetlist()
6206  call assert_equal(3, len(l))
6207  call assert_equal(['Xfile1', 1, 9, 'one two three'],
6208        \ [bufname(l[0].bufnr), l[0].lnum, l[0].col, l[0].text])
6209  call assert_equal(['Xfile2', 2, 1, 'three one two'],
6210        \ [bufname(l[1].bufnr), l[1].lnum, l[1].col, l[1].text])
6211  call assert_equal(['Xfile2', 4, 4, 'aaathreeaaa'],
6212        \ [bufname(l[2].bufnr), l[2].lnum, l[2].col, l[2].text])
6213
6214  Xvimgrep /aaa/fg Xfile*
6215  let l = g:Xgetlist()
6216  call assert_equal(4, len(l))
6217  call assert_equal(['Xfile1', 2, 1, 'aaaaaa'],
6218        \ [bufname(l[0].bufnr), l[0].lnum, l[0].col, l[0].text])
6219  call assert_equal(['Xfile1', 2, 4, 'aaaaaa'],
6220        \ [bufname(l[1].bufnr), l[1].lnum, l[1].col, l[1].text])
6221  call assert_equal(['Xfile2', 4, 1, 'aaathreeaaa'],
6222        \ [bufname(l[2].bufnr), l[2].lnum, l[2].col, l[2].text])
6223  call assert_equal(['Xfile2', 4, 9, 'aaathreeaaa'],
6224        \ [bufname(l[3].bufnr), l[3].lnum, l[3].col, l[3].text])
6225
6226  call assert_fails('Xvimgrep /xyz/fg Xfile*', 'E480:')
6227endfunc
6228
6229func Test_vimgrep_fuzzy_match()
6230  call writefile(['one two three', 'aaaaaa'], 'Xfile1')
6231  call writefile(['one', 'three one two', 'two', 'aaathreeaaa'], 'Xfile2')
6232  call Xvimgrep_fuzzy_match('c')
6233  call Xvimgrep_fuzzy_match('l')
6234  call delete('Xfile1')
6235  call delete('Xfile2')
6236endfunc
6237
6238func Test_locationlist_open_in_newtab()
6239  call s:create_test_file('Xqftestfile1')
6240  call s:create_test_file('Xqftestfile2')
6241  call s:create_test_file('Xqftestfile3')
6242
6243  %bwipe!
6244
6245  let lines =<< trim END
6246    Xqftestfile1:5:Line5
6247    Xqftestfile2:10:Line10
6248    Xqftestfile3:16:Line16
6249  END
6250  lgetexpr lines
6251
6252  silent! llast
6253  call assert_equal(1, tabpagenr('$'))
6254  call assert_equal('Xqftestfile3', bufname())
6255
6256  set switchbuf=newtab
6257
6258  silent! lfirst
6259  call assert_equal(2, tabpagenr('$'))
6260  call assert_equal('Xqftestfile1', bufname())
6261
6262  silent! lnext
6263  call assert_equal(3, tabpagenr('$'))
6264  call assert_equal('Xqftestfile2', bufname())
6265
6266  call delete('Xqftestfile1')
6267  call delete('Xqftestfile2')
6268  call delete('Xqftestfile3')
6269  set switchbuf&vim
6270
6271  %bwipe!
6272endfunc
6273
6274" Test for win_gettype() in quickfix and location list windows
6275func Test_win_gettype()
6276  copen
6277  call assert_equal("quickfix", win_gettype())
6278  let wid = win_getid()
6279  wincmd p
6280  call assert_equal("quickfix", win_gettype(wid))
6281  cclose
6282  lexpr ''
6283  lopen
6284  call assert_equal("loclist", win_gettype())
6285  let wid = win_getid()
6286  wincmd p
6287  call assert_equal("loclist", win_gettype(wid))
6288  lclose
6289endfunc
6290
6291fun Test_vimgrep_nomatch()
6292  call XexprTests('c')
6293  call g:Xsetlist([{'lnum':10,'text':'Line1'}])
6294  copen
6295  if has("win32")
6296    call assert_fails('vimgrep foo *.zzz', 'E479:')
6297    let expected = [{'lnum': 10, 'bufnr': 0, 'end_lnum': 0, 'pattern': '', 'valid': 0, 'vcol': 0, 'nr': 0, 'module': '', 'type': '', 'end_col': 0, 'col': 0, 'text': 'Line1'}]
6298  else
6299    call assert_fails('vimgrep foo *.zzz', 'E480:')
6300    let expected = []
6301  endif
6302  call assert_equal(expected, getqflist())
6303  cclose
6304endfunc
6305
6306" Test for opening the quickfix window in two tab pages and then closing one
6307" of the quickfix windows. This should not make the quickfix buffer unlisted.
6308" (github issue #9300).
6309func Test_two_qf_windows()
6310  cexpr "F1:1:line1"
6311  copen
6312  tabnew
6313  copen
6314  call assert_true(&buflisted)
6315  cclose
6316  tabfirst
6317  call assert_true(&buflisted)
6318  let bnum = bufnr()
6319  cclose
6320  " if all the quickfix windows are closed, then buffer should be unlisted.
6321  call assert_false(buflisted(bnum))
6322  %bw!
6323
6324  " Repeat the test for a location list
6325  lexpr "F2:2:line2"
6326  lopen
6327  let bnum = bufnr()
6328  tabnew
6329  exe "buffer" bnum
6330  tabfirst
6331  lclose
6332  tablast
6333  call assert_true(buflisted(bnum))
6334  tabclose
6335  lopen
6336  call assert_true(buflisted(bnum))
6337  lclose
6338  call assert_false(buflisted(bnum))
6339  %bw!
6340endfunc
6341
6342" Weird sequence of commands that caused entering a wiped-out buffer
6343func Test_lopen_bwipe()
6344  func R()
6345    silent! tab lopen
6346    e x
6347    silent! lfile
6348  endfunc
6349
6350  cal R()
6351  cal R()
6352  cal R()
6353  bw!
6354  delfunc R
6355endfunc
6356
6357" Another sequence of commands that caused all buffers to be wiped out
6358func Test_lopen_bwipe_all()
6359  let lines =<< trim END
6360    func R()
6361      silent! tab lopen
6362      e foo
6363      silent! lfile
6364    endfunc
6365    cal R()
6366    exe "norm \<C-W>\<C-V>0"
6367    cal R()
6368    bwipe
6369
6370    call writefile(['done'], 'Xresult')
6371    qall!
6372  END
6373  call writefile(lines, 'Xscript')
6374  if RunVim([], [], '-u NONE -n -X -Z -e -m -s -S Xscript')
6375    call assert_equal(['done'], readfile('Xresult'))
6376  endif
6377
6378  call delete('Xscript')
6379  call delete('Xresult')
6380endfunc
6381
6382" Test for calling setqflist() function recursively
6383func Test_recursive_setqflist()
6384  augroup QF_Test
6385    au!
6386    autocmd BufWinEnter quickfix call setqflist([], 'r')
6387  augroup END
6388
6389  copen
6390  call assert_fails("call setqflist([], 'a')", 'E952:')
6391
6392  augroup QF_Test
6393    au!
6394  augroup END
6395  %bw!
6396endfunc
6397
6398" Test for failure to create a new window when selecting a file from the
6399" quickfix window
6400func Test_cwindow_newwin_fails()
6401  cgetexpr ["Xfile1:10:L10", "Xfile1:20:L20"]
6402  cwindow
6403  only
6404  let qf_wid = win_getid()
6405  " create the maximum number of scratch windows
6406  let hor_win_count = (&lines - 1)/2
6407  let hor_split_count = hor_win_count - 1
6408  for s in range(1, hor_split_count) | new | set buftype=nofile | endfor
6409  call win_gotoid(qf_wid)
6410  call assert_fails('exe "normal \<CR>"', 'E36:')
6411  %bw!
6412endfunc
6413
6414" Test for updating the location list when only the location list window is
6415" present and the corresponding file window is closed.
6416func Test_loclist_update_with_llwin_only()
6417  %bw!
6418  new
6419  wincmd w
6420  lexpr ["Xfile1:1:Line1"]
6421  lopen
6422  wincmd p
6423  close
6424  call setloclist(2, [], 'r', {'lines': ["Xtest2:2:Line2"]})
6425  call assert_equal(['Xtest2|2| Line2'], getbufline(winbufnr(2), 1, '$'))
6426  %bw!
6427endfunc
6428
6429" Test for getting the quickfix list after a buffer with an error is wiped out
6430func Test_getqflist_wiped_out_buffer()
6431  %bw!
6432  cexpr ["Xtest1:34:Wiped out"]
6433  let bnum = bufnr('Xtest1')
6434  call assert_equal(bnum, getqflist()[0].bufnr)
6435  bw Xtest1
6436  call assert_equal(0, getqflist()[0].bufnr)
6437  %bw!
6438endfunc
6439
6440" Test for the status message that is displayed when opening a new quickfix
6441" list
6442func Test_qflist_statusmsg()
6443  cexpr "1\n2"
6444  cexpr "1\n2\n3\ntest_quickfix.vim:1:msg"
6445  call assert_equal('(4 of 4): msg', v:statusmsg)
6446  call setqflist([], 'f')
6447  %bw!
6448
6449  " When creating a new quickfix list, if an autocmd changes the quickfix list
6450  " in the stack, then an error message should be displayed.
6451  augroup QF_Test
6452    au!
6453    au BufEnter test_quickfix.vim colder
6454  augroup END
6455  cexpr "1\n2"
6456  call assert_fails('cexpr "1\n2\n3\ntest_quickfix.vim:1:msg"', 'E925:')
6457  call setqflist([], 'f')
6458  augroup QF_Test
6459    au!
6460  augroup END
6461  %bw!
6462
6463  augroup QF_Test
6464    au!
6465    au BufEnter test_quickfix.vim caddexpr "4"
6466  augroup END
6467  call assert_fails('cexpr "1\n2\n3\ntest_quickfix.vim:1:msg"', 'E925:')
6468  call setqflist([], 'f')
6469  augroup QF_Test
6470    au!
6471  augroup END
6472  %bw!
6473endfunc
6474
6475func Test_quickfixtextfunc_recursive()
6476  func s:QFTfunc(o)
6477    cgete '0'
6478  endfunc
6479  copen
6480  let &quickfixtextfunc = 's:QFTfunc'
6481  cex ""
6482
6483  let &quickfixtextfunc = ''
6484  cclose
6485endfunc
6486
6487" Test for replacing the location list from an autocmd. This used to cause a
6488" read from freed memory.
6489func Test_loclist_replace_autocmd()
6490  %bw!
6491  call setloclist(0, [], 'f')
6492  let s:bufnr = bufnr()
6493  cal setloclist(0, [{'0': 0, '': ''}])
6494  au BufEnter * cal setloclist(1, [{'t': ''}, {'bufnr': s:bufnr}], 'r')
6495  lopen
6496  try
6497    exe "norm j\<CR>"
6498  catch
6499  endtry
6500  lnext
6501  %bw!
6502  call setloclist(0, [], 'f')
6503endfunc
6504
6505" Test for a very long error line and a very long information line
6506func Test_very_long_error_line()
6507  let msg = repeat('abcdefghijklmn', 146)
6508  let emsg = 'Xlonglines.c:1:' . msg
6509  call writefile([msg, emsg], 'Xerror', 'D')
6510  cfile Xerror
6511  cwindow
6512  call assert_equal($'|| {msg}', getline(1))
6513  call assert_equal($'Xlonglines.c|1| {msg}', getline(2))
6514  cclose
6515
6516  let l = execute('clist!')->split("\n")
6517  call assert_equal([$' 1: {msg}', $' 2 Xlonglines.c:1: {msg}'], l)
6518
6519  let l = execute('cc')->split("\n")
6520  call assert_equal([$'(2 of 2): {msg}'], l)
6521
6522  call setqflist([], 'f')
6523endfunc
6524
6525" In the quickfix window, spaces at the beginning of an informational line
6526" should not be removed but should be removed from an error line.
6527func Test_info_line_with_space()
6528  cexpr ["a.c:20:12:         error: expected ';' before ':' token",
6529        \ '   20 |     Afunc():', '', '      |            ^']
6530  copen
6531  call assert_equal(["a.c|20 col 12| error: expected ';' before ':' token",
6532        \ '||    20 |     Afunc():', '|| ',
6533        \ '||       |            ^'], getline(1, '$'))
6534  cclose
6535
6536  let l = execute('clist!')->split("\n")
6537  call assert_equal([" 1 a.c:20 col 12: error: expected ';' before ':' token",
6538        \ ' 2:    20 |     Afunc():', ' 3:  ', ' 4:       |            ^'], l)
6539
6540  call setqflist([], 'f')
6541endfunc
6542
6543func s:QfTf(_)
6544endfunc
6545
6546func Test_setqflist_cb_arg()
6547  " This was changing the callback name in the dictionary.
6548  let d = #{quickfixtextfunc: 's:QfTf'}
6549  call setqflist([], 'a', d)
6550  call assert_equal('s:QfTf', d.quickfixtextfunc)
6551
6552  call setqflist([], 'f')
6553endfunc
6554
6555" Test that setqflist() should not prevent :stopinsert from working
6556func Test_setqflist_stopinsert()
6557  new
6558  call setqflist([], 'f')
6559  copen
6560  cclose
6561  func StopInsert()
6562    stopinsert
6563    call setqflist([{'text': 'foo'}])
6564    return ''
6565  endfunc
6566
6567  call setline(1, 'abc')
6568  call cursor(1, 1)
6569  call feedkeys("i\<C-R>=StopInsert()\<CR>$", 'tnix')
6570  call assert_equal('foo', getqflist()[0].text)
6571  call assert_equal([0, 1, 3, 0, v:maxcol], getcurpos())
6572  call assert_equal(['abc'], getline(1, '$'))
6573
6574  delfunc StopInsert
6575  call setqflist([], 'f')
6576  bwipe!
6577endfunc
6578
6579func Test_quickfix_buffer_contents()
6580  call setqflist([{'filename':'filename', 'pattern':'pattern', 'text':'text'}])
6581  copen
6582  call assert_equal(['filename|pattern| text'], getline(1, '$'))  " The assert failed with Vim v9.0.0736; '| text' did not appear after the pattern.
6583  call setqflist([], 'f')
6584endfunc
6585
6586func XquickfixUpdateTests(cchar)
6587  call s:setup_commands(a:cchar)
6588
6589  " Setup: populate a couple buffers
6590  new
6591  call setline(1, range(1, 5))
6592  let b1 = bufnr()
6593  new
6594  call setline(1, range(1, 3))
6595  let b2 = bufnr()
6596  " Setup: set a quickfix list.
6597  let items = [{'bufnr': b1, 'lnum': 1}, {'bufnr': b1, 'lnum': 2}, {'bufnr': b2, 'lnum': 1}, {'bufnr': b2, 'lnum': 2}]
6598  call g:Xsetlist(items)
6599
6600  " Open the quickfix list, select the third entry.
6601  Xopen
6602  exe "normal jj\<CR>"
6603  call assert_equal(3, g:Xgetlist({'idx' : 0}).idx)
6604
6605  " Update the quickfix list. Make sure the third entry is still selected.
6606  call g:Xsetlist([], 'u', { 'items': items })
6607  call assert_equal(3, g:Xgetlist({'idx' : 0}).idx)
6608
6609  " Update the quickfix list again, but this time with missing line number
6610  " information. Confirm that we keep the current buffer selected.
6611  call g:Xsetlist([{'bufnr': b1}, {'bufnr': b2}], 'u')
6612  call assert_equal(2, g:Xgetlist({'idx' : 0}).idx)
6613
6614  Xclose
6615
6616  " Cleanup the buffers we allocated during this test.
6617  %bwipe!
6618endfunc
6619
6620" Test for updating a quickfix list using the "u" flag in setqflist()
6621func Test_quickfix_update()
6622  call XquickfixUpdateTests('c')
6623  call XquickfixUpdateTests('l')
6624endfunc
6625
6626func Test_quickfix_update_with_missing_coordinate_info()
6627  new
6628  call setline(1, range(1, 5))
6629  let b1 = bufnr()
6630
6631  new
6632  call setline(1, range(1, 3))
6633  let b2 = bufnr()
6634
6635  new
6636  call setline(1, range(1, 2))
6637  let b3 = bufnr()
6638
6639  " Setup: set a quickfix list with no coordinate information at all.
6640  call setqflist([{}, {}])
6641
6642  " Open the quickfix list, select the second entry.
6643  copen
6644  exe "normal j\<CR>"
6645  call assert_equal(2, getqflist({'idx' : 0}).idx)
6646
6647  " Update the quickfix list. As the previously selected entry has no
6648  " coordinate information, we expect the first entry to now be selected.
6649  call setqflist([{'bufnr': b1}, {'bufnr': b2}, {'bufnr': b3}], 'u')
6650  call assert_equal(1, getqflist({'idx' : 0}).idx)
6651
6652  " Select the second entry in the quickfix list.
6653  copen
6654  exe "normal j\<CR>"
6655  call assert_equal(2, getqflist({'idx' : 0}).idx)
6656
6657  " Update the quickfix list again. The currently selected entry does not have
6658  " a line number, but we should keep the file selected.
6659  call setqflist([{'bufnr': b1}, {'bufnr': b2, 'lnum': 3}, {'bufnr': b3}], 'u')
6660  call assert_equal(2, getqflist({'idx' : 0}).idx)
6661
6662  " Update the quickfix list again. The currently selected entry (bufnr=b2, lnum=3)
6663  " is no longer present. We should pick the nearest entry.
6664  call setqflist([{'bufnr': b1}, {'bufnr': b2, 'lnum': 1}, {'bufnr': b2, 'lnum': 4}], 'u')
6665  call assert_equal(3, getqflist({'idx' : 0}).idx)
6666
6667  " Set the quickfix list again, with a specific column number. The currently selected entry doesn't have a
6668  " column number, but they share a line number.
6669  call setqflist([{'bufnr': b1}, {'bufnr': b2, 'lnum': 4, 'col': 5}, {'bufnr': b2, 'lnum': 4, 'col': 6}], 'u')
6670  call assert_equal(2, getqflist({'idx' : 0}).idx)
6671
6672  " Set the quickfix list again. The currently selected column number (6) is
6673  " no longer present. We should select the nearest column number.
6674  call setqflist([{'bufnr': b1}, {'bufnr': b2, 'lnum': 4, 'col': 2}, {'bufnr': b2, 'lnum': 4, 'col': 4}], 'u')
6675  call assert_equal(3, getqflist({'idx' : 0}).idx)
6676
6677  " Now set the quickfix list, but without columns. We should still pick the
6678  " same line.
6679  call setqflist([{'bufnr': b2, 'lnum': 3}, {'bufnr': b2, 'lnum': 4}, {'bufnr': b2, 'lnum': 4}], 'u')
6680  call assert_equal(2, getqflist({'idx' : 0}).idx)
6681
6682  " Cleanup the buffers we allocated during this test.
6683  %bwipe!
6684endfunc
6685
6686" Test for "%b" in "errorformat"
6687func Test_efm_format_b()
6688  call setqflist([], 'f')
6689  new
6690  call setline(1, ['1: abc', '1: def', '1: ghi'])
6691  let b1 = bufnr()
6692  new
6693  call setline(1, ['2: abc', '2: def', '2: ghi'])
6694  let b2 = bufnr()
6695  new
6696  call setline(1, ['3: abc', '3: def', '3: ghi'])
6697  let b3 = bufnr()
6698  new
6699  let lines =<< trim eval END
6700    {b1}:1:1
6701    {b2}:2:2
6702    {b3}:3:3
6703  END
6704  call setqflist([], ' ', #{lines: lines, efm: '%b:%l:%c'})
6705  cfirst
6706  call assert_equal([b1, 1, 1], [bufnr(), line('.'), col('.')])
6707  cnext
6708  call assert_equal([b2, 2, 2], [bufnr(), line('.'), col('.')])
6709  cnext
6710  call assert_equal([b3, 3, 3], [bufnr(), line('.'), col('.')])
6711  enew!
6712
6713  " Use a non-existing buffer
6714  let lines =<< trim eval END
6715    9991:1:1:m1
6716    9992:2:2:m2
6717    {b3}:3:3:m3
6718  END
6719  call setqflist([], ' ', #{lines: lines, efm: '%b:%l:%c:%m'})
6720  cfirst | cnext
6721  call assert_equal([b3, 3, 3], [bufnr(), line('.'), col('.')])
6722  " Lines with non-existing buffer numbers should be used as non-error lines
6723  call assert_equal([
6724    \ #{lnum: 0, bufnr: 0, end_lnum: 0, pattern: '', valid: 0, vcol: 0, nr: -1,
6725    \   module: '', type: '', end_col: 0, col: 0, text: '9991:1:1:m1'},
6726    \ #{lnum: 0, bufnr: 0, end_lnum: 0, pattern: '', valid: 0, vcol: 0, nr: -1,
6727    \   module: '', type: '', end_col: 0, col: 0, text: '9992:2:2:m2'},
6728    \ #{lnum: 3, bufnr: b3, end_lnum: 0, pattern: '', valid: 1, vcol: 0,
6729    \   nr: -1, module: '', type: '', end_col: 0, col: 3, text: 'm3'}],
6730    \ getqflist())
6731  %bw!
6732  call setqflist([], 'f')
6733endfunc
6734
6735func XbufferTests_range(cchar)
6736  call s:setup_commands(a:cchar)
6737
6738  enew!
6739  let lines =<< trim END
6740    Xtestfile7:700:10:Line 700
6741    Xtestfile8:800:15:Line 800
6742  END
6743  silent! call setline(1, lines)
6744  norm! Vy
6745  " Note: We cannot use :Xbuffer here,
6746  " it doesn't properly fail, so we need to
6747  " test using the raw c/l commands.
6748  " (also further down)
6749  if (a:cchar == 'c')
6750     exe "'<,'>cbuffer!"
6751  else
6752    exe "'<,'>lbuffer!"
6753  endif
6754  let l = g:Xgetlist()
6755  call assert_true(len(l) == 1 &&
6756	\ l[0].lnum == 700 && l[0].col == 10 && l[0].text ==# 'Line 700')
6757
6758  enew!
6759  let lines =<< trim END
6760    Xtestfile9:900:55:Line 900
6761    Xtestfile10:950:66:Line 950
6762  END
6763  silent! call setline(1, lines)
6764  if (a:cchar == 'c')
6765    1cgetbuffer
6766  else
6767    1lgetbuffer
6768  endif
6769  let l = g:Xgetlist()
6770  call assert_true(len(l) == 1 &&
6771	\ l[0].lnum == 900 && l[0].col == 55 && l[0].text ==# 'Line 900')
6772
6773  enew!
6774  let lines =<< trim END
6775    Xtestfile11:700:20:Line 700
6776    Xtestfile12:750:25:Line 750
6777  END
6778  silent! call setline(1, lines)
6779  if (a:cchar == 'c')
6780    1,1caddbuffer
6781  else
6782    1,1laddbuffer
6783  endif
6784  let l = g:Xgetlist()
6785  call assert_true(len(l) == 2 &&
6786	\ l[0].lnum == 900 && l[0].col == 55 && l[0].text ==# 'Line 900' &&
6787	\ l[1].lnum == 700 && l[1].col == 20 && l[1].text ==# 'Line 700')
6788  enew!
6789
6790  " Check for invalid range
6791  " Using Xbuffer will not run the range check in the cbuffer/lbuffer
6792  " commands. So directly call the commands.
6793  if (a:cchar == 'c')
6794      call assert_fails('900,999caddbuffer', 'E16:')
6795  else
6796      call assert_fails('900,999laddbuffer', 'E16:')
6797  endif
6798endfunc
6799
6800func Test_cbuffer_range()
6801  call XbufferTests_range('c')
6802  call XbufferTests_range('l')
6803endfunc
6804
6805" Test for displaying fname passed from setqflist() when the names include
6806" hard links to prevent seemingly duplicate entries.
6807func Xtest_hardlink_fname(cchar)
6808  call s:setup_commands(a:cchar)
6809  %bwipe
6810  " Create a sample source file
6811  let lines =<< trim END
6812    void sample() {}
6813    int main() { sample(); return 0; }
6814  END
6815  call writefile(lines, 'test_qf_hardlink1.c', 'D')
6816  defer delete('test_qf_hardlink1.c')
6817  defer delete('test_qf_hardlink2.c')
6818  call system('ln test_qf_hardlink1.c test_qf_hardlink2.c')
6819  if v:shell_error
6820    throw 'Skipped: ln throws error on this platform'
6821  endif
6822  call g:Xsetlist([], 'f')
6823  " Make a qflist that contains the file and it's hard link
6824  " like how LSP plugins set response into qflist
6825  call g:Xsetlist([{'filename' : 'test_qf_hardlink1.c', 'lnum' : 1},
6826        \ {'filename' : 'test_qf_hardlink2.c', 'lnum' : 1}], ' ')
6827  Xopen
6828  " Ensure that two entries are displayed with different name
6829  " so that they aren't seen as duplication.
6830  call assert_equal(['test_qf_hardlink1.c|1| ',
6831        \ 'test_qf_hardlink2.c|1| '], getline(1, '$'))
6832  Xclose
6833endfunc
6834
6835func Test_hardlink_fname()
6836  CheckUnix
6837  CheckExecutable ln
6838  call Xtest_hardlink_fname('c')
6839  call Xtest_hardlink_fname('l')
6840endfunc
6841
6842" Test for checking if correct number of tests are deleted
6843" and current list stays the same after setting Xhistory
6844" to a smaller number. Do roughly the same for growing the stack.
6845func Xtest_resize_list_stack(cchar)
6846  call s:setup_commands(a:cchar)
6847  Xsethist 100
6848
6849  for i in range(1, 100)
6850    Xexpr string(i)
6851  endfor
6852  Xopen
6853  call assert_equal(g:Xgetlist({'nr': '$'}).nr, 100)
6854  call assert_equal("|| 100", getline(1))
6855  Xsethist 8
6856  call assert_equal("|| 100", getline(1))
6857  Xolder 5
6858  call assert_equal("|| 95", getline(1))
6859  Xsethist 6
6860  call assert_equal("|| 95", getline(1))
6861  Xsethist 1
6862  call assert_equal("|| 100", getline(1))
6863
6864  " grow array again
6865  Xsethist 100
6866  for i in range(1, 99)
6867    Xexpr string(i)
6868  endfor
6869  call assert_equal("|| 99", getline(1))
6870  Xolder 99
6871  call assert_equal("|| 100", getline(1))
6872
6873  Xsethistdefault
6874endfunc
6875
6876func Test_resize_list_stack()
6877  call Xtest_resize_list_stack('c')
6878  call Xtest_resize_list_stack('l')
6879endfunc
6880
6881" Test to check if order of lists is from
6882" oldest at the bottom to newest at the top
6883func Xtest_Xhistory_check_order(cchar)
6884
6885  Xsethist 100
6886
6887  for i in range(1, 100)
6888    Xexpr string(i)
6889  endfor
6890
6891  Xopen
6892  for i in range(100, 1, -1)
6893    let l:ret = assert_equal("|| " .. i, getline(1))
6894
6895    if ret == 1 || i == 1
6896      break
6897    endif
6898    Xolder
6899  endfor
6900
6901  for i in range(1, 50)
6902    Xexpr string(i)
6903  endfor
6904
6905  for i in range(50, 1, -1)
6906    let l:ret = assert_equal("|| " .. i, getline(1))
6907
6908    if ret == 1 || i == 50
6909      break
6910    endif
6911    Xolder
6912  endfor
6913
6914  for i in range(50, 1, -1)
6915    let l:ret = assert_equal("|| " .. i, getline(1))
6916
6917    if ret == 1 || i == 50
6918      break
6919    endif
6920    Xolder
6921  endfor
6922
6923  Xsethistdefault
6924endfunc
6925
6926func Test_set_history_to_check_order()
6927  call Xtest_Xhistory_check_order('c')
6928  call Xtest_Xhistory_check_order('l')
6929endfunc
6930
6931" Check if 'lhistory' is the same between the location list window
6932" and associated normal window
6933func Test_win_and_loc_synced()
6934  new
6935  set lhistory=2
6936  lexpr "Text"
6937  lopen
6938
6939  " check if lhistory is synced when modified inside the
6940  " location list window
6941  setlocal lhistory=1
6942  wincmd k
6943  call assert_equal(&lhistory, 1)
6944
6945  " check if lhistory is synced when modified inside the
6946  " normal window
6947  setlocal lhistory=10
6948  lopen
6949  call assert_equal(&lhistory, 10)
6950
6951  wincmd k
6952  lclose
6953  wincmd q
6954
6955  set lhistory&
6956endfunc
6957
6958" Test if setting the lhistory of one window doesn't affect the other
6959func Test_two_win_are_independent_of_history()
6960  setlocal lhistory=10
6961  new
6962  setlocal lhistory=20
6963  wincmd  w
6964  call assert_equal(&lhistory, 10)
6965  wincmd w
6966  wincmd q
6967
6968  set lhistory&
6969endfunc
6970
6971" Test if lhistory is copied over to a new window
6972func Test_lhistory_copied_over()
6973  setlocal lhistory=3
6974  split
6975  call assert_equal(&lhistory, 3)
6976  wincmd q
6977
6978  set lhistory&
6979endfunc
6980
6981" Test if error occurs when given invalid history number
6982func Xtest_invalid_history_num(cchar)
6983  call s:setup_commands(a:cchar)
6984
6985  call assert_fails('Xsethist -10000', "E1542:")
6986  call assert_fails('Xsethist 10000', "E1543:")
6987  Xsethistdefault
6988endfunc
6989
6990func Test_invalid_history_num()
6991  call Xtest_invalid_history_num('c')
6992  call Xtest_invalid_history_num('l')
6993endfunc
6994
6995" Test if chistory and lhistory don't affect each other
6996func Test_chi_and_lhi_are_independent()
6997  set chistory=100
6998  set lhistory=100
6999
7000  set chistory=10
7001  call assert_equal(&lhistory, 100)
7002
7003  set lhistory=1
7004  call assert_equal(&chistory, 10)
7005
7006  set chistory&
7007  set lhistory&
7008endfunc
7009
7010func Test_quickfix_close_buffer_crash()
7011  new
7012  lexpr 'test' | lopen
7013  wincmd k
7014  lclose
7015  wincmd q
7016endfunc
7017
7018func Test_vimgrep_dummy_buffer_crash()
7019  augroup DummyCrash
7020    autocmd!
7021    " Make the dummy buffer non-current, but still open in a window.
7022    autocmd BufReadCmd * ++once let s:dummy_buf = bufnr()
7023          \| split | wincmd p | enew
7024
7025    " Autocmds from cleaning up the dummy buffer in this case should be blocked.
7026    autocmd BufWipeout *
7027          \ call assert_notequal(s:dummy_buf, str2nr(expand('<abuf>')))
7028  augroup END
7029
7030  silent! vimgrep /./ .
7031  redraw! " Window to freed dummy buffer used to remain; heap UAF.
7032  call assert_equal([], win_findbuf(s:dummy_buf))
7033  call assert_equal(0, bufexists(s:dummy_buf))
7034
7035  unlet! s:dummy_buf
7036  autocmd! DummyCrash
7037  %bw!
7038endfunc
7039
7040func Test_vimgrep_dummy_buffer_keep()
7041  augroup DummyKeep
7042    autocmd!
7043    " Trigger a wipe of the dummy buffer by aborting script processing. Prevent
7044    " wiping it by splitting it from the autocmd window into an only window.
7045    autocmd BufReadCmd * ++once let s:dummy_buf = bufnr()
7046          \| tab split | call interrupt()
7047  augroup END
7048
7049  call assert_fails('vimgrep /./ .')
7050  call assert_equal(1, bufexists(s:dummy_buf))
7051  " Ensure it's no longer considered a dummy; should be able to switch to it.
7052  execute s:dummy_buf 'sbuffer'
7053
7054  unlet! s:dummy_buf
7055  autocmd! DummyKeep
7056  %bw!
7057endfunc
7058
7059func Test_quickfix_restore_current_win()
7060  let curwin = win_getid()
7061  vsplit Xb
7062  wincmd p
7063  botright copen
7064  cclose
7065
7066  call assert_equal(curwin, win_getid())
7067  bw! Xb
7068endfunc
7069
7070func Test_quickfixtextfunc_wipes_buffer()
7071  let g:crash=""
7072  new
7073  fu QFexpr(dummy)
7074    bw
7075  endfu
7076  try
7077    set quickfixtextfunc=QFexpr
7078    lad "['0:4:e']"
7079    lw
7080  catch /^Vim\%((\S\+)\)\=:E565:/
7081    let g:crash='caught'
7082  endtry
7083  " close location list window
7084  bw
7085  delfunc QFexpr
7086  set quickfixtextfunc=
7087  call assert_equal('caught', g:crash)
7088  unlet g:crash
7089  " close the newly opened window
7090  bw
7091endfunc
7092
7093func Test_quickfix_longline_noeol()
7094  let qf = 'Xquickfix'
7095  let args = $"-q {qf}"
7096  let after =<< trim [CODE]
7097    call writefile(['okay'], "XDONE")
7098    qall!
7099  [CODE]
7100  defer delete("XDONE")
7101  call writefile([repeat('A', 1024)], qf, 'bD')
7102  call RunVim([], after, args)
7103  call WaitForAssert({-> assert_true(filereadable("XDONE"))})
7104  call assert_equal(['okay'], readfile("XDONE"))
7105endfunc
7106
7107func Test_efm_overlongline()
7108  let save_efm = &efm
7109  " %r captures the tail.
7110  set efm=%+O(%.%#)%r,%f:%l:%m
7111
7112  " First line is longer than IOSIZE (1025) so the parser puts it in
7113  " growbuf; the %r tail then far exceeds IObuff.
7114  let lines = ['(short)' .. repeat('x', 4000), 'Xfile:10:msg']
7115  call writefile(lines, 'Xqferrlong', 'D')
7116
7117  " Must complete without hanging or crashing.
7118  cgetfile Xqferrlong
7119
7120  " The well-formed line that follows is still parsed.
7121  let well_formed = filter(getqflist(), 'v:val.lnum == 10')
7122  call assert_equal(1, len(well_formed))
7123  call assert_equal('msg', well_formed[0].text)
7124
7125  let &efm = save_efm
7126  call setqflist([], 'f')
7127endfunc
7128
7129func Xtest_set_qftf_in_sandbox(cchar)
7130  call s:setup_commands(a:cchar)
7131
7132  call g:Xsetlist([{'filename': 'test.c', 'lnum': 1, 'text': 'trigger'}])
7133  let g:qftf_fn_called = v:false
7134  func Qftf_Fn(d)
7135    let g:qftf_fn_called = v:true
7136    return []
7137  endfunc
7138
7139  let g:caught_exception = v:false
7140  try
7141    sandbox call g:Xsetlist([], 'a', #{quickfixtextfunc: 'g:Qftf_Fn'})
7142  catch /E48:/
7143    let g:caught_exception = v:true
7144  endtry
7145  copen
7146  cclose
7147
7148  call assert_equal(v:true, g:caught_exception)
7149  call assert_equal(v:false, g:qftf_fn_called)
7150
7151  delfunc Qftf_Fn
7152  unlet g:caught_exception
7153  unlet g:qftf_fn_called
7154  %bw!
7155endfunc
7156
7157" Test for setting the 'quickfixtextfunc' in a sandbox
7158func Test_set_qftf_in_sandbox()
7159  call Xtest_set_qftf_in_sandbox('c')
7160  call Xtest_set_qftf_in_sandbox('l')
7161endfunc
7162
7163" Test for the 'statusline' height remaining at one when the quickfix buffer
7164" is wiped out when quickfix window is the only window open.
7165func Test_qf_statusline_height()
7166  %bw!
7167  copen
7168  wincmd p
7169  let prev_wh = winheight('.')
7170  wincmd p
7171  only
7172  bw!
7173  copen
7174  wincmd p
7175  call assert_equal(prev_wh, winheight('.'))
7176  %bw!
7177endfunc
7178
7179" vim: shiftwidth=2 sts=2 expandtab