robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
31.3 KiB1083 linesraw
1" Test for syntax and syntax iskeyword option
2
3source check.vim
4CheckFeature syntax
5
6source view_util.vim
7source screendump.vim
8
9func GetSyntaxItem(pat)
10  let c = ''
11  let a = ['a', getreg('a'), getregtype('a')]
12  0
13  redraw!
14  call search(a:pat, 'W')
15  let synid = synID(line('.'), col('.'), 1)
16  while synid == synID(line('.'), col('.'), 1)
17    norm! v"ay
18    " stop at whitespace
19    if @a =~# '\s'
20      break
21    endif
22    let c .= @a
23    norm! l
24  endw
25  call call('setreg', a)
26  0
27  return c
28endfunc
29
30func AssertHighlightGroups(lnum, startcol, expected, trans = 1, msg = "")
31  " Assert that the characters starting at a given (line, col)
32  " sequentially match the expected highlight groups.
33  " If groups are provided as a string, each character is assumed to be a
34  " group and spaces represent no group, useful for visually describing tests.
35  let l:expectedGroups = type(a:expected) == v:t_string
36        \ ? a:expected->split('\zs')->map({_, v -> trim(v)})
37        \ : a:expected
38  let l:errors = 0
39  let l:msg = (a:msg->empty() ? "" : a:msg .. ": ")
40        \ .. "Wrong highlight group at " .. a:lnum .. ","
41
42  for l:i in range(a:startcol, a:startcol + l:expectedGroups->len() - 1)
43    let l:errors += synID(a:lnum, l:i, a:trans)
44          \ ->synIDattr("name")
45          \ ->assert_equal(l:expectedGroups[l:i - 1],
46          \    l:msg .. l:i)
47  endfor
48endfunc
49
50func Test_syn_iskeyword()
51  new
52  call setline(1, [
53	\ 'CREATE TABLE FOOBAR(',
54	\ '    DLTD_BY VARCHAR2(100)',
55	\ ');',
56	\ ''])
57
58  syntax on
59  set ft=sql
60  syn match SYN /C\k\+\>/
61  hi link SYN ErrorMsg
62  call assert_equal('DLTD_BY', GetSyntaxItem('DLTD'))
63  /\<D\k\+\>/:norm! ygn
64  call assert_equal('DLTD_BY', @0)
65  redir @c
66  syn iskeyword
67  redir END
68  call assert_equal("\nsyntax iskeyword not set", @c)
69
70  syn iskeyword @,48-57,_,192-255
71  redir @c
72  syn iskeyword
73  redir END
74  call assert_equal("\nsyntax iskeyword @,48-57,_,192-255", @c)
75
76  call assert_fails("syntax iskeyword invalid_value", "E474:")
77  redir @c
78  syn iskeyword
79  redir END
80  " did not change
81  call assert_equal("\nsyntax iskeyword @,48-57,_,192-255", @c)
82
83  setlocal isk-=_
84  call assert_equal('DLTD_BY', GetSyntaxItem('DLTD'))
85  /\<D\k\+\>/:norm! ygn
86  let b2 = @0
87  call assert_equal('DLTD', @0)
88
89  syn iskeyword clear
90  redir @c
91  syn iskeyword
92  redir END
93  call assert_equal("\nsyntax iskeyword not set", @c)
94
95  quit!
96endfunc
97
98func Test_syntax_after_reload()
99  split Xsomefile
100  call setline(1, ['hello', 'there'])
101  w!
102  only!
103  setl filetype=hello
104  au FileType hello let g:gotit = 1
105  call assert_false(exists('g:gotit'))
106  edit other
107  buf Xsomefile
108  call assert_equal('hello', &filetype)
109  call assert_true(exists('g:gotit'))
110  call delete('Xsomefile')
111endfunc
112
113func Test_syntax_filetype_syntax()
114  set filetype=syntax
115  syntax on
116  syntax off
117  set filetype= syntax=
118endfunc
119
120func Test_syntime()
121  CheckFeature profile
122
123  syntax on
124  syntime on
125  let a = execute('syntime report')
126  call assert_equal("\nNo Syntax items defined for this buffer", a)
127
128  let a = execute('syntime clear')
129  call assert_equal("\nNo Syntax items defined for this buffer", a)
130
131  view ../memfile_test.c
132  setfiletype cpp
133  redraw
134  let a = execute('syntime report')
135  call assert_match('^  TOTAL *COUNT *MATCH *SLOWEST *AVERAGE *NAME *PATTERN', a)
136  call assert_match(' \d*\.\d* \+[^0]\d* .* cppRawString ', a)
137  call assert_match(' \d*\.\d* \+[^0]\d* .* cppNumber ', a)
138
139  syntime off
140  syntime clear
141  let a = execute('syntime report')
142  call assert_match('^  TOTAL *COUNT *MATCH *SLOWEST *AVERAGE *NAME *PATTERN', a)
143  call assert_notmatch('.* cppRawString *', a)
144  call assert_notmatch('.* cppNumber*', a)
145  call assert_notmatch('[1-9]', a)
146
147  call assert_fails('syntime abc', 'E475')
148
149  syntax clear
150  let a = execute('syntime report')
151  call assert_equal("\nNo Syntax items defined for this buffer", a)
152
153  bd
154endfunc
155
156func Test_syntime_completion()
157  if !has('profile')
158    return
159  endif
160
161  call feedkeys(":syntime \<C-A>\<C-B>\"\<CR>", 'tx')
162  call assert_equal('"syntime clear off on report', @:)
163endfunc
164
165func Test_syntax_list()
166  syntax on
167  let a = execute('syntax list')
168  call assert_equal("\nNo Syntax items defined for this buffer", a)
169
170  view ../memfile_test.c
171  setfiletype c
172
173  let a = execute('syntax list')
174  call assert_match('cInclude*', a)
175  call assert_match('cDefine', a)
176
177  let a = execute('syntax list cDefine')
178  call assert_notmatch('cInclude*', a)
179  call assert_match('cDefine', a)
180  call assert_match(' links to Macro$', a)
181
182  call assert_fails('syntax list ABCD', 'E28:')
183  call assert_fails('syntax list @ABCD', 'E392:')
184
185  syntax clear
186  let a = execute('syntax list')
187  call assert_equal("\nNo Syntax items defined for this buffer", a)
188
189  syntax keyword Type int containedin=g1 skipwhite skipempty skipnl nextgroup=Abc
190  let exp = "Type           xxx containedin=g1  nextgroup=Abc  skipnl skipwhite skipempty int"
191  call assert_equal(exp, split(execute("syntax list"), "\n")[1])
192
193  bd
194endfunc
195
196func Test_syntax_completion()
197  call feedkeys(":syn \<C-A>\<C-B>\"\<CR>", 'tx')
198  call assert_equal('"syn case clear cluster conceal enable foldlevel include iskeyword keyword list manual match off on region reset spell sync', @:)
199
200  call feedkeys(":syn case \<C-A>\<C-B>\"\<CR>", 'tx')
201  call assert_equal('"syn case ignore match', @:)
202
203  call feedkeys(":syn spell \<C-A>\<C-B>\"\<CR>", 'tx')
204  call assert_equal('"syn spell default notoplevel toplevel', @:)
205
206  call feedkeys(":syn sync \<C-A>\<C-B>\"\<CR>", 'tx')
207  call assert_equal('"syn sync ccomment clear fromstart linebreaks= linecont lines= match maxlines= minlines= region', @:)
208
209  " Check that clearing "Aap" avoids it showing up before Boolean.
210  hi @Aap ctermfg=blue
211  call feedkeys(":syn list \<C-A>\<C-B>\"\<CR>", 'tx')
212  call assert_match('^"syn list @Aap @attribute @attribute.builtin @boolean @character ', @:)
213  hi clear @Aap
214
215  call feedkeys(":syn list \<C-A>\<C-B>\"\<CR>", 'tx')
216  call assert_match('^"syn list @attribute @attribute.builtin @boolean @character ', @:)
217
218  call feedkeys(":syn match \<C-A>\<C-B>\"\<CR>", 'tx')
219  call assert_match('^"syn match @attribute @attribute.builtin @boolean @character ', @:)
220
221  syn cluster Aax contains=Aap
222  call feedkeys(":syn list @A\<C-A>\<C-B>\"\<CR>", 'tx')
223  call assert_match('^"syn list @Aax', @:)
224endfunc
225
226func Test_echohl_completion()
227  call feedkeys(":echohl no\<C-A>\<C-B>\"\<CR>", 'tx')
228  " call assert_equal('"echohl NonText Normal none', @:)
229  call assert_equal('"echohl NonText Normal NormalFloat NormalNC none', @:)
230endfunc
231
232func Test_syntax_arg_skipped()
233  syn clear
234  syntax case ignore
235  if 0
236    syntax case match
237  endif
238  call assert_match('case ignore', execute('syntax case'))
239
240  syn keyword Foo foo
241  call assert_match('Foo', execute('syntax'))
242  syn clear
243  call assert_match('case match', execute('syntax case'))
244  call assert_notmatch('Foo', execute('syntax'))
245
246  if has('conceal')
247    syn clear
248    syntax conceal on
249    if 0
250      syntax conceal off
251    endif
252    call assert_match('conceal on', execute('syntax conceal'))
253    syn clear
254    call assert_match('conceal off', execute('syntax conceal'))
255  endif
256
257  syntax conceal on
258  syntax conceal off
259  call assert_match('conceal off', execute('syntax conceal'))
260
261  syntax region Bar start=/</ end=/>/
262  if 0
263    syntax region NotTest start=/</ end=/>/ contains=@Spell
264  endif
265  call assert_match('Bar', execute('syntax'))
266  call assert_notmatch('NotTest', execute('syntax'))
267  call assert_notmatch('Spell', execute('syntax'))
268
269  hi Foo ctermfg=blue
270  let a = execute('hi Foo')
271  if 0
272    syntax rest
273  endif
274  call assert_equal(a, execute('hi Foo'))
275  hi clear Bar
276  hi clear Foo
277
278  set ft=tags
279  syn off
280  if 0
281    syntax enable
282  endif
283  call assert_match('No Syntax items defined', execute('syntax'))
284  syntax enable
285  call assert_match('tagComment', execute('syntax'))
286  set ft=
287
288  syn clear
289  if 0
290    syntax include @Spell nothing
291  endif
292  call assert_notmatch('Spell', execute('syntax'))
293
294  syn clear
295  syn iskeyword 48-57,$,_
296  call assert_match('48-57,$,_', execute('syntax iskeyword'))
297  if 0
298    syn clear
299    syn iskeyword clear
300  endif
301  call assert_match('48-57,$,_', execute('syntax iskeyword'))
302  syn iskeyword clear
303  call assert_match('not set', execute('syntax iskeyword'))
304  syn iskeyword 48-57,$,_
305  syn clear
306  call assert_match('not set', execute('syntax iskeyword'))
307
308  syn clear
309  syn keyword Foo foo
310  if 0
311    syn keyword NotAdded bar
312  endif
313  call assert_match('Foo', execute('syntax'))
314  call assert_notmatch('NotAdded', execute('highlight'))
315
316  syn clear
317  syn keyword Foo foo
318  call assert_match('Foo', execute('syntax'))
319  call assert_match('Foo', execute('syntax list'))
320  call assert_notmatch('Foo', execute('if 0 | syntax | endif'))
321  call assert_notmatch('Foo', execute('if 0 | syntax list | endif'))
322
323  syn clear
324  syn match Fopi /asdf/
325  if 0
326    syn match Fopx /asdf/
327  endif
328  call assert_match('Fopi', execute('syntax'))
329  call assert_notmatch('Fopx', execute('syntax'))
330
331  syn clear
332  syn spell toplevel
333  call assert_match('spell toplevel', execute('syntax spell'))
334  if 0
335    syn spell notoplevel
336  endif
337  call assert_match('spell toplevel', execute('syntax spell'))
338  syn spell notoplevel
339  call assert_match('spell notoplevel', execute('syntax spell'))
340  syn spell default
341  call assert_match('spell default', execute('syntax spell'))
342
343  syn clear
344  if 0
345    syntax cluster Spell
346  endif
347  call assert_notmatch('Spell', execute('syntax'))
348
349  syn clear
350  syn keyword Foo foo
351  syn sync ccomment
352  syn sync maxlines=5
353  if 0
354    syn sync maxlines=11
355  endif
356  call assert_match('on C-style comments', execute('syntax sync'))
357  call assert_match('maximal 5 lines', execute('syntax sync'))
358  syn sync clear
359  if 0
360    syn sync ccomment
361  endif
362  call assert_notmatch('on C-style comments', execute('syntax sync'))
363  syn sync fromstart
364  call assert_match('syncing starts at the first line', execute('syntax sync'))
365
366  syn clear
367endfunc
368
369" Check for an error. Used when multiple errors are thrown and we are checking
370" for an earliest error.
371func AssertFails(cmd, errcode)
372  let save_exception = ''
373  try
374    exe a:cmd
375  catch
376    let save_exception = v:exception
377  endtry
378  call assert_match(a:errcode, save_exception)
379endfunc
380
381func Test_syntax_invalid_arg()
382  call assert_fails('syntax case asdf', 'E390:')
383  if has('conceal')
384    call assert_fails('syntax conceal asdf', 'E390:')
385  endif
386  call assert_fails('syntax spell asdf', 'E390:')
387  call assert_fails('syntax clear @ABCD', 'E391:')
388  call assert_fails('syntax include random_file', 'E484:')
389  call assert_fails('syntax include <afile>', 'E495:')
390  call assert_fails('syntax sync x', 'E404:')
391  call assert_fails('syntax keyword Abc a[', 'E789:')
392  call assert_fails('syntax keyword Abc a[bc]d', 'E890:')
393  call assert_fails('syntax cluster Abc add=A add=', 'E406:')
394
395  " Test for too many \z\( and unmatched \z\(
396  " Not able to use assert_fails() here because both E50:/E879: and E475:
397  " messages are emitted.
398  set regexpengine=1
399  call AssertFails("syntax region MyRegion start='\\z\\(' end='\\*/'", 'E52:')
400
401  let cmd = "syntax region MyRegion start='"
402  let cmd ..= repeat("\\z\\(.\\)", 10) .. "' end='\*/'"
403  call AssertFails(cmd, 'E50:')
404
405  set regexpengine=2
406  call AssertFails("syntax region MyRegion start='\\z\\(' end='\\*/'", 'E54:')
407
408  let cmd = "syntax region MyRegion start='"
409  let cmd ..= repeat("\\z\\(.\\)", 10) .. "' end='\*/'"
410  call AssertFails(cmd, 'E879:')
411  set regexpengine&
412
413  call AssertFails('syntax keyword cMyItem grouphere G1', 'E393:')
414  call AssertFails('syntax sync match Abc grouphere MyItem "abc"', 'E394:')
415  call AssertFails('syn keyword Type contains int', 'E395:')
416  call assert_fails('syntax include @Xxx', 'E397:')
417  call AssertFails('syntax region X start', 'E398:')
418  call assert_fails('syntax region X start="{"', 'E399:')
419  call AssertFails('syntax cluster contains=Abc', 'E400:')
420  call AssertFails("syntax match Character /'.'", 'E401:')
421  call AssertFails("syntax match Character /'.'/a", 'E402:')
422  call assert_fails('syntax sync linecont /\%(/', 'E53:')
423  call assert_fails('syntax sync linecont /pat', 'E404:')
424  call assert_fails('syntax sync linecont', 'E404:')
425  call assert_fails('syntax sync linecont /pat1/ linecont /pat2/', 'E403:')
426  call assert_fails('syntax sync minlines=a', 'E404:')
427  call AssertFails('syntax match ABC /x/ contains=', 'E406:')
428  call AssertFails("syntax match Character contains /'.'/", 'E405:')
429  call AssertFails('syntax match ccFoo "Foo" nextgroup=ALLBUT,F', 'E407:')
430  call AssertFails('syntax region Block start="{" contains=F,ALLBUT', 'E408:')
431  call AssertFails("syntax match Characters contains=a.*x /'.'/", 'E409:')
432  call assert_fails('syntax match Search /abc/ contains=ALLBUT,/\%(/', 'E53:')
433endfunc
434
435func Test_syn_sync()
436  syntax region HereGroup start=/this/ end=/that/
437  syntax sync match SyncHere grouphere HereGroup "pattern"
438  call assert_match('SyncHere', execute('syntax sync'))
439  syn sync clear
440  call assert_notmatch('SyncHere', execute('syntax sync'))
441
442  syn sync minlines=10
443  syntax cluster xmlStuff contains=xmlGroup1,xmlGroup2
444  syntax region xmlComment start=/<!--/ end=/-->/ keepend contains=@Spell
445  syntax sync match xmlSync1 grouphere xmlComment /<!--/
446  syntax sync match xmlSync2 groupthere NONE /-->/
447  syntax cluster xmlAll contains=ALL
448  let out = execute('syntax sync')
449  call assert_match('xmlSync1', out)
450  call assert_match('xmlSync2', out)
451  call assert_match('grouphere xmlComment', out)
452  call assert_match('groupthere NONE', out)
453  call assert_notmatch('xmlStuff', out)
454  call assert_notmatch('xmlAll', out)
455  call assert_notmatch('cluster', out)
456  call assert_notmatch('keepend', out)
457  " should output 4 lines: 1 header + 3 syn sync lines
458  call assert_equal(4, len(split(out, '\n')))
459
460  syn clear
461endfunc
462
463func Test_syn_clear()
464  syntax keyword Foo foo
465  syntax keyword Bar tar
466  call assert_match('Foo', execute('syntax'))
467  call assert_match('Bar', execute('syntax'))
468  call assert_equal('Foo', synIDattr(hlID("Foo"), "name"))
469  syn clear Foo
470  call assert_notmatch('Foo', execute('syntax'))
471  call assert_match('Bar', execute('syntax'))
472  call assert_equal('Foo', synIDattr(hlID("Foo"), "name"))
473  syn clear Foo Bar
474  call assert_notmatch('Foo', execute('syntax'))
475  call assert_notmatch('Bar', execute('syntax'))
476  hi clear Foo
477  call assert_equal('Foo', synIDattr(hlID("Foo"), "name"))
478  hi clear Bar
479  call assert_fails('syntax clear invalid_syngroup', 'E28:')
480endfunc
481
482func Test_invalid_name()
483  syn clear
484  syn keyword Nop yes
485  call assert_fails("syntax keyword Wr\x17ong bar", 'E669:')
486  syntax keyword @Wrong bar
487  call assert_fails("syntax keyword @#Wrong bar", 'E5248:')
488  syn clear
489  hi clear Nop
490  hi clear @Wrong
491endfunc
492
493func Test_ownsyntax()
494  new XfooOwnSyntax
495  call setline(1, '#define FOO')
496  syntax on
497  set filetype=c
498
499  ownsyntax perl
500  " this should not crash
501  set
502
503  call assert_equal('perlComment', synIDattr(synID(line('.'), col('.'), 1), 'name'))
504  call assert_equal('c',    b:current_syntax)
505  call assert_equal('perl', w:current_syntax)
506
507  " A new split window should have the original syntax.
508  split
509  call assert_equal('cDefine', synIDattr(synID(line('.'), col('.'), 1), 'name'))
510  call assert_equal('c', b:current_syntax)
511  call assert_equal(0, exists('w:current_syntax'))
512
513  wincmd x
514  call assert_equal('perlComment', synIDattr(synID(line("."), col("."), 1), "name"))
515
516  syntax off
517  set filetype&
518  %bw!
519endfunc
520
521func Test_ownsyntax_completion()
522  call feedkeys(":ownsyntax java\<C-A>\<C-B>\"\<CR>", 'tx')
523  call assert_equal('"ownsyntax java javacc javascript javascriptreact', @:)
524endfunc
525
526func Test_highlight_invalid_arg()
527  if has('gui_running')
528    call assert_fails('hi XXX guifg=xxx', 'E254:')
529  endif
530  call assert_fails('hi DoesNotExist', 'E411:')
531  call assert_fails('hi link', 'E412:')
532  call assert_fails('hi link a', 'E412:')
533  call assert_fails('hi link a b c', 'E413:')
534  call assert_fails('hi XXX =', 'E415:')
535  call assert_fails('hi XXX cterm', 'E416:')
536  call assert_fails('hi XXX cterm=', 'E417:')
537  call assert_fails('hi XXX cterm=DoesNotExist', 'E418:')
538  call assert_fails('hi XXX ctermfg=DoesNotExist', 'E421:')
539  call assert_fails('hi XXX xxx=White', 'E423:')
540endfunc
541
542func Test_conceal()
543  if !has('conceal')
544    return
545  endif
546
547  new
548  call setline(1, ['', '123456'])
549  syn match test23 "23" conceal cchar=X
550  syn match test45 "45" conceal
551
552  set conceallevel=0
553  call assert_equal('123456 ', ScreenLines(2, 7)[0])
554  call assert_equal([[0, '', 0], [0, '', 0], [0, '', 0], [0, '', 0], [0, '', 0], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)'))
555
556  set conceallevel=1
557  call assert_equal('1X 6   ', ScreenLines(2, 7)[0])
558  call assert_equal([[0, '', 0], [1, 'X', 1], [1, 'X', 1], [1, ' ', 2], [1, ' ', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)'))
559
560  set conceallevel=1
561  set listchars=conceal:Y
562  call assert_equal([[0, '', 0], [1, 'X', 1], [1, 'X', 1], [1, 'Y', 2], [1, 'Y', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)'))
563  call assert_equal('1XY6   ', ScreenLines(2, 7)[0])
564
565  set conceallevel=2
566  call assert_match('1X6    ', ScreenLines(2, 7)[0])
567  call assert_equal([[0, '', 0], [1, 'X', 1], [1, 'X', 1], [1, '', 2], [1, '', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)'))
568
569  set conceallevel=3
570  call assert_match('16     ', ScreenLines(2, 7)[0])
571  call assert_equal([[0, '', 0], [1, '', 1], [1, '', 1], [1, '', 2], [1, '', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)'))
572
573  call AssertFails("syntax match Entity '&amp;' conceal cchar=\<Tab>", 'E844:')
574
575  syn clear
576  set conceallevel&
577  bw!
578endfunc
579
580func Test_bg_detection()
581  CheckNotGui
582
583  " auto-detection of &bg, make sure it isn't set anywhere before this test
584  hi Normal ctermbg=0
585  call assert_equal('dark', &bg)
586  hi Normal ctermbg=4
587  call assert_equal('dark', &bg)
588  hi Normal ctermbg=12
589  call assert_equal('light', &bg)
590  hi Normal ctermbg=15
591  call assert_equal('light', &bg)
592
593  " manually-set &bg takes precedence over auto-detection
594  set bg=light
595  hi Normal ctermbg=4
596  call assert_equal('light', &bg)
597  set bg=dark
598  hi Normal ctermbg=12
599  call assert_equal('dark', &bg)
600
601  hi Normal ctermbg=NONE
602endfunc
603
604func Test_syntax_hangs()
605  if !has('reltime') || !has('float') || !has('syntax')
606    return
607  endif
608
609  " This pattern takes a long time to match, it should timeout.
610  new
611  call setline(1, ['aaa', repeat('abc ', 1000), 'ccc'])
612  let start = reltime()
613  set nolazyredraw redrawtime=101
614  syn match Error /\%#=1a*.*X\@<=b*/
615  redraw
616  let elapsed = reltimefloat(reltime(start))
617  call assert_true(elapsed > 0.1)
618  call assert_true(elapsed < 1.0)
619
620  " second time syntax HL is disabled
621  let start = reltime()
622  redraw
623  let elapsed = reltimefloat(reltime(start))
624  call assert_true(elapsed < 0.1)
625
626  " after CTRL-L the timeout flag is reset
627  let start = reltime()
628  exe "normal \<C-L>"
629  redraw
630  let elapsed = reltimefloat(reltime(start))
631  call assert_true(elapsed > 0.1)
632  call assert_true(elapsed < 1.0)
633
634  set redrawtime&
635  bwipe!
636endfunc
637
638func Test_synstack_synIDtrans()
639  new
640  setfiletype c
641  syntax on
642  call setline(1, ' /* A comment with a TODO */')
643
644  call assert_equal([], synstack(1, 1))
645
646  norm f/
647  eval synstack(line("."), col("."))->map('synIDattr(v:val, "name")')->assert_equal(['cComment', 'cCommentStart'])
648  eval synstack(line("."), col("."))->map('synIDattr(synIDtrans(v:val), "name")')->assert_equal(['Comment', 'Comment'])
649
650  norm fA
651  call assert_equal(['cComment'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")'))
652  call assert_equal(['Comment'],  map(synstack(line("."), col(".")), 'synIDattr(synIDtrans(v:val), "name")'))
653
654  norm fT
655  call assert_equal(['cComment', 'cTodo'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")'))
656  call assert_equal(['Comment', 'Todo'],   map(synstack(line("."), col(".")), 'synIDattr(synIDtrans(v:val), "name")'))
657
658  call assert_fails("let n=synIDtrans([])", 'E745:')
659
660  syn clear
661  bw!
662endfunc
663
664" Check highlighting for a small piece of C code with a screen dump.
665func Test_syntax_c()
666  CheckScreendump
667  CheckRunVimInTerminal
668  call writefile([
669	\ '/* comment line at the top */',
670	\ 'int main(int argc, char **argv) { // another comment',
671	\ '#if 0',
672	\ '   int   not_used;',
673	\ '#else',
674	\ '   int   used;',
675	\ '#endif',
676	\ '   printf("Just an example piece of C code\n");',
677	\ '   return 0x0ff;',
678	\ '}',
679	\ "\t\t ",
680	\ '   static void',
681	\ 'myFunction(const double count, struct nothing, long there) {',
682	\ "\t// 123: nothing to endif here",
683	\ "\tfor (int i = 0; i < count; ++i) {",
684	\ "\t   break;",
685	\ "\t}",
686	\ "\tNote: asdf",
687	\ '}',
688	\ ], 'Xtest.c', 'D')
689
690  " This makes the default for 'background' use "dark", check that the
691  " response to t_RB corrects it to "light".
692  let $COLORFGBG = '15;0'
693
694  let buf = RunVimInTerminal('Xtest.c', {})
695  call term_sendkeys(buf, ":syn keyword Search Note\r")
696  call VerifyScreenDump(buf, 'Test_syntax_c_01', {})
697  call StopVimInTerminal(buf)
698
699  let $COLORFGBG = ''
700endfun
701
702" Test \z(...) along with \z1
703func Test_syn_zsub()
704  new
705  syntax on
706  call setline(1,  'xxx start foo xxx not end foo xxx end foo xxx')
707  let l:expected = '    ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ    '
708
709  for l:re in [0, 1, 2]
710    " Example taken from :help :syn-ext-match
711    syntax region Z start="start \z(\I\i*\)" skip="not end \z1" end="end \z1"
712    eval AssertHighlightGroups(1, 1, l:expected, 1, 'regexp=' .. l:re)
713    syntax clear Z
714  endfor
715
716  set re&
717  bw!
718endfunc
719
720func s:SynDumpBuffer(ft, lines)
721  new
722  syntax on
723  execute 'setfiletype ' .. a:ft
724  call setline(1, a:lines)
725  let result = []
726  for lnum in range(1, line('$'))
727    for col in range(1, max([1, len(getline(lnum))]))
728      call add(result, synIDattr(synID(lnum, col, 1), 'name'))
729    endfor
730  endfor
731  bwipe!
732  return result
733endfunc
734
735" The in_id_list() cache is a speed optimization only: highlighting must be
736" identical with the cache on (default) and off.  Compare full-buffer synID()
737" output both ways across filetypes that use "contains"/cluster lists.
738func Test_syntax_idlist_cache_unchanged()
739  throw 'Skipped: Nvim does not support test_override()'
740  let samples = {
741        \ 'c': ['#define M 0x1F', "char c = '\\n';",
742        \       'int f(int a) { return a + 0xAB; }'],
743        \ 'vim': ['func <SID>Foo() abort', '  let x = [1, 2] + {"k": 0z1f}',
744        \         'endfunc'],
745        \ 'python': ['class C:', '    def m(self): return {1: "s", 2: r"\d"}'],
746        \ 'sh': ['case $x in', '  a) echo "${y:-0xAB}";;', 'esac'],
747        \ }
748  for ft in sort(keys(samples))
749    call test_override('syn_idlist_cache', 0)
750    let l:on = s:SynDumpBuffer(ft, samples[ft])
751    call test_override('syn_idlist_cache', 1)
752    let l:off = s:SynDumpBuffer(ft, samples[ft])
753    call test_override('ALL', 0)
754    call assert_equal(l:off, l:on, 'filetype ' .. ft)
755  endfor
756endfunc
757
758" Using \z() in a region with NFA failing should not crash.
759func Test_syn_wrong_z_one()
760  new
761  call setline(1, ['just some text', 'with foo and bar to match with'])
762  syn region FooBar start="foo\z(.*\)bar" end="\z1"
763  " call test_override("nfa_fail", 1)
764  redraw!
765  redraw!
766  " call test_override("ALL", 0)
767  bwipe!
768endfunc
769
770func Test_syntax_after_bufdo()
771  call writefile(['/* aaa comment */'], 'Xaaa.c', 'D')
772  call writefile(['/* bbb comment */'], 'Xbbb.c', 'D')
773  call writefile(['/* ccc comment */'], 'Xccc.c', 'D')
774  call writefile(['/* ddd comment */'], 'Xddd.c', 'D')
775
776  let bnr = bufnr('%')
777  new Xaaa.c
778  badd Xbbb.c
779  badd Xccc.c
780  badd Xddd.c
781  exe "bwipe " . bnr
782  let l = []
783  bufdo call add(l, bufnr('%'))
784  call assert_equal(4, len(l))
785
786  syntax on
787
788  " This used to only enable syntax HL in the last buffer.
789  bufdo tab split
790  tabrewind
791  for tab in range(1, 4)
792    norm fm
793    call assert_equal(['cComment'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")'))
794    tabnext
795  endfor
796
797  bwipe! Xaaa.c
798  bwipe! Xbbb.c
799  bwipe! Xccc.c
800  bwipe! Xddd.c
801  syntax off
802endfunc
803
804func Test_syntax_foldlevel()
805  new
806  call setline(1, [
807   \ 'void f(int a)',
808   \ '{',
809   \ '    if (a == 1) {',
810   \ '        a = 0;',
811   \ '    } else if (a == 2) {',
812   \ '        a = 1;',
813   \ '    } else {',
814   \ '        a = 2;',
815   \ '    }',
816   \ '    if (a > 0) {',
817   \ '        if (a == 1) {',
818   \ '            a = 0;',
819   \ '        } /* missing newline */ } /* end of outer if */ else {',
820   \ '        a = 1;',
821   \ '    }',
822   \ '    if (a == 1)',
823   \ '    {',
824   \ '        a = 0;',
825   \ '    }',
826   \ '    else if (a == 2)',
827   \ '    {',
828   \ '        a = 1;',
829   \ '    }',
830   \ '    else',
831   \ '    {',
832   \ '        a = 2;',
833   \ '    }',
834   \ '}',
835   \ ])
836  setfiletype c
837  syntax on
838  set foldmethod=syntax
839
840  call assert_fails('syn foldlevel start start', 'E390')
841  call assert_fails('syn foldlevel not_an_option', 'E390')
842
843  set foldlevel=1
844
845  syn foldlevel start
846  redir @c
847  syn foldlevel
848  redir END
849  call assert_equal("\nsyntax foldlevel start", @c)
850  syn sync fromstart
851  call assert_match('from the first line$', execute('syn sync'))
852  let a = map(range(3,9), 'foldclosed(v:val)')
853  call assert_equal([3,3,3,3,3,3,3], a) " attached cascade folds together
854  let a = map(range(10,15), 'foldclosed(v:val)')
855  call assert_equal([10,10,10,10,10,10], a) " over-attached 'else' hidden
856  let a = map(range(16,27), 'foldclosed(v:val)')
857  let unattached_results = [-1,17,17,17,-1,21,21,21,-1,25,25,25]
858  call assert_equal(unattached_results, a) " unattached cascade folds separately
859
860  syn foldlevel minimum
861  redir @c
862  syn foldlevel
863  redir END
864  call assert_equal("\nsyntax foldlevel minimum", @c)
865  syn sync fromstart
866  let a = map(range(3,9), 'foldclosed(v:val)')
867  call assert_equal([3,3,5,5,7,7,7], a) " attached cascade folds separately
868  let a = map(range(10,15), 'foldclosed(v:val)')
869  call assert_equal([10,10,10,13,13,13], a) " over-attached 'else' visible
870  let a = map(range(16,27), 'foldclosed(v:val)')
871  call assert_equal(unattached_results, a) " unattached cascade folds separately
872
873  set foldlevel=2
874
875  syn foldlevel start
876  syn sync fromstart
877  let a = map(range(11,14), 'foldclosed(v:val)')
878  call assert_equal([11,11,11,-1], a) " over-attached 'else' hidden
879
880  syn foldlevel minimum
881  syn sync fromstart
882  let a = map(range(11,14), 'foldclosed(v:val)')
883  call assert_equal([11,11,-1,-1], a) " over-attached 'else' visible
884
885  quit!
886endfunc
887
888func Test_search_syntax_skip()
889  new
890  let lines =<< trim END
891
892        /* This is VIM */
893        Another Text for VIM
894         let a = "VIM"
895  END
896  call setline(1, lines)
897  syntax on
898  syntax match Comment "^/\*.*\*/"
899  syntax match String '".*"'
900
901  " Skip argument using string evaluation.
902  1
903  call search('VIM', 'w', '', 0, 'synIDattr(synID(line("."), col("."), 1), "name") =~? "comment"')
904  call assert_equal('Another Text for VIM', getline('.'))
905
906  1
907  call search('VIM', 'cw', '', 0, 'synIDattr(synID(line("."), col("."), 1), "name") !~? "string"')
908  call assert_equal(' let a = "VIM"', getline('.'))
909
910  " Skip argument using Lambda.
911  1
912  call search('VIM', 'w', '', 0, { -> synIDattr(synID(line("."), col("."), 1), "name") =~? "comment"})
913  call assert_equal('Another Text for VIM', getline('.'))
914
915  1
916  call search('VIM', 'cw', '', 0, { -> synIDattr(synID(line("."), col("."), 1), "name") !~? "string"})
917  call assert_equal(' let a = "VIM"', getline('.'))
918
919  " Skip argument using funcref.
920  func InComment()
921    return synIDattr(synID(line("."), col("."), 1), "name") =~? "comment"
922  endfunc
923  func NotInString()
924    return synIDattr(synID(line("."), col("."), 1), "name") !~? "string"
925  endfunc
926
927  1
928  call search('VIM', 'w', '', 0, function('InComment'))
929  call assert_equal('Another Text for VIM', getline('.'))
930
931  1
932  call search('VIM', 'cw', '', 0, function('NotInString'))
933  call assert_equal(' let a = "VIM"', getline('.'))
934
935  delfunc InComment
936  delfunc NotInString
937  bwipe!
938endfunc
939
940func Test_syn_contained_transparent()
941  " Comments starting with "Regression:" show the result when the highlighting
942  " span of the containing item is assigned to the contained region.
943  syntax on
944
945  let l:case = "Transparent region contained in region"
946  new
947  syntax region X start=/\[/ end=/\]/ contained transparent
948  syntax region Y start=/(/ end=/)/ contains=X
949
950  call setline(1,  "==(--[~~]--)==")
951  let l:expected = "  YYYYYYYYYY  "
952  eval AssertHighlightGroups(1, 1, l:expected, 1, l:case)
953  syntax clear Y X
954  bw!
955
956  let l:case = "Transparent region extends region"
957  new
958  syntax region X start=/\[/ end=/\]/ contained transparent
959  syntax region Y start=/(/ end=/)/ end=/e/ contains=X
960
961  call setline(1,  "==(--[~~e~~]--)==")
962  let l:expected = "  YYYYYYYYYYYYY  "
963  " Regression:    "  YYYYYYY   YYY  "
964  eval AssertHighlightGroups(1, 1, l:expected, 1, l:case)
965  syntax clear Y X
966  bw!
967
968  let l:case = "Nested transparent regions extend region"
969  new
970  syntax region X start=/\[/ end=/\]/ contained transparent
971  syntax region Y start=/(/ end=/)/ end=/e/ contains=X
972
973  call setline(1,  "==(--[~~e~~[~~e~~]~~e~~]--)==")
974  let l:expected = "  YYYYYYYYYYYYYYYYYYYYYYYYY  "
975  " Regression:    "  YYYYYYY         YYYYYYYYY  "
976  eval AssertHighlightGroups(1, 1, l:expected, 1, l:case)
977  syntax clear Y X
978  bw!
979
980  let l:case = "Transparent region contained in match"
981  new
982  syntax region X start=/\[/ end=/\]/ contained transparent
983  syntax match Y /(.\{-})/ contains=X
984
985  call setline(1,  "==(--[~~]--)==")
986  let l:expected = "  YYYYYYYYYY  "
987  eval AssertHighlightGroups(1, 1, l:expected, 1, l:case)
988  syntax clear Y X
989  bw!
990
991  let l:case = "Transparent region extends match"
992  new
993  syntax region X start=/\[/ end=/\]/ contained transparent
994  syntax match Y /(.\{-}[e)]/ contains=X
995
996  call setline(1,  "==(--[~~e~~]--)==")
997  let l:expected = "  YYYYYYYYYY     "
998  " Regression:    "  YYYYYYY        "
999  eval AssertHighlightGroups(1, 1, l:expected, 1, l:case)
1000  syntax clear Y X
1001  bw!
1002
1003  let l:case = "Nested transparent regions extend match"
1004  new
1005  syntax region X start=/\[/ end=/\]/ contained transparent
1006  syntax match Y /(.\{-}[e)]/ contains=X
1007
1008  call setline(1,  "==(--[~~e~~[~~e~~]~~e~~]--)==")
1009  let l:expected = "  YYYYYYYYYYYYYYYYYYYYYY     "
1010  " Regression:    "  YYYYYYY         YYYYYY     "
1011  eval AssertHighlightGroups(1, 1, l:expected, 1, l:case)
1012  syntax clear Y X
1013  bw!
1014endfunc
1015
1016func Test_syn_include_contains_TOP()
1017  let l:case = "TOP in included syntax refers to top level of that included syntax"
1018  new
1019  syntax include @INCLUDED syntax/c.vim
1020  syntax region FencedCodeBlockC start=/```c/ end=/```/ contains=@INCLUDED
1021
1022  call setline(1,  ['```c', '#if 0', 'int', '#else', 'int', '#endif', '```' ])
1023  let l:expected = ["cCppOutIf2"]
1024  eval AssertHighlightGroups(3, 1, l:expected, 1)
1025  " cCppOutElse has contains=TOP
1026  let l:expected = ["cType"]
1027  eval AssertHighlightGroups(5, 1, l:expected, 1, l:case)
1028  syntax clear
1029  bw!
1030endfunc
1031
1032func Test_syn_include_contains_TOP_excluding()
1033  new
1034  syntax include @INCLUDED syntax/c.vim
1035  syntax region FencedCodeBlockC start=/```c/ end=/```/ contains=@INCLUDED
1036
1037  call setline(1,  ['```c', '#if 0', 'int', '#else', 'int', '#if', '#endif', '```' ])
1038  let l:expected = ["cCppOutElse", "cConditional"]
1039  eval AssertHighlightGroups(6, 1, l:expected, 1)
1040  syntax clear
1041  bw!
1042endfunc
1043
1044" This was using freed memory
1045func Test_WinEnter_synstack_synID()
1046  autocmd WinEnter * call synstack(line("."), col("."))
1047  autocmd WinEnter * call synID(line('.'), col('.') - 1, 1)
1048  call setline(1, 'aaaaa')
1049  normal! $
1050  new
1051  close
1052
1053  au! WinEnter
1054  bw!
1055endfunc
1056
1057" This was going beyond the end of the "foo" line
1058func Test_syn_sync_grouphere_shorter_next_line()
1059  let lines =<< trim END
1060    if [[ "$var1" == 1 ]]; then
1061      foo
1062    else
1063      bar
1064    fi
1065  END
1066  let lines = ['a']->repeat(50) + lines + ['a']->repeat(48)
1067
1068  20new
1069  call setline(1, lines)
1070  syn region shIf transparent
1071        \ start="\<if\_s" skip=+-fi\>+ end="\<;\_s*then\>" end="\<fi\>"
1072  syn sync minlines=20 maxlines=40
1073  syn sync match shIfSync grouphere shIf "\<if\>"
1074  redraw!
1075
1076  normal! G
1077  " Should not go beyond end of line
1078  redraw!
1079
1080  bw!
1081endfunc
1082
1083" vim: shiftwidth=2 sts=2 expandtab