robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
226.8 KiB7056 linesraw
1" Test for insert completion
2
3source screendump.vim
4source check.vim
5source vim9.vim
6
7" Test for insert expansion
8func Test_ins_complete()
9  edit test_ins_complete.vim
10  " The files in the current directory interferes with the files
11  " used by this test. So use a separate directory for the test.
12  call mkdir('Xdir')
13  cd Xdir
14
15  set ff=unix
16  call writefile(["test11\t36Gepeto\t/Tag/",
17	      \ "asd\ttest11file\t36G",
18	      \ "Makefile\tto\trun"], 'Xtestfile')
19  call writefile(['', 'start of testfile',
20	      \ 'ru',
21	      \ 'run1',
22	      \ 'run2',
23	      \ 'STARTTEST',
24	      \ 'ENDTEST',
25	      \ 'end of testfile'], 'Xtestdata')
26  set ff&
27
28  enew!
29  edit Xtestdata
30  new
31  call append(0, ['#include "Xtestfile"', ''])
32  call cursor(2, 1)
33
34  set cot=
35  set cpt=.,w
36  " add-expands (word from next line) from other window
37  exe "normal iru\<C-N>\<C-N>\<C-X>\<C-N>\<Esc>\<C-A>"
38  call assert_equal('run1 run3', getline('.'))
39  " add-expands (current buffer first)
40  exe "normal o\<C-P>\<C-X>\<C-N>"
41  call assert_equal('run3 run3', getline('.'))
42  " Local expansion, ends in an empty line (unless it becomes a global
43  " expansion)
44  exe "normal o\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>"
45  call assert_equal('', getline('.'))
46  " starts Local and switches to global add-expansion
47  exe "normal o\<C-X>\<C-P>\<C-P>\<C-X>\<C-X>\<C-N>\<C-X>\<C-N>\<C-N>"
48  call assert_equal('run1 run2', getline('.'))
49
50  set cpt=.,\ ,w,i
51  " i-add-expands and switches to local
52  exe "normal OM\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-X>\<C-X>\<C-P>"
53  call assert_equal("Makefile\tto\trun3", getline('.'))
54  " add-expands lines (it would end in an empty line if it didn't ignore
55  " itself)
56  exe "normal o\<C-X>\<C-L>\<C-X>\<C-L>\<C-P>\<C-P>"
57  call assert_equal("Makefile\tto\trun3", getline('.'))
58  call assert_equal("Makefile\tto\trun3", getline(line('.') - 1))
59
60  set cpt=kXtestfile
61  " checks k-expansion, and file expansion (use Xtest11 instead of test11,
62  " because TEST11.OUT may match first on DOS)
63  write Xtest11.one
64  write Xtest11.two
65  exe "normal o\<C-N>\<Esc>IX\<Esc>A\<C-X>\<C-F>\<C-N>"
66  call assert_equal('Xtest11.two', getline('.'))
67
68  " use CTRL-X CTRL-F to complete Xtest11.one, remove it and then use CTRL-X
69  " CTRL-F again to verify this doesn't cause trouble.
70  exe "normal oXt\<C-X>\<C-F>\<BS>\<BS>\<BS>\<BS>\<BS>\<BS>\<BS>\<BS>\<C-X>\<C-F>"
71  call assert_equal('Xtest11.one', getline('.'))
72  normal ddk
73
74  " Test for expanding a non-existing filename
75  exe "normal oa1b2X3Y4\<C-X>\<C-F>"
76  call assert_equal('a1b2X3Y4', getline('.'))
77  normal ddk
78
79  set cpt=w
80  " checks make_cyclic in other window
81  exe "normal oST\<C-N>\<C-P>\<C-P>\<C-P>\<C-P>"
82  call assert_equal('STARTTEST', getline('.'))
83
84  set cpt=u nohid
85  " checks unloaded buffer expansion
86  only
87  exe "normal oEN\<C-N>"
88  call assert_equal('ENDTEST', getline('.'))
89  " checks adding mode abortion
90  exe "normal ounl\<C-N>\<C-X>\<C-X>\<C-P>"
91  call assert_equal('unless', getline('.'))
92
93  set cpt=t,d def=^\\k* tags=Xtestfile notagbsearch
94  " tag expansion, define add-expansion interrupted
95  exe "normal o\<C-X>\<C-]>\<C-X>\<C-D>\<C-X>\<C-D>\<C-X>\<C-X>\<C-D>\<C-X>\<C-D>\<C-X>\<C-D>\<C-X>\<C-D>"
96  call assert_equal('test11file	36Gepeto	/Tag/ asd', getline('.'))
97  " t-expansion
98  exe "normal oa\<C-N>\<Esc>"
99  call assert_equal('asd', getline('.'))
100
101  %bw!
102  call delete('Xtestfile')
103  call delete('Xtest11.one')
104  call delete('Xtest11.two')
105  call delete('Xtestdata')
106  set cpt& cot& def& tags& tagbsearch& hidden&
107  cd ..
108  call delete('Xdir', 'rf')
109endfunc
110
111func Test_ins_complete_invalid_byte()
112  if has('unix') && executable('base64')
113    " this weird command was causing an illegal memory access
114    call writefile(['bm9ybTlvMDCAMM4Dbw4OGA4ODg=='], 'Xinvalid64')
115    call system('base64 -d Xinvalid64 > Xinvalid')
116    call writefile(['qa!'], 'Xexit')
117    call RunVim([], [], " -i NONE -n -X -Z -e -m -s -S Xinvalid -S Xexit")
118    call delete('Xinvalid64')
119    call delete('Xinvalid')
120    call delete('Xexit')
121  endif
122endfunc
123
124func Test_omni_dash()
125  func Omni(findstart, base)
126    if a:findstart
127      return 5
128    else
129      return ['-help', '-v']
130    endif
131  endfunc
132  set omnifunc=Omni
133  new
134  exe "normal Gofind -\<C-x>\<C-o>"
135  call assert_equal("find -help", getline('$'))
136  %d
137  set complete=o
138  exe "normal Gofind -\<C-n>"
139  call assert_equal("find -help", getline('$'))
140
141  bwipe!
142  delfunc Omni
143  set omnifunc= complete&
144endfunc
145
146func Test_omni_throw()
147  let g:CallCount = 0
148  func Omni(findstart, base)
149    let g:CallCount += 1
150    if a:findstart
151      throw "he he he"
152    endif
153  endfunc
154  set omnifunc=Omni
155  new
156  try
157    exe "normal ifoo\<C-x>\<C-o>"
158    call assert_false(v:true, 'command should have failed')
159  catch
160    call assert_exception('he he he')
161    call assert_equal(1, g:CallCount)
162  endtry
163  %d
164  set complete=o
165  let g:CallCount = 0
166  try
167    exe "normal ifoo\<C-n>"
168    call assert_false(v:true, 'command should have failed')
169  catch
170    call assert_exception('he he he')
171    call assert_equal(1, g:CallCount)
172  endtry
173
174  bwipe!
175  delfunc Omni
176  unlet g:CallCount
177  set omnifunc= complete&
178endfunc
179
180func Test_omni_autoload()
181  let save_rtp = &rtp
182  set rtp=Xruntime/some
183  let dir = 'Xruntime/some/autoload'
184  call mkdir(dir, 'pR')
185
186  let lines =<< trim END
187      func omni#Func(findstart, base)
188          if a:findstart
189              return 1
190          else
191              return ['match']
192          endif
193      endfunc
194
195      eval 1 + 2
196  END
197  call writefile(lines, dir .. '/omni.vim')
198
199  new
200  setlocal omnifunc=omni#Func
201  call feedkeys("i\<C-X>\<C-O>\<Esc>", 'xt')
202
203  setlocal complete=.,Fomni#Func
204  call feedkeys("S\<C-N>\<Esc>", 'xt')
205  setlocal complete&
206
207  bwipe!
208  set omnifunc=
209  let &rtp = save_rtp
210endfunc
211
212func Test_completefunc_args()
213  let s:args = []
214  func! CompleteFunc(findstart, base)
215    let s:args += [[a:findstart, empty(a:base)]]
216  endfunc
217  new
218
219  set completefunc=CompleteFunc
220  call feedkeys("i\<C-X>\<C-U>\<Esc>", 'x')
221  call assert_equal([1, 1], s:args[0])
222  call assert_equal(0, s:args[1][0])
223  set completefunc=
224
225  let s:args = []
226  set omnifunc=CompleteFunc
227  call feedkeys("i\<C-X>\<C-O>\<Esc>", 'x')
228  call assert_equal([1, 1], s:args[0])
229  call assert_equal(0, s:args[1][0])
230  set omnifunc=
231
232  set complete=FCompleteFunc
233  call feedkeys("i\<C-N>\<Esc>", 'x')
234  call assert_equal([1, 1], s:args[0])
235  call assert_equal(0, s:args[1][0])
236  set complete=o
237  call feedkeys("i\<C-N>\<Esc>", 'x')
238  call assert_equal([1, 1], s:args[0])
239  call assert_equal(0, s:args[1][0])
240  set complete&
241
242  bwipe!
243  unlet s:args
244  delfunc CompleteFunc
245endfunc
246
247func s:CompleteDone_CompleteFuncNone( findstart, base )
248  throw 'skipped: Nvim does not support v:none'
249  if a:findstart
250    return 0
251  endif
252
253  return v:none
254endfunc
255
256func s:CompleteDone_CompleteFuncDict( findstart, base )
257  if a:findstart
258    return 0
259  endif
260
261  return {
262	  \ 'words': [
263	    \ {
264	      \ 'word': 'aword',
265	      \ 'abbr': 'wrd',
266	      \ 'menu': 'extra text',
267	      \ 'info': 'words are cool',
268	      \ 'kind': 'W',
269	      \ 'user_data': ['one', 'two']
270	    \ }
271	  \ ]
272	\ }
273endfunc
274
275func s:CompleteDone_CheckCompletedItemNone()
276  let s:called_completedone = 1
277endfunc
278
279func s:CompleteDone_CheckCompletedItemDict(pre)
280  call assert_equal( 'aword',          v:completed_item[ 'word' ] )
281  call assert_equal( 'wrd',            v:completed_item[ 'abbr' ] )
282  call assert_equal( 'extra text',     v:completed_item[ 'menu' ] )
283  call assert_equal( 'words are cool', v:completed_item[ 'info' ] )
284  call assert_equal( 'W',              v:completed_item[ 'kind' ] )
285  call assert_equal( ['one', 'two'],   v:completed_item[ 'user_data' ] )
286
287  if a:pre
288    call assert_equal(a:pre == 1 ? 'function' : 'keyword', complete_info().mode)
289  endif
290
291  let s:called_completedone = 1
292endfunc
293
294func Test_CompleteDoneNone()
295  throw 'skipped: Nvim does not support v:none'
296  au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemNone()
297  let oldline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')
298
299  set completefunc=<SID>CompleteDone_CompleteFuncNone
300  execute "normal a\<C-X>\<C-U>\<C-Y>"
301  set completefunc&
302  let newline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')
303
304  call assert_true(s:called_completedone)
305  call assert_equal(oldline, newline)
306  let s:called_completedone = 0
307
308  set complete=F<SID>CompleteDone_CompleteFuncNone
309  execute "normal a\<C-N>\<C-Y>"
310  set complete&
311  let newline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')
312
313  call assert_true(s:called_completedone)
314  call assert_equal(oldline, newline)
315  let s:called_completedone = 0
316  au! CompleteDone
317endfunc
318
319func Test_CompleteDone_vevent_keys()
320  func OnDone()
321    let g:complete_word = get(v:event, 'complete_word', v:null)
322    let g:complete_type = get(v:event, 'complete_type', v:null)
323  endfunction
324
325  autocmd CompleteDone * :call OnDone()
326
327  func CompleteFunc(findstart, base)
328    if a:findstart
329      return col(".")
330    endif
331    return [#{word: "foo"}, #{word: "bar"}]
332  endfunc
333  set omnifunc=CompleteFunc
334  set completefunc=CompleteFunc
335  set complete=.,FCompleteFunc
336  set completeopt+=menuone
337
338  new
339  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'tx')
340  call assert_equal('', g:complete_word)
341  call assert_equal('omni', g:complete_type)
342
343  call feedkeys("S\<C-X>\<C-O>\<C-Y>\<Esc>", 'tx')
344  call assert_equal('foo', g:complete_word)
345  call assert_equal('omni', g:complete_type)
346
347  call feedkeys("S\<C-X>\<C-O>\<C-N>\<C-Y>\<Esc>0", 'tx')
348  call assert_equal('bar', g:complete_word)
349  call assert_equal('omni', g:complete_type)
350
351  call feedkeys("Shello vim visual v\<C-X>\<C-N>\<ESC>", 'tx')
352  call assert_equal('', g:complete_word)
353  call assert_equal('keyword', g:complete_type)
354
355  call feedkeys("Shello vim visual v\<C-X>\<C-N>\<C-Y>", 'tx')
356  call assert_equal('vim', g:complete_word)
357  call assert_equal('keyword', g:complete_type)
358
359  call feedkeys("Shello vim visual v\<C-N>\<ESC>", 'tx')
360  call assert_equal('', g:complete_word)
361  call assert_equal('keyword', g:complete_type)
362
363  call feedkeys("Shello vim visual v\<C-N>\<C-Y>", 'tx')
364  call assert_equal('vim', g:complete_word)
365  call assert_equal('keyword', g:complete_type)
366
367  call feedkeys("Shello vim\<CR>completion test\<CR>\<C-X>\<C-l>\<C-Y>", 'tx')
368  call assert_equal('completion test', g:complete_word)
369  call assert_equal('whole_line', g:complete_type)
370
371  call feedkeys("S\<C-X>\<C-U>\<C-Y>", 'tx')
372  call assert_equal('foo', g:complete_word)
373  call assert_equal('function', g:complete_type)
374
375  inoremap <buffer> <f3> <cmd>call complete(1, ["red", "blue"])<cr>
376  call feedkeys("S\<f3>\<C-Y>", 'tx')
377  call assert_equal('red', g:complete_word)
378  call assert_equal('eval', g:complete_type)
379
380  call feedkeys("S\<C-X>\<C-V>\<C-Y>", 'tx')
381  call assert_equal('!', g:complete_word)
382  call assert_equal('cmdline', g:complete_type)
383
384  call writefile([''], 'foo_test', 'D')
385  call feedkeys("Sfoo\<C-X>\<C-F>\<C-Y>\<Esc>", 'tx')
386  call assert_equal('foo_test', g:complete_word)
387  call assert_equal('files', g:complete_type)
388
389  call writefile(['hello help'], 'Xtest_case.txt', 'D')
390  set dictionary=Xtest_case.txt
391  call feedkeys("ggdGSh\<C-X>\<C-K>\<C-Y>\<Esc>", 'tx')
392  call assert_equal('hello', g:complete_word)
393  call assert_equal('dictionary', g:complete_type)
394
395  set spell spelllang=en_us
396  call feedkeys("STheatre\<C-X>s\<C-Y>\<Esc>", 'tx')
397  call assert_equal('Theater', g:complete_word)
398  call assert_equal('spell', g:complete_type)
399
400  bwipe!
401  set completeopt& omnifunc& completefunc& spell& spelllang& dictionary& complete&
402  autocmd! CompleteDone
403  delfunc OnDone
404  delfunc CompleteFunc
405  unlet g:complete_word
406  unlet g:complete_type
407endfunc
408
409func Test_CompleteDoneDict()
410  au CompleteDonePre * :call <SID>CompleteDone_CheckCompletedItemDict(1)
411  au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDict(0)
412
413  set completefunc=<SID>CompleteDone_CompleteFuncDict
414  execute "normal a\<C-X>\<C-U>\<C-Y>"
415  set completefunc&
416
417  call assert_equal(['one', 'two'], v:completed_item[ 'user_data' ])
418  call assert_true(s:called_completedone)
419
420  let s:called_completedone = 0
421  au! CompleteDonePre
422  au! CompleteDone
423
424  au CompleteDonePre * :call <SID>CompleteDone_CheckCompletedItemDict(2)
425  au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDict(0)
426
427  set complete=.,F<SID>CompleteDone_CompleteFuncDict
428  execute "normal a\<C-N>\<C-Y>"
429  set complete&
430
431  call assert_equal(['one', 'two'], v:completed_item[ 'user_data' ])
432  call assert_true(s:called_completedone)
433
434  let s:called_completedone = 0
435  au! CompleteDonePre
436  au! CompleteDone
437endfunc
438
439func s:CompleteDone_CompleteFuncDictNoUserData(findstart, base)
440  if a:findstart
441    return 0
442  endif
443
444  return {
445	  \ 'words': [
446	    \ {
447	      \ 'word': 'aword',
448	      \ 'abbr': 'wrd',
449	      \ 'menu': 'extra text',
450	      \ 'info': 'words are cool',
451	      \ 'kind': 'W',
452	    \ }
453	  \ ]
454	\ }
455endfunc
456
457func s:CompleteDone_CheckCompletedItemDictNoUserData()
458  call assert_equal( 'aword',          v:completed_item[ 'word' ] )
459  call assert_equal( 'wrd',            v:completed_item[ 'abbr' ] )
460  call assert_equal( 'extra text',     v:completed_item[ 'menu' ] )
461  call assert_equal( 'words are cool', v:completed_item[ 'info' ] )
462  call assert_equal( 'W',              v:completed_item[ 'kind' ] )
463  call assert_equal( '',               v:completed_item[ 'user_data' ] )
464
465  let s:called_completedone = 1
466endfunc
467
468func Test_CompleteDoneDictNoUserData()
469  au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDictNoUserData()
470
471  set completefunc=<SID>CompleteDone_CompleteFuncDictNoUserData
472  execute "normal a\<C-X>\<C-U>\<C-Y>"
473  set completefunc&
474
475  call assert_equal('', v:completed_item[ 'user_data' ])
476  call assert_true(s:called_completedone)
477
478  let s:called_completedone = 0
479
480  set complete=.,F<SID>CompleteDone_CompleteFuncDictNoUserData
481  execute "normal a\<C-N>\<C-Y>"
482  set complete&
483
484  call assert_equal('', v:completed_item[ 'user_data' ])
485  call assert_true(s:called_completedone)
486
487  let s:called_completedone = 0
488  au! CompleteDone
489endfunc
490
491func s:CompleteDone_CompleteFuncList(findstart, base)
492  if a:findstart
493    return 0
494  endif
495
496  return [ 'aword' ]
497endfunc
498
499func s:CompleteDone_CheckCompletedItemList()
500  call assert_equal( 'aword', v:completed_item[ 'word' ] )
501  call assert_equal( '',      v:completed_item[ 'abbr' ] )
502  call assert_equal( '',      v:completed_item[ 'menu' ] )
503  call assert_equal( '',      v:completed_item[ 'info' ] )
504  call assert_equal( '',      v:completed_item[ 'kind' ] )
505  call assert_equal( '',      v:completed_item[ 'user_data' ] )
506
507  let s:called_completedone = 1
508endfunc
509
510func Test_CompleteDoneList()
511  au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemList()
512
513  set completefunc=<SID>CompleteDone_CompleteFuncList
514  execute "normal a\<C-X>\<C-U>\<C-Y>"
515  set completefunc&
516
517  call assert_equal('', v:completed_item[ 'user_data' ])
518  call assert_true(s:called_completedone)
519
520  let s:called_completedone = 0
521
522  set complete=.,F<SID>CompleteDone_CompleteFuncList
523  execute "normal a\<C-N>\<C-Y>"
524  set complete&
525
526  call assert_equal('', v:completed_item[ 'user_data' ])
527  call assert_true(s:called_completedone)
528
529  let s:called_completedone = 0
530
531  set complete=.,F
532  execute "normal a\<C-N>\<C-Y>"
533  set complete&
534
535  call assert_equal('', v:completed_item[ 'user_data' ])
536  call assert_true(s:called_completedone)
537
538  let s:called_completedone = 0
539  au! CompleteDone
540endfunc
541
542func Test_CompleteDone_undo()
543  au CompleteDone * call append(0, "prepend1")
544  new
545  call setline(1, ["line1", "line2"])
546  call feedkeys("Go\<C-X>\<C-N>\<CR>\<ESC>", "tx")
547  call assert_equal(["prepend1", "line1", "line2", "line1", ""],
548              \     getline(1, '$'))
549  undo
550  call assert_equal(["line1", "line2"], getline(1, '$'))
551  bwipe!
552  au! CompleteDone
553endfunc
554
555func Test_CompleteDone_modify()
556  let value = {
557        \ 'word': '',
558        \ 'abbr': '',
559        \ 'menu': '',
560        \ 'info': '',
561        \ 'kind': '',
562        \ 'user_data': '',
563        \ }
564  let v:completed_item = value
565  call assert_equal(value, v:completed_item)
566endfunc
567
568func CompleteTest(findstart, query)
569  if a:findstart
570    return col('.')
571  endif
572  return ['matched']
573endfunc
574
575func Test_completefunc_info()
576  new
577  set completeopt=menuone
578  set completefunc=CompleteTest
579    " Can be called outside of ins-completion
580  call feedkeys("i\<C-X>\<C-U>\<C-Y>\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
581  call assert_equal("matched{'preinserted_text': '', 'pum_visible': 0, 'mode': '', 'selected': -1, 'items': []}", getline(1))
582  %d
583  call feedkeys("i\<C-X>\<C-U>\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
584  call assert_equal("matched{'preinserted_text': '', 'pum_visible': 1, 'mode': 'function', 'selected': 0, 'items': [{'word': 'matched', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}]}", getline(1))
585  %d
586  set complete=.,FCompleteTest
587  call feedkeys("i\<C-N>\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
588  call assert_equal("matched{'preinserted_text': '', 'pum_visible': 1, 'mode': 'keyword', 'selected': 0, 'items': [{'word': 'matched', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}]}", getline(1))
589  %d
590  set complete=.,F
591  call feedkeys("i\<C-N>\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
592  call assert_equal("matched{'preinserted_text': '', 'pum_visible': 1, 'mode': 'keyword', 'selected': 0, 'items': [{'word': 'matched', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}]}", getline(1))
593  set completeopt&
594  set complete&
595  set completefunc&
596endfunc
597
598" For ^N completion, `completefunc` receives the same leader string in both the
599" 'info' and 'expansion' phases (the leader is not removed before expansion).
600" This avoids flicker when `completefunc` (e.g. an LSP client) is slow and calls
601" 'sleep', which triggers out_flush().
602func Test_completefunc_leader()
603  func CptColTest(findstart, query)
604    if a:findstart
605      call assert_equal(b:compl_line, getline(1))
606      call assert_equal(b:cursor_col, col('.'))
607      return col('.')
608    endif
609    call assert_equal(b:compl_line, getline(1))
610    call assert_equal(b:cursor_col, col('.'))
611    " return v:none
612    return []
613  endfunc
614
615  set complete=FCptColTest
616  new
617
618  " Replace mode
619  let b:compl_line = "foo barxyz"
620  let b:cursor_col = 10
621  call feedkeys("ifoo barbaz\<Esc>2hRxy\<C-N>", "tx")
622
623  " Insert mode
624  let b:compl_line = "foo bar"
625  let b:cursor_col = 8
626  call feedkeys("Sfoo bar\<C-N>", "tx")
627
628  set completeopt=longest
629  call feedkeys("Sfoo bar\<C-N>", "tx")
630
631  set completeopt=menuone
632  call feedkeys("Sfoo bar\<C-N>", "tx")
633
634  set completeopt=menuone,preinsert
635  call feedkeys("Sfoo bar\<C-N>", "tx")
636  bwipe!
637  set complete& completeopt&
638  delfunc CptColTest
639endfunc
640
641func ScrollInfoWindowUserDefinedFn(findstart, query)
642  " User defined function (i_CTRL-X_CTRL-U)
643  if a:findstart
644    return col('.')
645  endif
646  let infostr = range(20)->mapnew({_, v -> string(v)})->join("\n")
647  return [{'word': 'foo', 'info': infostr}, {'word': 'bar'}]
648endfunc
649
650func ScrollInfoWindowPageDown()
651  call win_execute(popup_findinfo(), "normal! \<PageDown>")
652  return ''
653endfunc
654
655func ScrollInfoWindowPageUp()
656  call win_execute(popup_findinfo(), "normal! \<PageUp>")
657  return ''
658endfunc
659
660func ScrollInfoWindowTest(mvmt, count, fline)
661  new
662  set completeopt=menuone,popup,noinsert,noselect
663  set completepopup=height:5
664  set completefunc=ScrollInfoWindowUserDefinedFn
665  let keyseq = "i\<C-X>\<C-U>\<C-N>"
666  for _ in range(a:count)
667    let keyseq .= (a:mvmt == "pageup" ? "\<C-R>\<C-R>=ScrollInfoWindowPageUp()\<CR>" :
668          \ "\<C-R>\<C-R>=ScrollInfoWindowPageDown()\<CR>")
669  endfor
670  let keyseq .= "\<C-R>\<C-R>=string(popup_getpos(popup_findinfo()))\<CR>\<ESC>"
671  call feedkeys(keyseq, "tx")
672  call assert_match('''firstline'': ' . a:fline, getline(1))
673  bwipe!
674  set completeopt&
675  set completepopup&
676  set completefunc&
677endfunc
678
679func Test_scroll_info_window()
680  throw 'Skipped: popup_findinfo() is N/A'
681  call ScrollInfoWindowTest("", 0, 1)
682  call ScrollInfoWindowTest("pagedown", 1, 4)
683  call ScrollInfoWindowTest("pagedown", 2, 7)
684  call ScrollInfoWindowTest("pagedown", 3, 11)
685  call ScrollInfoWindowTest("pageup", 3, 1)
686endfunc
687
688func CompleteInfoUserDefinedFn(findstart, query)
689  " User defined function (i_CTRL-X_CTRL-U)
690  if a:findstart
691    return col('.')
692  endif
693  return [{'word': 'foo'}, {'word': 'bar'}, {'word': 'baz'}, {'word': 'qux'}]
694endfunc
695
696func CompleteInfoTestUserDefinedFn(mvmt, idx, noselect)
697  if a:noselect
698    set completeopt=menuone,popup,noinsert,noselect
699  else
700    set completeopt=menu,preview
701  endif
702  let items = "[" .
703        \ "{'word': 'foo', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, " .
704        \ "{'word': 'bar', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, " .
705        \ "{'word': 'baz', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, " .
706        \ "{'word': 'qux', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}" .
707        \ "]"
708  new
709  set completefunc=CompleteInfoUserDefinedFn
710  call feedkeys("i\<C-X>\<C-U>" . a:mvmt . "\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
711  let completed = a:idx != -1 ? ['foo', 'bar', 'baz', 'qux']->get(a:idx) : ''
712  call assert_equal(completed. "{'preinserted_text': '', 'pum_visible': 1, 'mode': 'function', 'selected': " . a:idx . ", 'items': " . items . "}", getline(1))
713  %d
714  set complete=.,FCompleteInfoUserDefinedFn
715  call feedkeys("i\<C-N>" . a:mvmt . "\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
716  let completed = a:idx != -1 ? ['foo', 'bar', 'baz', 'qux']->get(a:idx) : ''
717  call assert_equal(completed. "{'preinserted_text': '', 'pum_visible': 1, 'mode': 'keyword', 'selected': " . a:idx . ", 'items': " . items . "}", getline(1))
718  %d
719  set complete=.,F
720  call feedkeys("i\<C-N>" . a:mvmt . "\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx")
721  let completed = a:idx != -1 ? ['foo', 'bar', 'baz', 'qux']->get(a:idx) : ''
722  call assert_equal(completed. "{'preinserted_text': '', 'pum_visible': 1, 'mode': 'keyword', 'selected': " . a:idx . ", 'items': " . items . "}", getline(1))
723  bwipe!
724  set completeopt& completefunc& complete&
725endfunc
726
727func Test_complete_info_user_defined_fn()
728  " forward
729  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>", 1, v:true)
730  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-N>", 2, v:true)
731  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>", 2, v:false)
732  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-N>", 3, v:false)
733  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-N>\<C-N>", -1, v:false)
734  " backward
735  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>", 2, v:true)
736  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>", 1, v:true)
737  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>", -1, v:true)
738  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>", 3, v:false)
739  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>", 2, v:false)
740  " forward backward
741  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-N>\<C-P>", 1, v:true)
742  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-P>", 0, v:true)
743  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-N>\<C-P>", 2, v:false)
744  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-N>\<C-N>\<C-P>", 3, v:false)
745  call CompleteInfoTestUserDefinedFn("\<C-N>\<C-N>\<C-P>", 1, v:false)
746  " backward forward
747  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-N>", 0, v:true)
748  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>\<C-N>", 2, v:true)
749  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-N>", 1, v:false)
750  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-P>\<C-P>\<C-N>", 3, v:false)
751  call CompleteInfoTestUserDefinedFn("\<C-P>\<C-N>\<C-N>", 1, v:false)
752endfunc
753
754" Test that mouse scrolling/movement should not interrupt completion.
755func Test_mouse_scroll_move_during_completion()
756  new
757  com! -buffer TestCommand1 echo 'TestCommand1'
758  com! -buffer TestCommand2 echo 'TestCommand2'
759  call setline(1, ['', '', '', '', ''])
760  call cursor(5, 1)
761
762  " Without completion menu scrolling can move text.
763  set completeopt-=menu wrap
764  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelDown>\<C-V>", 'tx')
765  call assert_equal('TestCommand2', getline('.'))
766  call assert_notequal(1, winsaveview().topline)
767  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelUp>\<C-V>", 'tx')
768  call assert_equal('TestCommand2', getline('.'))
769  call assert_equal(1, winsaveview().topline)
770  set nowrap
771  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelRight>\<C-V>", 'tx')
772  call assert_equal('TestCommand2', getline('.'))
773  call assert_notequal(0, winsaveview().leftcol)
774  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelLeft>\<C-V>", 'tx')
775  call assert_equal('TestCommand2', getline('.'))
776  call assert_equal(0, winsaveview().leftcol)
777  call feedkeys("ccT\<C-X>\<C-V>\<MouseMove>\<C-V>", 'tx')
778  call assert_equal('TestCommand2', getline('.'))
779
780  " With completion menu scrolling cannot move text.
781  set completeopt+=menu wrap
782  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelDown>\<C-V>", 'tx')
783  call assert_equal('TestCommand2', getline('.'))
784  call assert_equal(1, winsaveview().topline)
785  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelUp>\<C-V>", 'tx')
786  call assert_equal('TestCommand2', getline('.'))
787  call assert_equal(1, winsaveview().topline)
788  set nowrap
789  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelRight>\<C-V>", 'tx')
790  call assert_equal('TestCommand2', getline('.'))
791  call assert_equal(0, winsaveview().leftcol)
792  call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelLeft>\<C-V>", 'tx')
793  call assert_equal('TestCommand2', getline('.'))
794  call assert_equal(0, winsaveview().leftcol)
795  call feedkeys("ccT\<C-X>\<C-V>\<MouseMove>\<C-V>", 'tx')
796  call assert_equal('TestCommand2', getline('.'))
797
798  bwipe!
799  set completeopt& wrap&
800endfunc
801
802" Check that when using feedkeys() typeahead does not interrupt searching for
803" completions.
804func Test_compl_feedkeys()
805  new
806  set completeopt=menuone,noselect
807  call feedkeys("ajump ju\<C-X>\<C-N>\<C-P>\<ESC>", "tx")
808  call assert_equal("jump jump", getline(1))
809  bwipe!
810  set completeopt&
811endfunc
812
813func s:ComplInCmdwin_GlobalCompletion(a, l, p)
814  return 'global'
815endfunc
816
817func s:ComplInCmdwin_LocalCompletion(a, l, p)
818  return 'local'
819endfunc
820
821func Test_compl_in_cmdwin()
822  set wildmenu wildchar=<Tab>
823  com! -nargs=1 -complete=command GetInput let input = <q-args>
824  com! -buffer TestCommand echo 'TestCommand'
825  let w:test_winvar = 'winvar'
826  let b:test_bufvar = 'bufvar'
827
828  " User-defined commands
829  let input = ''
830  call feedkeys("q:iGetInput T\<C-x>\<C-v>\<CR>", 'tx!')
831  call assert_equal('TestCommand', input)
832
833  let input = ''
834  call feedkeys("q::GetInput T\<Tab>\<CR>:q\<CR>", 'tx!')
835  call assert_equal('T', input)
836
837  com! -nargs=1 -complete=var GetInput let input = <q-args>
838  " Window-local variables
839  let input = ''
840  call feedkeys("q:iGetInput w:test_\<C-x>\<C-v>\<CR>", 'tx!')
841  call assert_equal('w:test_winvar', input)
842
843  let input = ''
844  call feedkeys("q::GetInput w:test_\<Tab>\<CR>:q\<CR>", 'tx!')
845  call assert_equal('w:test_', input)
846
847  " Buffer-local variables
848  let input = ''
849  call feedkeys("q:iGetInput b:test_\<C-x>\<C-v>\<CR>", 'tx!')
850  call assert_equal('b:test_bufvar', input)
851
852  let input = ''
853  call feedkeys("q::GetInput b:test_\<Tab>\<CR>:q\<CR>", 'tx!')
854  call assert_equal('b:test_', input)
855
856
857  " Argument completion of buffer-local command
858  func s:ComplInCmdwin_GlobalCompletionList(a, l, p)
859    return ['global']
860  endfunc
861
862  func s:ComplInCmdwin_LocalCompletionList(a, l, p)
863    return ['local']
864  endfunc
865
866  func s:ComplInCmdwin_CheckCompletion(arg)
867    call assert_equal('local', a:arg)
868  endfunc
869
870  com! -nargs=1 -complete=custom,<SID>ComplInCmdwin_GlobalCompletion
871       \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>)
872  com! -buffer -nargs=1 -complete=custom,<SID>ComplInCmdwin_LocalCompletion
873       \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>)
874  call feedkeys("q:iTestCommand \<Tab>\<CR>", 'tx!')
875
876  com! -nargs=1 -complete=customlist,<SID>ComplInCmdwin_GlobalCompletionList
877       \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>)
878  com! -buffer -nargs=1 -complete=customlist,<SID>ComplInCmdwin_LocalCompletionList
879       \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>)
880
881  call feedkeys("q:iTestCommand \<Tab>\<CR>", 'tx!')
882
883  func! s:ComplInCmdwin_CheckCompletion(arg)
884    call assert_equal('global', a:arg)
885  endfunc
886  new
887  call feedkeys("q:iTestCommand \<Tab>\<CR>", 'tx!')
888  quit
889
890  delfunc s:ComplInCmdwin_GlobalCompletion
891  delfunc s:ComplInCmdwin_LocalCompletion
892  delfunc s:ComplInCmdwin_GlobalCompletionList
893  delfunc s:ComplInCmdwin_LocalCompletionList
894  delfunc s:ComplInCmdwin_CheckCompletion
895
896  delcom -buffer TestCommand
897  delcom TestCommand
898  delcom GetInput
899  unlet w:test_winvar
900  unlet b:test_bufvar
901  set wildmenu& wildchar&
902endfunc
903
904" Test for insert path completion with completeslash option
905func Test_ins_completeslash()
906  CheckMSWindows
907
908  call mkdir('Xdir')
909  let orig_shellslash = &shellslash
910  set cpt&
911  new
912
913  set noshellslash
914
915  set completeslash=
916  exe "normal oXd\<C-X>\<C-F>"
917  call assert_equal('Xdir\', getline('.'))
918
919  set completeslash=backslash
920  exe "normal oXd\<C-X>\<C-F>"
921  call assert_equal('Xdir\', getline('.'))
922
923  set completeslash=slash
924  exe "normal oXd\<C-X>\<C-F>"
925  call assert_equal('Xdir/', getline('.'))
926
927  set shellslash
928
929  set completeslash=
930  exe "normal oXd\<C-X>\<C-F>"
931  call assert_equal('Xdir/', getline('.'))
932
933  set completeslash=backslash
934  exe "normal oXd\<C-X>\<C-F>"
935  call assert_equal('Xdir\', getline('.'))
936
937  set completeslash=slash
938  exe "normal oXd\<C-X>\<C-F>"
939  call assert_equal('Xdir/', getline('.'))
940  %bw!
941  call delete('Xdir', 'rf')
942
943  " globpath() should always return forward slash separator
944  set noshellslash
945  set completeslash=backslash
946  call assert_true(stridx(globpath(&rtp, 'syntax/*.vim', 1, 1)[0], '\') == -1)
947
948  let &shellslash = orig_shellslash
949  set completeslash=
950endfunc
951
952func Test_pum_stopped_by_timer()
953  CheckScreendump
954
955  let lines =<< trim END
956    call setline(1, ['hello', 'hullo', 'heeee', ''])
957    func StartCompl()
958      call timer_start(100, { -> execute('stopinsert') })
959      call feedkeys("Gah\<C-N>")
960    endfunc
961  END
962
963  call writefile(lines, 'Xpumscript', 'D')
964  let buf = RunVimInTerminal('-S Xpumscript', #{rows: 12})
965  call term_sendkeys(buf, ":call StartCompl()\<CR>")
966  call TermWait(buf, 200)
967  call term_sendkeys(buf, "k")
968  call VerifyScreenDump(buf, 'Test_pum_stopped_by_timer', {})
969
970  call StopVimInTerminal(buf)
971endfunc
972
973" The completion popup menu must line up with the start of the completed text
974" on screen, also when there is concealed text before it on the line.
975func Test_pum_position_with_concealed_text()
976  CheckScreendump
977
978  let lines =<< trim END
979    call setline(1, ['CONCEALED foobar', 'CONCEALED foo'])
980    syntax match Hidden /CONCEALED / conceal
981    setlocal conceallevel=3 concealcursor=nvic
982    set completeopt=menu,menuone
983  END
984
985  call writefile(lines, 'Xpumconceal', 'D')
986  let buf = RunVimInTerminal('-S Xpumconceal', #{rows: 10})
987  call TermWait(buf, 50)
988  call term_sendkeys(buf, "2GA")
989  call TermWait(buf, 50)
990  call term_sendkeys(buf, "\<C-X>\<C-N>")
991  call VerifyScreenDump(buf, 'Test_pum_position_with_concealed_text', {})
992
993  call term_sendkeys(buf, "\<Esc>")
994  call StopVimInTerminal(buf)
995endfunc
996
997" Same alignment when the concealed text comes from a match and is shown as a
998" replacement character with 'conceallevel' 2.
999func Test_pum_position_with_concealed_match()
1000  CheckScreendump
1001
1002  let lines =<< trim END
1003    call setline(1, ['XXX foobar', 'XXX foo'])
1004    call matchadd('Conceal', 'XXX ', 10, -1, {'conceal': '+'})
1005    setlocal conceallevel=2 concealcursor=nvic
1006    set completeopt=menu,menuone
1007  END
1008
1009  call writefile(lines, 'Xpumconcealmatch', 'D')
1010  let buf = RunVimInTerminal('-S Xpumconcealmatch', #{rows: 10})
1011  call TermWait(buf, 50)
1012  call term_sendkeys(buf, "2GA")
1013  call TermWait(buf, 50)
1014  call term_sendkeys(buf, "\<C-X>\<C-N>")
1015  call VerifyScreenDump(buf, 'Test_pum_position_with_concealed_match', {})
1016
1017  call term_sendkeys(buf, "\<Esc>")
1018  call StopVimInTerminal(buf)
1019endfunc
1020
1021" The menu lines up with the visible text in a 'rightleft' window too, where
1022" the cursor screen column is mirrored.
1023func Test_pum_position_with_concealed_rl()
1024  CheckScreendump
1025  CheckFeature rightleft
1026
1027  let lines =<< trim END
1028    set rightleft
1029    call setline(1, ['CONCEALED foobar', 'CONCEALED foo'])
1030    syntax match Hidden /CONCEALED / conceal
1031    setlocal conceallevel=3 concealcursor=nvic
1032    set completeopt=menu,menuone
1033  END
1034
1035  call writefile(lines, 'Xpumconcealrl', 'D')
1036  let buf = RunVimInTerminal('-S Xpumconcealrl', #{rows: 10})
1037  call TermWait(buf, 50)
1038  call term_sendkeys(buf, "2GA")
1039  call TermWait(buf, 50)
1040  call term_sendkeys(buf, "\<C-X>\<C-N>")
1041  call VerifyScreenDump(buf, 'Test_pum_position_with_concealed_rl', {})
1042
1043  call term_sendkeys(buf, "\<Esc>")
1044  call StopVimInTerminal(buf)
1045endfunc
1046
1047" The recorded offset is per screen line, so the menu also lines up when the
1048" concealed text and the completion are on a wrapped continuation line.
1049func Test_pum_position_with_concealed_wrap()
1050  CheckScreendump
1051
1052  let lines =<< trim END
1053    call setline(1, ['foobar', 'aaaaaaaaaaaaaaaaaaaa CONCEALED foo'])
1054    syntax match Hidden /CONCEALED / conceal
1055    setlocal conceallevel=3 concealcursor=nvic
1056    set completeopt=menu,menuone
1057  END
1058
1059  call writefile(lines, 'Xpumconcealwrap', 'D')
1060  let buf = RunVimInTerminal('-S Xpumconcealwrap', #{rows: 10, cols: 20})
1061  call TermWait(buf, 50)
1062  call term_sendkeys(buf, "2GA")
1063  call TermWait(buf, 50)
1064  call term_sendkeys(buf, "\<C-X>\<C-N>")
1065  call VerifyScreenDump(buf, 'Test_pum_position_with_concealed_wrap', {})
1066
1067  call term_sendkeys(buf, "\<Esc>")
1068  call StopVimInTerminal(buf)
1069endfunc
1070
1071func Test_complete_stopinsert_startinsert()
1072  nnoremap <F2> <Cmd>startinsert<CR>
1073  inoremap <F2> <Cmd>stopinsert<CR>
1074  " This just checks if this causes an error
1075  call feedkeys("i\<C-X>\<C-N>\<F2>\<F2>", 'x')
1076  nunmap <F2>
1077  iunmap <F2>
1078endfunc
1079
1080func Test_pum_with_folds_two_tabs()
1081  CheckScreendump
1082
1083  let lines =<< trim END
1084    set fdm=marker
1085    call setline(1, ['" x {{{1', '" a some text'])
1086    call setline(3, range(&lines)->map({_, val -> '" a' .. val}))
1087    norm! zm
1088    tab sp
1089    call feedkeys('2Gzv', 'xt')
1090    call feedkeys("0fa", 'xt')
1091  END
1092
1093  call writefile(lines, 'Xpumscript')
1094  let buf = RunVimInTerminal('-S Xpumscript', #{rows: 10})
1095  call TermWait(buf, 50)
1096  call term_sendkeys(buf, "a\<C-N>")
1097  call VerifyScreenDump(buf, 'Test_pum_with_folds_two_tabs', {})
1098
1099  call term_sendkeys(buf, "\<Esc>")
1100  call StopVimInTerminal(buf)
1101  call delete('Xpumscript')
1102endfunc
1103
1104func Test_pum_with_preview_win()
1105  CheckScreendump
1106
1107  let lines =<< trim END
1108    funct Omni_test(findstart, base)
1109      if a:findstart
1110        return col(".") - 1
1111      endif
1112      return [#{word: "one", info: "1info"}, #{word: "two", info: "2info"}, #{word: "three", info: "3info"}]
1113    endfunc
1114    set omnifunc=Omni_test
1115    set completeopt+=longest
1116  END
1117
1118  call writefile(lines, 'Xpreviewscript')
1119  let buf = RunVimInTerminal('-S Xpreviewscript', #{rows: 12})
1120  call term_sendkeys(buf, "Gi\<C-X>\<C-O>")
1121  call TermWait(buf, 200)
1122  call term_sendkeys(buf, "\<C-N>")
1123  call VerifyScreenDump(buf, 'Test_pum_with_preview_win', {})
1124
1125  call term_sendkeys(buf, "\<Esc>")
1126  call StopVimInTerminal(buf)
1127  call delete('Xpreviewscript')
1128endfunc
1129
1130func Test_scrollbar_on_wide_char()
1131  CheckScreendump
1132
1133  let lines =<< trim END
1134    call setline(1, ['a', '            啊啊啊',
1135                        \ '             哦哦哦',
1136                        \ '              呃呃呃'])
1137    call setline(5, range(10)->map({i, v -> 'aa' .. v .. 'bb'}))
1138  END
1139  call writefile(lines, 'Xwidescript')
1140  let buf = RunVimInTerminal('-S Xwidescript', #{rows: 10})
1141  call term_sendkeys(buf, "A\<C-N>")
1142  call VerifyScreenDump(buf, 'Test_scrollbar_on_wide_char', {})
1143
1144  call StopVimInTerminal(buf)
1145  call delete('Xwidescript')
1146endfunc
1147
1148" Test for inserting the tag search pattern in insert mode
1149func Test_ins_compl_tag_sft()
1150  call writefile([
1151        \ "!_TAG_FILE_ENCODING\tutf-8\t//",
1152        \ "first\tXfoo\t/^int first() {}$/",
1153        \ "second\tXfoo\t/^int second() {}$/",
1154        \ "third\tXfoo\t/^int third() {}$/"],
1155        \ 'Xtags')
1156  set tags=Xtags
1157  let code =<< trim [CODE]
1158    int first() {}
1159    int second() {}
1160    int third() {}
1161  [CODE]
1162  call writefile(code, 'Xfoo')
1163
1164  enew
1165  set showfulltag
1166  exe "normal isec\<C-X>\<C-]>\<C-N>\<CR>"
1167  call assert_equal('int second() {}', getline(1))
1168  set noshowfulltag
1169
1170  call delete('Xtags')
1171  call delete('Xfoo')
1172  set tags&
1173  %bwipe!
1174endfunc
1175
1176" Test for 'completefunc' deleting text
1177func Test_completefunc_error()
1178  new
1179  " delete text when called for the first time
1180  func CompleteFunc(findstart, base)
1181    if a:findstart == 1
1182      normal dd
1183      return col('.') - 1
1184    endif
1185    return ['a', 'b']
1186  endfunc
1187  set completefunc=CompleteFunc
1188  call setline(1, ['', 'abcd', ''])
1189  call assert_fails('exe "normal 2G$a\<C-X>\<C-U>"', 'E565:')
1190  set complete=FCompleteFunc
1191  call assert_fails('exe "normal 2G$a\<C-N>"', 'E565:')
1192  set complete=F
1193  call assert_fails('exe "normal 2G$a\<C-N>"', 'E565:')
1194
1195  " delete text when called for the second time
1196  func CompleteFunc2(findstart, base)
1197    if a:findstart == 1
1198      return col('.') - 1
1199    endif
1200    normal dd
1201    return ['a', 'b']
1202  endfunc
1203  set completefunc=CompleteFunc2
1204  call setline(1, ['', 'abcd', ''])
1205  call assert_fails('exe "normal 2G$a\<C-X>\<C-U>"', 'E565:')
1206  set complete=FCompleteFunc2
1207  call assert_fails('exe "normal 2G$a\<C-N>"', 'E565:')
1208  set complete=F
1209  call assert_fails('exe "normal 2G$a\<C-N>"', 'E565:')
1210
1211  " Jump to a different window from the complete function
1212  func CompleteFunc3(findstart, base)
1213    if a:findstart == 1
1214      return col('.') - 1
1215    endif
1216    wincmd p
1217    return ['a', 'b']
1218  endfunc
1219  set completefunc=CompleteFunc3
1220  new
1221  call assert_fails('exe "normal a\<C-X>\<C-U>"', 'E565:')
1222  %d
1223  set complete=FCompleteFunc3
1224  call assert_fails('exe "normal a\<C-N>"', 'E565:')
1225  %d
1226  set complete=F
1227  call assert_fails('exe "normal a\<C-N>"', 'E565:')
1228  bw!
1229
1230  set completefunc& complete&
1231  delfunc CompleteFunc
1232  delfunc CompleteFunc2
1233  delfunc CompleteFunc3
1234  bw!
1235endfunc
1236
1237" Test for returning non-string values from 'completefunc'
1238func Test_completefunc_invalid_data()
1239  new
1240  func! CompleteFunc(findstart, base)
1241    if a:findstart == 1
1242      return col('.') - 1
1243    endif
1244    return [{}, '', 'moon']
1245  endfunc
1246  set completefunc=CompleteFunc
1247  exe "normal i\<C-X>\<C-U>"
1248  call assert_equal('moon', getline(1))
1249  %d
1250  set complete=FCompleteFunc
1251  exe "normal i\<C-N>"
1252  call assert_equal('moon', getline(1))
1253  %d
1254  set complete=F
1255  exe "normal i\<C-N>"
1256  call assert_equal('moon', getline(1))
1257  set completefunc& complete&
1258  delfunc! CompleteFunc
1259  bw!
1260endfunc
1261
1262" Test for errors in using complete() function
1263func Test_complete_func_error()
1264  call assert_fails('call complete(1, ["a"])', 'E785:')
1265  func ListColors()
1266    call complete(col('.'), "blue")
1267  endfunc
1268  call assert_fails('exe "normal i\<C-R>=ListColors()\<CR>"', 'E474:')
1269  func ListMonths()
1270    call complete(col('.'), test_null_list())
1271  endfunc
1272  " Nvim allows a NULL list
1273  " call assert_fails('exe "normal i\<C-R>=ListMonths()\<CR>"', 'E474:')
1274  delfunc ListColors
1275  delfunc ListMonths
1276  call assert_fails('call complete_info({})', 'E714:')
1277  call assert_equal([], complete_info(['items']).items)
1278endfunc
1279
1280" Test for recursively starting completion mode using complete()
1281func Test_recursive_complete_func()
1282  func ListColors()
1283    call complete(5, ["red", "blue"])
1284    return ''
1285  endfunc
1286  new
1287  call setline(1, ['a1', 'a2'])
1288  set complete=.
1289  exe "normal Goa\<C-X>\<C-L>\<C-R>=ListColors()\<CR>\<C-N>"
1290  call assert_equal('a2blue', getline(3))
1291  delfunc ListColors
1292  bw!
1293endfunc
1294
1295" Test for using complete() with completeopt+=longest
1296func Test_complete_with_longest()
1297  new
1298  inoremap <buffer> <f3> <cmd>call complete(1, ["iaax", "iaay", "iaaz"])<cr>
1299
1300  " default: insert first match
1301  set completeopt&
1302  call setline(1, ['i'])
1303  exe "normal Aa\<f3>\<esc>"
1304  call assert_equal('iaax', getline(1))
1305
1306  " with longest: insert longest prefix
1307  set completeopt+=longest
1308  call setline(1, ['i'])
1309  exe "normal Aa\<f3>\<esc>"
1310  call assert_equal('iaa', getline(1))
1311  set completeopt&
1312  bwipe!
1313endfunc
1314
1315" Test for buffer-local value of 'completeopt'
1316func Test_completeopt_buffer_local()
1317  set completeopt=menu
1318  new
1319  call setline(1, ['foofoo', 'foobar', 'foobaz', ''])
1320  call assert_equal('', &l:completeopt)
1321  call assert_equal('menu', &completeopt)
1322  call assert_equal('menu', &g:completeopt)
1323
1324  setlocal bufhidden=hide
1325  enew
1326  call setline(1, ['foofoo', 'foobar', 'foobaz', ''])
1327  call assert_equal('', &l:completeopt)
1328  call assert_equal('menu', &completeopt)
1329  call assert_equal('menu', &g:completeopt)
1330
1331  setlocal completeopt+=fuzzy,noinsert
1332  call assert_equal('menu,fuzzy,noinsert', &l:completeopt)
1333  call assert_equal('menu,fuzzy,noinsert', &completeopt)
1334  call assert_equal('menu', &g:completeopt)
1335  call feedkeys("Gccf\<C-X>\<C-N>bz\<C-Y>", 'tnix')
1336  call assert_equal('foobaz', getline('.'))
1337
1338  setlocal completeopt=
1339  call assert_equal('', &l:completeopt)
1340  call assert_equal('menu', &completeopt)
1341  call assert_equal('menu', &g:completeopt)
1342  call feedkeys("Gccf\<C-X>\<C-N>\<C-Y>", 'tnix')
1343  call assert_equal('foofoo', getline('.'))
1344
1345  setlocal completeopt+=longest
1346  call assert_equal('menu,longest', &l:completeopt)
1347  call assert_equal('menu,longest', &completeopt)
1348  call assert_equal('menu', &g:completeopt)
1349  call feedkeys("Gccf\<C-X>\<C-N>\<C-X>\<C-Z>", 'tnix')
1350  call assert_equal('foo', getline('.'))
1351
1352  setlocal bufhidden=hide
1353  buffer #
1354  call assert_equal('', &l:completeopt)
1355  call assert_equal('menu', &completeopt)
1356  call assert_equal('menu', &g:completeopt)
1357  call feedkeys("Gccf\<C-X>\<C-N>\<C-Y>", 'tnix')
1358  call assert_equal('foofoo', getline('.'))
1359
1360  setlocal completeopt+=fuzzy,noinsert
1361  call assert_equal('menu,fuzzy,noinsert', &l:completeopt)
1362  call assert_equal('menu,fuzzy,noinsert', &completeopt)
1363  call assert_equal('menu', &g:completeopt)
1364  call feedkeys("Gccf\<C-X>\<C-N>bz\<C-Y>", 'tnix')
1365  call assert_equal('foobaz', getline('.'))
1366
1367  buffer #
1368  call assert_equal('menu,longest', &l:completeopt)
1369  call assert_equal('menu,longest', &completeopt)
1370  call assert_equal('menu', &g:completeopt)
1371  call feedkeys("Gccf\<C-X>\<C-N>\<C-X>\<C-Z>", 'tnix')
1372  call assert_equal('foo', getline('.'))
1373
1374  setlocal bufhidden=wipe
1375  buffer! #
1376  bwipe!
1377  call assert_equal('', &l:completeopt)
1378  call assert_equal('menu', &completeopt)
1379  call assert_equal('menu', &g:completeopt)
1380
1381  new | only
1382  call setline(1, ['foofoo', 'foobar', 'foobaz', ''])
1383  set completeopt&
1384  setlocal completeopt=menu,fuzzy,noinsert
1385  setglobal completeopt=menu,longest
1386  call assert_equal('menu,fuzzy,noinsert', &completeopt)
1387  call assert_equal('menu,fuzzy,noinsert', &l:completeopt)
1388  call assert_equal('menu,longest', &g:completeopt)
1389  call feedkeys("Gccf\<C-X>\<C-N>bz\<C-Y>", 'tnix')
1390  call assert_equal('foobaz', getline('.'))
1391  setlocal bufhidden=wipe
1392  new | only!
1393  call setline(1, ['foofoo', 'foobar', 'foobaz', ''])
1394  call assert_equal('menu,longest', &completeopt)
1395  call assert_equal('menu,longest', &g:completeopt)
1396  call assert_equal('', &l:completeopt)
1397  call feedkeys("Gccf\<C-X>\<C-N>\<C-X>\<C-Z>", 'tnix')
1398  call assert_equal('foo', getline('.'))
1399  bwipe!
1400
1401  new | only
1402  call setline(1, ['foofoo', 'foobar', 'foobaz', ''])
1403  set completeopt&
1404  setlocal completeopt=menu,fuzzy,noinsert
1405  set completeopt=menu,longest
1406  call assert_equal('menu,longest', &completeopt)
1407  call assert_equal('menu,longest', &g:completeopt)
1408  call assert_equal('', &l:completeopt)
1409  call feedkeys("Gccf\<C-X>\<C-N>\<C-X>\<C-Z>", 'tnix')
1410  call assert_equal('foo', getline('.'))
1411  setlocal bufhidden=wipe
1412  new | only!
1413  call setline(1, ['foofoo', 'foobar', 'foobaz', ''])
1414  call assert_equal('menu,longest', &completeopt)
1415  call assert_equal('menu,longest', &g:completeopt)
1416  call assert_equal('', &l:completeopt)
1417  call feedkeys("Gccf\<C-X>\<C-N>\<C-X>\<C-Z>", 'tnix')
1418  call assert_equal('foo', getline('.'))
1419  bwipe!
1420
1421  set completeopt&
1422endfunc
1423
1424" Test for completing words following a completed word in a line
1425func Test_complete_wrapscan()
1426  " complete words from another buffer
1427  new
1428  call setline(1, ['one two', 'three four'])
1429  new
1430  setlocal complete=w
1431  call feedkeys("itw\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>", 'xt')
1432  call assert_equal('two three four', getline(1))
1433  bw!
1434  " complete words from the current buffer
1435  setlocal complete=.
1436  %d
1437  call setline(1, ['one two', ''])
1438  call cursor(2, 1)
1439  call feedkeys("ion\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>", 'xt')
1440  call assert_equal('one two one two', getline(2))
1441  bw!
1442endfunc
1443
1444" Test for completing special characters
1445func Test_complete_special_chars()
1446  new
1447  call setline(1, 'int .*[-\^$ func float')
1448  call feedkeys("oin\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>", 'xt')
1449  call assert_equal('int .*[-\^$ func float', getline(2))
1450  bw!
1451endfunc
1452
1453" Test for completion when text is wrapped across lines.
1454func Test_complete_across_line()
1455  new
1456  call setline(1, ['red green blue', 'one two three'])
1457  setlocal textwidth=20
1458  exe "normal 2G$a re\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>"
1459  call assert_equal(['one two three red', 'green blue one'], getline(2, '$'))
1460  bw!
1461endfunc
1462
1463" Test for completing words with a '.' at the end of a word.
1464func Test_complete_joinspaces()
1465  new
1466  call setline(1, ['one two.', 'three. four'])
1467  set joinspaces
1468  exe "normal Goon\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>"
1469  call assert_equal("one two.  three. four", getline(3))
1470  set joinspaces&
1471  bw!
1472endfunc
1473
1474" Test for using CTRL-L to add one character when completing matching
1475func Test_complete_add_onechar()
1476  new
1477  call setline(1, ['wool', 'woodwork'])
1478  call feedkeys("Gowoo\<C-P>\<C-P>\<C-P>\<C-L>f", 'xt')
1479  call assert_equal('woof', getline(3))
1480
1481  " use 'ignorecase' and backspace to erase characters from the prefix string
1482  " and then add letters using CTRL-L
1483  %d
1484  set ignorecase backspace=2
1485  setlocal complete=.
1486  call setline(1, ['workhorse', 'workload'])
1487  normal Go
1488  exe "normal aWOR\<C-P>\<bs>\<bs>\<bs>\<bs>\<bs>\<bs>\<C-L>\<C-L>\<C-L>"
1489  call assert_equal('workh', getline(3))
1490  set ignorecase& backspace&
1491  bw!
1492endfunc
1493
1494" Test for using CTRL-X CTRL-L to complete whole lines lines
1495func Test_complete_wholeline()
1496  new
1497  " complete one-line
1498  call setline(1, ['a1', 'a2'])
1499  exe "normal ggoa\<C-X>\<C-L>"
1500  call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))
1501  " go to the next match (wrapping around the buffer)
1502  exe "normal 2GCa\<C-X>\<C-L>\<C-N>"
1503  call assert_equal(['a1', 'a', 'a2'], getline(1, '$'))
1504  " go to the next match
1505  exe "normal 2GCa\<C-X>\<C-L>\<C-N>\<C-N>"
1506  call assert_equal(['a1', 'a2', 'a2'], getline(1, '$'))
1507  exe "normal 2GCa\<C-X>\<C-L>\<C-N>\<C-N>\<C-N>"
1508  call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))
1509  " repeat the test using CTRL-L
1510  " go to the next match (wrapping around the buffer)
1511  exe "normal 2GCa\<C-X>\<C-L>\<C-L>"
1512  call assert_equal(['a1', 'a2', 'a2'], getline(1, '$'))
1513  " go to the next match
1514  exe "normal 2GCa\<C-X>\<C-L>\<C-L>\<C-L>"
1515  call assert_equal(['a1', 'a', 'a2'], getline(1, '$'))
1516  exe "normal 2GCa\<C-X>\<C-L>\<C-L>\<C-L>\<C-L>"
1517  call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))
1518  %d
1519  " use CTRL-X CTRL-L to add one more line
1520  call setline(1, ['a1', 'b1'])
1521  setlocal complete=.
1522  exe "normal ggOa\<C-X>\<C-L>\<C-X>\<C-L>\<C-X>\<C-L>"
1523  call assert_equal(['a1', 'b1', '', 'a1', 'b1'], getline(1, '$'))
1524  bw!
1525endfunc
1526
1527" Test for using CTRL-X CTRL-S to complete spell suggestions
1528func Test_complete_spell()
1529  new
1530  setlocal spell
1531  " without fuzzy
1532  call setline(1, 'The rigth thing')
1533  exe "normal! A\<C-X>\<C-S>"
1534  call assert_equal('The right thing', getline(1))
1535  %d
1536  " with fuzzy
1537  setlocal completeopt+=fuzzy
1538  call setline(1, 'The rigth thing')
1539  exe "normal! A\<C-X>\<C-S>"
1540  call assert_equal('The right thing', getline(1))
1541  bw!
1542endfunc
1543
1544" Test insert completion with 'cindent' (adjust the indent)
1545func Test_complete_with_cindent()
1546  new
1547  setlocal cindent
1548  call setline(1, ['if (i == 1)', "    j = 2;"])
1549  exe "normal Go{\<CR>i\<C-X>\<C-L>\<C-X>\<C-L>\<CR>}"
1550  call assert_equal(['{', "\tif (i == 1)", "\t\tj = 2;", '}'], getline(3, '$'))
1551
1552  %d
1553  call setline(1, ['when while', '{', ''])
1554  setlocal cinkeys+==while
1555  exe "normal Giwh\<C-P> "
1556  call assert_equal("\twhile ", getline('$'))
1557  bw!
1558endfunc
1559
1560" Test for <CTRL-X> <CTRL-V> completion. Complete commands and functions
1561func Test_complete_cmdline()
1562  new
1563  exe "normal icaddb\<C-X>\<C-V>"
1564  call assert_equal('caddbuffer', getline(1))
1565  exe "normal ocall getqf\<C-X>\<C-V>"
1566  call assert_equal('call getqflist(', getline(2))
1567  exe "normal oabcxyz(\<C-X>\<C-V>"
1568  call assert_equal('abcxyz(', getline(3))
1569  com! -buffer TestCommand1 echo 'TestCommand1'
1570  com! -buffer TestCommand2 echo 'TestCommand2'
1571  write! TestCommand1Test
1572  write! TestCommand2Test
1573  " Test repeating <CTRL-X> <CTRL-V> and switching to another CTRL-X mode
1574  exe "normal oT\<C-X>\<C-V>\<C-X>\<C-V>\<C-X>\<C-F>\<Esc>"
1575  call assert_equal('TestCommand2Test', getline(4))
1576  call delete('TestCommand1Test')
1577  call delete('TestCommand2Test')
1578  delcom TestCommand1
1579  delcom TestCommand2
1580  bw!
1581endfunc
1582
1583" Test for <CTRL-X> <CTRL-Z> stopping completion without changing the match
1584func Test_complete_stop()
1585  new
1586  func Save_mode1()
1587    let g:mode1 = mode(1)
1588    return ''
1589  endfunc
1590  func Save_mode2()
1591    let g:mode2 = mode(1)
1592    return ''
1593  endfunc
1594  inoremap <F1> <C-R>=Save_mode1()<CR>
1595  inoremap <F2> <C-R>=Save_mode2()<CR>
1596  call setline(1, ['aaa bbb ccc '])
1597  exe "normal A\<C-N>\<C-P>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>"
1598  call assert_equal('ic', g:mode1)
1599  call assert_equal('i', g:mode2)
1600  call assert_equal('aaa bbb ccc ', getline(1))
1601  exe "normal A\<C-N>\<Down>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>"
1602  call assert_equal('ic', g:mode1)
1603  call assert_equal('i', g:mode2)
1604  call assert_equal('aaa bbb ccc aaa', getline(1))
1605  set completeopt+=noselect
1606  exe "normal A \<C-N>\<Down>\<Down>\<C-L>\<C-L>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>"
1607  call assert_equal('ic', g:mode1)
1608  call assert_equal('i', g:mode2)
1609  call assert_equal('aaa bbb ccc aaa bb', getline(1))
1610  set completeopt&
1611  exe "normal A d\<C-N>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>"
1612  call assert_equal('ic', g:mode1)
1613  call assert_equal('i', g:mode2)
1614  call assert_equal('aaa bbb ccc aaa bb d', getline(1))
1615  com! -buffer TestCommand1 echo 'TestCommand1'
1616  com! -buffer TestCommand2 echo 'TestCommand2'
1617  exe "normal oT\<C-X>\<C-V>\<C-X>\<C-V>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>"
1618  call assert_equal('ic', g:mode1)
1619  call assert_equal('i', g:mode2)
1620  call assert_equal('TestCommand2', getline(2))
1621  delcom TestCommand1
1622  delcom TestCommand2
1623  unlet g:mode1
1624  unlet g:mode2
1625  iunmap <F1>
1626  iunmap <F2>
1627  delfunc Save_mode1
1628  delfunc Save_mode2
1629  bw!
1630endfunc
1631
1632" Test for typing CTRL-R in insert completion mode to insert a register
1633" content.
1634func Test_complete_reginsert()
1635  new
1636  call setline(1, ['a1', 'a12', 'a123', 'a1234'])
1637
1638  " if a valid CTRL-X mode key is returned from <C-R>=, then it should be
1639  " processed. Otherwise, CTRL-X mode should be stopped and the key should be
1640  " inserted.
1641  exe "normal Goa\<C-P>\<C-R>=\"\\<C-P>\"\<CR>"
1642  call assert_equal('a123', getline(5))
1643  let @r = "\<C-P>\<C-P>"
1644  exe "normal GCa\<C-P>\<C-R>=@r\<CR>"
1645  call assert_equal('a12', getline(5))
1646  exe "normal GCa\<C-P>\<C-R>=\"x\"\<CR>"
1647  call assert_equal('a1234x', getline(5))
1648  bw!
1649endfunc
1650
1651func Test_issue_7021()
1652  CheckMSWindows
1653
1654  " Test that 'completeslash' doesn't affect the result of expand()
1655  set completeslash=backslash
1656  call assert_false(expand('~') =~ '\\')
1657
1658  set completeslash=
1659endfunc
1660
1661" Test for 'longest' setting in 'completeopt' with latin1 and utf-8 encodings
1662func Test_complete_longest_match()
1663  " for e in ['latin1', 'utf-8']
1664  for e in ['utf-8']
1665    exe 'set encoding=' .. e
1666    new
1667    set complete=.
1668    set completeopt=menu,longest
1669    call setline(1, ['pfx_a1', 'pfx_a12', 'pfx_a123', 'pfx_b1'])
1670    exe "normal Gopfx\<C-P>"
1671    call assert_equal('pfx_', getline(5))
1672    bw!
1673  endfor
1674
1675  " Test for completing additional words with longest match set
1676  new
1677  call setline(1, ['abc1', 'abd2'])
1678  exe "normal Goab\<C-P>\<C-X>\<C-P>"
1679  call assert_equal('ab', getline(3))
1680  bw!
1681  set complete& completeopt&
1682endfunc
1683
1684" Test for removing the first displayed completion match and selecting the
1685" match just before that.
1686func Test_complete_erase_firstmatch()
1687  new
1688  call setline(1, ['a12', 'a34', 'a56'])
1689  set complete=.
1690  exe "normal Goa\<C-P>\<BS>\<BS>3\<CR>"
1691  call assert_equal('a34', getline('$'))
1692  set complete&
1693  bw!
1694endfunc
1695
1696" Test for completing words from unloaded buffers
1697func Test_complete_from_unloadedbuf()
1698  call writefile(['abc'], "Xfile1")
1699  call writefile(['def'], "Xfile2")
1700  edit Xfile1
1701  edit Xfile2
1702  new | close
1703  enew
1704  bunload Xfile1 Xfile2
1705  set complete=u
1706  " complete from an unloaded buffer
1707  exe "normal! ia\<C-P>"
1708  call assert_equal('abc', getline(1))
1709  exe "normal! od\<C-P>"
1710  call assert_equal('def', getline(2))
1711  set complete&
1712  %bw!
1713  call delete("Xfile1")
1714  call delete("Xfile2")
1715endfunc
1716
1717" Test for completing whole lines from unloaded buffers
1718func Test_complete_wholeline_unloadedbuf()
1719  call writefile(['a line1', 'a line2', 'a line3'], "Xfile1")
1720  edit Xfile1
1721  enew
1722  set complete=u
1723  exe "normal! ia\<C-X>\<C-L>\<C-P>"
1724  call assert_equal('a line2', getline(1))
1725  %d
1726  " completing from an unlisted buffer should fail
1727  bdel Xfile1
1728  exe "normal! ia\<C-X>\<C-L>\<C-P>"
1729  call assert_equal('a', getline(1))
1730  set complete&
1731  %bw!
1732  call delete("Xfile1")
1733endfunc
1734
1735" Test for completing words from unlisted buffers
1736func Test_complete_from_unlistedbuf()
1737  call writefile(['abc'], "Xfile1")
1738  call writefile(['def'], "Xfile2")
1739  edit Xfile1
1740  edit Xfile2
1741  new | close
1742  bdel Xfile1 Xfile2
1743  set complete=U
1744  " complete from an unlisted buffer
1745  exe "normal! ia\<C-P>"
1746  call assert_equal('abc', getline(1))
1747  exe "normal! od\<C-P>"
1748  call assert_equal('def', getline(2))
1749  set complete&
1750  %bw!
1751  call delete("Xfile1")
1752  call delete("Xfile2")
1753endfunc
1754
1755" Test for completing whole lines from unlisted buffers
1756func Test_complete_wholeline_unlistedbuf()
1757  call writefile(['a line1', 'a line2', 'a line3'], "Xfile1")
1758  edit Xfile1
1759  enew
1760  set complete=U
1761  " completing from an unloaded buffer should fail
1762  exe "normal! ia\<C-X>\<C-L>\<C-P>"
1763  call assert_equal('a', getline(1))
1764  %d
1765  bdel Xfile1
1766  exe "normal! ia\<C-X>\<C-L>\<C-P>"
1767  call assert_equal('a line2', getline(1))
1768  set complete&
1769  %bw!
1770  call delete("Xfile1")
1771endfunc
1772
1773" Test for adding a multibyte character using CTRL-L in completion mode
1774func Test_complete_mbyte_char_add()
1775  new
1776  set complete=.
1777  call setline(1, 'abė')
1778  exe "normal! oa\<C-P>\<BS>\<BS>\<C-L>\<C-L>"
1779  call assert_equal('abė', getline(2))
1780  " Test for a leader with multibyte character
1781  %d
1782  call setline(1, 'abėĕ')
1783  exe "normal! oabė\<C-P>"
1784  call assert_equal('abėĕ', getline(2))
1785  bw!
1786endfunc
1787
1788" Test for using <C-X><C-P> for local expansion even if 'complete' is set to
1789" not to complete matches from the local buffer. Also test using multiple
1790" <C-X> to cancel the current completion mode.
1791func Test_complete_local_expansion()
1792  new
1793  set complete=t
1794  call setline(1, ['abc', 'def'])
1795  exe "normal! Go\<C-X>\<C-P>"
1796  call assert_equal("def", getline(3))
1797  exe "normal! Go\<C-P>"
1798  call assert_equal("", getline(4))
1799  exe "normal! Go\<C-X>\<C-N>"
1800  call assert_equal("abc", getline(5))
1801  exe "normal! Go\<C-N>"
1802  call assert_equal("", getline(6))
1803
1804  " use multiple <C-X> to cancel the previous completion mode
1805  exe "normal! Go\<C-P>\<C-X>\<C-P>"
1806  call assert_equal("", getline(7))
1807  exe "normal! Go\<C-P>\<C-X>\<C-X>\<C-P>"
1808  call assert_equal("", getline(8))
1809  exe "normal! Go\<C-P>\<C-X>\<C-X>\<C-X>\<C-P>"
1810  call assert_equal("abc", getline(9))
1811
1812  " interrupt the current completion mode
1813  set completeopt=menu,noinsert
1814  exe "normal! Go\<C-X>\<C-F>\<C-X>\<C-X>\<C-P>\<C-Y>"
1815  call assert_equal("abc", getline(10))
1816
1817  " when only one <C-X> is used to interrupt, do normal expansion
1818  exe "normal! Go\<C-X>\<C-F>\<C-X>\<C-P>"
1819  call assert_equal("", getline(11))
1820  set completeopt&
1821
1822  " using two <C-X> in non-completion mode and restarting the same mode
1823  exe "normal! God\<C-X>\<C-X>\<C-P>\<C-X>\<C-X>\<C-P>\<C-Y>"
1824  call assert_equal("def", getline(12))
1825
1826  " test for adding a match from the original empty text
1827  %d
1828  call setline(1, 'abc def g')
1829  exe "normal! o\<C-X>\<C-P>\<C-N>\<C-X>\<C-P>"
1830  call assert_equal('def', getline(2))
1831  exe "normal! 0C\<C-X>\<C-N>\<C-P>\<C-X>\<C-N>"
1832  call assert_equal('abc', getline(2))
1833
1834  bw!
1835endfunc
1836
1837" Test for undoing changes after a insert-mode completion
1838func Test_complete_undo()
1839  new
1840  set complete=.
1841  " undo with 'ignorecase'
1842  call setline(1, ['ABOVE', 'BELOW'])
1843  set ignorecase
1844  exe "normal! Goab\<C-G>u\<C-P>"
1845  call assert_equal("ABOVE", getline(3))
1846  undo
1847  call assert_equal("ab", getline(3))
1848  set ignorecase&
1849  %d
1850  " undo with longest match
1851  set completeopt=menu,longest
1852  call setline(1, ['above', 'about'])
1853  exe "normal! Goa\<C-G>u\<C-P>"
1854  call assert_equal("abo", getline(3))
1855  undo
1856  call assert_equal("a", getline(3))
1857  set completeopt&
1858  %d
1859  " undo for line completion
1860  call setline(1, ['above that change', 'below that change'])
1861  exe "normal! Goabove\<C-G>u\<C-X>\<C-L>"
1862  call assert_equal("above that change", getline(3))
1863  undo
1864  call assert_equal("above", getline(3))
1865
1866  bw!
1867endfunc
1868
1869" Test for completing a very long word
1870func Test_complete_long_word()
1871  set complete&
1872  new
1873  call setline(1, repeat('x', 950) .. ' one two three')
1874  exe "normal! Gox\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>"
1875  call assert_equal(repeat('x', 950) .. ' one two three', getline(2))
1876  %d
1877  " should fail when more than 950 characters are in a word
1878  call setline(1, repeat('x', 951) .. ' one two three')
1879  exe "normal! Gox\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>"
1880  call assert_equal(repeat('x', 951), getline(2))
1881
1882  " Test for adding a very long word to an existing completion
1883  %d
1884  call setline(1, ['abc', repeat('x', 1016) .. '012345'])
1885  exe "normal! Goab\<C-P>\<C-X>\<C-P>"
1886  call assert_equal('abc ' .. repeat('x', 1016) .. '0123', getline(3))
1887  bw!
1888endfunc
1889
1890" Test for some fields in the complete items used by complete()
1891func Test_complete_items()
1892  func CompleteItems(idx)
1893    let items = [[#{word: "one", dup: 1, user_data: 'u1'}, #{word: "one", dup: 1, user_data: 'u2'}],
1894          \ [#{word: "one", dup: 0, user_data: 'u3'}, #{word: "one", dup: 0, user_data: 'u4'}],
1895          \ [#{word: "one", icase: 1, user_data: 'u7'}, #{word: "oNE", icase: 1, user_data: 'u8'}],
1896          \ [#{user_data: 'u9'}],
1897          \ [#{word: "", user_data: 'u10'}],
1898          \ [#{word: "", empty: 1, user_data: 'u11'}]]
1899    call complete(col('.'), items[a:idx])
1900    return ''
1901  endfunc
1902  new
1903  exe "normal! i\<C-R>=CompleteItems(0)\<CR>\<C-N>\<C-Y>"
1904  call assert_equal('u2', v:completed_item.user_data)
1905  call assert_equal('one', getline(1))
1906  exe "normal! o\<C-R>=CompleteItems(1)\<CR>\<C-Y>"
1907  call assert_equal('u3', v:completed_item.user_data)
1908  call assert_equal('one', getline(2))
1909  exe "normal! o\<C-R>=CompleteItems(1)\<CR>\<C-N>"
1910  call assert_equal('', getline(3))
1911  set completeopt=menu,noinsert
1912  exe "normal! o\<C-R>=CompleteItems(2)\<CR>one\<C-N>\<C-Y>"
1913  call assert_equal('oNE', getline(4))
1914  call assert_equal('u8', v:completed_item.user_data)
1915  set completeopt&
1916  exe "normal! o\<C-R>=CompleteItems(3)\<CR>"
1917  call assert_equal('', getline(5))
1918  exe "normal! o\<C-R>=CompleteItems(4)\<CR>"
1919  call assert_equal('', getline(6))
1920  exe "normal! o\<C-R>=CompleteItems(5)\<CR>"
1921  call assert_equal('', getline(7))
1922  call assert_equal('u11', v:completed_item.user_data)
1923  " pass invalid argument to complete()
1924  let cmd = "normal! o\<C-R>=complete(1, [[]])\<CR>"
1925  call assert_fails('exe cmd', 'E730:')
1926  bw!
1927  delfunc CompleteItems
1928endfunc
1929
1930" Test for the "refresh" item in the dict returned by an insert completion
1931" function
1932func Test_complete_item_refresh_always()
1933  let g:CallCount = 0
1934  func! Tcomplete(findstart, base)
1935    if a:findstart
1936      " locate the start of the word
1937      let line = getline('.')
1938      let start = col('.') - 1
1939      while start > 0 && line[start - 1] =~ '\a'
1940        let start -= 1
1941      endwhile
1942      return start
1943    else
1944      let g:CallCount += 1
1945      let res = ["update1", "update12", "update123"]
1946      return #{words: res, refresh: 'always'}
1947    endif
1948  endfunc
1949  set completeopt=menu,longest
1950  set completefunc=Tcomplete
1951  new
1952  exe "normal! iup\<C-X>\<C-U>\<BS>\<BS>\<BS>\<BS>\<BS>"
1953  call assert_equal('up', getline(1))
1954  call assert_equal(6, g:CallCount)
1955  %d
1956  let g:CallCount = 0
1957  set complete=FTcomplete
1958  exe "normal! iup\<C-N>\<BS>\<BS>\<BS>\<BS>\<BS>"
1959  call assert_equal('up', getline(1))
1960  call assert_equal(6, g:CallCount)
1961  %d
1962  let g:CallCount = 0
1963  set complete=F
1964  exe "normal! iup\<C-N>\<BS>\<BS>\<BS>\<BS>\<BS>"
1965  call assert_equal('up', getline(1))
1966  call assert_equal(6, g:CallCount)
1967  %d
1968  let g:CallCount = 0
1969  set omnifunc=Tcomplete
1970  set complete=o
1971  exe "normal! iup\<C-N>\<BS>\<BS>\<BS>\<BS>\<BS>"
1972  call assert_equal('up', getline(1))
1973  call assert_equal(6, g:CallCount)
1974  bw!
1975  set completeopt&
1976  set complete&
1977  set completefunc&
1978  delfunc Tcomplete
1979endfunc
1980
1981" Test for 'cpt' user func that fails (return -2/-3) when refresh:always
1982func Test_cpt_func_refresh_always_fail()
1983  func! CompleteFail(retval, findstart, base)
1984    if a:findstart
1985      return a:retval
1986    endif
1987    call assert_equal(-999, a:findstart) " Should not reach here
1988  endfunc
1989  new
1990  set complete=Ffunction('CompleteFail'\\,\ [-2])
1991  exe "normal! ia\<C-N>"
1992  %d
1993  set complete=Ffunction('CompleteFail'\\,\ [-3])
1994  exe "normal! ia\<C-N>"
1995  bw!
1996
1997  func! CompleteFailIntermittent(retval, findstart, base)
1998    if a:findstart
1999      if g:CallCount == 2
2000        let g:CallCount += 1
2001        return a:retval
2002      endif
2003      return col('.') - 1
2004    endif
2005    let g:CallCount += 1
2006    let res = [[], ['foo', 'fbar'], ['foo1', 'foo2'], ['foofail'], ['fooo3']]
2007    return #{words: res[g:CallCount], refresh: 'always'}
2008  endfunc
2009  new
2010  set completeopt=menuone,noselect
2011  set complete=Ffunction('CompleteFailIntermittent'\\,\ [-2])
2012  let g:CallCount = 0
2013  exe "normal! if\<C-N>\<c-r>=complete_info([\"items\"])\<cr>"
2014  call assert_match('''word'': ''foo''.*''word'': ''fbar''', getline(1))
2015  call assert_equal(1, g:CallCount)
2016  %d
2017  let g:CallCount = 0
2018  exe "normal! if\<C-N>o\<c-r>=complete_info([\"items\", \"selected\"])\<cr>"
2019  call assert_match('''selected'': -1.*''word'': ''foo1''.*''word'': ''foo2''', getline(1))
2020  call assert_equal(2, g:CallCount)
2021  %d
2022  set complete=Ffunction('CompleteFailIntermittent'\\,\ [-3])
2023  let g:CallCount = 0
2024  exe "normal! if\<C-N>o\<c-r>=complete_info([\"items\", \"selected\"])\<cr>"
2025  call assert_match('''selected'': -1.*''word'': ''foo1''.*''word'': ''foo2''', getline(1))
2026  call assert_equal(2, g:CallCount)
2027  %d
2028  set complete=Ffunction('CompleteFailIntermittent'\\,\ [-2])
2029  " completion mode is dismissed when there are no matches in list
2030  let g:CallCount = 0
2031  exe "normal! if\<C-N>oo\<c-r>=complete_info([\"items\"])\<cr>"
2032  call assert_equal('foo{''items'': []}', getline(1))
2033  call assert_equal(3, g:CallCount)
2034  %d
2035  let g:CallCount = 0
2036  exe "normal! if\<C-N>oo\<bs>\<c-r>=complete_info([\"items\"])\<cr>"
2037  call assert_equal('fo{''items'': []}', getline(1))
2038  call assert_equal(3, g:CallCount)
2039  %d
2040  " completion mode continues when matches from other sources present
2041  set complete=.,Ffunction('CompleteFailIntermittent'\\,\ [-2])
2042  call setline(1, 'fooo1')
2043  let g:CallCount = 0
2044  exe "normal! Gof\<C-N>oo\<c-r>=complete_info([\"items\", \"selected\"])\<cr>"
2045  call assert_equal('foo{''selected'': -1, ''items'': [{''word'': ''fooo1'', ''menu'': '''', '
2046        \ . '''kind_hlgroup'': '''', ''abbr_hlgroup'': '''', ''user_data'': '''', ''info'': '''', ''kind'': '''', ''abbr'': ''''}]}',
2047        \ getline(2))
2048  call assert_equal(3, g:CallCount)
2049  %d
2050  call setline(1, 'fooo1')
2051  let g:CallCount = 0
2052  exe "normal! Gof\<C-N>oo\<bs>\<c-r>=complete_info([\"items\"])\<cr>"
2053  call assert_match('''word'': ''fooo1''.*''word'': ''fooo3''', getline(2))
2054  call assert_equal(4, g:CallCount)
2055  %d
2056  " refresh will stop when -3 is returned
2057  set complete=.,,\ Ffunction('CompleteFailIntermittent'\\,\ [-3])
2058  call setline(1, 'fooo1')
2059  let g:CallCount = 0
2060  exe "normal! Gof\<C-N>o\<bs>\<c-r>=complete_info([\"items\", \"selected\"])\<cr>"
2061  call assert_equal('f{''selected'': -1, ''items'': [{''word'': ''fooo1'', ''menu'': '''', '
2062        \ . '''kind_hlgroup'': '''', ''abbr_hlgroup'': '''', ''user_data'': '''', ''info'': '''', ''kind'': '''', ''abbr'': ''''}]}',
2063        \ getline(2))
2064  call assert_equal(3, g:CallCount)
2065  %d
2066  call setline(1, 'fooo1')
2067  let g:CallCount = 0
2068  exe "normal! Gof\<C-N>oo\<bs>\<c-r>=complete_info([\"items\", \"selected\"])\<cr>"
2069  call assert_equal('fo{''selected'': -1, ''items'': [{''word'': ''fooo1'', ''menu'': '''', '
2070        \ . '''kind_hlgroup'': '''', ''abbr_hlgroup'': '''', ''user_data'': '''', ''info'': '''', ''kind'': '''', ''abbr'': ''''}]}',
2071        \ getline(2))
2072  call assert_equal(3, g:CallCount)
2073  bw!
2074
2075  set complete& completeopt&
2076  delfunc CompleteFail
2077  delfunc CompleteFailIntermittent
2078endfunc
2079
2080" Select items before they are removed by refresh:always
2081func Test_cpt_select_item_refresh_always()
2082
2083  func CompleteMenuWords()
2084    let info = complete_info(["items", "selected"])
2085    call map(info.items, {_, v -> v.word})
2086    return info
2087  endfunc
2088
2089  func! CompleteItemsSelect(compl, findstart, base)
2090    if a:findstart
2091      return col('.') - 1
2092    endif
2093    let g:CallCount += 1
2094    if g:CallCount == 2
2095        return #{words: a:compl, refresh: 'always'}
2096    endif
2097    let res = [[], ['fo', 'foobar'], [], ['foo1', 'foo2']]
2098    return #{words: res[g:CallCount], refresh: 'always'}
2099  endfunc
2100
2101  new
2102  set complete=.,Ffunction('CompleteItemsSelect'\\,\ [[]])
2103  call setline(1, "foobarbar")
2104  let g:CallCount = 0
2105  exe "normal! Gof\<c-n>\<c-n>\<c-r>=CompleteMenuWords()\<cr>"
2106  call assert_equal('fo{''selected'': 1, ''items'': [''foobarbar'', ''fo'', ''foobar'']}', getline(2))
2107  call assert_equal(1, g:CallCount)
2108  %d
2109  call setline(1, "foobarbar")
2110  let g:CallCount = 0
2111  exe "normal! Gof\<c-p>\<c-p>\<c-p>\<c-r>=CompleteMenuWords()\<cr>"
2112  call assert_equal('fo{''selected'': 0, ''items'': [''fo'', ''foobar'', ''foobarbar'']}', getline(2))
2113  call assert_equal(1, g:CallCount)
2114  %d
2115  call setline(1, "foobarbar")
2116  let g:CallCount = 0
2117  exe "normal! Gof\<c-n>\<c-n>o\<c-r>=CompleteMenuWords()\<cr>"
2118  call assert_equal('foo{''selected'': -1, ''items'': []}' , getline(2))
2119  call assert_equal(1, g:CallCount)
2120  %d
2121  call setline(1, "foobarbar")
2122  let g:CallCount = 0
2123  exe "normal! Gof\<c-n>\<c-n>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2124  call assert_equal('f{''selected'': -1, ''items'': [''foobarbar'']}', getline(2))
2125  call assert_equal(2, g:CallCount)
2126  %d
2127  call setline(1, "foobarbar")
2128  let g:CallCount = 0
2129  exe "normal! Gof\<c-p>\<c-p>\<c-p>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2130  call assert_equal('f{''selected'': -1, ''items'': [''foobarbar'']}', getline(2))
2131  call assert_equal(2, g:CallCount)
2132
2133  %d
2134  set complete=.,Ffunction('CompleteItemsSelect'\\,\ [['foonext']])
2135  call setline(1, "foobarbar")
2136  let g:CallCount = 0
2137  exe "normal! Gof\<c-n>\<c-n>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2138  call assert_equal('f{''selected'': -1, ''items'': [''foobarbar'', ''foonext'']}', getline(2))
2139  call assert_equal(2, g:CallCount)
2140  %d
2141  call setline(1, "foobarbar")
2142  let g:CallCount = 0
2143  exe "normal! Gof\<c-p>\<c-p>\<c-p>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2144  call assert_equal('f{''selected'': -1, ''items'': [''foonext'', ''foobarbar'']}', getline(2))
2145  call assert_equal(2, g:CallCount)
2146
2147  %d
2148  call setline(1, "foob")
2149  let g:CallCount = 0
2150  exe "normal! Gof\<c-n>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2151  call assert_equal('foo{''selected'': 0, ''items'': [''foob'', ''foonext'']}', getline(2))
2152  call assert_equal(2, g:CallCount)
2153  %d
2154  call setline(1, "foob")
2155  let g:CallCount = 0
2156  exe "normal! Gof\<c-n>\<bs>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2157  call assert_equal('fo{''selected'': 0, ''items'': [''foob'', ''foo1'', ''foo2'']}', getline(2))
2158  call assert_equal(3, g:CallCount)
2159
2160  %d
2161  call setline(1, "foob")
2162  let g:CallCount = 0
2163  exe "normal! Gof\<c-p>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2164  call assert_equal('foo{''selected'': 1, ''items'': [''foonext'', ''foob'']}', getline(2))
2165  call assert_equal(2, g:CallCount)
2166  %d
2167  call setline(1, "foob")
2168  let g:CallCount = 0
2169  exe "normal! Gof\<c-p>\<bs>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2170  call assert_equal('fo{''selected'': 2, ''items'': [''foo1'', ''foo2'', ''foob'']}', getline(2))
2171  call assert_equal(3, g:CallCount)
2172
2173  %d
2174  set complete=.,Ffunction('CompleteItemsSelect'\\,\ [['fo'\\,\ 'foonext']])
2175  call setline(1, "foobarbar")
2176  let g:CallCount = 0
2177  exe "normal! Gof\<c-n>\<c-n>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2178  call assert_equal('f{''selected'': -1, ''items'': [''foobarbar'', ''fo'', ''foonext'']}', getline(2))
2179  call assert_equal(2, g:CallCount)
2180  %d
2181  call setline(1, "foobarbar")
2182  let g:CallCount = 0
2183  exe "normal! Gof\<c-p>\<c-p>\<c-p>\<bs>\<c-r>=CompleteMenuWords()\<cr>"
2184  call assert_equal('f{''selected'': -1, ''items'': [''fo'', ''foonext'', ''foobarbar'']}', getline(2))
2185  call assert_equal(2, g:CallCount)
2186  bw!
2187
2188  set complete&
2189  delfunc CompleteMenuWords
2190  delfunc CompleteItemsSelect
2191endfunc
2192
2193" Test two functions together, each returning refresh:always
2194func Test_cpt_multi_func_refresh_always()
2195
2196  func CompleteMenuMatches()
2197    let info = complete_info(["matches", "selected"])
2198    call map(info.matches, {_, v -> v.word})
2199    return info
2200  endfunc
2201
2202  func! CompleteItems1(findstart, base)
2203    if a:findstart
2204      return col('.') - 1
2205    endif
2206    let g:CallCount1 += 1
2207    let res = [[], [], ['foo1', 'foobar1'], [], ['foo11', 'foo12'], [], ['foo13', 'foo14']]
2208    return #{words: res[g:CallCount1], refresh: 'always'}
2209  endfunc
2210
2211  func! CompleteItems2(findstart, base)
2212    if a:findstart
2213      return col('.') - 1
2214    endif
2215    let g:CallCount2 += 1
2216    let res = [[], [], [], ['foo2', 'foobar2'], ['foo21', 'foo22'], ['foo23'], []]
2217    return #{words: res[g:CallCount2], refresh: 'always'}
2218  endfunc
2219
2220  set complete=
2221  exe "normal! if\<C-N>\<c-r>=CompleteMenuMatches()\<cr>"
2222  " \x0e is <c-n>
2223  call assert_equal("f\x0e" . '{''matches'': [], ''selected'': -1}', getline(1))
2224
2225  set completeopt=menuone,noselect
2226  set complete=FCompleteItems1,FCompleteItems2
2227
2228  new
2229  let g:CallCount1 = 0
2230  let g:CallCount2 = 0
2231  exe "normal! if\<c-n>o\<c-n>o\<c-r>=CompleteMenuMatches()\<cr>"
2232  call assert_equal('foo{''matches'': [''foo2'', ''foobar2''], ''selected'': -1}', getline(1))
2233  call assert_equal(3, g:CallCount1)
2234  call assert_equal(3, g:CallCount2)
2235  %d
2236  let g:CallCount1 = 0
2237  let g:CallCount2 = 0
2238  exe "normal! if\<c-p>o\<c-p>o\<c-r>=CompleteMenuMatches()\<cr>"
2239  call assert_equal('foo{''matches'': [''foo2'', ''foobar2''], ''selected'': -1}', getline(1))
2240  call assert_equal(3, g:CallCount1)
2241  call assert_equal(3, g:CallCount2)
2242  %d
2243  let g:CallCount1 = 0
2244  let g:CallCount2 = 0
2245  exe "normal! if\<c-p>\<c-r>=CompleteMenuMatches()\<cr>"
2246  call assert_equal('f{''matches'': [], ''selected'': -1}', getline(1))
2247  call assert_equal(1, g:CallCount1)
2248  call assert_equal(1, g:CallCount2)
2249  %d
2250  let g:CallCount1 = 1
2251  let g:CallCount2 = 1
2252  exe "normal! if\<c-n>\<c-r>=CompleteMenuMatches()\<cr>"
2253  call assert_equal('f{''matches'': [''foo1'', ''foobar1''], ''selected'': -1}', getline(1))
2254  call assert_equal(2, g:CallCount2)
2255  call assert_equal(2, g:CallCount2)
2256  %d
2257  let g:CallCount1 = 1
2258  let g:CallCount2 = 1
2259  exe "normal! if\<c-n>o\<c-r>=CompleteMenuMatches()\<cr>"
2260  call assert_equal('fo{''matches'': [''foo2'', ''foobar2''], ''selected'': -1}', getline(1))
2261  call assert_equal(3, g:CallCount2)
2262  call assert_equal(3, g:CallCount2)
2263  %d
2264  let g:CallCount1 = 1
2265  let g:CallCount2 = 1
2266  exe "normal! if\<c-p>o\<c-r>=CompleteMenuMatches()\<cr>"
2267  call assert_equal('fo{''matches'': [''foo2'', ''foobar2''], ''selected'': -1}', getline(1))
2268  call assert_equal(3, g:CallCount2)
2269  call assert_equal(3, g:CallCount2)
2270  %d
2271  let g:CallCount1 = 1
2272  let g:CallCount2 = 1
2273  exe "normal! if\<c-n>oo\<c-r>=CompleteMenuMatches()\<cr>"
2274  call assert_equal('foo{''matches'': [''foo11'', ''foo12'', ''foo21'', ''foo22''], ''selected'': -1}', getline(1))
2275  call assert_equal(4, g:CallCount2)
2276  call assert_equal(4, g:CallCount2)
2277  %d
2278  let g:CallCount1 = 1
2279  let g:CallCount2 = 1
2280  exe "normal! if\<c-n>oo\<bs>\<c-r>=CompleteMenuMatches()\<cr>"
2281  call assert_equal('fo{''matches'': [''foo23''], ''selected'': -1}', getline(1))
2282  call assert_equal(5, g:CallCount2)
2283  call assert_equal(5, g:CallCount2)
2284  %d
2285  let g:CallCount1 = 1
2286  let g:CallCount2 = 1
2287  exe "normal! if\<c-p>oo\<bs>\<c-r>=CompleteMenuMatches()\<cr>"
2288  call assert_equal('fo{''matches'': [''foo23''], ''selected'': -1}', getline(1))
2289  call assert_equal(5, g:CallCount2)
2290  call assert_equal(5, g:CallCount2)
2291  %d
2292  let g:CallCount1 = 1
2293  let g:CallCount2 = 1
2294  exe "normal! if\<c-n>oo\<bs>o\<c-r>=CompleteMenuMatches()\<cr>"
2295  call assert_equal('foo{''matches'': [''foo13'', ''foo14''], ''selected'': -1}', getline(1))
2296  call assert_equal(6, g:CallCount2)
2297  call assert_equal(6, g:CallCount2)
2298  bw!
2299
2300  set complete& completeopt&
2301  delfunc CompleteMenuMatches
2302  delfunc CompleteItems1
2303  delfunc CompleteItems2
2304endfunc
2305
2306" Test for completing from a thesaurus file without read permission
2307func Test_complete_unreadable_thesaurus_file()
2308  CheckUnix
2309  CheckNotRoot
2310
2311  call writefile(['about', 'above'], 'Xfile')
2312  call setfperm('Xfile', '---r--r--')
2313  new
2314  set complete=sXfile
2315  exe "normal! ia\<C-P>"
2316  call assert_equal('a', getline(1))
2317  bw!
2318  call delete('Xfile')
2319  set complete&
2320endfunc
2321
2322" Test to ensure 'Scanning...' messages are not recorded in messages history
2323func Test_z1_complete_no_history()
2324  new
2325  messages clear
2326  let currmess = execute('messages')
2327  setlocal dictionary=README.txt
2328  exe "normal owh\<C-X>\<C-K>"
2329  exe "normal owh\<C-N>"
2330  call assert_equal(currmess, execute('messages'))
2331  bwipe!
2332endfunc
2333
2334" A mapping is not used for the key after CTRL-X.
2335func Test_no_mapping_for_ctrl_x_key()
2336  new
2337  inoremap <buffer> <C-K> <Cmd>let was_mapped = 'yes'<CR>
2338  setlocal dictionary=README.txt
2339  call feedkeys("aexam\<C-X>\<C-K> ", 'xt')
2340  call assert_equal('example ', getline(1))
2341  call assert_false(exists('was_mapped'))
2342  bwipe!
2343endfunc
2344
2345" Test for different ways of setting a function in 'complete' option
2346func Test_cpt_func_callback()
2347  func CompleteFunc1(callnr, findstart, base)
2348    call add(g:CompleteFunc1Args, [a:callnr, a:findstart, a:base])
2349    return a:findstart ? 0 : []
2350  endfunc
2351  func CompleteFunc2(findstart, base)
2352    call add(g:CompleteFunc2Args, [a:findstart, a:base])
2353    return a:findstart ? 0 : []
2354  endfunc
2355
2356  let lines =<< trim END
2357    #" Test for using a global function name
2358    set complete=Fg:CompleteFunc2
2359    new
2360    call setline(1, 'global')
2361    LET g:CompleteFunc2Args = []
2362    call feedkeys("A\<C-N>\<Esc>", 'x')
2363    call assert_equal([[1, ''], [0, 'global']], g:CompleteFunc2Args)
2364    set complete&
2365    bw!
2366
2367    #" Test for using a function()
2368    set complete=Ffunction('g:CompleteFunc1'\\,\ [10])
2369    new
2370    call setline(1, 'one')
2371    LET g:CompleteFunc1Args = []
2372    call feedkeys("A\<C-N>\<Esc>", 'x')
2373    call assert_equal([[10, 1, ''], [10, 0, 'one']], g:CompleteFunc1Args)
2374    set complete&
2375    bw!
2376
2377    #" Using a funcref variable
2378    set complete=Ffuncref('g:CompleteFunc1'\\,\ [11])
2379    new
2380    call setline(1, 'two')
2381    LET g:CompleteFunc1Args = []
2382    call feedkeys("A\<C-N>\<Esc>", 'x')
2383    call assert_equal([[11, 1, ''], [11, 0, 'two']], g:CompleteFunc1Args)
2384    set complete&
2385    bw!
2386
2387  END
2388  call CheckLegacyAndVim9Success(lines)
2389
2390  " Test for using a script-local function name
2391  func s:CompleteFunc3(findstart, base)
2392    call add(g:CompleteFunc3Args, [a:findstart, a:base])
2393    return a:findstart ? 0 : []
2394  endfunc
2395  set complete=Fs:CompleteFunc3
2396  new
2397  call setline(1, 'script1')
2398  let g:CompleteFunc3Args = []
2399  call feedkeys("A\<C-N>\<Esc>", 'x')
2400  call assert_equal([[1, ''], [0, 'script1']], g:CompleteFunc3Args)
2401  set complete&
2402  bw!
2403
2404  let &complete = 'Fs:CompleteFunc3'
2405  new
2406  call setline(1, 'script2')
2407  let g:CompleteFunc3Args = []
2408  call feedkeys("A\<C-N>\<Esc>", 'x')
2409  call assert_equal([[1, ''], [0, 'script2']], g:CompleteFunc3Args)
2410  bw!
2411  delfunc s:CompleteFunc3
2412  set complete&
2413
2414  " In Vim9 script s: can be omitted
2415  let lines =<< trim END
2416      vim9script
2417      var CompleteFunc4Args = []
2418      def CompleteFunc4(findstart: bool, base: string): any
2419        add(CompleteFunc4Args, [findstart, base])
2420        return findstart ? 0 : []
2421      enddef
2422      set complete=FCompleteFunc4
2423      new
2424      setline(1, 'script1')
2425      feedkeys("A\<C-N>\<Esc>", 'x')
2426      assert_equal([[1, ''], [0, 'script1']], CompleteFunc4Args)
2427      set complete&
2428      bw!
2429  END
2430  call CheckScriptSuccess(lines)
2431
2432  " Vim9 tests
2433  let lines =<< trim END
2434    vim9script
2435
2436    def Vim9CompleteFunc(callnr: number, findstart: number, base: string): any
2437      add(g:Vim9completeFuncArgs, [callnr, findstart, base])
2438      return findstart ? 0 : []
2439    enddef
2440
2441    # Test for using a def function with completefunc
2442    set complete=Ffunction('Vim9CompleteFunc'\\,\ [60])
2443    new | only
2444    setline(1, 'one')
2445    g:Vim9completeFuncArgs = []
2446    feedkeys("A\<C-N>\<Esc>", 'x')
2447    assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9completeFuncArgs)
2448    bw!
2449
2450    # Test for using a global function name
2451    &complete = 'Fg:CompleteFunc2'
2452    new | only
2453    setline(1, 'two')
2454    g:CompleteFunc2Args = []
2455    feedkeys("A\<C-N>\<Esc>", 'x')
2456    assert_equal([[1, ''], [0, 'two']], g:CompleteFunc2Args)
2457    bw!
2458
2459    # Test for using a script-local function name
2460    def LocalCompleteFunc(findstart: number, base: string): any
2461      add(g:LocalCompleteFuncArgs, [findstart, base])
2462      return findstart ? 0 : []
2463    enddef
2464    &complete = 'FLocalCompleteFunc'
2465    new | only
2466    setline(1, 'three')
2467    g:LocalCompleteFuncArgs = []
2468    feedkeys("A\<C-N>\<Esc>", 'x')
2469    assert_equal([[1, ''], [0, 'three']], g:LocalCompleteFuncArgs)
2470    bw!
2471  END
2472  call CheckScriptSuccess(lines)
2473
2474  " cleanup
2475  set completefunc& complete&
2476  delfunc CompleteFunc1
2477  delfunc CompleteFunc2
2478  unlet g:CompleteFunc1Args g:CompleteFunc2Args
2479  %bw!
2480endfunc
2481
2482" Test for different ways of setting the 'completefunc' option
2483func Test_completefunc_callback()
2484  func CompleteFunc1(callnr, findstart, base)
2485    call add(g:CompleteFunc1Args, [a:callnr, a:findstart, a:base])
2486    return a:findstart ? 0 : []
2487  endfunc
2488  func CompleteFunc2(findstart, base)
2489    call add(g:CompleteFunc2Args, [a:findstart, a:base])
2490    return a:findstart ? 0 : []
2491  endfunc
2492
2493  let lines =<< trim END
2494    #" Test for using a global function name
2495    LET &completefunc = 'g:CompleteFunc2'
2496    new
2497    call setline(1, 'global')
2498    LET g:CompleteFunc2Args = []
2499    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2500    call assert_equal([[1, ''], [0, 'global']], g:CompleteFunc2Args)
2501    bw!
2502
2503    #" Test for using a function()
2504    set completefunc=function('g:CompleteFunc1',\ [10])
2505    new
2506    call setline(1, 'one')
2507    LET g:CompleteFunc1Args = []
2508    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2509    call assert_equal([[10, 1, ''], [10, 0, 'one']], g:CompleteFunc1Args)
2510    bw!
2511
2512    #" Using a funcref variable to set 'completefunc'
2513    VAR Fn = function('g:CompleteFunc1', [11])
2514    LET &completefunc = Fn
2515    new
2516    call setline(1, 'two')
2517    LET g:CompleteFunc1Args = []
2518    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2519    call assert_equal([[11, 1, ''], [11, 0, 'two']], g:CompleteFunc1Args)
2520    bw!
2521
2522    #" Using string(funcref_variable) to set 'completefunc'
2523    LET Fn = function('g:CompleteFunc1', [12])
2524    LET &completefunc = string(Fn)
2525    new
2526    call setline(1, 'two')
2527    LET g:CompleteFunc1Args = []
2528    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2529    call assert_equal([[12, 1, ''], [12, 0, 'two']], g:CompleteFunc1Args)
2530    bw!
2531
2532    #" Test for using a funcref()
2533    set completefunc=funcref('g:CompleteFunc1',\ [13])
2534    new
2535    call setline(1, 'three')
2536    LET g:CompleteFunc1Args = []
2537    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2538    call assert_equal([[13, 1, ''], [13, 0, 'three']], g:CompleteFunc1Args)
2539    bw!
2540
2541    #" Using a funcref variable to set 'completefunc'
2542    LET Fn = funcref('g:CompleteFunc1', [14])
2543    LET &completefunc = Fn
2544    new
2545    call setline(1, 'four')
2546    LET g:CompleteFunc1Args = []
2547    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2548    call assert_equal([[14, 1, ''], [14, 0, 'four']], g:CompleteFunc1Args)
2549    bw!
2550
2551    #" Using a string(funcref_variable) to set 'completefunc'
2552    LET Fn = funcref('g:CompleteFunc1', [15])
2553    LET &completefunc = string(Fn)
2554    new
2555    call setline(1, 'four')
2556    LET g:CompleteFunc1Args = []
2557    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2558    call assert_equal([[15, 1, ''], [15, 0, 'four']], g:CompleteFunc1Args)
2559    bw!
2560
2561    #" Test for using a lambda function with set
2562    VAR optval = "LSTART a, b LMIDDLE CompleteFunc1(16, a, b) LEND"
2563    LET optval = substitute(optval, ' ', '\\ ', 'g')
2564    exe "set completefunc=" .. optval
2565    new
2566    call setline(1, 'five')
2567    LET g:CompleteFunc1Args = []
2568    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2569    call assert_equal([[16, 1, ''], [16, 0, 'five']], g:CompleteFunc1Args)
2570    bw!
2571
2572    #" Set 'completefunc' to a lambda expression
2573    LET &completefunc = LSTART a, b LMIDDLE CompleteFunc1(17, a, b) LEND
2574    new
2575    call setline(1, 'six')
2576    LET g:CompleteFunc1Args = []
2577    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2578    call assert_equal([[17, 1, ''], [17, 0, 'six']], g:CompleteFunc1Args)
2579    bw!
2580
2581    #" Set 'completefunc' to string(lambda_expression)
2582    LET &completefunc = 'LSTART a, b LMIDDLE CompleteFunc1(18, a, b) LEND'
2583    new
2584    call setline(1, 'six')
2585    LET g:CompleteFunc1Args = []
2586    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2587    call assert_equal([[18, 1, ''], [18, 0, 'six']], g:CompleteFunc1Args)
2588    bw!
2589
2590    #" Set 'completefunc' to a variable with a lambda expression
2591    VAR Lambda = LSTART a, b LMIDDLE CompleteFunc1(19, a, b) LEND
2592    LET &completefunc = Lambda
2593    new
2594    call setline(1, 'seven')
2595    LET g:CompleteFunc1Args = []
2596    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2597    call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:CompleteFunc1Args)
2598    bw!
2599
2600    #" Set 'completefunc' to a string(variable with a lambda expression)
2601    LET Lambda = LSTART a, b LMIDDLE CompleteFunc1(20, a, b) LEND
2602    LET &completefunc = string(Lambda)
2603    new
2604    call setline(1, 'seven')
2605    LET g:CompleteFunc1Args = []
2606    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2607    call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:CompleteFunc1Args)
2608    bw!
2609
2610    #" Test for using a lambda function with incorrect return value
2611    LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND
2612    LET &completefunc = Lambda
2613    new
2614    call setline(1, 'eight')
2615    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2616    bw!
2617
2618    #" Test for clearing the 'completefunc' option
2619    set completefunc=''
2620    set completefunc&
2621    call assert_fails("set completefunc=function('abc')", "E700:")
2622    call assert_fails("set completefunc=funcref('abc')", "E700:")
2623
2624    #" set 'completefunc' to a non-existing function
2625    set completefunc=CompleteFunc2
2626    call setline(1, 'five')
2627    call assert_fails("set completefunc=function('NonExistingFunc')", 'E700:')
2628    call assert_fails("LET &completefunc = function('NonExistingFunc')", 'E700:')
2629    LET g:CompleteFunc2Args = []
2630    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2631    call assert_equal([[1, ''], [0, 'five']], g:CompleteFunc2Args)
2632    bw!
2633
2634    #" :setlocal and :setglobal
2635    set complete=F completefunc&
2636    setlocal completefunc=function('g:CompleteFunc1',\ [22])
2637    call setline(1, 'sun')
2638    LET g:CompleteFunc1Args = []
2639    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2640    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:CompleteFunc1Args)
2641    LET g:CompleteFunc1Args = []
2642    call feedkeys("A\<C-N>\<Esc>", 'x')
2643    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:CompleteFunc1Args)
2644    new
2645    call setline(1, 'sun')
2646    LET g:CompleteFunc1Args = []
2647    call assert_fails('call feedkeys("A\<C-X>\<C-U>\<Esc>", "x")', 'E764:')
2648    call assert_equal([], g:CompleteFunc1Args)
2649    LET g:CompleteFunc1Args = []
2650    call feedkeys("A\<C-N>\<Esc>", 'x')
2651    call assert_equal([], g:CompleteFunc1Args)
2652    bw!
2653    setglobal completefunc=function('g:CompleteFunc1',\ [23])
2654    call setline(1, 'sun')
2655    LET g:CompleteFunc1Args = []
2656    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2657    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:CompleteFunc1Args)
2658    LET g:CompleteFunc1Args = []
2659    call feedkeys("A\<C-N>\<Esc>", 'x')
2660    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:CompleteFunc1Args)
2661    setlocal completefunc&
2662    call setline(1, 'sun')
2663    LET g:CompleteFunc1Args = []
2664    call assert_fails('call feedkeys("A\<C-X>\<C-U>\<Esc>", "x")', 'E764:')
2665    call assert_equal([], g:CompleteFunc1Args)
2666    LET g:CompleteFunc1Args = []
2667    call feedkeys("A\<C-N>\<Esc>", 'x')
2668    call assert_equal([], g:CompleteFunc1Args)
2669    new
2670    call setline(1, 'sun')
2671    LET g:CompleteFunc1Args = []
2672    call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2673    call assert_equal([[23, 1, ''], [23, 0, 'sun']], g:CompleteFunc1Args)
2674    LET g:CompleteFunc1Args = []
2675    call feedkeys("A\<C-N>\<Esc>", 'x')
2676    call assert_equal([[23, 1, ''], [23, 0, 'sun']], g:CompleteFunc1Args)
2677    set complete& completefunc&
2678    :%bw!
2679  END
2680  call CheckLegacyAndVim9Success(lines)
2681
2682  " Test for using a script-local function name
2683  func s:CompleteFunc3(findstart, base)
2684    call add(g:CompleteFunc3Args, [a:findstart, a:base])
2685    return a:findstart ? 0 : []
2686  endfunc
2687  set completefunc=s:CompleteFunc3
2688  new
2689  call setline(1, 'script1')
2690  let g:CompleteFunc3Args = []
2691  call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2692  call assert_equal([[1, ''], [0, 'script1']], g:CompleteFunc3Args)
2693  bw!
2694
2695  let &completefunc = 's:CompleteFunc3'
2696  new
2697  call setline(1, 'script2')
2698  let g:CompleteFunc3Args = []
2699  call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2700  call assert_equal([[1, ''], [0, 'script2']], g:CompleteFunc3Args)
2701  bw!
2702  delfunc s:CompleteFunc3
2703
2704  " In Vim9 script s: can be omitted
2705  let lines =<< trim END
2706      vim9script
2707      var CompleteFunc4Args = []
2708      def CompleteFunc4(findstart: bool, base: string): any
2709        add(CompleteFunc4Args, [findstart, base])
2710        return findstart ? 0 : []
2711      enddef
2712      set completefunc=CompleteFunc4
2713      new
2714      setline(1, 'script1')
2715      feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2716      assert_equal([[1, ''], [0, 'script1']], CompleteFunc4Args)
2717      bw!
2718  END
2719  call CheckScriptSuccess(lines)
2720
2721  " invalid return value
2722  let &completefunc = {a -> 'abc'}
2723  call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2724
2725  " Using Vim9 lambda expression in legacy context should fail
2726  set completefunc=(a,\ b)\ =>\ CompleteFunc1(21,\ a,\ b)
2727  new | only
2728  let g:CompleteFunc1Args = []
2729  call assert_fails('call feedkeys("A\<C-X>\<C-U>\<Esc>", "x")', 'E117:')
2730  call assert_equal([], g:CompleteFunc1Args)
2731
2732  " set 'completefunc' to a partial with dict. This used to cause a crash.
2733  func SetCompleteFunc()
2734    let params = {'complete': function('g:DictCompleteFunc')}
2735    let &completefunc = params.complete
2736  endfunc
2737  func g:DictCompleteFunc(_) dict
2738  endfunc
2739  call SetCompleteFunc()
2740  new
2741  call SetCompleteFunc()
2742  bw
2743  call test_garbagecollect_now()
2744  new
2745  set completefunc=
2746  wincmd w
2747  set completefunc=
2748  %bw!
2749  delfunc g:DictCompleteFunc
2750  delfunc SetCompleteFunc
2751
2752  " Vim9 tests
2753  let lines =<< trim END
2754    vim9script
2755
2756    def Vim9CompleteFunc(callnr: number, findstart: number, base: string): any
2757      add(g:Vim9completeFuncArgs, [callnr, findstart, base])
2758      return findstart ? 0 : []
2759    enddef
2760
2761    # Test for using a def function with completefunc
2762    set completefunc=function('Vim9CompleteFunc',\ [60])
2763    new | only
2764    setline(1, 'one')
2765    g:Vim9completeFuncArgs = []
2766    feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2767    assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9completeFuncArgs)
2768    bw!
2769
2770    # Test for using a global function name
2771    &completefunc = g:CompleteFunc2
2772    new | only
2773    setline(1, 'two')
2774    g:CompleteFunc2Args = []
2775    feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2776    assert_equal([[1, ''], [0, 'two']], g:CompleteFunc2Args)
2777    bw!
2778
2779    # Test for using a script-local function name
2780    def LocalCompleteFunc(findstart: number, base: string): any
2781      add(g:LocalCompleteFuncArgs, [findstart, base])
2782      return findstart ? 0 : []
2783    enddef
2784    &completefunc = LocalCompleteFunc
2785    new | only
2786    setline(1, 'three')
2787    g:LocalCompleteFuncArgs = []
2788    feedkeys("A\<C-X>\<C-U>\<Esc>", 'x')
2789    assert_equal([[1, ''], [0, 'three']], g:LocalCompleteFuncArgs)
2790    bw!
2791  END
2792  call CheckScriptSuccess(lines)
2793
2794  " cleanup
2795  set completefunc&
2796  delfunc CompleteFunc1
2797  delfunc CompleteFunc2
2798  unlet g:CompleteFunc1Args g:CompleteFunc2Args
2799  %bw!
2800endfunc
2801
2802" Test for different ways of setting the 'omnifunc' option
2803func Test_omnifunc_callback()
2804  func OmniFunc1(callnr, findstart, base)
2805    call add(g:OmniFunc1Args, [a:callnr, a:findstart, a:base])
2806    return a:findstart ? 0 : []
2807  endfunc
2808  func OmniFunc2(findstart, base)
2809    call add(g:OmniFunc2Args, [a:findstart, a:base])
2810    return a:findstart ? 0 : []
2811  endfunc
2812
2813  let lines =<< trim END
2814    #" Test for using a function name
2815    LET &omnifunc = 'g:OmniFunc2'
2816    new
2817    call setline(1, 'zero')
2818    LET g:OmniFunc2Args = []
2819    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2820    call assert_equal([[1, ''], [0, 'zero']], g:OmniFunc2Args)
2821    bw!
2822
2823    #" Test for using a function()
2824    set omnifunc=function('g:OmniFunc1',\ [10])
2825    new
2826    call setline(1, 'one')
2827    LET g:OmniFunc1Args = []
2828    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2829    call assert_equal([[10, 1, ''], [10, 0, 'one']], g:OmniFunc1Args)
2830    bw!
2831
2832    #" Using a funcref variable to set 'omnifunc'
2833    VAR Fn = function('g:OmniFunc1', [11])
2834    LET &omnifunc = Fn
2835    new
2836    call setline(1, 'two')
2837    LET g:OmniFunc1Args = []
2838    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2839    call assert_equal([[11, 1, ''], [11, 0, 'two']], g:OmniFunc1Args)
2840    bw!
2841
2842    #" Using a string(funcref_variable) to set 'omnifunc'
2843    LET Fn = function('g:OmniFunc1', [12])
2844    LET &omnifunc = string(Fn)
2845    new
2846    call setline(1, 'two')
2847    LET g:OmniFunc1Args = []
2848    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2849    call assert_equal([[12, 1, ''], [12, 0, 'two']], g:OmniFunc1Args)
2850    bw!
2851
2852    #" Test for using a funcref()
2853    set omnifunc=funcref('g:OmniFunc1',\ [13])
2854    new
2855    call setline(1, 'three')
2856    LET g:OmniFunc1Args = []
2857    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2858    call assert_equal([[13, 1, ''], [13, 0, 'three']], g:OmniFunc1Args)
2859    bw!
2860
2861    #" Use let to set 'omnifunc' to a funcref
2862    LET Fn = funcref('g:OmniFunc1', [14])
2863    LET &omnifunc = Fn
2864    new
2865    call setline(1, 'four')
2866    LET g:OmniFunc1Args = []
2867    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2868    call assert_equal([[14, 1, ''], [14, 0, 'four']], g:OmniFunc1Args)
2869    bw!
2870
2871    #" Using a string(funcref) to set 'omnifunc'
2872    LET Fn = funcref("g:OmniFunc1", [15])
2873    LET &omnifunc = string(Fn)
2874    new
2875    call setline(1, 'four')
2876    LET g:OmniFunc1Args = []
2877    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2878    call assert_equal([[15, 1, ''], [15, 0, 'four']], g:OmniFunc1Args)
2879    bw!
2880
2881    #" Test for using a lambda function with set
2882    VAR optval = "LSTART a, b LMIDDLE OmniFunc1(16, a, b) LEND"
2883    LET optval = substitute(optval, ' ', '\\ ', 'g')
2884    exe "set omnifunc=" .. optval
2885    new
2886    call setline(1, 'five')
2887    LET g:OmniFunc1Args = []
2888    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2889    call assert_equal([[16, 1, ''], [16, 0, 'five']], g:OmniFunc1Args)
2890    bw!
2891
2892    #" Set 'omnifunc' to a lambda expression
2893    LET &omnifunc = LSTART a, b LMIDDLE OmniFunc1(17, a, b) LEND
2894    new
2895    call setline(1, 'six')
2896    LET g:OmniFunc1Args = []
2897    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2898    call assert_equal([[17, 1, ''], [17, 0, 'six']], g:OmniFunc1Args)
2899    bw!
2900
2901    #" Set 'omnifunc' to a string(lambda_expression)
2902    LET &omnifunc = 'LSTART a, b LMIDDLE OmniFunc1(18, a, b) LEND'
2903    new
2904    call setline(1, 'six')
2905    LET g:OmniFunc1Args = []
2906    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2907    call assert_equal([[18, 1, ''], [18, 0, 'six']], g:OmniFunc1Args)
2908    bw!
2909
2910    #" Set 'omnifunc' to a variable with a lambda expression
2911    VAR Lambda = LSTART a, b LMIDDLE OmniFunc1(19, a, b) LEND
2912    LET &omnifunc = Lambda
2913    new
2914    call setline(1, 'seven')
2915    LET g:OmniFunc1Args = []
2916    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2917    call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:OmniFunc1Args)
2918    bw!
2919
2920    #" Set 'omnifunc' to a string(variable with a lambda expression)
2921    LET Lambda = LSTART a, b LMIDDLE OmniFunc1(20, a, b) LEND
2922    LET &omnifunc = string(Lambda)
2923    new
2924    call setline(1, 'seven')
2925    LET g:OmniFunc1Args = []
2926    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2927    call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:OmniFunc1Args)
2928    bw!
2929
2930    #" Test for using a lambda function with incorrect return value
2931    LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND
2932    LET &omnifunc = Lambda
2933    new
2934    call setline(1, 'eight')
2935    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2936    bw!
2937
2938    #" Test for clearing the 'omnifunc' option
2939    set omnifunc=''
2940    set omnifunc&
2941    call assert_fails("set omnifunc=function('abc')", "E700:")
2942    call assert_fails("set omnifunc=funcref('abc')", "E700:")
2943
2944    #" set 'omnifunc' to a non-existing function
2945    set omnifunc=OmniFunc2
2946    call setline(1, 'nine')
2947    call assert_fails("set omnifunc=function('NonExistingFunc')", 'E700:')
2948    call assert_fails("LET &omnifunc = function('NonExistingFunc')", 'E700:')
2949    LET g:OmniFunc2Args = []
2950    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2951    call assert_equal([[1, ''], [0, 'nine']], g:OmniFunc2Args)
2952    bw!
2953
2954    #" :setlocal and :setglobal
2955    set complete=o omnifunc&
2956    setlocal omnifunc=function('g:OmniFunc1',\ [22])
2957    call setline(1, 'sun')
2958    LET g:OmniFunc1Args = []
2959    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2960    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:OmniFunc1Args)
2961    LET g:OmniFunc1Args = []
2962    call feedkeys("A\<C-N>\<Esc>", 'x')
2963    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:OmniFunc1Args)
2964    new
2965    call setline(1, 'sun')
2966    LET g:OmniFunc1Args = []
2967    call assert_fails('call feedkeys("A\<C-X>\<C-O>\<Esc>", "x")', 'E764:')
2968    call assert_equal([], g:OmniFunc1Args)
2969    LET g:OmniFunc1Args = []
2970    call feedkeys("A\<C-N>\<Esc>", 'x')
2971    call assert_equal([], g:OmniFunc1Args)
2972    bw!
2973    setglobal omnifunc=function('g:OmniFunc1',\ [23])
2974    call setline(1, 'sun')
2975    LET g:OmniFunc1Args = []
2976    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2977    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:OmniFunc1Args)
2978    LET g:OmniFunc1Args = []
2979    call feedkeys("A\<C-N>\<Esc>", 'x')
2980    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:OmniFunc1Args)
2981    setlocal omnifunc&
2982    call setline(1, 'sun')
2983    LET g:OmniFunc1Args = []
2984    call assert_fails('call feedkeys("A\<C-X>\<C-O>\<Esc>", "x")', 'E764:')
2985    call assert_equal([], g:OmniFunc1Args)
2986    LET g:OmniFunc1Args = []
2987    call feedkeys("A\<C-N>\<Esc>", 'x')
2988    call assert_equal([], g:OmniFunc1Args)
2989    new
2990    call setline(1, 'sun')
2991    LET g:OmniFunc1Args = []
2992    call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
2993    call assert_equal([[23, 1, ''], [23, 0, 'sun']], g:OmniFunc1Args)
2994    LET g:OmniFunc1Args = []
2995    call feedkeys("A\<C-N>\<Esc>", 'x')
2996    call assert_equal([[23, 1, ''], [23, 0, 'sun']], g:OmniFunc1Args)
2997    set complete& omnifunc&
2998    :%bw!
2999  END
3000  call CheckLegacyAndVim9Success(lines)
3001
3002  " Test for using a script-local function name
3003  func s:OmniFunc3(findstart, base)
3004    call add(g:OmniFunc3Args, [a:findstart, a:base])
3005    return a:findstart ? 0 : []
3006  endfunc
3007  set omnifunc=s:OmniFunc3
3008  new
3009  call setline(1, 'script1')
3010  let g:OmniFunc3Args = []
3011  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
3012  call assert_equal([[1, ''], [0, 'script1']], g:OmniFunc3Args)
3013  bw!
3014
3015  set complete=Fs:OmniFunc3
3016  new
3017  call setline(1, 'script1')
3018  let g:OmniFunc3Args = []
3019  call feedkeys("A\<C-N>\<Esc>", 'x')
3020  call assert_equal([[1, ''], [0, 'script1']], g:OmniFunc3Args)
3021  bw!
3022  set complete&
3023
3024  let &omnifunc = 's:OmniFunc3'
3025  new
3026  call setline(1, 'script2')
3027  let g:OmniFunc3Args = []
3028  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
3029  call assert_equal([[1, ''], [0, 'script2']], g:OmniFunc3Args)
3030  bw!
3031  delfunc s:OmniFunc3
3032
3033  " invalid return value
3034  let &omnifunc = {a -> 'abc'}
3035  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
3036
3037  " Using Vim9 lambda expression in legacy context should fail
3038  set omnifunc=(a,\ b)\ =>\ OmniFunc1(21,\ a,\ b)
3039  new | only
3040  let g:OmniFunc1Args = []
3041  call assert_fails('call feedkeys("A\<C-X>\<C-O>\<Esc>", "x")', 'E117:')
3042  call assert_equal([], g:OmniFunc1Args)
3043
3044  " set 'omnifunc' to a partial with dict. This used to cause a crash.
3045  func SetOmniFunc()
3046    let params = {'omni': function('g:DictOmniFunc')}
3047    let &omnifunc = params.omni
3048  endfunc
3049  func g:DictOmniFunc(_) dict
3050  endfunc
3051  call SetOmniFunc()
3052  new
3053  call SetOmniFunc()
3054  bw
3055  call test_garbagecollect_now()
3056  new
3057  set omnifunc=
3058  wincmd w
3059  set omnifunc=
3060  %bw!
3061  delfunc g:DictOmniFunc
3062  delfunc SetOmniFunc
3063
3064  " Vim9 tests
3065  let lines =<< trim END
3066    vim9script
3067
3068    def Vim9omniFunc(callnr: number, findstart: number, base: string): any
3069      add(g:Vim9omniFunc_Args, [callnr, findstart, base])
3070      return findstart ? 0 : []
3071    enddef
3072
3073    # Test for using a def function with omnifunc
3074    set omnifunc=function('Vim9omniFunc',\ [60])
3075    new | only
3076    setline(1, 'one')
3077    g:Vim9omniFunc_Args = []
3078    feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
3079    assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9omniFunc_Args)
3080    bw!
3081
3082    # Test for using a global function name
3083    &omnifunc = g:OmniFunc2
3084    new | only
3085    setline(1, 'two')
3086    g:OmniFunc2Args = []
3087    feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
3088    assert_equal([[1, ''], [0, 'two']], g:OmniFunc2Args)
3089    bw!
3090
3091    # Test for using a script-local function name
3092    def LocalOmniFunc(findstart: number, base: string): any
3093      add(g:LocalOmniFuncArgs, [findstart, base])
3094      return findstart ? 0 : []
3095    enddef
3096    &omnifunc = LocalOmniFunc
3097    new | only
3098    setline(1, 'three')
3099    g:LocalOmniFuncArgs = []
3100    feedkeys("A\<C-X>\<C-O>\<Esc>", 'x')
3101    assert_equal([[1, ''], [0, 'three']], g:LocalOmniFuncArgs)
3102    bw!
3103  END
3104  call CheckScriptSuccess(lines)
3105
3106  " cleanup
3107  set omnifunc&
3108  delfunc OmniFunc1
3109  delfunc OmniFunc2
3110  unlet g:OmniFunc1Args g:OmniFunc2Args
3111  %bw!
3112endfunc
3113
3114" Test for different ways of setting the 'thesaurusfunc' option
3115func Test_thesaurusfunc_callback()
3116  func TsrFunc1(callnr, findstart, base)
3117    call add(g:TsrFunc1Args, [a:callnr, a:findstart, a:base])
3118    return a:findstart ? 0 : []
3119  endfunc
3120  func TsrFunc2(findstart, base)
3121    call add(g:TsrFunc2Args, [a:findstart, a:base])
3122    return a:findstart ? 0 : ['sunday']
3123  endfunc
3124
3125  let lines =<< trim END
3126    #" Test for using a function name
3127    LET &thesaurusfunc = 'g:TsrFunc2'
3128    new
3129    call setline(1, 'zero')
3130    LET g:TsrFunc2Args = []
3131    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3132    call assert_equal([[1, ''], [0, 'zero']], g:TsrFunc2Args)
3133    bw!
3134
3135    #" Test for using a function()
3136    set thesaurusfunc=function('g:TsrFunc1',\ [10])
3137    new
3138    call setline(1, 'one')
3139    LET g:TsrFunc1Args = []
3140    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3141    call assert_equal([[10, 1, ''], [10, 0, 'one']], g:TsrFunc1Args)
3142    bw!
3143
3144    #" Using a funcref variable to set 'thesaurusfunc'
3145    VAR Fn = function('g:TsrFunc1', [11])
3146    LET &thesaurusfunc = Fn
3147    new
3148    call setline(1, 'two')
3149    LET g:TsrFunc1Args = []
3150    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3151    call assert_equal([[11, 1, ''], [11, 0, 'two']], g:TsrFunc1Args)
3152    bw!
3153
3154    #" Using a string(funcref_variable) to set 'thesaurusfunc'
3155    LET Fn = function('g:TsrFunc1', [12])
3156    LET &thesaurusfunc = string(Fn)
3157    new
3158    call setline(1, 'two')
3159    LET g:TsrFunc1Args = []
3160    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3161    call assert_equal([[12, 1, ''], [12, 0, 'two']], g:TsrFunc1Args)
3162    bw!
3163
3164    #" Test for using a funcref()
3165    set thesaurusfunc=funcref('g:TsrFunc1',\ [13])
3166    new
3167    call setline(1, 'three')
3168    LET g:TsrFunc1Args = []
3169    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3170    call assert_equal([[13, 1, ''], [13, 0, 'three']], g:TsrFunc1Args)
3171    bw!
3172
3173    #" Using a funcref variable to set 'thesaurusfunc'
3174    LET Fn = funcref('g:TsrFunc1', [14])
3175    LET &thesaurusfunc = Fn
3176    new
3177    call setline(1, 'four')
3178    LET g:TsrFunc1Args = []
3179    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3180    call assert_equal([[14, 1, ''], [14, 0, 'four']], g:TsrFunc1Args)
3181    bw!
3182
3183    #" Using a string(funcref_variable) to set 'thesaurusfunc'
3184    LET Fn = funcref('g:TsrFunc1', [15])
3185    LET &thesaurusfunc = string(Fn)
3186    new
3187    call setline(1, 'four')
3188    LET g:TsrFunc1Args = []
3189    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3190    call assert_equal([[15, 1, ''], [15, 0, 'four']], g:TsrFunc1Args)
3191    bw!
3192
3193    #" Test for using a lambda function
3194    VAR optval = "LSTART a, b LMIDDLE TsrFunc1(16, a, b) LEND"
3195    LET optval = substitute(optval, ' ', '\\ ', 'g')
3196    exe "set thesaurusfunc=" .. optval
3197    new
3198    call setline(1, 'five')
3199    LET g:TsrFunc1Args = []
3200    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3201    call assert_equal([[16, 1, ''], [16, 0, 'five']], g:TsrFunc1Args)
3202    bw!
3203
3204    #" Test for using a lambda function with set
3205    LET &thesaurusfunc = LSTART a, b LMIDDLE TsrFunc1(17, a, b) LEND
3206    new
3207    call setline(1, 'six')
3208    LET g:TsrFunc1Args = []
3209    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3210    call assert_equal([[17, 1, ''], [17, 0, 'six']], g:TsrFunc1Args)
3211    bw!
3212
3213    #" Set 'thesaurusfunc' to a string(lambda expression)
3214    LET &thesaurusfunc = 'LSTART a, b LMIDDLE TsrFunc1(18, a, b) LEND'
3215    new
3216    call setline(1, 'six')
3217    LET g:TsrFunc1Args = []
3218    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3219    call assert_equal([[18, 1, ''], [18, 0, 'six']], g:TsrFunc1Args)
3220    bw!
3221
3222    #" Set 'thesaurusfunc' to a variable with a lambda expression
3223    VAR Lambda = LSTART a, b LMIDDLE TsrFunc1(19, a, b) LEND
3224    LET &thesaurusfunc = Lambda
3225    new
3226    call setline(1, 'seven')
3227    LET g:TsrFunc1Args = []
3228    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3229    call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:TsrFunc1Args)
3230    bw!
3231
3232    #" Set 'thesaurusfunc' to a string(variable with a lambda expression)
3233    LET Lambda = LSTART a, b LMIDDLE TsrFunc1(20, a, b) LEND
3234    LET &thesaurusfunc = string(Lambda)
3235    new
3236    call setline(1, 'seven')
3237    LET g:TsrFunc1Args = []
3238    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3239    call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:TsrFunc1Args)
3240    bw!
3241
3242    #" Test for using a lambda function with incorrect return value
3243    LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND
3244    LET &thesaurusfunc = Lambda
3245    new
3246    call setline(1, 'eight')
3247    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3248    bw!
3249
3250    #" Test for clearing the 'thesaurusfunc' option
3251    set thesaurusfunc=''
3252    set thesaurusfunc&
3253    call assert_fails("set thesaurusfunc=function('abc')", "E700:")
3254    call assert_fails("set thesaurusfunc=funcref('abc')", "E700:")
3255
3256    #" set 'thesaurusfunc' to a non-existing function
3257    set thesaurusfunc=TsrFunc2
3258    call setline(1, 'ten')
3259    call assert_fails("set thesaurusfunc=function('NonExistingFunc')", 'E700:')
3260    call assert_fails("LET &thesaurusfunc = function('NonExistingFunc')", 'E700:')
3261    LET g:TsrFunc2Args = []
3262    call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3263    call assert_equal([[1, ''], [0, 'ten']], g:TsrFunc2Args)
3264    bw!
3265
3266    #" Use a buffer-local value and a global value
3267    set thesaurusfunc&
3268    setlocal thesaurusfunc=function('g:TsrFunc1',\ [22])
3269    call setline(1, 'sun')
3270    LET g:TsrFunc1Args = []
3271    call feedkeys("A\<C-X>\<C-T>\<Esc>", "x")
3272    call assert_equal('sun', getline(1))
3273    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args)
3274    new
3275    call setline(1, 'sun')
3276    LET g:TsrFunc1Args = []
3277    " Nvim: message is an actual error rather than message with error highlight
3278    silent! call feedkeys("A\<C-X>\<C-T>\<Esc>", "x")
3279    call assert_equal('sun', getline(1))
3280    call assert_equal([], g:TsrFunc1Args)
3281    set thesaurusfunc=function('g:TsrFunc1',\ [23])
3282    wincmd w
3283    call setline(1, 'sun')
3284    LET g:TsrFunc1Args = []
3285    call feedkeys("A\<C-X>\<C-T>\<Esc>", "x")
3286    call assert_equal('sun', getline(1))
3287    call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args)
3288    :%bw!
3289  END
3290  call CheckLegacyAndVim9Success(lines)
3291
3292  " Test for using a script-local function name
3293  func s:TsrFunc3(findstart, base)
3294    call add(g:TsrFunc3Args, [a:findstart, a:base])
3295    return a:findstart ? 0 : []
3296  endfunc
3297
3298  set tsrfu=s:TsrFunc3
3299  new
3300  call setline(1, 'script1')
3301  let g:TsrFunc3Args = []
3302  call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3303  call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args)
3304  bw!
3305
3306  let &tsrfu = 's:TsrFunc3'
3307  new
3308  call setline(1, 'script2')
3309  let g:TsrFunc3Args = []
3310  call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3311  call assert_equal([[1, ''], [0, 'script2']], g:TsrFunc3Args)
3312  bw!
3313
3314  new | only
3315  set thesaurusfunc=
3316  setlocal thesaurusfunc=NoSuchFunc
3317  setglobal thesaurusfunc=s:TsrFunc3
3318  " A callback-option (e.g. 'findfunc') stores funcref as its unambiguous <SNR> form.
3319  let tsrfunc3 = expand('<SID>') .. 'TsrFunc3'
3320  call assert_equal('NoSuchFunc', &thesaurusfunc)
3321  call assert_equal('NoSuchFunc', &l:thesaurusfunc)
3322  call assert_equal(tsrfunc3, &g:thesaurusfunc)
3323  new | only
3324  call assert_equal(tsrfunc3, &thesaurusfunc)
3325  call assert_equal(tsrfunc3, &g:thesaurusfunc)
3326  call assert_equal('', &l:thesaurusfunc)
3327  call setline(1, 'script1')
3328  let g:TsrFunc3Args = []
3329  call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3330  call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args)
3331  bw!
3332
3333  new | only
3334  set thesaurusfunc=
3335  setlocal thesaurusfunc=NoSuchFunc
3336  set thesaurusfunc=s:TsrFunc3
3337  call assert_equal(tsrfunc3, &thesaurusfunc)
3338  call assert_equal(tsrfunc3, &g:thesaurusfunc)
3339  call assert_equal('', &l:thesaurusfunc)
3340  call setline(1, 'script1')
3341  let g:TsrFunc3Args = []
3342  call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3343  call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args)
3344  setlocal bufhidden=wipe
3345  new | only!
3346  call assert_equal(tsrfunc3, &thesaurusfunc)
3347  call assert_equal(tsrfunc3, &g:thesaurusfunc)
3348  call assert_equal('', &l:thesaurusfunc)
3349  call setline(1, 'script1')
3350  let g:TsrFunc3Args = []
3351  call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3352  call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args)
3353  bw!
3354
3355  delfunc s:TsrFunc3
3356
3357  " invalid return value
3358  let &thesaurusfunc = {a -> 'abc'}
3359  call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3360
3361  " Using Vim9 lambda expression in legacy context should fail
3362  set thesaurusfunc=(a,\ b)\ =>\ TsrFunc1(21,\ a,\ b)
3363  new | only
3364  let g:TsrFunc1Args = []
3365  call assert_fails('call feedkeys("A\<C-X>\<C-T>\<Esc>", "x")', 'E117:')
3366  call assert_equal([], g:TsrFunc1Args)
3367  bw!
3368
3369  " set 'thesaurusfunc' to a partial with dict. This used to cause a crash.
3370  func SetTsrFunc()
3371    let params = {'thesaurus': function('g:DictTsrFunc')}
3372    let &thesaurusfunc = params.thesaurus
3373  endfunc
3374  func g:DictTsrFunc(_) dict
3375  endfunc
3376  call SetTsrFunc()
3377  new
3378  call SetTsrFunc()
3379  bw
3380  call test_garbagecollect_now()
3381  new
3382  set thesaurusfunc=
3383  wincmd w
3384  %bw!
3385  delfunc SetTsrFunc
3386
3387  " set buffer-local 'thesaurusfunc' to a partial with dict. This used to
3388  " cause a crash.
3389  func SetLocalTsrFunc()
3390    let params = {'thesaurus': function('g:DictTsrFunc')}
3391    let &l:thesaurusfunc = params.thesaurus
3392  endfunc
3393  call SetLocalTsrFunc()
3394  call test_garbagecollect_now()
3395  call SetLocalTsrFunc()
3396  set thesaurusfunc=
3397  bw!
3398  delfunc g:DictTsrFunc
3399  delfunc SetLocalTsrFunc
3400
3401  " Vim9 tests
3402  let lines =<< trim END
3403    vim9script
3404
3405    def Vim9tsrFunc(callnr: number, findstart: number, base: string): any
3406      add(g:Vim9tsrFunc_Args, [callnr, findstart, base])
3407      return findstart ? 0 : []
3408    enddef
3409
3410    # Test for using a def function with thesaurusfunc
3411    set thesaurusfunc=function('Vim9tsrFunc',\ [60])
3412    new | only
3413    setline(1, 'one')
3414    g:Vim9tsrFunc_Args = []
3415    feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3416    assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9tsrFunc_Args)
3417    bw!
3418
3419    # Test for using a global function name
3420    &thesaurusfunc = g:TsrFunc2
3421    new | only
3422    setline(1, 'two')
3423    g:TsrFunc2Args = []
3424    feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3425    assert_equal([[1, ''], [0, 'two']], g:TsrFunc2Args)
3426    bw!
3427
3428    # Test for using a script-local function name
3429    def LocalTsrFunc(findstart: number, base: string): any
3430      add(g:LocalTsrFuncArgs, [findstart, base])
3431      return findstart ? 0 : []
3432    enddef
3433    &thesaurusfunc = LocalTsrFunc
3434    new | only
3435    setline(1, 'three')
3436    g:LocalTsrFuncArgs = []
3437    feedkeys("A\<C-X>\<C-T>\<Esc>", 'x')
3438    assert_equal([[1, ''], [0, 'three']], g:LocalTsrFuncArgs)
3439    bw!
3440  END
3441  call CheckScriptSuccess(lines)
3442
3443  " cleanup
3444  set thesaurusfunc&
3445  delfunc TsrFunc1
3446  delfunc TsrFunc2
3447  unlet g:TsrFunc1Args g:TsrFunc2Args
3448  %bw!
3449endfunc
3450
3451func FooBarComplete(findstart, base)
3452  if a:findstart
3453    return col('.') - 1
3454  else
3455    return ["Foo", "Bar", "}"]
3456  endif
3457endfunc
3458
3459func Test_complete_smartindent()
3460  new
3461  setlocal smartindent completefunc=FooBarComplete
3462  exe "norm! o{\<cr>\<c-x>\<c-u>\<c-p>}\<cr>\<esc>"
3463  let result = getline(1,'$')
3464  call assert_equal(['', '{','}',''], result)
3465  %d
3466  setlocal complete=FFooBarComplete
3467  exe "norm! o{\<cr>\<c-n>\<c-p>}\<cr>\<esc>"
3468  let result = getline(1,'$')
3469  call assert_equal(['', '{','}',''], result)
3470  %d
3471  setlocal complete=F
3472  exe "norm! o{\<cr>\<c-n>\<c-p>}\<cr>\<esc>"
3473  let result = getline(1,'$')
3474  call assert_equal(['', '{','}',''], result)
3475  bw!
3476  delfunction! FooBarComplete
3477endfunc
3478
3479func Test_complete_overrun()
3480  " this was going past the end of the copied text
3481  new
3482  sil norm si”0s0
3483  bwipe!
3484endfunc
3485
3486func Test_infercase_very_long_line()
3487  " this was truncating the line when inferring case
3488  new
3489  let longLine = "blah "->repeat(300)
3490  let verylongLine = "blah "->repeat(400)
3491  call setline(1, verylongLine)
3492  call setline(2, longLine)
3493  set ic infercase
3494  exe "normal 2Go\<C-X>\<C-L>\<Esc>"
3495  call assert_equal(longLine, getline(3))
3496
3497  " check that the too long text is NUL terminated
3498  %del
3499  norm o
3500  norm 1987ax
3501  exec "norm ox\<C-X>\<C-L>"
3502  call assert_equal(repeat('x', 1987), getline(3))
3503
3504  bwipe!
3505  set noic noinfercase
3506endfunc
3507
3508func Test_ins_complete_add()
3509  " this was reading past the end of allocated memory
3510  new
3511  norm o
3512  norm 7o€€
3513  sil! norm o
3514
3515  bwipe!
3516endfunc
3517
3518func Test_ins_complete_end_of_line()
3519  " this was reading past the end of the line
3520  new
3521  " Note that the 'space' at the end of the expression below is a non-breaking
3522  " space, U+00a0.
3523  execute "norm 8o€ý "
3524  sil! norm o
3525
3526  bwipe!
3527endfunc
3528
3529func s:Tagfunc(t,f,o)
3530  bwipe!
3531  return []
3532endfunc
3533
3534" A match from an included file shows the file by its name under the current
3535" directory, without the "./" of the include line.
3536func Test_complete_included_file_name()
3537  CheckRunVimInTerminal
3538  call mkdir('Xincl/sub', 'pR')
3539  call writefile(['let included_word = 1'], 'Xincl/sub/inc.vim')
3540  call writefile(['source ./sub/inc.vim', ''], 'Xincl/main.vim')
3541  let lines =<< trim END
3542    setlocal include=^\\s*source\\s\\+ complete=i completeopt=menuone,noselect
3543  END
3544  call writefile(lines, 'Xincl/setup.vim')
3545  let buf = RunVimInTerminal('-S Xincl/setup.vim Xincl/main.vim',
3546        \ {'rows': 8, 'cols': 120})
3547  call term_sendkeys(buf, "Goincluded_\<C-N>")
3548  call WaitForAssert({-> assert_match('included_word\s\+Xincl/sub/inc.vim\s',
3549        \ term_getline(buf, 4))})
3550  call term_sendkeys(buf, "\<Esc>")
3551  call StopVimInTerminal(buf)
3552endfunc
3553
3554" This was using freed memory, since 'complete' was in a wiped out buffer.
3555" Also using a window that was closed.
3556func Test_tagfunc_wipes_out_buffer()
3557  new
3558  set complete=.,t,w,b,u,i
3559  se tagfunc=s:Tagfunc
3560  sil norm i
3561
3562  bwipe!
3563endfunc
3564
3565func s:TagfuncComplete(t,f,o)
3566  call complete(1, ['ddd', 'eee', 'fff'])
3567  return []
3568endfunc
3569
3570" 'tagfunc' calling complete() should not cause hang or E684.
3571func Test_tagfunc_calls_complete()
3572  new
3573  call setline(1, ['aaa', 'bbb', 'ccc'])
3574  setlocal tagfunc=s:TagfuncComplete
3575  setlocal completeopt=menu,noselect
3576
3577  let v:errmsg = ''
3578
3579  " This used to hang.
3580  setlocal complete=.,t
3581  call feedkeys("Go\<C-N>\<C-E>\<Esc>", 'tx')
3582  call assert_equal('', getline('.'))
3583  call assert_equal('', v:errmsg)
3584
3585  " This used to cause E684.
3586  setlocal complete=t,.
3587  call feedkeys("cc\<C-N>\<C-E>\<Esc>", 'tx')
3588  call assert_equal('', getline('.'))
3589  call assert_equal('', v:errmsg)
3590
3591  bwipe!
3592endfunc
3593
3594func Test_ins_complete_popup_position()
3595  CheckScreendump
3596
3597  let lines =<< trim END
3598      vim9script
3599      set nowrap
3600      setline(1, ['one', 'two', 'this is line ', 'four'])
3601      prop_type_add('test', {highlight: 'Error'})
3602      prop_add(3, 0, {
3603          text_align: 'above',
3604          text: 'The quick brown fox jumps over the lazy dog',
3605          type: 'test'
3606      })
3607  END
3608  call writefile(lines, 'XinsPopup', 'D')
3609  let buf = RunVimInTerminal('-S XinsPopup', #{rows: 10})
3610
3611  call term_sendkeys(buf, "3GA\<C-N>")
3612  call VerifyScreenDump(buf, 'Test_ins_complete_popup_position_1', {})
3613
3614  call StopVimInTerminal(buf)
3615endfunc
3616
3617func GetCompleteInfo()
3618  let g:compl_info = complete_info()
3619  return ''
3620endfunc
3621
3622func Test_completion_restart()
3623  new
3624  set complete=. completeopt=menuone backspace=2
3625  call setline(1, 'workhorse workhorse')
3626  exe "normal $a\<C-N>\<BS>\<BS>\<C-R>=GetCompleteInfo()\<CR>"
3627  call assert_equal(1, len(g:compl_info['items']))
3628  call assert_equal('workhorse', g:compl_info['items'][0]['word'])
3629  set complete& completeopt& backspace&
3630  bwipe!
3631endfunc
3632
3633func Test_complete_info_index()
3634  new
3635  call setline(1, ["aaa", "bbb", "ccc", "ddd", "eee", "fff"])
3636  inoremap <buffer><F5> <C-R>=GetCompleteInfo()<CR>
3637
3638  " Ensure 'index' in complete_info() is coherent with the 'items' array.
3639
3640  set completeopt=menu,preview
3641  " Search forward
3642  call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>_dd", 'tx')
3643  call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word'])
3644  call assert_equal(6 , len(g:compl_info['items']))
3645  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3646  call assert_equal("bbb", g:compl_info['items'][g:compl_info['selected']]['word'])
3647  call assert_equal(6 , len(g:compl_info['items']))
3648  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3649  call assert_equal("ccc", g:compl_info['items'][g:compl_info['selected']]['word'])
3650  call assert_equal(6 , len(g:compl_info['items']))
3651  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3652  call assert_equal("ddd", g:compl_info['items'][g:compl_info['selected']]['word'])
3653  call assert_equal(6 , len(g:compl_info['items']))
3654  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3655  call assert_equal("eee", g:compl_info['items'][g:compl_info['selected']]['word'])
3656  call assert_equal(6 , len(g:compl_info['items']))
3657  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3658  call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word'])
3659  call assert_equal(6 , len(g:compl_info['items']))
3660  " Search forward: unselected item
3661  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3662  call assert_equal(6 , len(g:compl_info['items']))
3663  call assert_equal(-1 , g:compl_info['selected'])
3664
3665  " Search backward
3666  call feedkeys("Go\<C-X>\<C-P>\<F5>\<Esc>_dd", 'tx')
3667  call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word'])
3668  call assert_equal(6 , len(g:compl_info['items']))
3669  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3670  call assert_equal("eee", g:compl_info['items'][g:compl_info['selected']]['word'])
3671  call assert_equal(6 , len(g:compl_info['items']))
3672  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3673  call assert_equal("ddd", g:compl_info['items'][g:compl_info['selected']]['word'])
3674  call assert_equal(6 , len(g:compl_info['items']))
3675  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3676  call assert_equal("ccc", g:compl_info['items'][g:compl_info['selected']]['word'])
3677  call assert_equal(6 , len(g:compl_info['items']))
3678  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3679  call assert_equal("bbb", g:compl_info['items'][g:compl_info['selected']]['word'])
3680  call assert_equal(6 , len(g:compl_info['items']))
3681  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3682  call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word'])
3683  call assert_equal(6 , len(g:compl_info['items']))
3684  " search backwards: unselected item
3685  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3686  call assert_equal(6 , len(g:compl_info['items']))
3687  call assert_equal(-1 , g:compl_info['selected'])
3688
3689  " switch direction: forwards, then backwards
3690  call feedkeys("Go\<C-X>\<C-N>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3691  call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word'])
3692  call assert_equal(6 , len(g:compl_info['items']))
3693  " switch direction: forwards, then backwards, then forwards again
3694  call feedkeys("Go\<C-X>\<C-N>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx')
3695  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-P>\<C-P>\<C-N>\<F5>\<Esc>_dd", 'tx')
3696  call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word'])
3697  call assert_equal(6 , len(g:compl_info['items']))
3698
3699  " switch direction: backwards, then forwards
3700  call feedkeys("Go\<C-X>\<C-P>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3701  call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word'])
3702  call assert_equal(6 , len(g:compl_info['items']))
3703  " switch direction: backwards, then forwards, then backwards again
3704  call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-N>\<C-N>\<C-P>\<F5>\<Esc>_dd", 'tx')
3705  call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word'])
3706  call assert_equal(6 , len(g:compl_info['items']))
3707
3708  " Add 'noselect', check that 'selected' is -1 when nothing is selected.
3709  set completeopt+=noselect
3710  " Search forward.
3711  call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>_dd", 'tx')
3712  call assert_equal(-1, g:compl_info['selected'])
3713
3714  " Search backward.
3715  call feedkeys("Go\<C-X>\<C-P>\<F5>\<Esc>_dd", 'tx')
3716  call assert_equal(-1, g:compl_info['selected'])
3717
3718  call feedkeys("Go\<C-X>\<C-N>\<C-P>\<F5>\<Esc>_dd", 'tx')
3719  call assert_equal(5, g:compl_info['selected'])
3720  call assert_equal(6 , len(g:compl_info['items']))
3721  call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word'])
3722  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx')
3723  call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word'])
3724  call assert_equal(6 , len(g:compl_info['items']))
3725  call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>_dd", 'tx')
3726  call assert_equal(-1, g:compl_info['selected'])
3727  call assert_equal(6 , len(g:compl_info['items']))
3728
3729  set completeopt&
3730  bwipe!
3731endfunc
3732
3733func Test_complete_changed_complete_info()
3734  CheckRunVimInTerminal
3735  " this used to crash vim, see #13929
3736  let lines =<< trim END
3737    set completeopt=menuone
3738    autocmd CompleteChanged * call complete_info(['items'])
3739    call feedkeys("iii\<cr>\<c-p>")
3740  END
3741  call writefile(lines, 'Xsegfault', 'D')
3742  let buf = RunVimInTerminal('-S Xsegfault', #{rows: 5})
3743  call WaitForAssert({-> assert_match('^ii', term_getline(buf, 1))}, 1000)
3744  call StopVimInTerminal(buf)
3745endfunc
3746
3747func Test_completefunc_first_call_complete_add()
3748  new
3749
3750  func Complete(findstart, base) abort
3751    if a:findstart
3752      let col = col('.')
3753      call complete_add('#')
3754      return col - 1
3755    else
3756      return []
3757    endif
3758  endfunc
3759
3760  set completeopt=longest completefunc=Complete
3761  " This used to cause heap-buffer-overflow
3762  call assert_fails('call feedkeys("ifoo#\<C-X>\<C-U>", "xt")', 'E840:')
3763
3764  delfunc Complete
3765  set completeopt& completefunc&
3766  bwipe!
3767endfunc
3768
3769func Test_complete_opt_fuzzy()
3770  func OnPumChange()
3771    let g:item = get(v:event, 'completed_item', {})
3772    let g:word = get(g:item, 'word', v:null)
3773    let g:abbr = get(g:item, 'abbr', v:null)
3774    let g:selected = get(complete_info(['selected']), 'selected')
3775  endfunction
3776
3777  augroup AAAAA_Group
3778    au!
3779    autocmd CompleteChanged * :call OnPumChange()
3780  augroup END
3781
3782  let g:change = 0
3783  func Omni_test(findstart, base)
3784    if a:findstart
3785      return col(".")
3786    endif
3787    if g:change == 0
3788      return [#{word: "foo"}, #{word: "foobar"}, #{word: "fooBaz"}, #{word: "foobala"}, #{word: "你好吗"}, #{word: "我好"}]
3789    elseif g:change == 1
3790      return [#{word: "cp_match_array"}, #{word: "cp_str"}, #{word: "cp_score"}]
3791    else
3792      return [#{word: "for i = .."}, #{word: "bar"}, #{word: "foo"}, #{word: "for .. ipairs"}, #{word: "for .. pairs"}]
3793    endif
3794  endfunc
3795
3796  new
3797  set omnifunc=Omni_test
3798  set completeopt+=noinsert,fuzzy
3799  call feedkeys("Gi\<C-x>\<C-o>", 'tx')
3800  call assert_equal('foo', g:word)
3801  call feedkeys("S\<C-x>\<C-o>fb", 'tx')
3802  call assert_equal('fooBaz', g:word)
3803  call feedkeys("S\<C-x>\<C-o>fa", 'tx')
3804  call assert_equal('foobar', g:word)
3805  " select next
3806  call feedkeys("S\<C-x>\<C-o>fb\<C-n>", 'tx')
3807  call assert_equal('foobar', g:word)
3808  " can cyclically select next
3809  call feedkeys("S\<C-x>\<C-o>fb\<C-n>\<C-n>\<C-n>", 'tx')
3810  call assert_equal(v:null, g:word)
3811  " select prev
3812  call feedkeys("S\<C-x>\<C-o>fb\<C-p>", 'tx')
3813  call assert_equal(v:null, g:word)
3814  " can cyclically select prev
3815  call feedkeys("S\<C-x>\<C-o>fb\<C-p>\<C-p>\<C-p>\<C-p>", 'tx')
3816  call assert_equal('fooBaz', g:word)
3817
3818  func Comp()
3819    call complete(col('.'), ["fooBaz", "foobar", "foobala"])
3820    return ''
3821  endfunc
3822  call feedkeys("i\<C-R>=Comp()\<CR>", 'tx')
3823  call assert_equal('fooBaz', g:word)
3824
3825  " respect noselect
3826  set completeopt+=noselect
3827  call feedkeys("S\<C-x>\<C-o>fb", 'tx')
3828  call assert_equal(v:null, g:word)
3829  call feedkeys("S\<C-x>\<C-o>fb\<C-n>", 'tx')
3830  call assert_equal('fooBaz', g:word)
3831
3832  " test case for nosort option
3833  set cot=menuone,menu,noinsert,fuzzy,nosort
3834  " "fooBaz" should have a higher score when the leader is "fb".
3835  " With "nosort", "foobar" should still be shown first in the popup menu.
3836  call feedkeys("S\<C-x>\<C-o>fb", 'tx')
3837  call assert_equal('foobar', g:word)
3838  call feedkeys("S\<C-x>\<C-o>好", 'tx')
3839  call assert_equal("你好吗", g:word)
3840
3841  set cot+=noselect
3842  call feedkeys("S\<C-x>\<C-o>好", 'tx')
3843  call assert_equal(v:null, g:word)
3844  call feedkeys("S\<C-x>\<C-o>好\<C-N>", 'tx')
3845  call assert_equal('你好吗', g:word)
3846
3847  " "nosort" shouldn't enable fuzzy filtering when "fuzzy" isn't present.
3848  set cot=menuone,noinsert,nosort
3849  call feedkeys("S\<C-x>\<C-o>fooB\<C-Y>", 'tx')
3850  call assert_equal('fooBaz', getline('.'))
3851
3852  set cot=menuone,fuzzy,nosort
3853  func CompAnother()
3854    call complete(col('.'), [#{word: "do" }, #{word: "echo"}, #{word: "for (${1:expr1}, ${2:expr2}, ${3:expr3}) {\n\t$0\n}", abbr: "for" }, #{word: "foo"}])
3855    return ''
3856  endfunc
3857  call feedkeys("i\<C-R>=CompAnother()\<CR>\<C-N>\<C-N>", 'tx')
3858  call assert_equal("for", g:abbr)
3859  call assert_equal(2, g:selected)
3860
3861  set cot+=noinsert
3862  call feedkeys("i\<C-R>=CompAnother()\<CR>f", 'tx')
3863  call assert_equal("for", g:abbr)
3864  call assert_equal(2, g:selected)
3865
3866  set cot=menu,menuone,noselect,fuzzy
3867  call feedkeys("i\<C-R>=CompAnother()\<CR>\<C-N>\<C-N>\<C-N>\<C-N>", 'tx')
3868  call assert_equal("foo", g:word)
3869  call feedkeys("i\<C-R>=CompAnother()\<CR>\<C-P>", 'tx')
3870  call assert_equal("foo", g:word)
3871  call feedkeys("i\<C-R>=CompAnother()\<CR>\<C-P>\<C-P>", 'tx')
3872  call assert_equal("for", g:abbr)
3873
3874  %d
3875  set cot=menu,fuzzy
3876  call feedkeys("Sblue\<CR>bar\<CR>b\<C-X>\<C-P>\<C-Y>\<ESC>", 'tx')
3877  call assert_equal('blue', getline('.'))
3878  call feedkeys("Sb\<C-X>\<C-N>\<C-Y>\<ESC>", 'tx')
3879  call assert_equal('bar', getline('.'))
3880  call feedkeys("Sb\<C-X>\<C-P>\<C-N>\<C-Y>\<ESC>", 'tx')
3881  call assert_equal('b', getline('.'))
3882
3883  " chain completion
3884  call feedkeys("Slore spum\<CR>lor\<C-X>\<C-P>\<C-X>\<C-P>\<ESC>", 'tx')
3885  call assert_equal('lore spum', getline('.'))
3886
3887  " issue #15412
3888  call feedkeys("Salpha bravio charlie\<CR>alpha\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<ESC>", 'tx')
3889  call assert_equal('alpha bravio charlie', getline('.'))
3890
3891  set cot=fuzzy,menu,noinsert
3892  call feedkeys(":let g:change=2\<CR>")
3893  call feedkeys("S\<C-X>\<C-O>for\<C-N>\<C-N>\<C-N>", 'tx')
3894  call assert_equal('for', getline('.'))
3895  call feedkeys("S\<C-X>\<C-O>for\<C-P>", 'tx')
3896  call assert_equal('for', getline('.'))
3897  call feedkeys("S\<C-X>\<C-O>for\<C-P>\<C-P>", 'tx')
3898  call assert_equal('for .. ipairs', getline('.'))
3899
3900  call feedkeys(":let g:change=1\<CR>")
3901  call feedkeys("S\<C-X>\<C-O>c\<C-Y>", 'tx')
3902  call assert_equal('cp_str', getline('.'))
3903
3904  " Issue 18488: sort after collection when "fuzzy" (unless "nosort")
3905  %d
3906  set completeopt&
3907  set completeopt+=fuzzy,noselect
3908  func! PrintMenuWords()
3909    let info = complete_info(["items"])
3910    call map(info.items, {_, v -> v.word})
3911    return info
3912  endfunc
3913  call setline(1, ['func1', 'xfunc', 'func2'])
3914  call feedkeys("Gof\<C-N>\<C-R>=PrintMenuWords()\<CR>\<Esc>0", 'tx')
3915  call assert_equal('f{''items'': [''func1'', ''func2'', ''xfunc'']}', getline('.'))
3916
3917  " Issue #18802: Reset selected item after fuzzy sort
3918  %d
3919  call setline(1, ['aa', 'aaa', 'aaaa'])
3920  set completeopt=menuone,noinsert,fuzzy
3921  call feedkeys("Goa\<C-N>\<C-Y>\<Esc>", 'tx')
3922  call assert_equal('aa', getline('.'))
3923  call feedkeys("Goa\<C-P>\<C-Y>\<Esc>", 'tx')
3924  call assert_equal('aaaa', getline('.'))
3925
3926  %d
3927  set autoindent
3928  set completeopt=menuone,fuzzy
3929  call feedkeys("A\<TAB>hello world\<CR>word is on fire\<CR>w\<C-X>\<C-L>\<C-Y>", 'tx')
3930  call assert_equal("\thello world", getline('.'))
3931
3932  " clean up
3933  set omnifunc=
3934  bw!
3935  set complete& completeopt& autoindent&
3936  autocmd! AAAAA_Group
3937  augroup! AAAAA_Group
3938  delfunc OnPumChange
3939  delfunc Omni_test
3940  delfunc Comp
3941  delfunc PrintMenuWords
3942  unlet g:item
3943  unlet g:word
3944  unlet g:abbr
3945endfunc
3946
3947func Test_complete_fuzzy_collect()
3948  new
3949  redraw  " need this to prevent NULL dereference in Nvim
3950  set completeopt+=fuzzy
3951  call setline(1, ['hello help hero h'])
3952  " Use "!" flag of feedkeys() so that ex_normal_busy is not set and
3953  " ins_compl_check_keys() is not skipped.
3954  " Add a "0" after the <Esc> to avoid waiting for an escape sequence.
3955  call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!')
3956  call assert_equal('hello help hero hello', getline('.'))
3957  set completeopt+=noinsert
3958  call setline(1, ['hello help hero h'])
3959  call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!')
3960  call assert_equal('hello help hero h', getline('.'))
3961
3962  set completeopt-=noinsert
3963  call setline(1, ['xyz  yxz  x'])
3964  call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!')
3965  call assert_equal('xyz  yxz  xyz', getline('.'))
3966  " can fuzzy get yxz when use Ctrl-N twice
3967  call setline(1, ['xyz  yxz  x'])
3968  call feedkeys("A\<C-X>\<C-N>\<C-N>\<Esc>0", 'tx!')
3969  call assert_equal('xyz  yxz  yxz', getline('.'))
3970
3971  call setline(1, ['你好 你'])
3972  call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!')
3973  call assert_equal('你好 你好', getline('.'))
3974  call setline(1, ['你的 我的 的'])
3975  call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!')
3976  call assert_equal('你的 我的 你的', getline('.'))
3977  " can fuzzy get multiple-byte word when use Ctrl-N twice
3978  call setline(1, ['你的 我的 的'])
3979  call feedkeys("A\<C-X>\<C-N>\<C-N>\<Esc>0", 'tx!')
3980  call assert_equal('你的 我的 我的', getline('.'))
3981
3982  " check that "adding" expansion works
3983  call setline(1, ['hello world foo bar'])
3984  call feedkeys("Ohlo\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<Esc>0", 'tx!')
3985  call assert_equal('hello world foo bar', getline('.'))
3986  call feedkeys("Swld\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<Esc>0", 'tx!')
3987  call assert_equal('world foo bar', getline('.'))
3988  %delete
3989
3990  " fuzzy on file
3991  call writefile([''], 'fobar', 'D')
3992  call writefile([''], 'foobar', 'D')
3993  call setline(1, ['fob'])
3994  call cursor(1, 1)
3995  call feedkeys("A\<C-X>\<C-f>\<Esc>0", 'tx!')
3996  call assert_equal('fobar', getline('.'))
3997  call feedkeys("Sfob\<C-X>\<C-f>\<C-N>\<Esc>0", 'tx!')
3998  call assert_equal('foobar', getline('.'))
3999  call feedkeys("S../\<C-X>\<C-f>\<Esc>0", 'tx!')
4000  call assert_match('../*', getline('.'))
4001  call feedkeys("S../td\<C-X>\<C-f>\<Esc>0", 'tx!')
4002  call assert_match('../testdir', getline('.'))
4003
4004  " can get completion from other buffer
4005  vnew
4006  call setline(1, ["completeness,", "compatibility", "Composite", "Omnipotent"])
4007  wincmd p
4008  call feedkeys("Somp\<C-N>\<Esc>0", 'tx!')
4009  call assert_equal('completeness', getline('.'))
4010  call feedkeys("Somp\<C-N>\<C-N>\<Esc>0", 'tx!')
4011  call assert_equal('compatibility', getline('.'))
4012  call feedkeys("Somp\<C-P>\<Esc>0", 'tx!')
4013  call assert_equal('Omnipotent', getline('.'))
4014  call feedkeys("Somp\<C-P>\<C-P>\<Esc>0", 'tx!')
4015  call assert_equal('Composite', getline('.'))
4016  call feedkeys("S omp\<C-N>\<Esc>0", 'tx!')
4017  call assert_equal(' completeness', getline('.'))
4018
4019  " fuzzy on whole line completion
4020  call setline(1, ["world is on fire", "no one can save me but you", 'user can execute', ''])
4021  call cursor(4, 1)
4022  call feedkeys("Swio\<C-X>\<C-L>\<Esc>0", 'tx!')
4023  call assert_equal('world is on fire', getline('.'))
4024  call feedkeys("Su\<C-X>\<C-L>\<C-P>\<Esc>0", 'tx!')
4025  call assert_equal('no one can save me but you', getline('.'))
4026
4027  " issue #15526
4028  set completeopt=menuone,menu,noselect,fuzzy
4029  call setline(1, ['Text', 'ToText', ''])
4030  call cursor(3, 1)
4031  call feedkeys("STe\<C-X>\<C-N>x\<CR>\<Esc>0", 'tx!')
4032  call assert_equal('Tex', getline(line('.') - 1))
4033
4034  call setline(1, ['fuzzy', 'fuzzycollect', 'completefuzzycollect'])
4035  call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<CR>\<Esc>0", 'tx!')
4036  call assert_equal('fuzzycollect', getline(line('.') - 1))
4037  call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<CR>\<Esc>0", 'tx!')
4038  call assert_equal('completefuzzycollect', getline(line('.') - 1))
4039
4040  " keywords in 'dictionary'
4041  call writefile(['hello', 'think'], 'Xtest_dict.txt', 'D')
4042  set dict=Xtest_dict.txt
4043  call feedkeys("Sh\<C-X>\<C-K>\<C-N>\<CR>\<Esc>0", 'tx!')
4044  call assert_equal('hello', getline(line('.') - 1))
4045  call feedkeys("Sh\<C-X>\<C-K>\<C-N>\<C-N>\<CR>\<Esc>0", 'tx!')
4046  call assert_equal('think', getline(line('.') - 1))
4047
4048  call setline(1, ['foo bar fuzzy', 'completefuzzycollect'])
4049  call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!')
4050  call assert_equal('completefuzzycollect', getline('.'))
4051
4052  %d _
4053  call setline(1, ['fuzzy', 'fuzzy foo', "fuzzy bar", 'fuzzycollect'])
4054  call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!')
4055  call assert_equal('fuzzycollect', getline('.'))
4056
4057  " when 'fuzzy' is not set, and 'infercase' and 'ignorecase' are set, then
4058  " uppercase completes from lowercase words in dictionary
4059  set completeopt&
4060  set infercase ignorecase
4061  call writefile(['hello'], 'Xtest_case.txt', 'D')
4062  set dictionary=Xtest_case.txt
4063  call feedkeys("ggdGSH\<C-X>\<C-K>\<C-Y>\<Esc>", 'tx')
4064  call assert_equal('Hello', getline('.'))
4065  call feedkeys("ggdGSHE\<C-X>\<C-K>\<C-Y>\<Esc>", 'tx')
4066  call assert_equal('HELLO', getline('.'))
4067
4068  bw!
4069  bw!
4070  set dict&
4071  set completeopt& cpt& ignorecase& infercase&
4072endfunc
4073
4074" Issue #19434
4075" Fuzzy whole-line completion should not loop infinitely when the cursor is in
4076" the middle of the line (non-zero column).
4077func Test_complete_fuzzy_wholeline_no_hang()
4078  new
4079  set completeopt=preview,fuzzy,noinsert,menuone
4080  call setline(1, [
4081        \ '<!DOCTYPE html>',
4082        \ '<html lang="en-US">',
4083        \ '  <head>',
4084        \ '  </head>',
4085        \ '  <body>',
4086        \ '    <div class="page-landscape">',
4087        \ '    </div>',
4088        \ '  </body>',
4089        \ '</html>',
4090        \ ])
4091  call cursor(6, 1)
4092  call feedkeys("faC\<C-X>\<C-L>\<Esc>0", 'tx!')
4093  call assert_equal('    <div cl', getline(6))
4094
4095  bw!
4096  set completeopt&
4097endfunc
4098
4099" Issue #18752
4100func Test_complete_fuzzy_collect_multiwin()
4101  new
4102  set completeopt=fuzzy
4103
4104  vnew
4105  call setline(1, ["completeness,", "compatibility", "Composite", "Omnipotent"])
4106  wincmd p
4107  call feedkeys("Somp\<C-P>\<Esc>0", 'tx!')
4108  call assert_equal('Omnipotent', getline('.'))
4109
4110  bw!
4111  set completeopt&
4112endfunc
4113
4114func Test_cfc_with_longest()
4115  new
4116  set completeopt=menu,menuone,longest,fuzzy
4117
4118  " keyword
4119  exe "normal ggdGShello helio think h\<C-X>\<C-N>\<ESC>"
4120  call assert_equal("hello helio think hel", getline('.'))
4121  exe "normal hello helio think h\<C-X>\<C-P>\<ESC>"
4122  call assert_equal("hello helio think hel", getline('.'))
4123
4124  " skip non-consecutive prefixes
4125  exe "normal ggdGShello helio heo\<C-X>\<C-N>\<ESC>"
4126  call assert_equal("hello helio heo", getline('.'))
4127
4128  " dict
4129  call writefile(['help'], 'test_keyword.txt', 'D')
4130  set complete=ktest_keyword.txt
4131  exe "normal ggdGSh\<C-N>\<ESC>"
4132  " auto insert help when only have one match
4133  call assert_equal("help", getline('.'))
4134  call writefile(['hello', 'help', 'think'], 'xtest_keyword.txt', 'D')
4135  set complete=kxtest_keyword.txt
4136  " auto insert hel
4137  exe "normal ggdGSh\<C-N>\<ESC>"
4138  call assert_equal("hel", getline('.'))
4139
4140  " line start with a space
4141  call writefile([' hello'], 'test_case1.txt', 'D')
4142  set complete=ktest_case1.txt
4143  exe "normal ggdGSh\<C-N>\<ESC>"
4144  call assert_equal("hello", getline('.'))
4145
4146  " multiple matches
4147  set complete=ktest_case2.txt
4148  call writefile([' hello help what'], 'test_case2.txt', 'D')
4149  exe "normal ggdGSh\<C-N>\<C-N>\<C-N>\<C-N>\<ESC>"
4150  call assert_equal("what", getline('.'))
4151
4152  " multiple lines of matches
4153  set complete=ktest_case3.txt
4154  call writefile([' hello help what', 'hola', '     hey'], 'test_case3.txt', 'D')
4155  exe "normal ggdGSh\<C-N>\<C-N>\<ESC>"
4156  call assert_equal("hey", getline('.'))
4157  exe "normal ggdGSh\<C-N>\<C-N>\<C-N>\<C-N>\<ESC>"
4158  call assert_equal("hola", getline('.'))
4159
4160  set complete=ktest_case4.txt
4161  call writefile(['  auto int   enum register', 'why'], 'test_case4.txt', 'D')
4162  exe "normal ggdGSe\<C-N>\<C-N>\<ESC>"
4163  call assert_equal("enum", getline('.'))
4164
4165  set complete=ktest_case5.txt
4166  call writefile(['hello friends', 'go', 'hero'], 'test_case5.txt', 'D')
4167  exe "normal ggdGSh\<C-N>\<C-N>\<ESC>"
4168  call assert_equal("hero", getline('.'))
4169  set complete&
4170
4171  " file
4172  call writefile([''], 'hello', 'D')
4173  call writefile([''], 'helio', 'D')
4174  exe "normal ggdGS./h\<C-X>\<C-f>\<ESC>"
4175  call assert_equal('./hel', getline('.'))
4176
4177  " word
4178  call setline(1, ['what do you think', 'why i have that', ''])
4179  call cursor(3,1)
4180  call feedkeys("Sw\<C-X>\<C-l>\<C-N>\<Esc>0", 'tx!')
4181  call assert_equal('wh', getline('.'))
4182
4183  exe "normal ggdG"
4184  " auto complete when only one match
4185  exe "normal Shello\<CR>h\<C-X>\<C-N>\<esc>"
4186  call assert_equal('hello', getline('.'))
4187  exe "normal Sh\<C-N>\<C-P>\<esc>"
4188  call assert_equal('hello', getline('.'))
4189
4190  exe "normal Shello\<CR>h\<C-X>\<C-N>\<Esc>cch\<C-X>\<C-N>\<Esc>"
4191  call assert_equal('hello', getline('.'))
4192
4193  " continue search for new leader after insert common prefix
4194  exe "normal ohellokate\<CR>h\<C-X>\<C-N>k\<C-N>\<C-y>\<esc>"
4195  call assert_equal('hellokate', getline('.'))
4196
4197  bw!
4198  set completeopt&
4199endfunc
4200
4201func Test_completefuzzycollect_with_completeslash()
4202  CheckMSWindows
4203
4204  call writefile([''], 'fobar', 'D')
4205  let orig_shellslash = &shellslash
4206  set cpt&
4207  new
4208  set completeopt+=fuzzy
4209  set noshellslash
4210
4211  " Test with completeslash unset
4212  set completeslash=
4213  call setline(1, ['.\fob'])
4214  call feedkeys("A\<C-X>\<C-F>\<Esc>0", 'tx!')
4215  call assert_equal('.\fobar', getline('.'))
4216
4217  " Test with completeslash=backslash
4218  set completeslash=backslash
4219  call feedkeys("S.\\fob\<C-X>\<C-F>\<Esc>0", 'tx!')
4220  call assert_equal('.\fobar', getline('.'))
4221
4222  " Test with completeslash=slash
4223  set completeslash=slash
4224  call feedkeys("S.\\fob\<C-X>\<C-F>\<Esc>0", 'tx!')
4225  call assert_equal('./fobar', getline('.'))
4226
4227  " Reset and clean up
4228  let &shellslash = orig_shellslash
4229  set completeslash=
4230  %bw!
4231endfunc
4232
4233" Check that tie breaking is stable for completeopt+=fuzzy (which should
4234" behave the same on different platforms).
4235func Test_complete_fuzzy_match_tie()
4236  new
4237  set completeopt+=fuzzy,noselect
4238  call setline(1, ['aaabbccc', 'aaabbCCC', 'aaabbcccc', 'aaabbCCCC', ''])
4239
4240  call feedkeys("Gcc\<C-X>\<C-N>ab\<C-N>\<C-Y>", 'tx')
4241  call assert_equal('aaabbccc', getline('.'))
4242  call feedkeys("Gcc\<C-X>\<C-N>ab\<C-N>\<C-N>\<C-Y>", 'tx')
4243  call assert_equal('aaabbCCC', getline('.'))
4244  call feedkeys("Gcc\<C-X>\<C-N>ab\<C-N>\<C-N>\<C-N>\<C-Y>", 'tx')
4245  call assert_equal('aaabbcccc', getline('.'))
4246  call feedkeys("Gcc\<C-X>\<C-N>ab\<C-N>\<C-N>\<C-N>\<C-N>\<C-Y>", 'tx')
4247  call assert_equal('aaabbCCCC', getline('.'))
4248
4249  bwipe!
4250  set completeopt&
4251endfunc
4252
4253func Test_complete_backwards_default()
4254  new
4255  call append(1, ['foobar', 'foobaz'])
4256  new
4257  call feedkeys("i\<c-p>", 'tx')
4258  call assert_equal('foobaz', getline('.'))
4259  bw!
4260  bw!
4261endfunc
4262
4263func Test_complete_info_matches()
4264  let g:what = ['matches']
4265  func ShownInfo()
4266    let g:compl_info = complete_info(g:what)
4267    return ''
4268  endfunc
4269  set completeopt+=noinsert
4270
4271  new
4272  call setline(1, ['aaa', 'aab', 'aba', 'abb'])
4273  inoremap <buffer><F5> <C-R>=ShownInfo()<CR>
4274
4275  call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>dd", 'tx')
4276  call assert_equal([
4277    \ {'word': 'aaa', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},
4278    \ {'word': 'aab', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},
4279    \ {'word': 'aba', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},
4280    \ {'word': 'abb', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},
4281    \], g:compl_info['matches'])
4282
4283  call feedkeys("Goa\<C-X>\<C-N>b\<F5>\<Esc>dd", 'tx')
4284  call assert_equal([
4285    \ {'word': 'aba', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},
4286    \ {'word': 'abb', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},
4287    \], g:compl_info['matches'])
4288
4289  " items and matches both in what
4290  let g:what = ['items', 'matches']
4291  call feedkeys("Goa\<C-X>\<C-N>b\<F5>\<Esc>dd", 'tx')
4292  call assert_equal([
4293    \ {'word': 'aaa', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'match': v:false, 'info': '', 'kind': '', 'abbr': ''},
4294    \ {'word': 'aab', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'match': v:false, 'info': '', 'kind': '', 'abbr': ''},
4295    \ {'word': 'aba', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'match': v:true, 'info': '', 'kind': '', 'abbr': ''},
4296    \ {'word': 'abb', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'match': v:true, 'info': '', 'kind': '', 'abbr': ''},
4297    \], g:compl_info['items'])
4298  call assert_false(has_key(g:compl_info, 'matches'))
4299
4300  bw!
4301  unlet g:what
4302  delfunc ShownInfo
4303  set cot&
4304endfunc
4305
4306func Test_complete_info_completed()
4307  func ShownInfo()
4308    let g:compl_info = complete_info(['completed'])
4309    return ''
4310  endfunc
4311  set completeopt+=noinsert
4312
4313  new
4314  call setline(1, ['aaa', 'aab', 'aba', 'abb'])
4315  inoremap <buffer><F5> <C-R>=ShownInfo()<CR>
4316
4317  call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>dd", 'tx')
4318  call assert_equal({'word': 'aaa', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},  g:compl_info['completed'])
4319
4320  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<F5>\<Esc>dd", 'tx')
4321  call assert_equal({'word': 'aab', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},  g:compl_info['completed'])
4322
4323  call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>dd", 'tx')
4324  call assert_equal({'word': 'abb', 'menu': '', 'kind_hlgroup': '', 'abbr_hlgroup': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''},  g:compl_info['completed'])
4325
4326  set completeopt+=noselect
4327  call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>dd", 'tx')
4328  call assert_equal({}, g:compl_info)
4329
4330  bw!
4331  delfunc ShownInfo
4332  set cot&
4333endfunc
4334
4335func Test_complete_info_selected()
4336  set completeopt=menuone,noselect
4337  new
4338  call setline(1, ["ward", "werd", "wurd", "wxrd"])
4339
4340  exe "normal! Gow\<c-n>u\<c-n>\<c-r>=complete_info().selected\<cr>"
4341  call assert_equal('wurd2', getline(5))
4342
4343  exe "normal! Sw\<c-n>u\<c-n>\<c-r>=complete_info(['selected']).selected\<cr>"
4344  call assert_equal('wurd2', getline(5))
4345
4346  exe "normal! Sw\<c-n>u\<c-n>\<c-r>=complete_info(['items', 'selected']).selected\<cr>"
4347  call assert_equal('wurd2', getline(5))
4348
4349  exe "normal! Sw\<c-n>u\<c-n>\<c-r>=complete_info(['matches', 'selected']).selected\<cr>"
4350  call assert_equal('wurd0', getline(5))
4351
4352  bw!
4353  set cot&
4354endfunc
4355
4356func Test_completeopt_preinsert()
4357  func Omni_test(findstart, base)
4358    if a:findstart
4359      return col(".")
4360    endif
4361    return [#{word: "fobar"}, #{word: "foobar"}, #{word: "你的"}, #{word: "你好世界"}]
4362  endfunc
4363  set omnifunc=Omni_test
4364  set completeopt=menu,menuone,preinsert
4365  func GetLine()
4366    let g:line = getline('.')
4367    let g:col = col('.')
4368  endfunc
4369
4370  new
4371  inoremap <buffer><F5> <C-R>=GetLine()<CR>
4372  call feedkeys("S\<C-X>\<C-O>f\<F5>\<ESC>", 'tx')
4373  call assert_equal("fobar", g:line)
4374  call assert_equal(2, g:col)
4375
4376  call feedkeys("S\<C-X>\<C-O>foo\<F5>\<ESC>", 'tx')
4377  call assert_equal("foobar", g:line)
4378
4379  call feedkeys("S\<C-X>\<C-O>foo\<BS>\<BS>\<BS>", 'tx')
4380  call assert_equal("", getline('.'))
4381
4382  " delete a character and input new leader
4383  call feedkeys("S\<C-X>\<C-O>foo\<BS>b\<F5>\<ESC>", 'tx')
4384  call assert_equal("fobar", g:line)
4385  call assert_equal(4, g:col)
4386
4387  " delete preinsert when prepare completion
4388  call feedkeys("S\<C-X>\<C-O>f\<Space>", 'tx')
4389  call assert_equal("f ", getline('.'))
4390
4391  call feedkeys("S\<C-X>\<C-O>你\<F5>\<ESC>", 'tx')
4392  call assert_equal("你的", g:line)
4393  call assert_equal(4, g:col)
4394
4395  call feedkeys("S\<C-X>\<C-O>你好\<F5>\<ESC>", 'tx')
4396  call assert_equal("你好世界", g:line)
4397  call assert_equal(7, g:col)
4398
4399  call feedkeys("Shello   wo\<Left>\<Left>\<Left>\<C-X>\<C-O>f\<F5>\<ESC>", 'tx')
4400  call assert_equal("hello  fobar wo", g:line)
4401  call assert_equal(9, g:col)
4402
4403  call feedkeys("Shello   wo\<Left>\<Left>\<Left>\<C-X>\<C-O>f\<BS>\<F5>\<ESC>", 'tx')
4404  call assert_equal("hello   wo", g:line)
4405  call assert_equal(8, g:col)
4406
4407  call feedkeys("Shello   wo\<Left>\<Left>\<Left>\<C-X>\<C-O>foo\<F5>\<ESC>", 'tx')
4408  call assert_equal("hello  foobar wo", g:line)
4409  call assert_equal(11, g:col)
4410
4411  call feedkeys("Shello   wo\<Left>\<Left>\<Left>\<C-X>\<C-O>foo\<BS>b\<F5>\<ESC>", 'tx')
4412  call assert_equal("hello  fobar wo", g:line)
4413  call assert_equal(11, g:col)
4414
4415  " confirm
4416  call feedkeys("S\<C-X>\<C-O>f\<C-Y>", 'tx')
4417  call assert_equal("fobar", getline('.'))
4418  call assert_equal(5, col('.'))
4419
4420  " cancel
4421  call feedkeys("S\<C-X>\<C-O>fo\<C-E>", 'tx')
4422  call assert_equal("fo", getline('.'))
4423  call assert_equal(2, col('.'))
4424
4425  call feedkeys("S hello hero\<CR>h\<C-X>\<C-N>\<F5>\<ESC>", 'tx')
4426  call assert_equal("hello", g:line)
4427  call assert_equal(2, col('.'))
4428
4429  call feedkeys("Sh\<C-X>\<C-N>\<C-Y>", 'tx')
4430  call assert_equal("hello", getline('.'))
4431  call assert_equal(5, col('.'))
4432
4433  " delete preinsert part
4434  call feedkeys("S\<C-X>\<C-O>fo ", 'tx')
4435  call assert_equal("fo ", getline('.'))
4436  call assert_equal(3, col('.'))
4437
4438  call feedkeys("She\<C-X>\<C-N>\<C-U>", 'tx')
4439  call assert_equal("", getline('.'))
4440  call assert_equal(1, col('.'))
4441
4442  call feedkeys("She\<C-X>\<C-N>\<C-W>", 'tx')
4443  call assert_equal("", getline('.'))
4444  call assert_equal(1, col('.'))
4445
4446  " whole line
4447  call feedkeys("Shello hero\<CR>\<C-X>\<C-L>\<F5>\<ESC>", 'tx')
4448  call assert_equal("hello hero", g:line)
4449  call assert_equal(1, g:col)
4450
4451  call feedkeys("Shello hero\<CR>he\<C-X>\<C-L>\<F5>\<ESC>", 'tx')
4452  call assert_equal("hello hero", g:line)
4453  call assert_equal(3, g:col)
4454
4455  call feedkeys("Shello hero\<CR>h\<C-X>\<C-N>er\<F5>\<ESC>", 'tx')
4456  call assert_equal("hero", g:line)
4457  call assert_equal(4, g:col)
4458
4459  " can not work with fuzzy
4460  set cot+=fuzzy
4461  call feedkeys("S\<C-X>\<C-O>", 'tx')
4462  call assert_equal("fobar", getline('.'))
4463  call assert_equal(5, col('.'))
4464
4465  " test for fuzzy and noinsert
4466  set cot+=noinsert
4467  call feedkeys("S\<C-X>\<C-O>fb\<F5>\<ESC>", 'tx')
4468  call assert_equal("fb", g:line)
4469  call assert_equal(3, g:col)
4470
4471  call feedkeys("S\<C-X>\<C-O>你\<F5>\<ESC>", 'tx')
4472  call assert_equal("你", g:line)
4473  call assert_equal(4, g:col)
4474
4475  call feedkeys("S\<C-X>\<C-O>fb\<C-Y>", 'tx')
4476  call assert_equal("fobar", getline('.'))
4477  call assert_equal(5, col('.'))
4478
4479  " When the pum is not visible, the preinsert has no effect
4480  set cot=preinsert
4481  call feedkeys("Sfoo1 foo2\<CR>f\<C-X>\<C-N>bar", 'tx')
4482  call assert_equal("foo1bar", getline('.'))
4483  call assert_equal(7, col('.'))
4484
4485  set cot=preinsert,menuone
4486  call feedkeys("Sfoo1 foo2\<CR>f\<C-X>\<C-N>\<F5>\<ESC>", 'tx')
4487  call assert_equal("foo1", g:line)
4488  call assert_equal(2, g:col)
4489
4490  inoremap <buffer> <f3> <cmd>call complete(4, [{'word': "fobar"}, {'word': "foobar"}])<CR>
4491  call feedkeys("Swp.\<F3>\<F5>\<BS>\<ESC>", 'tx')
4492  call assert_equal("wp.fobar", g:line)
4493  call assert_equal(4, g:col)
4494  call assert_equal("wp.", getline('.'))
4495
4496  %delete _
4497  let &l:undolevels = &l:undolevels
4498  normal! ifoo
4499  let &l:undolevels = &l:undolevels
4500  normal! obar
4501  let &l:undolevels = &l:undolevels
4502  normal! obaz
4503  let &l:undolevels = &l:undolevels
4504
4505  func CheckUndo()
4506    let g:errmsg = ''
4507    call assert_equal(['foo', 'bar', 'baz'], getline(1, '$'))
4508    undo
4509    call assert_equal(['foo', 'bar'], getline(1, '$'))
4510    undo
4511    call assert_equal(['foo'], getline(1, '$'))
4512    undo
4513    call assert_equal([''], getline(1, '$'))
4514    later 3
4515    call assert_equal(['foo', 'bar', 'baz'], getline(1, '$'))
4516    call assert_equal('', v:errmsg)
4517  endfunc
4518
4519  " Check that switching buffer with "preinsert" doesn't corrupt undo.
4520  new
4521  setlocal bufhidden=wipe
4522  inoremap <buffer> <F2> <Cmd>enew!<CR>
4523  call feedkeys("i\<C-X>\<C-O>\<F2>\<Esc>", 'tx')
4524  bwipe!
4525  call CheckUndo()
4526
4527  " Check that closing window with "preinsert" doesn't corrupt undo.
4528  new
4529  setlocal bufhidden=wipe
4530  inoremap <buffer> <F2> <Cmd>close!<CR>
4531  call feedkeys("i\<C-X>\<C-O>\<F2>\<Esc>", 'tx')
4532  call CheckUndo()
4533
4534  %delete _
4535  delfunc CheckUndo
4536
4537  bw!
4538  set cot&
4539  set omnifunc&
4540  delfunc Omni_test
4541endfunc
4542
4543func Test_autocomplete_completeopt_preinsert()
4544  func Omni_test(findstart, base)
4545    if a:findstart
4546      return col(".") - 1
4547    endif
4548    return [#{word: "fobar"}, #{word: "foobar"}]
4549  endfunc
4550  set omnifunc=Omni_test complete+=o
4551  set completeopt=preinsert autocomplete
4552  func GetLine()
4553    let g:line = getline('.')
4554    let g:col = col('.')
4555  endfunc
4556
4557  call Ntest_override("char_avail", 1)
4558  new
4559  inoremap <buffer><F5> <C-R>=GetLine()<CR>
4560  call feedkeys("Sfo\<F5>\<ESC>", 'tx')
4561  call assert_equal("fobar", g:line)
4562  call assert_equal(3, g:col)
4563
4564  call feedkeys("Sfoo\<F5>\<ESC>", 'tx')
4565  call assert_equal("foobar", g:line)
4566
4567  call feedkeys("Sfoo\<BS>\<BS>\<BS>", 'tx')
4568  call assert_equal("", getline('.'))
4569
4570  " delete a character
4571  call feedkeys("Sfoo\<BS>b\<F5>\<ESC>", 'tx')
4572  call assert_equal("fobar", g:line)
4573  call assert_equal(4, g:col)
4574
4575  set complete&
4576  %d
4577  call setline(1, ['fobar', 'foobar'])
4578
4579  call feedkeys("Gofoo\<BS>\<BS>\<F5>\<ESC>", 'tx')
4580  call assert_equal("fobar", g:line)
4581  call assert_equal(2, g:col)
4582
4583  call feedkeys("Shello   wo\<Left>\<Left>\<Left>f\<F5>\<ESC>", 'tx')
4584  call assert_equal("hello  fobar wo", g:line)
4585  call assert_equal(9, g:col)
4586
4587  call feedkeys("Shello   wo\<Left>\<Left>\<Left>f\<BS>\<F5>\<ESC>", 'tx')
4588  call assert_equal("hello   wo", g:line)
4589  call assert_equal(8, g:col)
4590
4591  call feedkeys("Shello   wo\<Left>\<Left>\<Left>foo\<F5>\<ESC>", 'tx')
4592  call assert_equal("hello  foobar wo", g:line)
4593  call assert_equal(11, g:col)
4594
4595  call feedkeys("Shello   wo\<Left>\<Left>\<Left>foo\<BS>b\<F5>\<ESC>", 'tx')
4596  call assert_equal("hello  fobar wo", g:line)
4597  call assert_equal(11, g:col)
4598
4599  " confirm
4600  call feedkeys("Sf\<C-Y>", 'tx')
4601  call assert_equal("fobar", getline('.'))
4602  call assert_equal(5, col('.'))
4603
4604  " cancel
4605  call feedkeys("Sfo\<C-E>", 'tx')
4606  call assert_equal("fo", getline('.'))
4607  call assert_equal(2, col('.'))
4608
4609  " delete preinsert part
4610  call feedkeys("Sfo ", 'tx')
4611  call assert_equal("fo ", getline('.'))
4612  call assert_equal(3, col('.'))
4613
4614  " can not work with fuzzy
4615  set cot+=fuzzy
4616  call feedkeys("Sf", 'tx')
4617  call assert_equal("f", getline('.'))
4618  set cot-=fuzzy
4619
4620  " does not work with 'ignorecase' unless 'infercase' is also enabled
4621  %d
4622  call setline(1, ['FIX', 'fobar', 'foobar'])
4623  set ignorecase
4624  call feedkeys("Gof\<F5>\<ESC>", 'tx')
4625  call assert_equal("f", g:line)  " should not produce 'FIX'
4626  set infercase
4627  call feedkeys("Gof\<F5>\<ESC>", 'tx')
4628  call assert_equal("fix", g:line)
4629  set ignorecase& infercase&
4630
4631  %delete _
4632  let &l:undolevels = &l:undolevels
4633  normal! ifoo
4634  let &l:undolevels = &l:undolevels
4635  normal! obar
4636  let &l:undolevels = &l:undolevels
4637  normal! obaz
4638  let &l:undolevels = &l:undolevels
4639
4640  func CheckUndo()
4641    let g:errmsg = ''
4642    call assert_equal(['foo', 'bar', 'baz'], getline(1, '$'))
4643    undo
4644    call assert_equal(['foo', 'bar'], getline(1, '$'))
4645    undo
4646    call assert_equal(['foo'], getline(1, '$'))
4647    undo
4648    call assert_equal([''], getline(1, '$'))
4649    later 3
4650    call assert_equal(['foo', 'bar', 'baz'], getline(1, '$'))
4651    call assert_equal('', v:errmsg)
4652  endfunc
4653
4654  " Check that switching buffer with "preinsert" doesn't corrupt undo.
4655  new
4656  setlocal bufhidden=wipe
4657  inoremap <buffer> <F2> <Cmd>enew!<CR>
4658  call feedkeys("if\<F2>\<Esc>", 'tx')
4659  bwipe!
4660  call CheckUndo()
4661
4662  " Check that closing window with "preinsert" doesn't corrupt undo.
4663  new
4664  setlocal bufhidden=wipe
4665  inoremap <buffer> <F2> <Cmd>close!<CR>
4666  call feedkeys("if\<F2>\<Esc>", 'tx')
4667  call CheckUndo()
4668
4669  %delete _
4670  delfunc CheckUndo
4671
4672  bw!
4673  set cot&
4674  set omnifunc&
4675  set autocomplete&
4676  call Ntest_override("char_avail", 0)
4677  delfunc Omni_test
4678  delfunc GetLine
4679endfunc
4680
4681" Check that mark positions are correct after triggering multiline completion.
4682func Test_complete_multiline_marks()
4683  func Omni_test(findstart, base)
4684    if a:findstart
4685      return col(".")
4686    endif
4687    return [
4688          \ #{word: "func ()\n\t\nend"},
4689          \ #{word: "foobar"},
4690          \ #{word: "你好\n\t\n我好"}
4691          \ ]
4692  endfunc
4693  set omnifunc=Omni_test
4694
4695  new
4696  let lines = mapnew(range(10), 'string(v:val)')
4697  call setline(1, lines)
4698  call setpos("'a", [0, 3, 1, 0])
4699
4700  call feedkeys("A \<C-X>\<C-O>\<C-E>\<BS>", 'tx')
4701  call assert_equal(lines, getline(1, '$'))
4702  call assert_equal([0, 3, 1, 0], getpos("'a"))
4703
4704  call feedkeys("A \<C-X>\<C-O>\<C-N>\<C-E>\<BS>", 'tx')
4705  call assert_equal(lines, getline(1, '$'))
4706  call assert_equal([0, 3, 1, 0], getpos("'a"))
4707
4708  call feedkeys("A \<C-X>\<C-O>\<C-N>\<C-N>\<C-E>\<BS>", 'tx')
4709  call assert_equal(lines, getline(1, '$'))
4710  call assert_equal([0, 3, 1, 0], getpos("'a"))
4711
4712  call feedkeys("A \<C-X>\<C-O>\<C-N>\<C-N>\<C-N>\<C-E>\<BS>", 'tx')
4713  call assert_equal(lines, getline(1, '$'))
4714  call assert_equal([0, 3, 1, 0], getpos("'a"))
4715
4716  call feedkeys("A \<C-X>\<C-O>\<C-Y>", 'tx')
4717  call assert_equal(['0 func ()', "\t", 'end'] + lines[1:], getline(1, '$'))
4718  call assert_equal([0, 5, 1, 0], getpos("'a"))
4719
4720  bw!
4721  set omnifunc&
4722  delfunc Omni_test
4723endfunc
4724
4725func Test_complete_match_count()
4726  func! PrintMenuWords()
4727    let info = complete_info(["selected", "matches"])
4728    call map(info.matches, {_, v -> v.word})
4729    return info
4730  endfunc
4731
4732  new
4733  set cpt=.^0,w
4734  call setline(1, ["fo", "foo", "foobar", "fobarbaz"])
4735  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4736  call assert_equal('fo{''matches'': [''fo'', ''foo'', ''foobar'', ''fobarbaz''], ''selected'': 0}', getline(5))
4737  5d
4738  set cpt=.^0,w
4739  exe "normal! Gof\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4740  call assert_equal('fobarbaz{''matches'': [''fo'', ''foo'', ''foobar'', ''fobarbaz''], ''selected'': 3}', getline(5))
4741  5d
4742  set cpt=.^1,w
4743  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4744  call assert_equal('fo{''matches'': [''fo''], ''selected'': 0}', getline(5))
4745  5d
4746  " max_matches is ignored for backward search
4747  exe "normal! Gof\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4748  call assert_equal('fobarbaz{''matches'': [''fo'', ''foo'', ''foobar'', ''fobarbaz''], ''selected'': 3}', getline(5))
4749  5d
4750  set cpt=.^2,w
4751  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4752  call assert_equal('fo{''matches'': [''fo'', ''foo''], ''selected'': 0}', getline(5))
4753  5d
4754  set cot=menuone,noselect
4755  set cpt=.^1,w
4756  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4757  call assert_equal('f{''matches'': [''fo''], ''selected'': -1}', getline(5))
4758  " With non-matching items
4759  %d
4760  call setline(1, ["free", "freebar", "foo", "fobarbaz"])
4761  set cpt=.^2,w
4762  exe "normal! Gofo\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4763  call assert_equal('fo{''matches'': [''foo'', ''fobarbaz''], ''selected'': -1}', getline(5))
4764  set cot&
4765
4766  func ComplFunc(findstart, base)
4767    if a:findstart
4768      return col(".")
4769    endif
4770    return ["foo1", "foo2", "foo3", "foo4"]
4771  endfunc
4772
4773  %d
4774  set completefunc=ComplFunc
4775  set cpt=.^1,F^2
4776  call setline(1, ["fo", "foo", "foobar", "fobarbaz"])
4777  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4778  call assert_equal('fo{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 0}', getline(5))
4779  5d
4780  set cpt=.^1,,,F^2,,,
4781  call setline(1, ["fo", "foo", "foobar", "fobarbaz"])
4782  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4783  call assert_equal('fo{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 0}', getline(5))
4784  5d
4785  exe "normal! Gof\<c-n>\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4786  call assert_equal('foo1{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 1}', getline(5))
4787  5d
4788  exe "normal! Gof\<c-n>\<c-n>\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4789  call assert_equal('foo2{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 2}', getline(5))
4790  5d
4791  exe "normal! Gof\<c-n>\<c-n>\<c-n>\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4792  call assert_equal('f{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': -1}', getline(5))
4793  5d
4794  exe "normal! Gof\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4795  call assert_equal('fo{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 0}', getline(5))
4796
4797  5d
4798  exe "normal! Gof\<c-n>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4799  call assert_equal('f{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': -1}', getline(5))
4800  5d
4801  exe "normal! Gof\<c-n>\<c-p>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4802  call assert_equal('foo2{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 2}', getline(5))
4803  5d
4804  exe "normal! Gof\<c-n>\<c-p>\<c-p>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4805  call assert_equal('foo1{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 1}', getline(5))
4806  5d
4807  exe "normal! Gof\<c-n>\<c-p>\<c-p>\<c-p>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4808  call assert_equal('fo{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': 0}', getline(5))
4809  5d
4810  exe "normal! Gof\<c-n>\<c-p>\<c-p>\<c-p>\<c-p>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4811  call assert_equal('f{''matches'': [''fo'', ''foo1'', ''foo2''], ''selected'': -1}', getline(5))
4812
4813  %d
4814  call setline(1, ["foo"])
4815  set cpt=FComplFunc^2,.
4816  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4817  call assert_equal('foo1{''matches'': [''foo1'', ''foo2'', ''foo''], ''selected'': 0}', getline(2))
4818  bw!
4819
4820  " Test refresh:always with max_items
4821  let g:CallCount = 0
4822  func! CompleteItemsSelect(findstart, base)
4823    if a:findstart
4824      return col('.') - 1
4825    endif
4826    let g:CallCount += 1
4827    let res = [[], ['foobar'], ['foo1', 'foo2', 'foo3'], ['foo4', 'foo5', 'foo6']]
4828    return #{words: res[g:CallCount], refresh: 'always'}
4829  endfunc
4830
4831  new
4832  set complete=.,Ffunction('CompleteItemsSelect')^2
4833  call setline(1, "foobarbar")
4834  let g:CallCount = 0
4835  exe "normal! Gof\<c-n>\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4836  call assert_equal('foobar{''matches'': [''foobarbar'', ''foobar''], ''selected'': 1}', getline(2))
4837  call assert_equal(1, g:CallCount)
4838  %d
4839  call setline(1, "foobarbar")
4840  let g:CallCount = 0
4841  exe "normal! Gof\<c-n>\<c-p>o\<c-r>=PrintMenuWords()\<cr>"
4842  call assert_equal('fo{''matches'': [''foobarbar'', ''foo1'', ''foo2''], ''selected'': -1}', getline(2))
4843  call assert_equal(2, g:CallCount)
4844  %d
4845  call setline(1, "foobarbar")
4846  let g:CallCount = 0
4847  exe "normal! Gof\<c-n>\<c-p>o\<bs>\<c-r>=PrintMenuWords()\<cr>"
4848  call assert_equal('f{''matches'': [''foobarbar'', ''foo4'', ''foo5''], ''selected'': -1}', getline(2))
4849  call assert_equal(3, g:CallCount)
4850  bw!
4851
4852  " Test 'fuzzy' with max_items
4853  new
4854  set completeopt=menu,noselect,fuzzy
4855  set complete=.
4856  call setline(1, ["abcd", "abac", "abdc"])
4857  exe "normal! Goa\<c-n>c\<c-r>=PrintMenuWords()\<cr>"
4858  call assert_equal('ac{''matches'': [''abac'', ''abcd'', ''abdc''], ''selected'': -1}', getline(4))
4859  exe "normal! Sa\<c-n>c\<c-n>\<c-n>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4860  call assert_equal('abac{''matches'': [''abac'', ''abcd'', ''abdc''], ''selected'': 0}', getline(4))
4861  execute "normal Sa\<c-n>c\<c-n>"
4862  call assert_equal('abac', getline(4))
4863  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>"
4864  call assert_equal('abac', getline(4))
4865  set complete=.^1
4866  exe "normal! Sa\<c-n>c\<c-n>\<c-n>\<c-p>\<c-r>=PrintMenuWords()\<cr>"
4867  call assert_equal('abac{''matches'': [''abac''], ''selected'': 0}', getline(4))
4868  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>"
4869  call assert_equal('abac', getline(4))
4870  set complete=.^2
4871  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>\<c-n>"
4872  call assert_equal('abac', getline(4))
4873  set complete=.^3
4874  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>"
4875  call assert_equal('abac', getline(4))
4876  set complete=.^4
4877  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>"
4878  call assert_equal('abac', getline(4))
4879
4880  func! ComplFunc(findstart, base)
4881    if a:findstart
4882      return col(".")
4883    endif
4884    return ["abcde", "abacr"]
4885  endfunc
4886
4887  set complete=.,FComplFunc^1
4888  execute "normal Sa\<c-n>c\<c-n>\<c-n>"
4889  call assert_equal('abacr', getline(4))
4890  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>"
4891  call assert_equal('abac', getline(4))
4892  set complete=.^1,FComplFunc^1
4893  execute "normal Sa\<c-n>c\<c-n>\<c-n>\<c-n>\<c-n>"
4894  call assert_equal('abac', getline(4))
4895  bw!
4896
4897  " Items with '\n' that cause menu to shift, with no leader (issue #17394)
4898  func! ComplFunc(findstart, base)
4899    if a:findstart == 1
4900      return col('.')  - 1
4901    endif
4902    return ["one\ntwo\nthree", "four five six", "hello\nworld\nhere"]
4903  endfunc
4904  set completeopt=menuone,popup,noselect,fuzzy infercase
4905  set complete=.^1,FComplFunc^5
4906  new
4907  call setline(1, ["foo", "bar", "baz"])
4908  execute "normal Go\<c-n>\<c-n>\<c-n>"
4909  call assert_equal(['one', 'two', 'three'], getline(4, 6))
4910  %d
4911  call setline(1, ["foo", "bar", "baz"])
4912  execute "normal Go\<c-n>\<c-n>\<c-n>\<c-p>"
4913  call assert_equal('foo', getline(4))
4914  execute "normal S\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>"
4915  call assert_equal('foo', getline(4))
4916  set complete=.^1,FComplFunc^2
4917  execute "normal S\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>"
4918  call assert_equal('foo', getline(4))
4919  execute "normal S\<c-n>\<c-p>\<c-p>\<c-p>\<c-n>\<c-n>"
4920  call assert_equal('four five six', getline(4))
4921  bw!
4922
4923  set completeopt& complete& infercase&
4924  delfunc PrintMenuWords
4925  delfunc ComplFunc
4926  delfunc CompleteItemsSelect
4927endfunc
4928
4929func Test_complete_append_selected_match_default()
4930  " when typing a normal character during completion,
4931  " completion is ended, see
4932  " :h popupmenu-completion ("There are three states:")
4933  func PrintMenuWords()
4934    let info = complete_info(["selected", "matches"])
4935    call map(info.matches, {_, v -> v.word})
4936    return info
4937  endfunc
4938
4939  new
4940  call setline(1, ["fo", "foo", "foobar", "fobarbaz"])
4941  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
4942  call assert_equal('fo{''matches'': [''fo'', ''foo'', ''foobar'', ''fobarbaz''], ''selected'': 0}', getline(5))
4943  %d
4944  call setline(1, ["fo", "foo", "foobar", "fobarbaz"])
4945  exe "normal! Gof\<c-n>o\<c-r>=PrintMenuWords()\<cr>"
4946  call assert_equal('foo{''matches'': [], ''selected'': -1}', getline(5))
4947  %d
4948  set completeopt=menu,noselect
4949  call setline(1, ["fo", "foo", "foobar", "fobarbaz"])
4950  exe "normal! Gof\<c-n>\<c-n>o\<c-r>=PrintMenuWords()\<cr>"
4951  call assert_equal('foo{''matches'': [], ''selected'': -1}', getline(5))
4952  bw!
4953
4954  set completeopt&
4955  delfunc PrintMenuWords
4956endfunc
4957
4958" Test normal mode (^N/^P/^X^N/^X^P) with smartcase when 1) matches are first
4959" found and 2) matches are filtered (when a character is typed).
4960func Test_smartcase_normal_mode()
4961
4962  func! PrintMenu()
4963    let info = complete_info(["matches"])
4964    call map(info.matches, {_, v -> v.word})
4965    return info
4966  endfunc
4967
4968  func! TestInner(key)
4969    let pr = "\<c-r>=PrintMenu()\<cr>"
4970
4971    new
4972    set completeopt=menuone,noselect ignorecase smartcase
4973    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
4974    exe $"normal! ggOF{a:key}{pr}"
4975    call assert_equal('F{''matches'': [''Fast'', ''FAST'', ''False'',
4976          \ ''FALSE'']}', getline(1))
4977    %d
4978    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
4979    exe $"normal! ggOF{a:key}a{pr}"
4980    call assert_equal('Fa{''matches'': [''Fast'', ''False'']}', getline(1))
4981    %d
4982    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
4983    exe $"normal! ggOF{a:key}a\<bs>{pr}"
4984    call assert_equal('F{''matches'': [''Fast'', ''FAST'', ''False'',
4985          \ ''FALSE'']}', getline(1))
4986    %d
4987    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
4988    exe $"normal! ggOF{a:key}ax{pr}"
4989    call assert_equal('Fax{''matches'': []}', getline(1))
4990    %d
4991    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
4992    exe $"normal! ggOF{a:key}ax\<bs>{pr}"
4993    call assert_equal('Fa{''matches'': [''Fast'', ''False'']}', getline(1))
4994
4995    %d
4996    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
4997    exe $"normal! ggOF{a:key}A{pr}"
4998    call assert_equal('FA{''matches'': [''FAST'', ''FALSE'']}', getline(1))
4999    %d
5000    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
5001    exe $"normal! ggOF{a:key}A\<bs>{pr}"
5002    call assert_equal('F{''matches'': [''Fast'', ''FAST'', ''False'',
5003          \ ''FALSE'']}', getline(1))
5004    %d
5005    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
5006    exe $"normal! ggOF{a:key}AL{pr}"
5007    call assert_equal('FAL{''matches'': [''FALSE'']}', getline(1))
5008    %d
5009    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
5010    exe $"normal! ggOF{a:key}ALx{pr}"
5011    call assert_equal('FALx{''matches'': []}', getline(1))
5012    %d
5013    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
5014    exe $"normal! ggOF{a:key}ALx\<bs>{pr}"
5015    call assert_equal('FAL{''matches'': [''FALSE'']}', getline(1))
5016
5017    %d
5018    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
5019    exe $"normal! ggOf{a:key}{pr}"
5020    call assert_equal('f{''matches'': [''Fast'', ''FAST'', ''False'', ''FALSE'',
5021          \ ''fast'', ''false'']}', getline(1))
5022    %d
5023    call setline(1, ["Fast", "FAST", "False", "FALSE", "fast", "false"])
5024    exe $"normal! ggOf{a:key}a{pr}"
5025    call assert_equal('fa{''matches'': [''Fast'', ''FAST'', ''False'', ''FALSE'',
5026          \ ''fast'', ''false'']}', getline(1))
5027
5028    %d
5029    exe $"normal! ggOf{a:key}{pr}"
5030    call assert_equal('f{''matches'': []}', getline(1))
5031    exe $"normal! ggOf{a:key}a\<bs>{pr}"
5032    call assert_equal('f{''matches'': []}', getline(1))
5033    set ignorecase& smartcase& completeopt&
5034    bw!
5035  endfunc
5036
5037  call TestInner("\<c-n>")
5038  call TestInner("\<c-p>")
5039  call TestInner("\<c-x>\<c-n>")
5040  call TestInner("\<c-x>\<c-p>")
5041  delfunc PrintMenu
5042  delfunc TestInner
5043endfunc
5044
5045" Test 'nearest' flag of 'completeopt'
5046func Test_nearest_cpt_option()
5047
5048  func! PrintMenuWords()
5049    let info = complete_info(["selected", "matches"])
5050    call map(info.matches, {_, v -> v.word})
5051    return info
5052  endfunc
5053
5054  new
5055  set completeopt+=nearest
5056  call setline(1, ["fo", "foo", "foobar"])
5057  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5058  call assert_equal('foobar{''matches'': [''foobar'', ''foo'', ''fo''], ''selected'': 0}', getline(4))
5059  %d
5060  call setline(1, ["fo", "foo", "foobar"])
5061  exe "normal! Of\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5062  call assert_equal('foobar{''matches'': [''fo'', ''foo'', ''foobar''], ''selected'': 2}', getline(1))
5063  %d
5064
5065  set completeopt=menu,noselect,nearest
5066  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5067  exe "normal! Gof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5068  call assert_equal('f{''matches'': [''foobarbaz'', ''foobar'', ''foo'', ''fo''], ''selected'': -1}', getline(5))
5069  %d
5070  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5071  exe "normal! Gof\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5072  call assert_equal('f{''matches'': [''foobarbaz'', ''foobar'', ''foo'', ''fo''], ''selected'': -1}', getline(5))
5073  %d
5074  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5075  exe "normal! Of\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5076  call assert_equal('f{''matches'': [''fo'', ''foo'', ''foobar'', ''foobarbaz''], ''selected'': -1}', getline(1))
5077  %d
5078  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5079  exe "normal! Of\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5080  call assert_equal('f{''matches'': [''fo'', ''foo'', ''foobar'', ''foobarbaz''], ''selected'': -1}', getline(1))
5081  %d
5082  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5083  exe "normal! of\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5084  call assert_equal('f{''matches'': [''foo'', ''fo'', ''foobar'', ''foobarbaz''], ''selected'': -1}', getline(2))
5085  %d
5086  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5087  exe "normal! of\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5088  call assert_equal('f{''matches'': [''foo'', ''fo'', ''foobar'', ''foobarbaz''], ''selected'': -1}', getline(2))
5089  %d
5090  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5091  exe "normal! jof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5092  call assert_equal('f{''matches'': [''foobar'', ''foo'', ''foobarbaz'', ''fo''], ''selected'': -1}', getline(3))
5093  %d
5094  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5095  exe "normal! jof\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5096  call assert_equal('f{''matches'': [''foobar'', ''foo'', ''foobarbaz'', ''fo''], ''selected'': -1}', getline(3))
5097  %d
5098  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5099  exe "normal! 2jof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5100  call assert_equal('f{''matches'': [''foobarbaz'', ''foobar'', ''foo'', ''fo''], ''selected'': -1}', getline(4))
5101  %d
5102  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5103  exe "normal! 2jof\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5104  call assert_equal('f{''matches'': [''foobarbaz'', ''foobar'', ''foo'', ''fo''], ''selected'': -1}', getline(4))
5105
5106  %d
5107  set completeopt=menuone,noselect,nearest
5108  call setline(1, "foo")
5109  exe "normal! Of\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5110  call assert_equal('f{''matches'': [''foo''], ''selected'': -1}', getline(1))
5111  %d
5112  call setline(1, "foo")
5113  exe "normal! o\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5114  call assert_equal('{''matches'': [''foo''], ''selected'': -1}', getline(2))
5115  %d
5116  exe "normal! o\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5117  call assert_equal('', getline(1))
5118  %d
5119  exe "normal! o\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5120  call assert_equal('', getline(1))
5121
5122  " Reposition match: node is at tail but score is too small
5123  %d
5124  call setline(1, ["foo1", "bar1", "bar2", "foo2", "foo1"])
5125  exe "normal! of\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5126  call assert_equal('f{''matches'': [''foo1'', ''foo2''], ''selected'': -1}', getline(2))
5127  " Reposition match: node is in middle but score is too big
5128  %d
5129  call setline(1, ["foo1", "bar1", "bar2", "foo3", "foo1", "foo2"])
5130  exe "normal! of\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5131  call assert_equal('f{''matches'': [''foo1'', ''foo3'', ''foo2''], ''selected'': -1}', getline(2))
5132
5133  " Multiple sources
5134  func F1(findstart, base)
5135    if a:findstart
5136      return col('.') - 1
5137    endif
5138    return ['foo4', 'foo5']
5139  endfunc
5140  %d
5141  set complete+=FF1
5142  call setline(1, ["foo1", "foo2", "bar1", "foo3"])
5143  exe "normal! 2jof\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5144  call assert_equal('f{''matches'': [''foo3'', ''foo2'', ''foo1'', ''foo4'', ''foo5''],
5145        \ ''selected'': -1}', getline(4))
5146  set complete-=FF1
5147  delfunc F1
5148
5149  set completeopt=menu,longest,nearest
5150  %d
5151  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5152  exe "normal! of\<c-n>\<c-r>=PrintMenuWords()\<cr>"
5153  call assert_equal('fo{''matches'': [''foo'', ''fo'', ''foobar'', ''foobarbaz''], ''selected'': -1}', getline(2))
5154  %d
5155  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5156  exe "normal! 2jof\<c-p>\<c-r>=PrintMenuWords()\<cr>"
5157  call assert_equal('fo{''matches'': [''foobarbaz'', ''foobar'', ''foo'', ''fo''], ''selected'': -1}', getline(4))
5158  bw!
5159
5160  set completeopt&
5161  delfunc PrintMenuWords
5162endfunc
5163
5164func Test_register_completion()
5165  let @a = "completion test apple application"
5166  let @b = "banana behavior better best"
5167  let @c = "complete completion compliment computer"
5168  let g:save_reg = ''
5169  func GetItems()
5170    let g:result = complete_info(['pum_visible'])
5171  endfunc
5172
5173  new
5174  call setline(1, "comp")
5175  call cursor(1, 4)
5176  call feedkeys("a\<C-X>\<C-R>\<C-N>\<C-N>\<Esc>", 'tx')
5177  call assert_equal("compliment", getline(1))
5178
5179  inoremap <buffer><F2> <C-R>=GetItems()<CR>
5180  call feedkeys("S\<C-X>\<C-R>\<F2>\<ESC>", 'tx')
5181  call assert_equal(1, g:result['pum_visible'])
5182
5183  call setline(1, "app")
5184  call cursor(1, 3)
5185  call feedkeys("a\<C-X>\<C-R>\<C-N>\<Esc>", 'tx')
5186  call assert_equal("application", getline(1))
5187
5188  " Test completion with case differences
5189  set ignorecase
5190  let @e = "TestCase UPPERCASE lowercase"
5191  call setline(1, "testc")
5192  call cursor(1, 5)
5193  call feedkeys("a\<C-X>\<C-R>\<Esc>", 'tx')
5194  call assert_equal("TestCase", getline(1))
5195
5196  " Test clipboard registers if available
5197  if has('clipboard_working')
5198    let g:save_reg = getreg('*')
5199    call setreg('*', "clipboard selection unique words")
5200    call setline(1, "uni")
5201    call cursor(1, 3)
5202    call feedkeys("a\<C-X>\<C-R>\<Esc>", 'tx')
5203    call assert_equal("unique", getline(1))
5204    call setreg('*', g:save_reg)
5205
5206    let g:save_reg = getreg('+')
5207    call setreg('+', "system clipboard special content")
5208    call setline(1, "spe")
5209    call cursor(1, 3)
5210    call feedkeys("a\<C-X>\<C-R>\<Esc>", 'tx')
5211    call assert_equal("special", getline(1))
5212    call setreg('+', g:save_reg)
5213
5214    call setreg('*', g:save_reg)
5215    call setreg('a', "normal register")
5216    call setreg('*', "clipboard mixed content")
5217    call setline(1, "mix")
5218    call cursor(1, 3)
5219    call feedkeys("a\<C-X>\<C-R>\<Esc>", 'tx')
5220    call assert_equal("mixed", getline(1))
5221    call setreg('*', g:save_reg)
5222  endif
5223
5224  " Test black hole register should be skipped
5225  let @_ = "blackhole content should not appear"
5226  call setline(1, "black")
5227  call cursor(1, 5)
5228  call feedkeys("a\<C-X>\<C-R>\<Esc>", 'tx')
5229  call assert_equal("black", getline(1))
5230
5231  let @1 = "recent yank zero"
5232  call setline(1, "ze")
5233  call cursor(1, 2)
5234  call feedkeys("a\<C-X>\<C-R>\<Esc>", 'tx')
5235  call assert_equal("zero", getline(1))
5236
5237  call feedkeys("Sze\<C-X>\<C-R>\<C-R>=string(complete_info(['mode']))\<CR>\<ESC>", "tx")
5238  call assert_equal("zero{'mode': 'register'}", getline(1))
5239
5240  " Test consecutive CTRL-X CTRL-R (adding mode)
5241  " First CTRL-X CTRL-R should split into words, second should use full content
5242  let @f = "hello world test complete"
5243  call setline(1, "hel")
5244  call cursor(1, 3)
5245  call feedkeys("a\<C-X>\<C-R>\<C-N>\<Esc>", 'tx')
5246  call assert_equal("hello", getline(1))
5247
5248  " Second consecutive CTRL-X CTRL-R should complete with full content
5249  call setline(1, "hello")
5250  call cursor(1, 5)
5251  call feedkeys("a\<C-X>\<C-R>\<C-X>\<C-R>\<Esc>", 'tx')
5252  call assert_equal("hello world test complete", getline(1))
5253
5254  " Test consecutive completion with multi-line register
5255  let @g = "first line content\nsecond line here\nthird line data"
5256  call setline(1, "first")
5257  call cursor(1, 5)
5258  call feedkeys("a\<C-X>\<C-R>\<C-X>\<C-R>\<Esc>", 'tx')
5259  call assert_equal("first line content", getline(1))
5260
5261  " Clean up
5262  bwipe!
5263  delfunc GetItems
5264  unlet g:result
5265  unlet g:save_reg
5266  set ignorecase&
5267endfunc
5268
5269" Test refresh:always with unloaded buffers (issue #17363)
5270func Test_complete_unloaded_buf_refresh_always()
5271  func TestComplete(findstart, base)
5272    if a:findstart
5273      let line = getline('.')
5274      let start = col('.') - 1
5275      while start > 0 && line[start - 1] =~ '\a'
5276        let start -= 1
5277      endwhile
5278      return start
5279    else
5280      let g:CallCount += 1
5281      let res = ["update1", "update12", "update123"]
5282      return #{words: res, refresh: 'always'}
5283    endif
5284  endfunc
5285
5286  let g:CallCount = 0
5287  set completeopt=menu,longest
5288  set completefunc=TestComplete
5289  set complete=b,u,t,i,F
5290  badd foo1
5291  badd foo2
5292  new
5293  exe "normal! iup\<C-N>\<BS>\<BS>\<BS>\<BS>\<BS>"
5294  call assert_equal('up', getline(1))
5295  call assert_equal(6, g:CallCount)
5296
5297  bd! foo1
5298  bd! foo2
5299  bw!
5300  set completeopt&
5301  set complete&
5302  set completefunc&
5303  delfunc TestComplete
5304endfunc
5305
5306" Verify that the order of matches from each source is consistent
5307" during both ^N and ^P completions (Issue #17425).
5308func Test_complete_with_multiple_function_sources()
5309  func F1(findstart, base)
5310    if a:findstart
5311      return col('.') - 1
5312    endif
5313    return ['one', 'two', 'three']
5314  endfunc
5315
5316  func F2(findstart, base)
5317    if a:findstart
5318      return col('.') - 1
5319    endif
5320    return ['four', 'five', 'six']
5321  endfunc
5322
5323  func F3(findstart, base)
5324    if a:findstart
5325      return col('.') - 1
5326    endif
5327    return ['seven', 'eight', 'nine']
5328  endfunc
5329
5330  new
5331  setlocal complete=.,FF1,FF2,FF3
5332  inoremap <buffer> <F2> <Cmd>let b:matches = complete_info(["matches"]).matches<CR>
5333  call setline(1, ['xxx', 'yyy', 'zzz', ''])
5334
5335  call feedkeys("GS\<C-N>\<F2>\<Esc>0", 'tx!')
5336  call assert_equal([
5337        \ 'xxx', 'yyy', 'zzz',
5338        \ 'one', 'two', 'three',
5339        \ 'four', 'five', 'six',
5340        \ 'seven', 'eight', 'nine',
5341        \ ], b:matches->mapnew('v:val.word'))
5342
5343  call feedkeys("GS\<C-P>\<F2>\<Esc>0", 'tx!')
5344  call assert_equal([
5345        \ 'seven', 'eight', 'nine',
5346        \ 'four', 'five', 'six',
5347        \ 'one', 'two', 'three',
5348        \ 'xxx', 'yyy', 'zzz',
5349        \ ], b:matches->mapnew('v:val.word'))
5350
5351  %delete
5352
5353  call feedkeys("GS\<C-N>\<F2>\<Esc>0", 'tx!')
5354  call assert_equal([
5355        \ 'one', 'two', 'three',
5356        \ 'four', 'five', 'six',
5357        \ 'seven', 'eight', 'nine',
5358        \ ], b:matches->mapnew('v:val.word'))
5359
5360  call feedkeys("GS\<C-P>\<F2>\<Esc>0", 'tx!')
5361  call assert_equal([
5362        \ 'seven', 'eight', 'nine',
5363        \ 'four', 'five', 'six',
5364        \ 'one', 'two', 'three',
5365        \ ], b:matches->mapnew('v:val.word'))
5366
5367  bwipe!
5368  delfunc F1
5369  delfunc F2
5370  delfunc F3
5371endfunc
5372
5373func Test_complete_fuzzy_omnifunc_backspace()
5374  let g:do_complete = v:false
5375  func Omni_test(findstart, base)
5376    if a:findstart
5377      let g:do_complete = !g:do_complete
5378    endif
5379    if g:do_complete
5380      return a:findstart ? 0 : [#{word: a:base .. 'def'}, #{word: a:base .. 'ghi'}]
5381    endif
5382    return a:findstart ? -3 : {}
5383  endfunc
5384
5385  new
5386  redraw  " need this to prevent NULL dereference in Nvim
5387  setlocal omnifunc=Omni_test
5388  setlocal completeopt=menuone,fuzzy,noinsert
5389  call setline(1, 'abc')
5390  call feedkeys("A\<C-X>\<C-O>\<BS>\<Esc>0", 'tx!')
5391  call assert_equal('ab', getline(1))
5392
5393  bwipe!
5394  delfunc Omni_test
5395  unlet g:do_complete
5396endfunc
5397
5398" Test that option shortmess=c turns off completion messages
5399func Test_shortmess()
5400  CheckScreendump
5401
5402  let lines =<< trim END
5403    call setline(1, ['hello', 'hullo', 'heee'])
5404  END
5405
5406  call writefile(lines, 'Xpumscript', 'D')
5407  let buf = RunVimInTerminal('-S Xpumscript', #{rows: 12})
5408  call term_sendkeys(buf, "Goh\<C-N>")
5409  call TermWait(buf, 200)
5410  call VerifyScreenDump(buf, 'Test_shortmess_complmsg_1', {})
5411  call term_sendkeys(buf, "\<ESC>:set shm+=c\<CR>")
5412  call term_sendkeys(buf, "Sh\<C-N>")
5413  call TermWait(buf, 200)
5414  call VerifyScreenDump(buf, 'Test_shortmess_complmsg_2', {})
5415
5416  call StopVimInTerminal(buf)
5417endfunc
5418
5419" Test 'complete' containing F{func} that complete from nonkeyword
5420func Test_nonkeyword_trigger()
5421
5422  " Trigger expansion even when another char is waiting in the typehead
5423  call Ntest_override("char_avail", 1)
5424
5425  let g:CallCount = 0
5426  func! NonKeywordComplete(findstart, base)
5427    let line = getline('.')->strpart(0, col('.') - 1)
5428    let nonkeyword2 = len(line) > 1 && match(line[-2:-2], '\k') != 0
5429    if a:findstart
5430      return nonkeyword2 ? col('.') - 3 : (col('.') - 2)
5431    else
5432      let g:CallCount += 1
5433      return [$"{a:base}foo", $"{a:base}bar"]
5434    endif
5435  endfunc
5436
5437  new
5438  inoremap <buffer> <F2> <Cmd>let b:matches = complete_info(["matches"]).matches<CR>
5439  inoremap <buffer> <F3> <Cmd>let b:selected = complete_info(["selected"]).selected<CR>
5440  call setline(1, ['abc', 'abcd', 'fo', 'b', ''])
5441
5442  " Test 1a: Nonkeyword before cursor lists words with at least two letters
5443  call feedkeys("GS=\<C-N>\<F2>\<Esc>0", 'tx!')
5444  call assert_equal(['abc', 'abcd', 'fo'], b:matches->mapnew('v:val.word'))
5445  call assert_equal('=abc', getline('.'))
5446
5447  " Test 1b: With F{func} nonkeyword collects matches
5448  set complete=.,FNonKeywordComplete
5449  for noselect in range(2)
5450    if noselect
5451      set completeopt+=noselect
5452    endif
5453    let g:CallCount = 0
5454    call feedkeys("S=\<C-N>\<F2>\<Esc>0", 'tx!')
5455    call assert_equal(['abc', 'abcd', 'fo', '=foo', '=bar'], b:matches->mapnew('v:val.word'))
5456    call assert_equal(1, g:CallCount)
5457    call assert_equal(noselect ? '=' : '=abc', getline('.'))
5458    let g:CallCount = 0
5459    call feedkeys("S->\<C-N>\<F2>\<Esc>0", 'tx!')
5460    call assert_equal(['abc', 'abcd', 'fo', '->foo', '->bar'], b:matches->mapnew('v:val.word'))
5461    call assert_equal(1, g:CallCount)
5462    call assert_equal(noselect ? '->' : '->abc', getline('.'))
5463    set completeopt&
5464  endfor
5465
5466  " Test 1c: Keyword collects from {func}
5467  let g:CallCount = 0
5468  call feedkeys("Sa\<C-N>\<F2>\<Esc>0", 'tx!')
5469  call assert_equal(['abc', 'abcd', 'afoo', 'abar'], b:matches->mapnew('v:val.word'))
5470  call assert_equal(1, g:CallCount)
5471  call assert_equal('abc', getline('.'))
5472
5473  set completeopt+=noselect
5474  let g:CallCount = 0
5475  call feedkeys("Sa\<C-N>\<F2>\<Esc>0", 'tx!')
5476  call assert_equal(['abc', 'abcd', 'afoo', 'abar'], b:matches->mapnew('v:val.word'))
5477  call assert_equal(1, g:CallCount)
5478  call assert_equal('a', getline('.'))
5479
5480  " Test 1d: Nonkeyword after keyword collects items again
5481  let g:CallCount = 0
5482  call feedkeys("Sa\<C-N>#\<C-N>\<F2>\<Esc>0", 'tx!')
5483  call assert_equal(['abc', 'abcd', 'fo', '#foo', '#bar'], b:matches->mapnew('v:val.word'))
5484  call assert_equal(2, g:CallCount)
5485  call assert_equal('a#', getline('.'))
5486  set completeopt&
5487
5488  " Test 2: Filter nonkeyword and keyword matches with different startpos
5489  set completeopt+=menuone,noselect
5490  call feedkeys("S#a\<C-N>b\<F2>\<F3>\<Esc>0", 'tx!')
5491  call assert_equal(['abc', 'abcd', '#abar'], b:matches->mapnew('v:val.word'))
5492  call assert_equal(-1, b:selected)
5493  call assert_equal('#ab', getline('.'))
5494
5495  set completeopt+=fuzzy
5496  call feedkeys("S#a\<C-N>b\<F2>\<F3>\<Esc>0", 'tx!')
5497  call assert_equal(['#abar', 'abc', 'abcd'], b:matches->mapnew('v:val.word'))
5498  call assert_equal(-1, b:selected)
5499  call assert_equal('#ab', getline('.'))
5500  set completeopt&
5501
5502  " Test 3: Navigate menu containing nonkeyword and keyword items
5503  call feedkeys("S->\<C-N>\<F2>\<Esc>0", 'tx!')
5504  call assert_equal(['abc', 'abcd', 'fo', '->foo', '->bar'], b:matches->mapnew('v:val.word'))
5505  call assert_equal('->abc', getline('.'))
5506  call feedkeys("S->" . repeat("\<C-N>", 3) . "\<Esc>0", 'tx!')
5507  call assert_equal('->fo', getline('.'))
5508  call feedkeys("S->" . repeat("\<C-N>", 4) . "\<Esc>0", 'tx!')
5509  call assert_equal('->foo', getline('.'))
5510  call feedkeys("S->" . repeat("\<C-N>", 4) . "\<C-P>\<Esc>0", 'tx!')
5511  call assert_equal('->fo', getline('.'))
5512  call feedkeys("S->" . repeat("\<C-N>", 5) . "\<Esc>0", 'tx!')
5513  call assert_equal('->bar', getline('.'))
5514  call feedkeys("S->" . repeat("\<C-N>", 5) . "\<C-P>\<Esc>0", 'tx!')
5515  call assert_equal('->foo', getline('.'))
5516  call feedkeys("S->" . repeat("\<C-N>", 6) . "\<Esc>0", 'tx!')
5517  call assert_equal('->', getline('.'))
5518  call feedkeys("S->" . repeat("\<C-N>", 7) . "\<Esc>0", 'tx!')
5519  call assert_equal('->abc', getline('.'))
5520  call feedkeys("S->" . repeat("\<C-P>", 7) . "\<Esc>0", 'tx!')
5521  call assert_equal('->fo', getline('.'))
5522  " Replace
5523  call feedkeys("S# x y z\<Esc>0lR\<C-N>\<Esc>0", 'tx!')
5524  call assert_equal('#abcy z', getline('.'))
5525  call feedkeys("S# x y z\<Esc>0lR" . repeat("\<C-P>", 4) . "\<Esc>0", 'tx!')
5526  call assert_equal('#bary z', getline('.'))
5527
5528  bw!
5529  call Ntest_override("char_avail", 0)
5530  delfunc NonKeywordComplete
5531  set complete&
5532  unlet g:CallCount
5533endfunc
5534
5535func Test_autocomplete_trigger()
5536  " Trigger expansion even when another char is waiting in the typehead
5537  call Ntest_override("char_avail", 1)
5538
5539  let g:CallCount = 0
5540  func! NonKeywordComplete(findstart, base)
5541    let line = getline('.')->strpart(0, col('.') - 1)
5542    let nonkeyword2 = len(line) > 1 && match(line[-2:-2], '\k') != 0
5543    if a:findstart
5544      return nonkeyword2 ? col('.') - 3 : (col('.') - 2)
5545    else
5546      let g:CallCount += 1
5547      return [$"{a:base}foo", $"{a:base}bar"]
5548    endif
5549  endfunc
5550
5551  new
5552  inoremap <buffer> <F2> <Cmd>let b:matches = complete_info(["matches"]).matches<CR>
5553  inoremap <buffer> <F3> <Cmd>let b:selected = complete_info(["matches", "selected"]).selected<CR>
5554
5555  call setline(1, ['abc', 'abcd', 'fo', 'b', ''])
5556  set autocomplete
5557
5558  " Test 1a: Nonkeyword doesn't open menu without F{func} when autocomplete
5559  call feedkeys("GS=\<F2>\<Esc>0", 'tx!')
5560  call assert_equal([], b:matches)
5561  call assert_equal('=', getline('.'))
5562  " ^N opens menu of keywords (of len > 1)
5563  call feedkeys("S=\<C-E>\<C-N>\<F2>\<Esc>0", 'tx!')
5564  call assert_equal(['abc', 'abcd', 'fo'], b:matches->mapnew('v:val.word'))
5565  call assert_equal('=abc', getline('.'))
5566
5567  " Test 1b: With F{func} nonkeyword collects matches
5568  set complete=.,FNonKeywordComplete
5569  let g:CallCount = 0
5570  call feedkeys("S=\<F2>\<Esc>0", 'tx!')
5571  call assert_equal(['=foo', '=bar'], b:matches->mapnew('v:val.word'))
5572  call assert_equal(1, g:CallCount)
5573  call assert_equal('=', getline('.'))
5574  let g:CallCount = 0
5575  call feedkeys("S->\<F2>\<Esc>0", 'tx!')
5576  call assert_equal(['->foo', '->bar'], b:matches->mapnew('v:val.word'))
5577  call assert_equal(2, g:CallCount)
5578  call assert_equal('->', getline('.'))
5579
5580  " Test 1c: Keyword after nonkeyword can collect both types of items
5581  let g:CallCount = 0
5582  call feedkeys("S#a\<F2>\<Esc>0", 'tx!')
5583  call assert_equal(['abcd', 'abc', '#afoo', '#abar'], b:matches->mapnew('v:val.word'))
5584  call assert_equal(2, g:CallCount)
5585  call assert_equal('#a', getline('.'))
5586  let g:CallCount = 0
5587  call feedkeys("S#a.\<F2>\<Esc>0", 'tx!')
5588  call assert_equal(['.foo', '.bar'], b:matches->mapnew('v:val.word'))
5589  call assert_equal(3, g:CallCount)
5590  call assert_equal('#a.', getline('.'))
5591  let g:CallCount = 0
5592  call feedkeys("S#a.a\<F2>\<Esc>0", 'tx!')
5593  call assert_equal(['abcd', 'abc', '.afoo', '.abar'], b:matches->mapnew('v:val.word'))
5594  call assert_equal(4, g:CallCount)
5595  call assert_equal('#a.a', getline('.'))
5596
5597  " Test 1d: Nonkeyword after keyword collects items again
5598  let g:CallCount = 0
5599  call feedkeys("Sa\<F2>\<Esc>0", 'tx!')
5600  call assert_equal(['abcd', 'abc', 'afoo', 'abar'], b:matches->mapnew('v:val.word'))
5601  call assert_equal(1, g:CallCount)
5602  call assert_equal('a', getline('.'))
5603  let g:CallCount = 0
5604  call feedkeys("Sa#\<F2>\<Esc>0", 'tx!')
5605  call assert_equal(['#foo', '#bar'], b:matches->mapnew('v:val.word'))
5606  call assert_equal(2, g:CallCount)
5607  call assert_equal('a#', getline('.'))
5608
5609  " Test 2: Filter nonkeyword and keyword matches with different startpos
5610  for fuzzy in range(2)
5611    if fuzzy
5612      set completeopt+=fuzzy
5613    endif
5614    call feedkeys("S#ab\<F2>\<F3>\<Esc>0", 'tx!')
5615    if fuzzy
5616      call assert_equal(['#abar', 'abc', 'abcd'], b:matches->mapnew('v:val.word'))
5617    else " Ordering of items is by 'nearest' to cursor by default
5618      call assert_equal(['abcd', 'abc', '#abar'], b:matches->mapnew('v:val.word'))
5619    endif
5620    call assert_equal(-1, b:selected)
5621    call assert_equal('#ab', getline('.'))
5622    call feedkeys("S#ab" . repeat("\<C-N>", 3) . "\<F3>\<Esc>0", 'tx!')
5623    call assert_equal(fuzzy ? '#abcd' : '#abar', getline('.'))
5624    call assert_equal(2, b:selected)
5625
5626    let g:CallCount = 0
5627    call feedkeys("GS#aba\<F2>\<Esc>0", 'tx!')
5628    call assert_equal(['#abar'], b:matches->mapnew('v:val.word'))
5629    call assert_equal(2, g:CallCount)
5630    call assert_equal('#aba', getline('.'))
5631
5632    let g:CallCount = 0
5633    call feedkeys("S#abc\<F2>\<Esc>0", 'tx!')
5634    if fuzzy
5635      call assert_equal(['abc', 'abcd'], b:matches->mapnew('v:val.word'))
5636    else
5637      call assert_equal(['abcd', 'abc'], b:matches->mapnew('v:val.word'))
5638    endif
5639    call assert_equal(2, g:CallCount)
5640    set completeopt&
5641  endfor
5642
5643  " Test 3: Navigate menu containing nonkeyword and keyword items
5644  call feedkeys("S#a\<F2>\<Esc>0", 'tx!')
5645  call assert_equal(['abcd', 'abc', '#afoo', '#abar'], b:matches->mapnew('v:val.word'))
5646  call feedkeys("S#a" . repeat("\<C-N>", 3) . "\<Esc>0", 'tx!')
5647  call assert_equal('#afoo', getline('.'))
5648  call feedkeys("S#a" . repeat("\<C-N>", 3) . "\<C-P>\<Esc>0", 'tx!')
5649  call assert_equal('#abc', getline('.'))
5650
5651  call feedkeys("S#a.a\<F2>\<Esc>0", 'tx!')
5652  call assert_equal(['abcd', 'abc', '.afoo', '.abar'], b:matches->mapnew('v:val.word'))
5653  call feedkeys("S#a.a" . repeat("\<C-N>", 2) . "\<Esc>0", 'tx!')
5654  call assert_equal('#a.abc', getline('.'))
5655  call feedkeys("S#a.a" . repeat("\<C-N>", 3) . "\<Esc>0", 'tx!')
5656  call assert_equal('#a.afoo', getline('.'))
5657  call feedkeys("S#a.a" . repeat("\<C-N>", 3) . "\<C-P>\<Esc>0", 'tx!')
5658  call assert_equal('#a.abc', getline('.'))
5659  call feedkeys("S#a.a" . repeat("\<C-P>", 6) . "\<Esc>0", 'tx!')
5660  call assert_equal('#a.abar', getline('.'))
5661
5662  " Test 4a: When autocomplete menu is active, ^X^N completes buffer keywords
5663  let g:CallCount = 0
5664  call feedkeys("S#a\<C-E>\<C-X>\<C-N>\<F2>\<Esc>0", 'tx!')
5665  call assert_equal(['abc', 'abcd'], b:matches->mapnew('v:val.word'))
5666  call assert_equal(2, g:CallCount)
5667
5668  " Test 4b: When autocomplete menu is active, ^X^O completes omnifunc
5669  let g:CallCount = 0
5670  set omnifunc=NonKeywordComplete
5671  call feedkeys("S#a\<C-X>\<C-O>\<F2>\<Esc>0", 'tx!')
5672  call assert_equal(['#afoo', '#abar'], b:matches->mapnew('v:val.word'))
5673  call assert_equal(3, g:CallCount)
5674
5675  " Test 4c: When autocomplete menu is active, ^E^N completes keyword
5676  call feedkeys("Sa\<C-E>\<F2>\<Esc>0", 'tx!')
5677  call assert_equal([], b:matches->mapnew('v:val.word'))
5678  let g:CallCount = 0
5679  call feedkeys("Sa\<C-E>\<C-N>\<F2>\<Esc>0", 'tx!')
5680  call assert_equal(['abc', 'abcd', 'afoo', 'abar'], b:matches->mapnew('v:val.word'))
5681  call assert_equal(2, g:CallCount)
5682
5683  " Test 4d: When autocomplete menu is active, ^X^L completes lines
5684  %d
5685  let g:CallCount = 0
5686  call setline(1, ["afoo bar", "barbar foo", "foo bar", "and"])
5687  call feedkeys("Goa\<C-X>\<C-L>\<F2>\<Esc>0", 'tx!')
5688  call assert_equal(['afoo bar', 'and'], b:matches->mapnew('v:val.word'))
5689  call assert_equal(1, g:CallCount)
5690
5691  " Issue #18044
5692  %d
5693  call setline(1, ["first line", "second line"])
5694  call feedkeys("Gof\<C-X>\<C-L>\<Esc>", 'tx!')
5695  call assert_equal("first line", getline(3))
5696  call feedkeys("Sf\<C-X>\<C-L>\<C-X>\<C-L>\<Esc>", 'tx!')
5697  call assert_equal("second line", getline(4))
5698
5699  " Test 5: When invalid prefix stops completion, backspace should restart it
5700  %d
5701  set complete&
5702  call setline(1, ["afoo bar", "barbar foo", "foo bar", "and"])
5703  call feedkeys("Goabc\<F2>\<Esc>0", 'tx!')
5704  call assert_equal([], b:matches->mapnew('v:val.word'))
5705  call feedkeys("Sabc\<BS>\<BS>\<F2>\<Esc>0", 'tx!')
5706  call assert_equal(['and', 'afoo'], b:matches->mapnew('v:val.word'))
5707  call feedkeys("Szx\<BS>\<F2>\<Esc>0", 'tx!')
5708  call assert_equal([], b:matches->mapnew('v:val.word'))
5709  call feedkeys("Sazx\<Left>\<BS>\<F2>\<Esc>0", 'tx!')
5710  call assert_equal(['and', 'afoo'], b:matches->mapnew('v:val.word'))
5711
5712  " Test 6: <BS> should clear the selected item (PR #18265)
5713  %d
5714  call setline(1, ["foobarfoo", "foobar", "foobarbaz"])
5715  call feedkeys("Gofo\<C-N>\<C-N>\<F2>\<F3>\<Esc>0", 'tx!')
5716  call assert_equal(['foobarbaz', 'foobar', 'foobarfoo'], b:matches->mapnew('v:val.word'))
5717  call assert_equal(1, b:selected)
5718  call feedkeys("Sfo\<C-N>\<C-N>\<BS>\<F2>\<F3>\<Esc>0", 'tx!')
5719  call assert_equal(['foobarbaz', 'foobar', 'foobarfoo'], b:matches->mapnew('v:val.word'))
5720  call assert_equal(-1, b:selected)
5721  call assert_equal('fooba', getline(4))
5722  call feedkeys("Sfo\<C-N>\<C-N>\<BS>\<C-N>\<F2>\<F3>\<Esc>0", 'tx!')
5723  call assert_equal(['foobarbaz', 'foobar', 'foobarfoo'], b:matches->mapnew('v:val.word'))
5724  call assert_equal(0, b:selected)
5725  call assert_equal('foobarbaz', getline(4))
5726
5727  " Test 7: Remove selection when menu contents change (PR #18265)
5728  %d
5729  call setline(1, ["foobar", "fodxyz", "fodabc"])
5730  call feedkeys("Gofoo\<C-N>\<BS>\<BS>\<BS>\<BS>d\<F2>\<F3>\<Esc>0", 'tx!')
5731  call assert_equal(['fodabc', 'fodxyz'], b:matches->mapnew('v:val.word'))
5732  call assert_equal(-1, b:selected)
5733
5734  " Test 8: Ctrl_W / Ctrl_U (delete word/line) should restart autocompletion
5735  func! TestComplete(findstart, base)
5736    if a:findstart
5737      return col('.') - 1
5738    endif
5739    return ['fooze', 'faberge']
5740  endfunc
5741  set omnifunc=TestComplete
5742  set complete+=o
5743  call feedkeys("Sprefix->fo\<F2>\<Esc>0", 'tx!')
5744  call assert_equal(['fodabc', 'fodxyz', 'foobar', 'fooze'], b:matches->mapnew('v:val.word'))
5745  call feedkeys("Sprefix->fo\<C-W>\<F2>\<Esc>0", 'tx!')
5746  call assert_equal(['fooze', 'faberge'], b:matches->mapnew('v:val.word'))
5747  call feedkeys("Sprefix->\<Esc>afo\<C-U>\<F2>\<Esc>0", 'tx!')
5748  call assert_equal(['fooze', 'faberge'], b:matches->mapnew('v:val.word'))
5749
5750  " Test 9: Trigger autocomplete immediately upon entering Insert mode
5751  " 'faberge' is filtered out because it doesn't start with the current prefix
5752  " 'foo'; non-prefix omnifunc matches are excluded from the PUM when leader
5753  " is NULL (compl_orig_text is used as a fallback filter).
5754  call feedkeys("Sprefix->foo\<Esc>a\<F2>\<Esc>0", 'tx!')
5755  call assert_equal(['foobar', 'fooze'], b:matches->mapnew('v:val.word'))
5756  call feedkeys("Sprefix->fooxx\<Esc>hcw\<F2>\<Esc>0", 'tx!')
5757  call assert_equal(['foobar', 'fooze'], b:matches->mapnew('v:val.word'))
5758
5759  bw!
5760  call Ntest_override("char_avail", 0)
5761  delfunc NonKeywordComplete
5762  delfunc TestComplete
5763  set autocomplete& omnifunc& complete&
5764  unlet g:CallCount
5765endfunc
5766
5767" Test autocomplete timing
5768func Test_autocomplete_timer()
5769
5770  let g:CallCount = 0
5771  func! TestComplete(delay, check, refresh, findstart, base)
5772    if a:findstart
5773      return col('.') - 1
5774    else
5775      let g:CallCount += 1
5776      if a:delay
5777        sleep 310m  " Exceed timeout
5778      endif
5779      if a:check
5780        while !complete_check()
5781          sleep 2m
5782        endwhile
5783        " return v:none  " This should trigger after interrupted by timeout
5784        return []
5785      endif
5786      let res = [["ab", "ac", "ad"], ["abb", "abc", "abd"], ["acb", "cc", "cd"]]
5787      if a:refresh
5788        return #{words: res[g:CallCount - 1], refresh: 'always'}
5789      endif
5790      return res[g:CallCount - 1]
5791    endif
5792  endfunc
5793
5794  " Trigger expansion even when another char is waiting in the typehead
5795  call Ntest_override("char_avail", 1)
5796
5797  new
5798  inoremap <buffer> <F2> <Cmd>let b:matches = complete_info(["matches"]).matches<CR>
5799  inoremap <buffer> <F3> <Cmd>let b:selected = complete_info(["selected"]).selected<CR>
5800  set autocomplete
5801
5802  call setline(1, ['abc', 'bcd', 'cde'])
5803
5804  " Test 1: When matches are found before timeout expires, it exits
5805  " 'collection' mode and transitions to 'filter' mode.
5806  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 0\\,\ 0])
5807  let g:CallCount = 0
5808  call feedkeys("Goa\<F2>\<Esc>0", 'tx!')
5809  call assert_equal(['abc', 'ab', 'ac', 'ad'], b:matches->mapnew('v:val.word'))
5810  call assert_equal(1, g:CallCount)
5811
5812  let g:CallCount = 0
5813  call feedkeys("Sab\<F2>\<Esc>0", 'tx!')
5814  call assert_equal(['abc', 'ab'], b:matches->mapnew('v:val.word'))
5815  call assert_equal(1, g:CallCount)
5816
5817  " Test 2: When timeout expires before all matches are found, it returns
5818  " with partial list but still transitions to 'filter' mode.
5819  set complete=.,Ffunction('TestComplete'\\,\ [1\\,\ 0\\,\ 0])
5820  let g:CallCount = 0
5821  call feedkeys("Sab\<F2>\<Esc>0", 'tx!')
5822  call assert_equal(['abc', 'ab'], b:matches->mapnew('v:val.word'))
5823  call assert_equal(1, g:CallCount)
5824
5825  " Test 3: When interrupted by ^N before timeout expires, it remains in
5826  " 'collection' mode without transitioning.
5827  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 1\\,\ 0])
5828  let g:CallCount = 0
5829  call feedkeys("Sa\<C-N>b\<F2>\<Esc>0", 'tx!')
5830  call assert_equal(2, g:CallCount)
5831
5832  let g:CallCount = 0
5833  call feedkeys("Sa\<C-N>b\<C-N>c\<F2>\<Esc>0", 'tx!')
5834  call assert_equal(3, g:CallCount)
5835
5836  " Test 4: Simulate long running func that is stuck in complete_check()
5837  let g:CallCount = 0
5838  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 1\\,\ 0])
5839  call feedkeys("Sa\<F2>\<Esc>0", 'tx!')
5840  call assert_equal(['abc'], b:matches->mapnew('v:val.word'))
5841  call assert_equal(1, g:CallCount)
5842
5843  let g:CallCount = 0
5844  call feedkeys("Sab\<F2>\<Esc>0", 'tx!')
5845  call assert_equal(['abc'], b:matches->mapnew('v:val.word'))
5846  call assert_equal(1, g:CallCount)
5847
5848  " Test 5: refresh:always stays in 'collection' mode
5849  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 0\\,\ 1])
5850  let g:CallCount = 0
5851  call feedkeys("Sa\<F2>\<Esc>0", 'tx!')
5852  call assert_equal(['abc', 'ab', 'ac', 'ad'], b:matches->mapnew('v:val.word'))
5853  call assert_equal(1, g:CallCount)
5854
5855  let g:CallCount = 0
5856  call feedkeys("Sab\<F2>\<Esc>0", 'tx!')
5857  call assert_equal(['abc', 'abb', 'abd'], b:matches->mapnew('v:val.word'))
5858  call assert_equal(2, g:CallCount)
5859
5860  " Test 6: <c-n> and <c-p> navigate menu
5861  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 0\\,\ 0])
5862  let g:CallCount = 0
5863  call feedkeys("Sab\<c-n>\<F2>\<F3>\<Esc>0", 'tx!')
5864  call assert_equal(['abc', 'ab'], b:matches->mapnew('v:val.word'))
5865  call assert_equal(0, b:selected)
5866  call assert_equal(1, g:CallCount)
5867  call feedkeys("Sab\<c-n>\<c-n>\<F2>\<F3>\<Esc>0", 'tx!')
5868  call assert_equal(1, b:selected)
5869  call feedkeys("Sab\<c-n>\<c-p>\<F2>\<F3>\<Esc>0", 'tx!')
5870  call assert_equal(-1, b:selected)
5871
5872  " Test 7: Following 'cot' option values have no effect
5873  set completeopt=menu,menuone,noselect,noinsert,longest
5874  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 0\\,\ 0])
5875  let g:CallCount = 0
5876  call feedkeys("Sab\<c-n>\<F2>\<F3>\<Esc>0", 'tx!')
5877  call assert_equal(['abc', 'ab'], b:matches->mapnew('v:val.word'))
5878  call assert_equal(0, b:selected)
5879  call assert_equal(1, g:CallCount)
5880  call assert_equal('abc', getline(4))
5881  set completeopt&
5882
5883  " Test 8: {func} completes after space, but not '.'
5884  set complete=.,Ffunction('TestComplete'\\,\ [0\\,\ 0\\,\ 0])
5885  let g:CallCount = 0
5886  call feedkeys("S \<F2>\<F3>\<Esc>0", 'tx!')
5887  call assert_equal(['ab', 'ac', 'ad'], b:matches->mapnew('v:val.word'))
5888  call assert_equal(1, g:CallCount)
5889  set complete=.
5890  call feedkeys("S \<F2>\<F3>\<Esc>0", 'tx!')
5891  call assert_equal([], b:matches->mapnew('v:val.word'))
5892
5893  " Test 9: Matches nearest to the cursor are prioritized (by default)
5894  %d
5895  let g:CallCount = 0
5896  set complete=.
5897  call setline(1, ["fo", "foo", "foobar", "foobarbaz"])
5898  call feedkeys("jof\<F2>\<Esc>0", 'tx!')
5899  call assert_equal(['foo', 'foobar', 'fo', 'foobarbaz'], b:matches->mapnew('v:val.word'))
5900
5901  bw!
5902  call Ntest_override("char_avail", 0)
5903  delfunc TestComplete
5904  set autocomplete& complete&
5905  unlet g:CallCount
5906endfunc
5907
5908func s:TestCompleteScriptLocal(findstart, base)
5909  if a:findstart
5910    return 1
5911  else
5912    return ['foo', 'foobar']
5913  endif
5914endfunc
5915
5916" Issue 17869
5917func Test_scriptlocal_autoload_func()
5918  let save_rtp = &rtp
5919  set rtp=Xruntime/some
5920  let dir = 'Xruntime/some/autoload'
5921  call mkdir(dir, 'pR')
5922
5923  let lines =<< trim END
5924      func compl#Func(findstart, base)
5925          if a:findstart
5926              return 1
5927          else
5928              return ['match', 'matchfoo']
5929          endif
5930      endfunc
5931  END
5932  call writefile(lines, dir .. '/compl.vim')
5933
5934  call Ntest_override("char_avail", 1)
5935  new
5936  inoremap <buffer> <F2> <Cmd>let b:matches = complete_info(["matches"]).matches<CR>
5937  setlocal autocomplete
5938
5939  setlocal complete=.,Fcompl#Func
5940  call feedkeys("im\<F2>\<Esc>0", 'xt!')
5941  call assert_equal(['match', 'matchfoo'], b:matches->mapnew('v:val.word'))
5942
5943  setlocal complete=.,F<SID>TestCompleteScriptLocal
5944  call feedkeys("Sf\<F2>\<Esc>0", 'xt!')
5945  call assert_equal(['foo', 'foobar'], b:matches->mapnew('v:val.word'))
5946
5947  setlocal complete&
5948  bwipe!
5949  call Ntest_override("char_avail", 0)
5950  let &rtp = save_rtp
5951endfunc
5952
5953" Issue #17907
5954func Test_omni_start_invalid_col()
5955  func OmniFunc(startcol, findstart, base)
5956    if a:findstart
5957      return a:startcol
5958    else
5959      return ['foo', 'foobar']
5960    endif
5961  endfunc
5962
5963  new
5964  redraw  " need this to prevent NULL dereference in Nvim
5965  set complete=o
5966  set omnifunc=funcref('OmniFunc',\ [-1])
5967  call setline(1, ['baz '])
5968  call feedkeys("A\<C-N>\<Esc>0", 'tx!')
5969  call assert_equal('baz foo', getline(1))
5970
5971  set omnifunc=funcref('OmniFunc',\ [1000])
5972  call setline(1, ['bar '])
5973  call feedkeys("A\<C-N>\<Esc>0", 'tx!')
5974  call assert_equal('bar foo', getline(1))
5975  bw!
5976
5977  delfunc OmniFunc
5978  set omnifunc& complete&
5979endfunc
5980
5981func Test_completetimeout_autocompletetimeout()
5982  func OmniFunc(findstart, base)
5983    if a:findstart
5984      return 1
5985    else
5986      return ['fooOmni']
5987    endif
5988  endfunc
5989
5990  set omnifunc=OmniFunc
5991  call Ntest_override("char_avail", 1)
5992  inoremap <F2> <Cmd>let b:matches = complete_info(["matches"]).matches<CR>
5993
5994  call setline(1, ['foobar', 'foobarbaz'])
5995  new
5996  call setline(1, ['foo', 'foobaz', ''])
5997  set complete=.,o,w
5998  call feedkeys("G", 'xt!')
5999
6000  set autocomplete
6001  for tt in [1, 80, 1000, -1, 0]
6002    exec $'set autocompletetimeout={tt}'
6003    call feedkeys("\<Esc>Sf\<F2>\<Esc>0", 'xt!')
6004    call assert_equal(['foobaz', 'foo', 'fooOmni', 'foobar', 'foobarbaz'], b:matches->mapnew('v:val.word'))
6005  endfor
6006  set autocomplete&
6007
6008  for tt in [80, 1000, -1, 0]
6009    exec $'set completetimeout={tt}'
6010    call feedkeys("\<Esc>Sf\<C-N>\<F2>\<Esc>0", 'xt!')
6011    call assert_equal(['foo', 'foobaz', 'fooOmni', 'foobar', 'foobarbaz'], b:matches->mapnew('v:val.word'))
6012  endfor
6013
6014  " Clock does not have fine granularity, so checking 'elapsed time' is only
6015  " approximate. We can only test that some type of timeout is enforced.
6016  call setline(1, map(range(60000), '"foo" . v:val'))
6017  set completetimeout=1
6018  call feedkeys("Gof\<C-N>\<F2>\<Esc>0", 'xt!')
6019  let match_count = len(b:matches->mapnew('v:val.word'))
6020  " How many matches are collected in 1 msec varies with machine speed, only
6021  " check the timeout truncated the collection.
6022  call assert_true(match_count < 60000)
6023
6024  set completetimeout=1000
6025  call feedkeys("\<Esc>Sf\<C-N>\<F2>\<Esc>0", 'xt!')
6026  let match_count = len(b:matches->mapnew('v:val.word'))
6027  call assert_true(match_count > 2000)
6028
6029  set autocomplete
6030  set autocompletetimeout=81
6031  " Use enough long words that collecting all of them takes well over the
6032  " timeout even on a fast machine.
6033  let pad = repeat('y', 60)
6034  call setline(1, map(range(200000), '"foo" . v:val . pad'))
6035  call feedkeys("\<Esc>Sf\<F2>\<Esc>0", 'xt!')
6036  let match_count = len(b:matches->mapnew('v:val.word'))
6037  " The timeout must have truncated the collection.
6038  call assert_true(match_count < 200000)
6039
6040  set complete& omnifunc& autocomplete& autocompletetimeout& completetimeout&
6041  bwipe!
6042  %d
6043  call Ntest_override("char_avail", 0)
6044  iunmap <F2>
6045  delfunc OmniFunc
6046endfunc
6047
6048func Test_autocompletedelay()
6049  CheckScreendump
6050
6051  let lines =<< trim [SCRIPT]
6052    call setline(1, ['foo', 'foobar', 'foobarbaz'])
6053    setlocal autocomplete
6054  [SCRIPT]
6055  call writefile(lines, 'XTest_autocomplete_delay', 'D')
6056  let buf = RunVimInTerminal('-S XTest_autocomplete_delay', {'rows': 10})
6057
6058  call term_sendkeys(buf, "Gof")
6059  call VerifyScreenDump(buf, 'Test_autocompletedelay_1', {})
6060
6061  call term_sendkeys(buf, "\<Esc>:set autocompletedelay=500\<CR>")
6062  call term_sendkeys(buf, "Sf")
6063  call VerifyScreenDump(buf, 'Test_autocompletedelay_2', {})
6064  call term_sendkeys(buf, "o")
6065  call VerifyScreenDump(buf, 'Test_autocompletedelay_3', {})
6066  sleep 500m
6067  call VerifyScreenDump(buf, 'Test_autocompletedelay_4', {})
6068  call term_sendkeys(buf, "\<BS>")
6069  call VerifyScreenDump(buf, 'Test_autocompletedelay_5', {})
6070  sleep 500m
6071  call VerifyScreenDump(buf, 'Test_autocompletedelay_5', {})
6072
6073  " During delay wait, user can open menu using CTRL_N completion
6074  call term_sendkeys(buf, "\<Esc>:set completeopt=menuone\<CR>")
6075  call term_sendkeys(buf, "Sf\<C-N>")
6076  call VerifyScreenDump(buf, 'Test_autocompletedelay_7', {})
6077
6078  " After the menu is open, ^N/^P and Up/Down should not delay.
6079  " Wait a bit longer than 'autocompletedelay' so the popup is surely shown
6080  " before sending CTRL-N, otherwise the keys race with the deferred popup.
6081  call term_sendkeys(buf, "\<Esc>:set completeopt=menu noruler\<CR>")
6082  call term_sendkeys(buf, "\<Esc>Sf")
6083  sleep 600ms
6084  call term_sendkeys(buf, "\<C-N>")
6085  call VerifyScreenDump(buf, 'Test_autocompletedelay_8', {})
6086  call term_sendkeys(buf, "\<Down>")
6087  call VerifyScreenDump(buf, 'Test_autocompletedelay_9', {})
6088
6089  " When menu is not open Up/Down moves cursor to different line
6090  call term_sendkeys(buf, "\<Esc>Sf")
6091  call term_sendkeys(buf, "\<Up>")
6092  call VerifyScreenDump(buf, 'Test_autocompletedelay_10', {})
6093  call term_sendkeys(buf, "\<Down>")
6094  call VerifyScreenDump(buf, 'Test_autocompletedelay_11', {})
6095
6096  call term_sendkeys(buf, "\<esc>")
6097  call StopVimInTerminal(buf)
6098endfunc
6099
6100func Run_test_autocompletedelay_ctrl_g_U(delay1, delay2)
6101  new
6102  call setline(1, 'foo bar baz')
6103  inoremap <buffer> ( ()<C-g>U
6104  set autocomplete autocompletedelay=200
6105
6106  call timer_start(a:delay1, { -> feedkeys('(', 't') })
6107  call timer_start(a:delay2, { -> feedkeys("\<Left>a\<Esc>", 't') })
6108  call feedkeys('ob', 'tx!')
6109  call assert_equal(['foo bar baz', 'b(a)'], getline(1, '$'))
6110  undo
6111  call assert_equal(['foo bar baz'], getline(1, '$'))
6112
6113  set autocomplete& autocompletedelay&
6114  bwipe!
6115endfunc
6116
6117func Test_autocompletedelay_ctrl_g_U()
6118  " '(' typed after 'autocompletedelay' expires
6119  call Run_test_autocompletedelay_ctrl_g_U(250, 500)
6120  " '(' typed before 'autocompletedelay' expires
6121  call Run_test_autocompletedelay_ctrl_g_U(150, 500)
6122endfunc
6123
6124func Run_test_autocompletedelay_ctrl_k(delay1, delay2)
6125  new
6126  call setline(1, 'foo bar baz')
6127  set autocomplete autocompletedelay=200
6128
6129  call timer_start(a:delay1, { -> feedkeys("\<C-K>", 't') })
6130  call timer_start(a:delay2, { -> feedkeys(".,\<Esc>", 't') })
6131  call feedkeys('ob', 'tx!')
6132  call assert_equal(['foo bar baz', 'b…'], getline(1, '$'))
6133
6134  set autocomplete& autocompletedelay&
6135  bwipe!
6136endfunc
6137
6138func Test_autocompletedelay_ctrl_k()
6139  throw 'Skipped: use test/functional/editor/completion_spec.lua'
6140  " Ctrl-K typed after 'autocompletedelay' expires
6141  call Run_test_autocompletedelay_ctrl_k(250, 500)
6142  " Ctrl-K typed before 'autocompletedelay' expires
6143  call Run_test_autocompletedelay_ctrl_k(150, 500)
6144endfunc
6145
6146func Test_autocompletedelay_no_record()
6147  " The K_COMPLETE_DELAY pseudo key must not be recorded into a register while
6148  " recording a macro, like K_CURSORHOLD.
6149  new
6150  call setline(1, 'foobar')
6151  set autocomplete autocompletedelay=100
6152
6153  let @a = ''
6154  " Type a char that arms the delay, idle past 'autocompletedelay' so a
6155  " K_COMPLETE_DELAY would be injected, then end Insert mode and stop recording.
6156  call timer_start(300, { -> feedkeys("\<Esc>q", 't') })
6157  call feedkeys("qaSf", 'tx!')
6158  call assert_equal("Sf\<Esc>", @a)
6159
6160  " Delayed autocompletion still works when recording.
6161  if !has('win32') || has('nvim')
6162    call setline(1, 'foobar foofoo')
6163    call timer_start(300, { -> feedkeys("\<Down>\<C-Y>\<Esc>q", 't') })
6164    call feedkeys("qaof", 'tx!')
6165    call assert_equal('foobar', getline('.'))
6166    " XXX: This doesn't produce the same result when replaying.
6167    call assert_equal("of\<Down>\<C-Y>\<Esc>", @a)
6168  endif
6169
6170  set autocomplete& autocompletedelay&
6171  bwipe!
6172endfunc
6173
6174" Preinsert longest prefix when autocomplete
6175func Test_autocomplete_longest()
6176  func GetLine()
6177    let g:line = getline('.')
6178    let g:col = col('.')
6179    let g:preinserted = preinserted()
6180  endfunc
6181
6182  call Ntest_override("char_avail", 1)
6183  new
6184  inoremap <buffer><F5> <C-R>=GetLine()<CR>
6185  set completeopt+=longest autocomplete
6186  call setline(1, ["foobar", "foozbar"])
6187  call feedkeys("Go\<ESC>", 'tx')
6188
6189  func DoTest(typed, line, col)
6190    call feedkeys($"S{a:typed}\<F5>\<ESC>", 'tx')
6191    call assert_equal(a:line, g:line)
6192    call assert_equal(a:col, g:col)
6193  endfunc
6194
6195  call DoTest("f", 'foo', 2)
6196  call DoTest("fo", 'foo', 3)
6197  call DoTest("foo", 'foo', 4)
6198  call DoTest("foob", 'foobar', 5)
6199  call DoTest("foob\<BS>", 'foo', 4)
6200  call DoTest("foob\<BS>\<BS>", 'foo', 3)
6201  call DoTest("foo\<BS>", 'foo', 3)
6202  call DoTest("foo\<BS>\<BS>", 'foo', 2)
6203  call DoTest("foo\<BS>\<BS>\<BS>", '', 1)
6204
6205  call DoTest("foo \<BS>", 'foo', 4)
6206  call DoTest("foo \<BS>\<BS>", 'foo', 3)
6207
6208  call DoTest("f\<C-N>", 'foozbar', 8)
6209  call DoTest("f\<C-N>\<C-N>", 'foobar', 7)
6210  call DoTest("f\<C-N>\<C-N>\<C-N>", 'foo', 2)
6211  call DoTest("f\<C-N>\<C-N>\<C-N>\<C-N>", 'foozbar', 8)
6212  call DoTest("f\<C-N>\<C-N>\<C-N>\<C-N>\<C-P>", 'foo', 2)
6213  call DoTest("f\<C-N>\<C-N>\<C-N>\<C-N>\<C-P>\<C-P>", 'foobar', 7)
6214  call DoTest("f\<C-P>", 'foobar', 7)
6215  call DoTest("fo\<BS>\<C-P>", 'foobar', 7)
6216
6217  " <C-Y> to accept preinserted text
6218  inoremap <buffer><F6> <C-R>=pumvisible()<CR>
6219  call DoTest("zar\<C-O>0f", 'foozar', 2)
6220  call DoTest("zar\<C-O>0f\<C-Y>", 'foozar', 4)
6221  call DoTest("zar\<C-O>0f\<C-Y>\<F6>", 'foo1zar', 5)
6222  call DoTest("zar\<C-O>0f\<C-Y>\<BS>", 'foozar', 3)
6223  call DoTest("zar\<C-O>0f\<C-Y>\<BS>\<F6>", 'fo1zar', 4)
6224
6225  " Select items in menu
6226  call DoTest("zar\<C-O>0f\<C-N>", 'foozbarzar', 8)
6227  call DoTest("zar\<C-O>0f\<C-N>\<C-N>", 'foobarzar', 7)
6228  call DoTest("zar\<C-O>0f\<C-N>\<C-N>\<C-N>", 'foozar', 2)
6229  call DoTest("zar\<C-O>0f\<C-N>\<C-N>\<C-N>\<C-N>", 'foozbarzar', 8)
6230  call DoTest("zar\<C-O>0f\<C-N>\<C-N>\<C-N>\<C-N>\<C-P>", 'foozar', 2)
6231  call DoTest("zar\<C-O>0f\<C-N>\<C-N>\<C-N>\<C-N>\<C-P>\<C-P>", 'foobarzar', 7)
6232  call DoTest("zar\<C-O>0f\<C-P>", 'foobarzar', 7)
6233
6234  " Should not work with fuzzy
6235  set cot+=fuzzy
6236  call DoTest("f", 'f', 2)
6237  set cot-=fuzzy
6238
6239  " preinserted()
6240  call DoTest("f", 'foo', 2)
6241  call assert_equal(1, g:preinserted)
6242  call assert_equal(0, preinserted())
6243  call DoTest("f\<BS>", '', 1)
6244  call assert_equal(0, g:preinserted)
6245  call DoTest("f ", 'f ', 3)
6246  call assert_equal(0, g:preinserted)
6247  call DoTest("foob", 'foobar', 5)
6248  call assert_equal(1, g:preinserted)
6249  call DoTest("foob\<BS>\<BS>x", 'fox', 4)
6250  call assert_equal(0, g:preinserted)
6251
6252  " Complete non-keyword
6253  func Omni(findstart, base)
6254    if a:findstart
6255        return 5
6256    else
6257	return ['xyz:']
6258    endif
6259  endfunc
6260  set omnifunc=Omni
6261  set cpt+=o
6262  call DoTest("xyz:", "xyz:xyz:", 5)
6263  call DoTest("xyz:\<BS>\<BS>", "xyz:", 3)
6264  set omnifunc& cpt&
6265  delfunc Omni
6266
6267  " leader should match prefix of inserted word
6268  %delete
6269  set smartcase ignorecase
6270  call setline(1, ["FOO"])
6271  call feedkeys($"Gof\<F5>\<Esc>", 'tx')
6272  call assert_equal('f', g:line)
6273  call feedkeys($"SF\<F5>\<Esc>", 'tx')
6274  call assert_equal('FOO', g:line)
6275  set smartcase& ignorecase&
6276
6277  " avoid repeating text that is already present after the cursor
6278  %delete
6279  call setline(1, ["foobarbaz", ""])
6280  call feedkeys($"G", 'tx')
6281  call DoTest("baz\<C-O>0f", "foobarbaz", 2)
6282  call feedkeys($"Sxfoozar\<CR>\<Esc>", 'tx')
6283  call DoTest("baz\<C-O>0f", "foobarbaz", 2)
6284  call feedkeys($"Sfoozar\<CR>\<Esc>", 'tx')
6285  call DoTest("baz\<C-O>0f", "foobaz", 2)
6286
6287  " Verify that redo (dot) works
6288  %delete
6289  call setline(1, ["foobar", "foozbar", "foobaz", "changed", "change"])
6290  call feedkeys($"/foo\<CR>", 'tx')
6291  call feedkeys($"cwch\<C-N>\<Esc>n.n.", 'tx')
6292  call assert_equal(repeat(['changed'], 3), getline(1, 3))
6293
6294  " Select a match and delete up to text equal to another match
6295  %delete
6296  call setline(1, ["foobar", "foo"])
6297  call feedkeys("Go\<ESC>", 'tx')
6298  call DoTest("f\<C-N>\<C-N>\<BS>\<BS>\<BS>\<BS>", 'foo', 3)
6299
6300  " Issue #18410: When both "preinsert" and "longest" are set, "preinsert"
6301  " takes precedence
6302  %delete
6303  set autocomplete completeopt+=longest,preinsert
6304  call setline(1, ['foobar', 'foofoo', 'foobaz', ''])
6305  call feedkeys("G", 'tx')
6306  call DoTest("f", 'foobar', 2)
6307  call assert_equal(1, g:preinserted)
6308
6309  " complete_info()
6310  %delete
6311  func GetPreinsert()
6312    let g:cinfo = complete_info(['preinserted_text'])
6313    return ""
6314  endfunc
6315  inoremap <buffer><F6> <C-R>=GetPreinsert()<CR>
6316  call setline(1, ["foo_bar_xyz", "foo__xyz"])
6317
6318  set completeopt& completeopt+=preinsert
6319  call feedkeys("G4li\<F6>\<C-Y>", 'tx')
6320  call assert_equal("bar_xyz", g:cinfo.preinserted_text)
6321
6322  set completeopt& completeopt+=longest
6323  call feedkeys("Gof\<F6>\<ESC>", 'tx')
6324  call assert_equal("oo_bar_xyz", g:cinfo.preinserted_text)
6325  unlet g:cinfo
6326  delfunc GetPreinsert
6327  set completeopt&
6328
6329  " Undo
6330  %delete _
6331  let &l:undolevels = &l:undolevels
6332  normal! ifoo
6333  let &l:undolevels = &l:undolevels
6334  normal! ofoobar
6335  let &l:undolevels = &l:undolevels
6336  normal! ofoobaz
6337  let &l:undolevels = &l:undolevels
6338
6339  func CheckUndo()
6340    let g:errmsg = ''
6341    call assert_equal(['foo', 'foobar', 'foobaz'], getline(1, '$'))
6342    undo
6343    call assert_equal(['foo', 'foobar'], getline(1, '$'))
6344    undo
6345    call assert_equal(['foo'], getline(1, '$'))
6346    undo
6347    call assert_equal([''], getline(1, '$'))
6348    later 3
6349    call assert_equal(['foo', 'foobar', 'foobaz'], getline(1, '$'))
6350    call assert_equal('', v:errmsg)
6351  endfunc
6352
6353  " Check that switching buffer with "longest" doesn't corrupt undo.
6354  new
6355  setlocal bufhidden=wipe
6356  inoremap <buffer> <F2> <Cmd>enew!<CR>
6357  call feedkeys("if\<F2>\<Esc>", 'tx')
6358  bwipe!
6359  call CheckUndo()
6360
6361  " Check that closing window with "longest" doesn't corrupt undo.
6362  new
6363  setlocal bufhidden=wipe
6364  inoremap <buffer> <F2> <Cmd>close!<CR>
6365  call feedkeys("if\<F2>\<Esc>", 'tx')
6366  call CheckUndo()
6367
6368  %delete _
6369  delfunc CheckUndo
6370
6371  " Check that behavior of "longest" in manual completion is unchanged.
6372  for ac in [v:false, v:true]
6373    let &ac = ac
6374    set completeopt=menuone,longest
6375    call feedkeys("Ssign u\<C-X>\<C-V>", 'tx')
6376    call assert_equal('sign un', getline('.'))
6377    call feedkeys("Ssign u\<C-X>\<C-V>\<C-V>", 'tx')
6378    call assert_equal('sign undefine', getline('.'))
6379    call feedkeys("Ssign u\<C-X>\<C-V>\<C-V>\<C-V>", 'tx')
6380    call assert_equal('sign unplace', getline('.'))
6381    call feedkeys("Ssign u\<C-X>\<C-V>\<C-V>\<C-V>\<C-V>", 'tx')
6382    call assert_equal('sign u', getline('.'))
6383    %delete
6384  endfor
6385
6386  bw!
6387  set cot& autocomplete&
6388  delfunc GetLine
6389  delfunc DoTest
6390  call Ntest_override("char_avail", 0)
6391endfunc
6392
6393" Issue #18326
6394func Test_fuzzy_select_item_when_acl()
6395  CheckScreendump
6396  let lines =<< trim [SCRIPT]
6397    call setline(1, ["v", "vi", "vim"])
6398    set autocomplete completeopt=menuone,noinsert,fuzzy autocompletedelay=300
6399  [SCRIPT]
6400  call writefile(lines, 'XTest_autocomplete_delay', 'D')
6401  let buf = RunVimInTerminal('-S XTest_autocomplete_delay', {'rows': 10})
6402
6403  call term_sendkeys(buf, "Govi")
6404  call VerifyScreenDump(buf, 'Test_fuzzy_autocompletedelay_1', {})
6405
6406  call term_sendkeys(buf, "\<Esc>Sv")
6407  call VerifyScreenDump(buf, 'Test_fuzzy_autocompletedelay_2', {})
6408  sleep 500m
6409  call term_sendkeys(buf, "i")
6410  call VerifyScreenDump(buf, 'Test_fuzzy_autocompletedelay_3', {})
6411
6412  call term_sendkeys(buf, "\<esc>")
6413  call StopVimInTerminal(buf)
6414endfunc
6415
6416" Issue #18378: crash when fuzzy reorders items during refresh:always
6417func Test_refresh_always_with_fuzzy()
6418  func ComplFunc1(findstart, base)
6419    if a:findstart
6420      return 1
6421    else
6422      return ['foo', 'foobar']
6423    endif
6424  endfunc
6425  func ComplFunc2(findstart, base)
6426    if a:findstart
6427      return 1
6428    else
6429      return #{words: ['foo'], refresh: 'always'}
6430    endif
6431  endfunc
6432  set complete=.,FComplFunc1,FComplFunc2
6433  set autocomplete
6434  call Ntest_override("char_avail", 1)
6435  new
6436  call setline(1, ['fox'])
6437  exe "normal! Gofo"
6438  bw!
6439  delfunc ComplFunc1
6440  delfunc ComplFunc2
6441  set complete& autocomplete&
6442  call Ntest_override("char_avail", 0)
6443endfunc
6444
6445func Test_autocompletedelay_longest_preinsert()
6446  CheckScreendump
6447  let lines =<< trim [SCRIPT]
6448    call setline(1, ['autocomplete', 'autocomxxx'])
6449    set autocomplete completeopt+=longest autocompletedelay=500
6450  [SCRIPT]
6451  call writefile(lines, 'XTest_autocompletedelay', 'D')
6452  let buf = RunVimInTerminal('-S XTest_autocompletedelay', {'rows': 10})
6453
6454  " No spurious characters when autocompletedelay is in effect
6455  call term_sendkeys(buf, "Goau")
6456  sleep 10m
6457  call term_sendkeys(buf, "toc")
6458  sleep 100m
6459  call VerifyScreenDump(buf, 'Test_autocompletedelay_longest_1', {})
6460  sleep 500m
6461  call VerifyScreenDump(buf, 'Test_autocompletedelay_longest_2', {})
6462
6463  " Deleting a char should still show longest text
6464  call term_sendkeys(buf, "\<Esc>Saut")
6465  sleep 10m
6466  call term_sendkeys(buf, "\<BS>")
6467  sleep 100m
6468  call VerifyScreenDump(buf, 'Test_autocompletedelay_longest_3', {})
6469  sleep 500m
6470  call VerifyScreenDump(buf, 'Test_autocompletedelay_longest_4', {})
6471
6472  " Preinsert
6473  call term_sendkeys(buf, "\<Esc>:set completeopt& completeopt+=preinsert\<CR>")
6474  call term_sendkeys(buf, "\<Esc>Sau")
6475  sleep 100m
6476  call VerifyScreenDump(buf, 'Test_autocompletedelay_preinsert_1', {})
6477  sleep 500m
6478  call VerifyScreenDump(buf, 'Test_autocompletedelay_preinsert_2', {})
6479
6480  call term_sendkeys(buf, "\<esc>")
6481  call StopVimInTerminal(buf)
6482endfunc
6483
6484" Issue 18493
6485func Test_longest_preinsert_accept()
6486  call Ntest_override("char_avail", 1)
6487  new
6488  call setline(1, ['func1', 'xfunc', 'func2'])
6489  set completeopt+=noselect
6490
6491  call feedkeys("Gof\<C-N>\<Down>\<C-Y>", 'tx')
6492  call assert_equal('func1', getline('.'))
6493
6494  set completeopt+=longest autocomplete
6495  call feedkeys("Sf\<Down>\<C-Y>", 'tx')
6496  call assert_equal('func2', getline('.'))
6497  call feedkeys("Sf\<C-Y>", 'tx')
6498  call assert_equal('func', getline('.'))
6499
6500  set completeopt& autocomplete&
6501  bw!
6502  call Ntest_override("char_avail", 0)
6503endfunc
6504
6505" Issue 19114
6506func Test_fuzzy_filenames_compl_autocompl()
6507  CheckScreendump
6508  let dir = 'Xtempdir'
6509  call mkdir(dir, 'pR')
6510  call writefile([], dir .. '/.name')
6511  call writefile([], dir .. '/name')
6512  call writefile([], dir .. '/test.vim')
6513
6514  let buf = RunVimInTerminal('', {'rows': 10})
6515  call term_sendkeys(buf, ':call test_override("char_avail", 1)')
6516  call term_sendkeys(buf, "\<CR>")
6517  call term_sendkeys(buf, "iset ac cot=fuzzy,longest\<ESC>")
6518  call term_sendkeys(buf, ":source\<CR>")
6519  call term_sendkeys(buf, "o.na\<C-X>\<C-F>")  " this used to cause segfault
6520  call TermWait(buf, 200)
6521  call VerifyScreenDump(buf, 'Test_fuzzy_filenames_compl_autocompl', {})
6522  call StopVimInTerminal(buf)
6523endfunc
6524
6525" Issue 19130
6526func Test_helptags_autocomplete_timeout()
6527  func! TestComplete(findstart, base)
6528    if a:findstart
6529      return col('.') - 1
6530    else
6531      sleep 310m  " Exceed timeout
6532      return ["foo"]
6533    endif
6534  endfunc
6535
6536  call Ntest_override("char_avail", 1)
6537  new
6538  set autocomplete completeopt=fuzzy complete=.,FTestComplete
6539  call feedkeys("Goa\<Esc>0", 'tx!')
6540  call feedkeys(":h\<CR>", 'tx')  " used to throw E149 exception
6541  call Ntest_override("char_avail", 0)
6542  set autocomplete& completeopt& complete&
6543  bw!
6544endfunc
6545
6546func Test_autocomplete_preinsert_null_leader()
6547  " Test that non-prefix matches from omnifunc are filtered when leader is NULL.
6548  " When autocomplete first fires, compl_leader is NULL.  Previously the prefix
6549  " filter was bypassed, allowing non-prefix fuzzy matches to be incorrectly
6550  " shown in the PUM and preinserted.
6551  func NonPrefixOmni(findstart, base)
6552    if a:findstart
6553      return col(".") - 1
6554    endif
6555    " Return "key" (doesn't start with 'y') and "yellow" (starts with 'y').
6556    " Simulates what a fuzzy omnifunc returns (e.g. vimcomplete#Complete with
6557    " wildoptions=fuzzy).
6558    return ["key", "yellow"]
6559  endfunc
6560
6561  call Ntest_override("char_avail", 1)
6562  new
6563  set omnifunc=NonPrefixOmni complete=o
6564  set completeopt=preinsert autocomplete
6565
6566  func GetState()
6567    let g:line = getline('.')
6568    let g:col = col('.')
6569    let g:matches = complete_info(['matches']).matches->mapnew('v:val.word')
6570  endfunc
6571  inoremap <buffer> <F5> <C-R>=GetState()<CR>
6572
6573  " Type 'y': "key" should be filtered out (doesn't start with 'y'),
6574  " "yellow" should be the only PUM entry and preinserted with cursor after 'y'.
6575  call feedkeys("iy\<F5>\<C-E>\<Esc>", 'tx')
6576  call assert_equal("yellow", g:line)
6577  call assert_equal(2, g:col)
6578  call assert_equal(['yellow'], g:matches)
6579
6580  bw!
6581  set omnifunc& complete& completeopt& autocomplete&
6582  call Ntest_override("char_avail", 0)
6583  delfunc NonPrefixOmni
6584  delfunc GetState
6585endfunc
6586
6587" Issue #19329: When register contents are inserted, remove preinserted text
6588func Test_ins_register_preinsert_autocomplete()
6589  func TestOmni(findstart, base)
6590    if a:findstart
6591      return col(".") - 1
6592    endif
6593    return ["foo", "foobar"]
6594  endfunc
6595
6596  call Ntest_override("char_avail", 1)
6597  new
6598  set omnifunc=TestOmni complete^=o
6599  set completeopt=preinsert autocomplete
6600
6601  call feedkeys("ifoo \<C-R>\<C-P>=\"xyz\"\<CR>\<Esc>", 'tx')
6602  call assert_equal("foo xyz", getline('.'))
6603  bw!
6604  set omnifunc& complete& completeopt& autocomplete&
6605  call Ntest_override("char_avail", 0)
6606  delfunc TestOmni
6607endfunc
6608
6609func Test_autocomplete_with_auto_format()
6610  call Ntest_override("char_avail", 1)
6611  new
6612  setlocal formatoptions=tcq textwidth=9 autocomplete noautoindent
6613  call feedkeys("ia b c d\<Esc>ie f g\<Esc>", 'tx')
6614  call assert_equal(['a b c e f', 'gd'], getline(1, '$'))
6615
6616  %delete
6617  setlocal autoindent
6618  call feedkeys("ia b c d\<Esc>ie f g\<Esc>", 'tx')
6619  call assert_equal(['a b c e f', 'gd'], getline(1, '$'))
6620
6621  bw!
6622  call Ntest_override("char_avail", 0)
6623endfunc
6624
6625func Test_completion_with_mapped_ctrl_r()
6626  new
6627  let b:n = 0
6628  let @a = 'AABBCCDDEE'
6629  " Ctrl-R mapping is triggered
6630  inoremap <buffer> <C-R> <Cmd>let b:n += 1<CR>
6631  inoremap <buffer> <F2> <Cmd>call complete(col('.'), [])<CR>
6632  call feedkeys("i\<F2>\<*C-R>abcde\<Esc>", 'tx')
6633  call assert_equal(1, b:n)
6634  call assert_equal('abcde', getline('.'))
6635
6636  " Ctrl-X Ctrl-R still works with Ctrl-R mapped
6637  call feedkeys("ccAAB\<*C-X>\<*C-R>\<*C-Y>\<Esc>", 'tx')
6638  call assert_equal(1, b:n)
6639  call assert_equal('AABBCCDDEE', getline('.'))
6640
6641  let @a = ''
6642  bwipe!
6643endfunc
6644
6645" Keys are mapped during completion started by complete(), but not in other
6646" CTRL-X modes.
6647func Test_mapped_ctrl_n_during_complete_function()
6648  new
6649  inoremap <buffer> <F2> <Cmd>call complete(1, ['foo', 'foobar'])<CR>
6650  inoremap <buffer> <F3> <Cmd>let b:info =
6651        \ [getline('.'), complete_info(['selected']).selected]<CR>
6652
6653  " During completion started by complete() the <C-N> mapping applies:
6654  " <Down> moves the selection without inserting it.
6655  inoremap <buffer> <expr> <C-N> complete_info().mode ==# 'eval' ? '<Down>' : '<C-N>'
6656  call feedkeys("i\<F2>\<*C-N>\<F3>\<C-Y>\<Esc>", 'tx')
6657  call assert_equal(['foo', 1], b:info)
6658  call assert_equal('foobar', getline(1))
6659
6660  " In other CTRL-X modes the mapping is ignored: the builtin <C-N> selects
6661  " and inserts the next match.
6662  %delete _
6663  call setline(1, ['foo', 'foobar', ''])
6664  inoremap <buffer> <expr> <C-N> pumvisible() ? '<Down>' : '<C-N>'
6665  call feedkeys("3GAf\<C-X>\<C-N>\<C-N>\<F3>\<C-Y>\<Esc>", 'tx')
6666  call assert_equal(['foobar', 1], b:info)
6667
6668  bwipe!
6669endfunc
6670
6671func Test_smartcase_longest()
6672  func! GetMatches()
6673    let info = complete_info(["matches"])
6674    return map(copy(info.matches), {_, v -> v.word})
6675  endfunc
6676
6677  func! TestInner(key)
6678    let pr = "\<c-r>=string(GetMatches())\<cr>"
6679    let words = ["InputEvent", "inputmap", "INPUT_MAP"]
6680
6681    new
6682    set completeopt=menuone,noselect,longest ignorecase smartcase
6683
6684    " Lowercase 'inp' all three (case-insensitive).
6685    call setline(1, words)
6686    exe $"normal! ggOinp{a:key}{pr}"
6687    let line = getline(1)
6688    call assert_match('\c^input', line, 'inp prefix, key=' .. strtrans(a:key))
6689    call assert_equal("['InputEvent', 'inputmap', 'INPUT_MAP']",
6690          \ substitute(line, '\c^input', '', ''),
6691          \ 'inp matches, key=' .. strtrans(a:key))
6692
6693    " Uppercase 'I' excludes lowercase 'inputmap'
6694    %d
6695    call setline(1, words)
6696    exe $"normal! ggOI{a:key}{pr}"
6697    let line = getline(1)
6698    call assert_match('\c^input', line, 'I prefix, key=' .. strtrans(a:key))
6699    call assert_equal("['InputEvent', 'INPUT_MAP']",
6700          \ substitute(line, '\c^input', '', ''),
6701          \ 'I matches, key=' .. strtrans(a:key))
6702
6703    set ignorecase& smartcase& completeopt&
6704    bw!
6705  endfunc
6706
6707  call TestInner("\<c-n>")
6708  call TestInner("\<c-p>")
6709  call TestInner("\<c-x>\<c-n>")
6710  call TestInner("\<c-x>\<c-p>")
6711  delfunc GetMatches
6712  delfunc TestInner
6713endfunc
6714
6715" Check that calling complete() while filtering Ctrl-N completion doesn't
6716" break dot-repeat.
6717func Test_call_complete_while_filtering()
6718  new
6719  setlocal complete=. completeopt=menuone,noselect
6720  inoremap <buffer> <F2> <Cmd>call complete(3, ['obar', 'obaz'])<CR>
6721  call setline(1, ['foobar', 'foobaz'])
6722
6723  call feedkeys("Gofo\<C-N>ob\<F2>cd\<Esc>", 'tx')
6724  call assert_equal(['foobar', 'foobaz', 'foobcd'], getline(1, '$'))
6725  normal! .
6726  call assert_equal(['foobar', 'foobaz', 'foobcd', 'foobcd'], getline(1, '$'))
6727
6728  bwipe!
6729endfunc
6730
6731func Test_complete_check_mapped_typed_key()
6732  func SlowComplete(findstart, base)
6733    if a:findstart
6734      return col('.') - 1
6735    endif
6736    call complete_add('foobar')
6737    let g:compl_iterations = 0
6738    while !complete_check() && g:compl_iterations < 100
6739      let g:compl_iterations += 1
6740      sleep 5m
6741    endwhile
6742    return []
6743  endfunc
6744
6745  new
6746  setlocal completefunc=SlowComplete
6747  setlocal completeopt=menuone,noselect
6748  inoremap <buffer> <Space> <Space><Space>
6749
6750  let g:compl_iterations = -1
6751  call feedkeys("Sfoo\<C-X>\<C-U> \<Esc>", 'tx')
6752  call assert_inrange(0, 99, g:compl_iterations)
6753
6754  bwipe!
6755  delfunc SlowComplete
6756  unlet g:compl_iterations
6757endfunc
6758
6759" Test for the duplicate check when adding completion matches
6760func Test_ins_complete_dedup()
6761  new
6762  setl complete=.
6763
6764  " a word that occurs several times only results in one match
6765  call setline(1, ['alpha beta alpha gamma', 'beta alpha delta beta', ''])
6766  call cursor(3, 1)
6767  call feedkeys("Aal\<C-N>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6768  call assert_equal(['alpha'], g:compl_info.items->mapnew('v:val.word'))
6769
6770  " the duplicate check is case-sensitive
6771  %delete _
6772  call setline(1, ['Foo foo FOO fooBar Foo foo', ''])
6773  call cursor(2, 1)
6774  call feedkeys("Afo\<C-N>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6775  call assert_equal(['foo', 'fooBar'], g:compl_info.items->mapnew('v:val.word'))
6776
6777  " with 'ignorecase' and 'infercase' case variants fold into one match
6778  setl ignorecase infercase
6779  %delete _
6780  call setline(1, ['Word word WORD wordy Word', ''])
6781  call cursor(2, 1)
6782  call feedkeys("Awo\<C-N>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6783  call assert_equal(['word', 'wordy'], g:compl_info.items->mapnew('v:val.word'))
6784  setl noignorecase noinfercase
6785
6786  " duplicate dictionary entries only appear once; with 'ignorecase' case
6787  " variants all match but stay separate matches
6788  call writefile(['apple', 'apple', 'Apple', 'apricot', 'apricot', 'banana'],
6789        \ 'Xcompldict', 'D')
6790  setl dictionary=Xcompldict
6791  set ignorecase
6792  %delete _
6793  call feedkeys("Aap\<C-X>\<C-K>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6794  call assert_equal(['apple', 'Apple', 'apricot'], g:compl_info.items->mapnew('v:val.word'))
6795  set noignorecase
6796  setl dictionary&
6797
6798  " duplicate items passed to complete() are only added once
6799  inoremap <buffer> <F5> <Cmd>call complete(1, ['dup', 'dup', 'uniq', 'dup'])<CR>
6800  %delete _
6801  call feedkeys("i\<F5>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6802  call assert_equal(['dup', 'uniq'], g:compl_info.items->mapnew('v:val.word'))
6803
6804  " restarting a completion rebuilds the matches without duplicates
6805  %delete _
6806  call setline(1, ['echo edit eecho edit echo', ''])
6807  call cursor(2, 1)
6808  call feedkeys("Ae\<C-N>\<C-E>\<Esc>", 'tx')
6809  call feedkeys("A\<C-N>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6810  call assert_equal(['echo', 'edit', 'eecho'], g:compl_info.items->mapnew('v:val.word'))
6811
6812  " With "dup" matches from several sources, refreshing one source removes
6813  " its duplicate but must not forget about the equal match of the other
6814  " source: adding "dupword" again without "dup" is still a duplicate.
6815  let g:dedup_calls = 0
6816  func! DedupSrcA(findstart, base)
6817    if a:findstart
6818      return 0
6819    endif
6820    let g:dedup_calls += 1
6821    if g:dedup_calls == 1
6822      return #{words: [#{word: 'dupword', dup: 1}], refresh: 'always'}
6823    endif
6824    return #{words: [#{word: 'dupword'}], refresh: 'always'}
6825  endfunc
6826  func! DedupSrcB(findstart, base)
6827    if a:findstart
6828      return 0
6829    endif
6830    return #{words: [#{word: 'dupword', dup: 1}]}
6831  endfunc
6832  setl complete=FDedupSrcA,FDedupSrcB
6833  %delete _
6834  call feedkeys("Sdup\<C-N>\<BS>\<C-R>=GetCompleteInfo()\<CR>\<C-E>\<Esc>", 'tx')
6835  call assert_equal(['dupword'], g:compl_info.items->mapnew('v:val.word'))
6836  setl complete&
6837  delfunc DedupSrcA
6838  delfunc DedupSrcB
6839  unlet g:dedup_calls
6840
6841  bwipe!
6842  unlet g:compl_info
6843endfunc
6844
6845func Test_complete_info_hlgroup()
6846  new
6847  set completeopt&
6848  func DoComplete()
6849    call complete(1, [
6850          \ #{word: 'aaa', abbr_hlgroup: 'Title', kind_hlgroup: 'SpecialKey'},
6851          \ #{word: 'bbb', abbr_hlgroup: 'MyAbbr', kind_hlgroup: 'MyKind'},
6852          \ #{word: 'ccc'}])
6853    return ''
6854  endfunc
6855  func ShownItems()
6856    let g:items = complete_info(['items']).items
6857    return ''
6858  endfunc
6859
6860  call assert_false(hlexists('MyAbbr'))
6861  call feedkeys("i\<C-R>=DoComplete()\<CR>\<C-R>=ShownItems()\<CR>\<Esc>", 'tx')
6862  call assert_equal(['Title', 'MyAbbr', ''],
6863        \ map(copy(g:items), 'v:val.abbr_hlgroup'))
6864  call assert_equal(['SpecialKey', 'MyKind', ''],
6865        \ map(copy(g:items), 'v:val.kind_hlgroup'))
6866  call assert_true(hlexists('MyAbbr'))
6867
6868  unlet g:items
6869  delfunc DoComplete
6870  delfunc ShownItems
6871  bwipe!
6872endfunc
6873
6874" Test that complete_info() tells a completion Vim started by itself from one
6875" that a key asked for.
6876func Test_complete_info_auto()
6877  call Ntest_override("char_avail", 1)
6878  new
6879  func! AutoOmni(findstart, base)
6880    if a:findstart
6881      call add(g:auto, complete_info(['auto']).auto)
6882      return 4
6883    endif
6884    return ['alpha', 'alphabet']
6885  endfunc
6886  setlocal omnifunc=AutoOmni
6887  setlocal complete=o
6888  setlocal completeopt=menuone
6889  call setline(1, '    al')
6890
6891  " 'autocomplete' starts it, nothing was asked for.
6892  setlocal autocomplete
6893  let g:auto = []
6894  call feedkeys("A\<Esc>", 'tx')
6895  call assert_equal([1], g:auto)
6896
6897  " The second call is the one CTRL-X CTRL-O asked for.
6898  let g:auto = []
6899  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'tx')
6900  call assert_equal([1, 0], g:auto)
6901
6902  " CTRL-X CTRL-O is typed before 'autocompletedelay' expires.
6903  set autocompletedelay=100
6904  let g:auto = []
6905  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'tx')
6906  call assert_equal([0], g:auto)
6907
6908  set autocompletedelay&
6909  setlocal noautocomplete
6910  let g:auto = []
6911  call feedkeys("A\<C-X>\<C-O>\<Esc>", 'tx')
6912  call assert_equal([0], g:auto)
6913
6914  call Ntest_override("ALL", 0)
6915  unlet g:auto
6916  delfunc AutoOmni
6917  bwipe!
6918endfunc
6919
6920" A completion asked for while 'autocompletedelay' runs is not given the
6921" implicit "noselect" of autocompletion.
6922func Test_complete_asked_for_during_delay()
6923  call Ntest_override("char_avail", 1)
6924  new
6925  func! AutoOmni(findstart, base)
6926    if a:findstart
6927      return 4
6928    endif
6929    return ['alpha', 'alphabet']
6930  endfunc
6931  func! Selected()
6932    let g:selected = complete_info(['selected']).selected
6933    return ''
6934  endfunc
6935  setlocal omnifunc=AutoOmni
6936  setlocal complete=o
6937  setlocal completeopt=menuone
6938  setlocal autocomplete
6939  call setline(1, '    al')
6940
6941  " CTRL-X CTRL-O before the delay expires: the first match is selected,
6942  " and taken.
6943  set autocompletedelay=100
6944  call feedkeys("A\<C-X>\<C-O>\<C-R>=Selected()\<CR>\<Esc>", 'tx')
6945  call assert_equal(0, g:selected)
6946  call assert_equal('    alpha', getline(1))
6947
6948  " What autocompletion puts up on its own selects nothing, so the word is
6949  " left as it was.
6950  set autocompletedelay&
6951  call setline(1, '    al')
6952  call feedkeys("A\<C-R>=Selected()\<CR>\<Esc>", 'tx')
6953  call assert_equal(-1, g:selected)
6954  call assert_equal('    al', getline(1))
6955
6956  call Ntest_override("ALL", 0)
6957  unlet g:selected
6958  delfunc AutoOmni
6959  delfunc Selected
6960  bwipe!
6961endfunc
6962
6963func Test_complete_fuzzy_resort()
6964  new
6965  set completeopt=menu,menuone,noselect,fuzzy
6966
6967  inoremap <buffer> <F5> <Cmd>call complete(1, ['xxxb', 'xb', 'b'])<CR>
6968  call feedkeys("i\<F5>b\<C-R>=string(map(complete_info(['items']).items, 'v:val.word'))\<CR>\<Esc>", 'tx')
6969  call assert_equal("b['b', 'xb', 'xxxb']", getline(1))
6970
6971  %d _
6972  call setline(1, ['xxxbar', 'xbar', 'bar'])
6973  call feedkeys("Go\<C-P>b\<C-R>=string(map(complete_info(['items']).items, 'v:val.word'))\<CR>\<Esc>", 'tx')
6974  call assert_equal("b['bar', 'xbar', 'xxxbar']", getline('$'))
6975
6976  bwipe!
6977  set completeopt&
6978endfunc
6979
6980" Test for 'complete' F{func} callbacks when using ":setglobal"
6981func Test_complete_cpt_func_setglobal()
6982  func! CptSetglobalOne(findstart, base)
6983    if a:findstart
6984      return col('.') - 1
6985    endif
6986    return ['one']
6987  endfunc
6988  func! CptSetglobalTwo(findstart, base)
6989    if a:findstart
6990      return col('.') - 1
6991    endif
6992    return ['two']
6993  endfunc
6994
6995  new
6996  setlocal complete=FCptSetglobalOne
6997  " ":setglobal" does not change the buffer-local value
6998  setglobal complete=t,FCptSetglobalTwo
6999  exe "normal! i\<C-N>\<Esc>"
7000  call assert_equal('one', getline(1))
7001
7002  " A new buffer uses the global value, the callbacks must match it
7003  new
7004  exe "normal! i\<C-N>\<Esc>"
7005  call assert_equal('two', getline(1))
7006  bwipe!
7007  bwipe!
7008
7009  " When the global value has more entries than the buffer-local one, the
7010  " callback array used to be indexed out of bounds
7011  new
7012  setlocal complete=.
7013  setglobal complete=FCptSetglobalTwo,FCptSetglobalTwo,FCptSetglobalTwo,FCptSetglobalTwo,FCptSetglobalTwo,FCptSetglobalTwo,FCptSetglobalTwo,FCptSetglobalTwo
7014  new
7015  exe "normal! i\<C-N>\<Esc>"
7016  call assert_equal('two', getline(1))
7017  bwipe!
7018  bwipe!
7019
7020  " ":setlocal" does not change the callbacks cached for the global value
7021  new
7022  setlocal complete=FCptSetglobalOne
7023  new
7024  exe "normal! i\<C-N>\<Esc>"
7025  call assert_equal('two', getline(1))
7026  bwipe!
7027  bwipe!
7028
7029  set complete&
7030  delfunc CptSetglobalOne
7031  delfunc CptSetglobalTwo
7032endfunc
7033
7034
7035" change the completion value while being triggered
7036func Test_complete_cpt_func_changes_complete()
7037  func! CptChange(findstart, base)
7038    if a:findstart
7039      set complete=.
7040      return col('.') - 1
7041    endif
7042    return ['changed']
7043  endfunc
7044
7045  new
7046  call setline(1, ['alpha', ''])
7047  setlocal complete=FCptChange,FCptChange,FCptChange
7048  exe "normal! Gi\<C-N>\<Esc>"
7049  call assert_equal('alpha', getline(2))
7050
7051  set complete&
7052  delfunc CptChange
7053  bwipe!
7054endfunc
7055
7056" vim: shiftwidth=2 sts=2 expandtab nofoldenable