robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
64.6 KiB1658 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4
5local describe, it, before_each, finally = t.describe, t.it, t.before_each, t.finally
6local clear = n.clear
7local insert = n.insert
8local exec_lua = n.exec_lua
9local eval = n.eval
10local feed = n.feed
11local command = n.command
12local api = n.api
13local fn = n.fn
14local eq = t.eq
15
16local hl_query_c = [[
17  ; query
18  (ERROR) @error
19
20  "if" @keyword
21  "else" @keyword
22  "for" @keyword
23  "return" @keyword
24
25  "const" @type
26  "static" @type
27  "struct" @type
28  "enum" @type
29  "extern" @type
30
31  ; nonexistent specializer for string should fallback to string
32  (string_literal) @string.nonexistent_specializer
33
34  (number_literal) @number
35  (char_literal) @string
36
37  (type_identifier) @type
38  ((type_identifier) @constant.builtin (#eq? @constant.builtin "LuaRef"))
39
40  (primitive_type) @type
41  (sized_type_specifier) @type
42
43  ; Use lua regexes
44  ((identifier) @function (#contains? @function "lua_"))
45  ((identifier) @Constant (#lua-match? @Constant "^[A-Z_]+$"))
46  ((identifier) @Normal (#vim-match? @Normal "^lstate$"))
47
48  ((binary_expression left: (identifier) @warning.left right: (identifier) @warning.right) (#eq? @warning.left @warning.right))
49
50  (comment) @comment
51]]
52
53local hl_text_c = [[
54/// Schedule Lua callback on main loop's event queue
55static int nlua_schedule(lua_State *const lstate)
56{
57  if (lua_type(lstate, 1) != LUA_TFUNCTION
58      || lstate != lstate) {
59    lua_pushliteral(lstate, "vim.schedule: expected function");
60    return lua_error(lstate);
61  }
62
63  LuaRef cb = nlua_ref(lstate, 1);
64
65  multiqueue_put(main_loop.events, nlua_schedule_event,
66                 1, (void *)(ptrdiff_t)cb);
67  return 0;
68}]]
69
70local hl_grid_legacy_c = [[
71  {18:^/// Schedule Lua callback on main loop's event queue}             |
72  {6:static} {6:int} nlua_schedule(lua_State *{6:const} lstate)                |
73  {                                                                |
74    {15:if} (lua_type(lstate, {26:1}) != LUA_TFUNCTION                       |
75        || lstate != lstate) {                                     |
76      lua_pushliteral(lstate, {26:"vim.schedule: expected function"});  |
77      {15:return} lua_error(lstate);                                    |
78    }                                                              |
79                                                                   |
80    LuaRef cb = nlua_ref(lstate, {26:1});                               |
81                                                                   |
82    multiqueue_put(main_loop.events, nlua_schedule_event,          |
83                   {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
84    {15:return} {26:0};                                                      |
85  }                                                                |
86  {1:~                                                                }|*2
87  14 more lines                                                    |
88]]
89
90local hl_grid_ts_c = [[
91  {18:^/// Schedule Lua callback on main loop's event queue}             |
92  {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
93  {                                                                |
94    {15:if} ({25:lua_type}(lstate, {26:1}) != {26:LUA_TFUNCTION}                       |
95        || {19:lstate} != {19:lstate}) {                                     |
96      {25:lua_pushliteral}(lstate, {26:"vim.schedule: expected function"});  |
97      {15:return} {25:lua_error}(lstate);                                    |
98    }                                                              |
99                                                                   |
100    {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
101                                                                   |
102    multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
103                   {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
104    {15:return} {26:0};                                                      |
105  }                                                                |
106  {1:~                                                                }|*2
107  {MATCH:1?4? m?o?r?e? l?i?n?e?s?.*}|
108]]
109
110local test_text_c = [[
111void ui_refresh(void)
112{
113  int width = INT_MAX, height = INT_MAX;
114  bool ext_widgets[kUIExtCount];
115  for (UIExtension i = 0; (int)i < kUIExtCount; i++) {
116    ext_widgets[i] = true;
117  }
118
119  bool inclusive = ui_override();
120  for (size_t i = 0; i < ui_count; i++) {
121    UI *ui = uis[i];
122    width = MIN(ui->width, width);
123    height = MIN(ui->height, height);
124    foo = BAR(ui->bazaar, bazaar);
125    for (UIExtension j = 0; (int)j < kUIExtCount; j++) {
126      ext_widgets[j] &= (ui->ui_ext[j] || inclusive);
127    }
128  }
129}]]
130
131local injection_text_c = [[
132int x = INT_MAX;
133#define READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
134#define foo void main() { \
135              return 42;  \
136            }
137]]
138
139local injection_grid_c = [[
140  int x = INT_MAX;                                                 |
141  #define READ_STRING(x, y) (char *)read_string((x), (size_t)(y))  |
142  #define foo void main() { \                                      |
143                return 42;  \                                      |
144              }                                                    |
145  ^                                                                 |
146  {1:~                                                                }|*11
147                                                                   |
148]]
149
150local injection_grid_expected_c = [[
151  {6:int} x = {26:INT_MAX};                                                 |
152  #define {26:READ_STRING}(x, y) ({6:char} *)read_string((x), ({6:size_t})(y))  |
153  #define foo {6:void} main() { \                                      |
154                {15:return} {26:42};  \                                      |
155              }                                                    |
156  ^                                                                 |
157  {1:~                                                                }|*11
158                                                                   |
159]]
160
161describe('treesitter highlighting (C)', function()
162  local screen --- @type test.functional.ui.screen
163
164  before_each(function()
165    clear()
166    screen = Screen.new(65, 18)
167    command [[ hi link @error ErrorMsg ]]
168    command [[ hi link @warning WarningMsg ]]
169  end)
170
171  it('starting and stopping treesitter highlight works', function()
172    command('setfiletype c | syntax on')
173    fn.setreg('r', hl_text_c)
174    feed('i<C-R><C-O>r<Esc>gg')
175    -- legacy syntax highlighting is used by default
176    screen:expect(hl_grid_legacy_c)
177
178    exec_lua(function()
179      vim.treesitter.query.set('c', 'highlights', hl_query_c)
180      vim.treesitter.start()
181    end)
182    -- treesitter highlighting is used
183    screen:expect(hl_grid_ts_c)
184
185    -- A second start() on an already-highlighted buffer is a no-op: it returns the existing
186    -- highlighter instead of replacing it (replacing it would leak the old instance's
187    -- on_bytes/on_changedtree callbacks, since destroy() is never called on it).
188    eq(
189      true,
190      exec_lua(function()
191        local buf = vim.api.nvim_get_current_buf()
192        local first = vim.treesitter.highlighter.active[buf]
193        vim.treesitter.start()
194        return first == vim.treesitter.highlighter.active[buf]
195      end)
196    )
197
198    exec_lua(function()
199      vim.treesitter.stop()
200    end)
201    -- legacy syntax highlighting is used
202    screen:expect(hl_grid_legacy_c)
203
204    exec_lua(function()
205      vim.treesitter.start()
206    end)
207    -- treesitter highlighting is used
208    screen:expect(hl_grid_ts_c)
209
210    exec_lua(function()
211      vim.treesitter.stop()
212    end)
213    -- legacy syntax highlighting is used
214    screen:expect(hl_grid_legacy_c)
215
216    exec_lua(function()
217      vim.cmd 'new | wincmd p'
218      vim.treesitter.start()
219      vim.cmd 'bdelete!'
220    end)
221    -- Does not change &syntax of the other, unrelated buffer.
222    eq('', eval('&syntax'))
223  end)
224
225  it('is updated with edits', function()
226    insert(hl_text_c)
227    feed('gg')
228    screen:expect {
229      grid = [[
230      ^/// Schedule Lua callback on main loop's event queue             |
231      static int nlua_schedule(lua_State *const lstate)                |
232      {                                                                |
233        if (lua_type(lstate, 1) != LUA_TFUNCTION                       |
234            || lstate != lstate) {                                     |
235          lua_pushliteral(lstate, "vim.schedule: expected function");  |
236          return lua_error(lstate);                                    |
237        }                                                              |
238                                                                       |
239        LuaRef cb = nlua_ref(lstate, 1);                               |
240                                                                       |
241        multiqueue_put(main_loop.events, nlua_schedule_event,          |
242                       1, (void *)(ptrdiff_t)cb);                      |
243        return 0;                                                      |
244      }                                                                |
245      {1:~                                                                }|*2
246                                                                       |
247    ]],
248    }
249
250    exec_lua(function()
251      local parser = vim.treesitter.get_parser(0, 'c')
252      local highlighter = vim.treesitter.highlighter
253      highlighter.new(parser, { queries = { c = hl_query_c } })
254    end)
255    screen:expect(hl_grid_ts_c)
256
257    feed('5Goc<esc>dd')
258
259    screen:expect({
260      grid = [[
261        {18:/// Schedule Lua callback on main loop's event queue}             |
262        {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
263        {                                                                |
264          {15:if} ({25:lua_type}(lstate, {26:1}) != {26:LUA_TFUNCTION}                       |
265              || {19:lstate} != {19:lstate}) {                                     |
266            {25:^lua_pushliteral}(lstate, {26:"vim.schedule: expected function"});  |
267            {15:return} {25:lua_error}(lstate);                                    |
268          }                                                              |
269                                                                         |
270          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
271                                                                         |
272          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
273                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
274          {15:return} {26:0};                                                      |
275        }                                                                |
276        {1:~                                                                }|*2
277                                                                         |
278      ]],
279    })
280
281    feed('7Go*/<esc>')
282    screen:expect({
283      grid = [[
284        {18:/// Schedule Lua callback on main loop's event queue}             |
285        {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
286        {                                                                |
287          {15:if} ({25:lua_type}(lstate, {26:1}) != {26:LUA_TFUNCTION}                       |
288              || {19:lstate} != {19:lstate}) {                                     |
289            {25:lua_pushliteral}(lstate, {26:"vim.schedule: expected function"});  |
290            {15:return} {25:lua_error}(lstate);                                    |
291        {9:*^/}                                                               |
292          }                                                              |
293                                                                         |
294          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
295                                                                         |
296          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
297                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
298          {15:return} {26:0};                                                      |
299        }                                                                |
300        {1:~                                                                }|
301                                                                         |
302      ]],
303    })
304
305    feed('3Go/*<esc>')
306    screen:expect({
307      grid = [[
308        {18:/// Schedule Lua callback on main loop's event queue}             |
309        {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
310        {                                                                |
311        {18:/^*}                                                               |
312        {18:  if (lua_type(lstate, 1) != LUA_TFUNCTION}                       |
313        {18:      || lstate != lstate) {}                                     |
314        {18:    lua_pushliteral(lstate, "vim.schedule: expected function");}  |
315        {18:    return lua_error(lstate);}                                    |
316        {18:*/}                                                               |
317          }                                                              |
318                                                                         |
319          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
320                                                                         |
321          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
322                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
323          {15:return} {26:0};                                                      |
324        {9:}}                                                                |
325                                                                         |
326      ]],
327    })
328
329    feed('gg$')
330    feed('~')
331    screen:expect({
332      grid = [[
333        {18:/// Schedule Lua callback on main loop's event queu^E}             |
334        {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
335        {                                                                |
336        {18:/*}                                                               |
337        {18:  if (lua_type(lstate, 1) != LUA_TFUNCTION}                       |
338        {18:      || lstate != lstate) {}                                     |
339        {18:    lua_pushliteral(lstate, "vim.schedule: expected function");}  |
340        {18:    return lua_error(lstate);}                                    |
341        {18:*/}                                                               |
342          }                                                              |
343                                                                         |
344          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
345                                                                         |
346          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
347                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
348          {15:return} {26:0};                                                      |
349        {9:}}                                                                |
350                                                                         |
351      ]],
352    })
353
354    feed('re')
355    screen:expect({
356      grid = [[
357        {18:/// Schedule Lua callback on main loop's event queu^e}             |
358        {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
359        {                                                                |
360        {18:/*}                                                               |
361        {18:  if (lua_type(lstate, 1) != LUA_TFUNCTION}                       |
362        {18:      || lstate != lstate) {}                                     |
363        {18:    lua_pushliteral(lstate, "vim.schedule: expected function");}  |
364        {18:    return lua_error(lstate);}                                    |
365        {18:*/}                                                               |
366          }                                                              |
367                                                                         |
368          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
369                                                                         |
370          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
371                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
372          {15:return} {26:0};                                                      |
373        {9:}}                                                                |
374                                                                         |
375      ]],
376    })
377  end)
378
379  it('is updated with :sort', function()
380    insert(test_text_c)
381    exec_lua(function()
382      local parser = vim.treesitter.get_parser(0, 'c')
383      vim.treesitter.highlighter.new(parser, { queries = { c = hl_query_c } })
384    end)
385    screen:expect({
386      grid = [[
387          {6:int} width = {26:INT_MAX}, height = {26:INT_MAX};                         |
388          {6:bool} ext_widgets[kUIExtCount];                                 |
389          {15:for} ({6:UIExtension} i = {26:0}; ({6:int})i < kUIExtCount; i++) {           |
390            ext_widgets[i] = true;                                       |
391          }                                                              |
392                                                                         |
393          {6:bool} inclusive = ui_override();                                |
394          {15:for} ({6:size_t} i = {26:0}; i < ui_count; i++) {                        |
395            {6:UI} *ui = uis[i];                                             |
396            width = {26:MIN}(ui->width, width);                               |
397            height = {26:MIN}(ui->height, height);                            |
398            foo = {26:BAR}(ui->bazaar, bazaar);                               |
399            {15:for} ({6:UIExtension} j = {26:0}; ({6:int})j < kUIExtCount; j++) {         |
400              ext_widgets[j] &= (ui->ui_ext[j] || inclusive);            |
401            }                                                            |
402          }                                                              |
403        ^}                                                                |
404                                                                         |
405      ]],
406    })
407
408    feed ':sort<cr>'
409    screen:expect({
410      grid = [[
411        ^                                                                 |
412              ext_widgets[j] &= (ui->ui_ext[j] || inclusive);            |
413            {6:UI} *ui = uis[i];                                             |
414            ext_widgets[i] = true;                                       |
415            foo = {26:BAR}(ui->bazaar, bazaar);                               |
416            {15:for} ({6:UIExtension} j = {26:0}; ({6:int})j < kUIExtCount; j++) {         |
417            height = {26:MIN}(ui->height, height);                            |
418            width = {26:MIN}(ui->width, width);                               |
419            }                                                            |
420          {6:bool} ext_widgets[kUIExtCount];                                 |
421          {6:bool} inclusive = ui_override();                                |
422          {15:for} ({6:UIExtension} i = {26:0}; ({6:int})i < kUIExtCount; i++) {           |
423          {15:for} ({6:size_t} i = {26:0}; i < ui_count; i++) {                        |
424          {6:int} width = {26:INT_MAX}, height = {26:INT_MAX};                         |
425          }                                                              |*2
426        {6:void} ui_refresh({6:void})                                            |
427        :sort                                                            |
428      ]],
429    })
430
431    feed 'u:<esc>'
432
433    screen:expect({
434      grid = [[
435          {6:int} width = {26:INT_MAX}, height = {26:INT_MAX};                         |
436          {6:bool} ext_widgets[kUIExtCount];                                 |
437          {15:for} ({6:UIExtension} i = {26:0}; ({6:int})i < kUIExtCount; i++) {           |
438            ext_widgets[i] = true;                                       |
439          }                                                              |
440                                                                         |
441          {6:bool} inclusive = ui_override();                                |
442          {15:for} ({6:size_t} i = {26:0}; i < ui_count; i++) {                        |
443            {6:UI} *ui = uis[i];                                             |
444            width = {26:MIN}(ui->width, width);                               |
445            height = {26:MIN}(ui->height, height);                            |
446            foo = {26:BAR}(ui->bazaar, bazaar);                               |
447            {15:for} ({6:UIExtension} j = {26:0}; ({6:int})j < kUIExtCount; j++) {         |
448              ext_widgets[j] &= (ui->ui_ext[j] || inclusive);            |
449            }                                                            |
450          }                                                              |
451        ^}                                                                |
452                                                                         |
453      ]],
454    })
455  end)
456
457  it('supports with custom parser', function()
458    insert(test_text_c)
459
460    screen:expect {
461      grid = [[
462      int width = INT_MAX, height = INT_MAX;                         |
463      bool ext_widgets[kUIExtCount];                                 |
464      for (UIExtension i = 0; (int)i < kUIExtCount; i++) {           |
465        ext_widgets[i] = true;                                       |
466      }                                                              |
467                                                                     |
468      bool inclusive = ui_override();                                |
469      for (size_t i = 0; i < ui_count; i++) {                        |
470        UI *ui = uis[i];                                             |
471        width = MIN(ui->width, width);                               |
472        height = MIN(ui->height, height);                            |
473        foo = BAR(ui->bazaar, bazaar);                               |
474        for (UIExtension j = 0; (int)j < kUIExtCount; j++) {         |
475          ext_widgets[j] &= (ui->ui_ext[j] || inclusive);            |
476        }                                                            |
477      }                                                              |
478    ^}                                                                |
479                                                                     |
480    ]],
481    }
482
483    exec_lua(function()
484      local parser = vim.treesitter.get_parser(0, 'c')
485      local query = vim.treesitter.query.parse('c', '(declaration) @decl')
486
487      local nodes = {}
488      for _, node in query:iter_captures(parser:parse()[1]:root(), 0, 0, 19) do
489        table.insert(nodes, node)
490      end
491
492      parser:set_included_regions({ nodes })
493
494      vim.treesitter.highlighter.new(parser, { queries = { c = '(identifier) @type' } })
495    end)
496
497    screen:expect({
498      grid = [[
499          int {6:width} = {6:INT_MAX}, {6:height} = {6:INT_MAX};                         |
500          bool {6:ext_widgets}[{6:kUIExtCount}];                                 |
501          for (UIExtension {6:i} = 0; (int)i < kUIExtCount; i++) {           |
502            ext_widgets[i] = true;                                       |
503          }                                                              |
504                                                                         |
505          bool {6:inclusive} = {6:ui_override}();                                |
506          for (size_t {6:i} = 0; i < ui_count; i++) {                        |
507            UI *{6:ui} = {6:uis}[{6:i}];                                             |
508            width = MIN(ui->width, width);                               |
509            height = MIN(ui->height, height);                            |
510            foo = BAR(ui->bazaar, bazaar);                               |
511            for (UIExtension {6:j} = 0; (int)j < kUIExtCount; j++) {         |
512              ext_widgets[j] &= (ui->ui_ext[j] || inclusive);            |
513            }                                                            |
514          }                                                              |
515        ^}                                                                |
516                                                                         |
517      ]],
518    })
519  end)
520
521  it('supports injected languages', function()
522    insert(injection_text_c)
523
524    screen:expect { grid = injection_grid_c }
525
526    exec_lua(function()
527      local parser = vim.treesitter.get_parser(0, 'c', {
528        injections = {
529          c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))',
530        },
531      })
532      local highlighter = vim.treesitter.highlighter
533      highlighter.new(parser, { queries = { c = hl_query_c } })
534    end)
535
536    screen:expect { grid = injection_grid_expected_c }
537  end)
538
539  it('supports combined injections #31777', function()
540    insert([=[
541      -- print([[
542      -- some
543      -- random
544      -- text
545      -- here]])
546    ]=])
547
548    exec_lua(function()
549      local parser = vim.treesitter.get_parser(0, 'lua', {
550        injections = {
551          lua = [[
552          ; query
553          ((comment_content) @injection.content
554            (#set! injection.self)
555            (#set! injection.combined))
556          ]],
557        },
558      })
559      local highlighter = vim.treesitter.highlighter
560      highlighter.new(parser, {
561        queries = {
562          lua = [[
563            ; query
564            (string) @string
565            (comment) @comment
566            (function_call (identifier) @function.call)
567            [ "(" ")" ] @punctuation.bracket
568          ]],
569        },
570      })
571    end)
572
573    screen:expect([=[
574      {18:-- }{25:print}{16:(}{26:[[}                                                      |
575      {18:--}{26: some}                                                          |
576      {18:--}{26: random}                                                        |
577      {18:--}{26: text}                                                          |
578      {18:--}{26: here]]}{16:)}                                                       |
579      ^                                                                 |
580      {1:~                                                                }|*11
581                                                                       |
582    ]=])
583  end)
584
585  it('supports complicated combined injections', function()
586    insert([[
587      -- # Markdown here
588      --
589      -- ```c
590      -- int main() {
591      --   printf("Hello, world!");
592      -- }
593      -- ```
594    ]])
595
596    exec_lua(function()
597      local parser = vim.treesitter.get_parser(0, 'lua', {
598        injections = {
599          lua = [[
600          ; query
601          ((comment) @injection.content
602            (#offset! @injection.content 0 3 0 1)
603            (#lua-match? @injection.content "[-][-] ")
604            (#set! injection.combined)
605            (#set! injection.include-children)
606            (#set! injection.language "markdown"))
607          ]],
608        },
609      })
610      local highlighter = vim.treesitter.highlighter
611      highlighter.new(parser, {
612        queries = {
613          lua = [[
614            ; query
615            (string) @string
616            (comment) @comment
617            (function_call (identifier) @function.call)
618            [ "(" ")" ] @punctuation.bracket
619          ]],
620        },
621      })
622    end)
623
624    screen:add_extra_attr_ids({
625      [131] = { foreground = Screen.colors.Fuchsia, bold = true },
626    })
627
628    screen:expect([[
629      {18:-- }{131:# Markdown here}                                               |
630      {18:--}                                                               |
631      {18:-- ```}{15:c}                                                          |
632      {18:-- }{16:int}{18: }{25:main}{16:()}{18: }{16:{}                                                  |
633      {18:--   }{25:printf}{16:(}{26:"Hello, world!"}{16:);}                                    |
634      {18:-- }{16:}}                                                             |
635      {18:-- ```}                                                           |
636      ^                                                                 |
637      {1:~                                                                }|*9
638                                                                       |
639    ]])
640  end)
641
642  it("supports injecting by ft name in metadata['injection.language']", function()
643    insert(injection_text_c)
644
645    screen:expect { grid = injection_grid_c }
646
647    exec_lua(function()
648      vim.treesitter.language.register('c', 'foo')
649      local parser = vim.treesitter.get_parser(0, 'c', {
650        injections = {
651          c = '(preproc_def (preproc_arg) @injection.content (#set! injection.language "foo")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "foo"))',
652        },
653      })
654      local highlighter = vim.treesitter.highlighter
655      highlighter.new(parser, { queries = { c = hl_query_c } })
656    end)
657
658    screen:expect { grid = injection_grid_expected_c }
659  end)
660
661  it('supports overriding queries, like ', function()
662    insert([[
663    int x = INT_MAX;
664    #define READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
665    #define foo void main() { \
666                  return 42;  \
667                }
668    ]])
669
670    exec_lua(function()
671      local injection_query =
672        '(preproc_def (preproc_arg) @injection.content (#set! injection.language "c")) (preproc_function_def value: (preproc_arg) @injection.content (#set! injection.language "c"))'
673      vim.treesitter.query.set('c', 'highlights', hl_query_c)
674      vim.treesitter.query.set('c', 'injections', injection_query)
675
676      vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
677    end)
678
679    screen:expect({
680      grid = [[
681        {6:int} x = {26:INT_MAX};                                                 |
682        #define {26:READ_STRING}(x, y) ({6:char} *)read_string((x), ({6:size_t})(y))  |
683        #define foo {6:void} main() { \                                      |
684                      {15:return} {26:42};  \                                      |
685                    }                                                    |
686        ^                                                                 |
687        {1:~                                                                }|*11
688                                                                         |
689      ]],
690    })
691  end)
692
693  it('supports highlighting with custom highlight groups', function()
694    insert(hl_text_c)
695    feed('gg')
696
697    exec_lua(function()
698      local parser = vim.treesitter.get_parser(0, 'c')
699      vim.treesitter.highlighter.new(parser, { queries = { c = hl_query_c } })
700    end)
701
702    screen:expect(hl_grid_ts_c)
703
704    -- This will change ONLY the literal strings to look like comments
705    -- The only literal string is the "vim.schedule: expected function" in this test.
706    exec_lua [[vim.cmd("highlight link @string.nonexistent_specializer comment")]]
707    screen:expect({
708      grid = [[
709        {18:^/// Schedule Lua callback on main loop's event queue}             |
710        {6:static} {6:int} {25:nlua_schedule}({6:lua_State} *{6:const} lstate)                |
711        {                                                                |
712          {15:if} ({25:lua_type}(lstate, {26:1}) != {26:LUA_TFUNCTION}                       |
713              || {19:lstate} != {19:lstate}) {                                     |
714            {25:lua_pushliteral}(lstate, {18:"vim.schedule: expected function"});  |
715            {15:return} {25:lua_error}(lstate);                                    |
716          }                                                              |
717                                                                         |
718          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
719                                                                         |
720          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
721                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
722          {15:return} {26:0};                                                      |
723        }                                                                |
724        {1:~                                                                }|*2
725                                                                         |
726      ]],
727    })
728    screen:expect { unchanged = true }
729  end)
730
731  it('supports highlighting with priority', function()
732    insert([[
733    int x = INT_MAX;
734    #define READ_STRING(x, y) (char *)read_string((x), (size_t)(y))
735    #define foo void main() { \
736                  return 42;  \
737                }
738    ]])
739
740    exec_lua(function()
741      local parser = vim.treesitter.get_parser(0, 'c')
742      vim.treesitter.highlighter.new(parser, {
743        queries = {
744          c = hl_query_c .. '\n((translation_unit) @constant (#set! "priority" 101))\n',
745        },
746      })
747    end)
748    -- expect everything to have Constant highlight
749    screen:expect {
750      grid = [[
751      {12:int}{8: x = INT_MAX;}                                                 |
752      {8:#define READ_STRING(x, y) (}{12:char}{8: *)read_string((x), (}{12:size_t}{8:)(y))}  |
753      {8:#define foo }{12:void}{8: main() { \}                                      |
754      {8:              }{12:return}{8: 42;  \}                                      |
755      {8:            }}                                                    |
756      ^                                                                 |
757      {1:~                                                                }|*11
758                                                                       |
759    ]],
760      attr_ids = {
761        [1] = { bold = true, foreground = Screen.colors.Blue1 },
762        [8] = { foreground = Screen.colors.Magenta1 },
763        -- bold will not be overwritten at the moment
764        [12] = { bold = true, foreground = Screen.colors.Magenta1 },
765      },
766    }
767
768    eq({
769      {
770        capture = 'constant',
771        metadata = { priority = '101' },
772        lang = 'c',
773        id = 14,
774        pattern_id = 23,
775        row = 0,
776        col = 0,
777        end_row = 6,
778        end_col = 0,
779      },
780      {
781        capture = 'type',
782        metadata = {},
783        lang = 'c',
784        id = 3,
785        pattern_id = 16,
786        row = 0,
787        col = 0,
788        end_row = 0,
789        end_col = 3,
790      },
791    }, exec_lua [[ return vim.treesitter.get_captures_at_pos(0, 0, 2) ]])
792  end)
793
794  it(
795    "allows to use captures with dots (don't use fallback when specialization of foo exists)",
796    function()
797      insert([[
798    char* x = "Will somebody ever read this?";
799    ]])
800
801      screen:expect {
802        grid = [[
803      char* x = "Will somebody ever read this?";                       |
804      ^                                                                 |
805      {1:~                                                                }|*15
806                                                                       |
807    ]],
808      }
809
810      command [[
811      hi link @foo.bar Type
812      hi link @foo String
813    ]]
814      exec_lua(function()
815        local parser = vim.treesitter.get_parser(0, 'c', {})
816        local highlighter = vim.treesitter.highlighter
817        highlighter.new(
818          parser,
819          { queries = { c = '(primitive_type) @foo.bar (string_literal) @foo' } }
820        )
821      end)
822
823      screen:expect({
824        grid = [[
825          {6:char}* x = {26:"Will somebody ever read this?"};                       |
826          ^                                                                 |
827          {1:~                                                                }|*15
828                                                                           |
829        ]],
830      })
831
832      -- clearing specialization reactivates fallback
833      command [[ hi clear @foo.bar ]]
834      screen:expect({
835        grid = [[
836          {26:char}* x = {26:"Will somebody ever read this?"};                       |
837          ^                                                                 |
838          {1:~                                                                }|*15
839                                                                           |
840        ]],
841      })
842    end
843  )
844
845  it('supports conceal attribute', function()
846    insert(hl_text_c)
847
848    -- conceal can be empty or a single cchar.
849    exec_lua(function()
850      vim.opt.cole = 2
851      local parser = vim.treesitter.get_parser(0, 'c')
852      vim.treesitter.highlighter.new(parser, {
853        queries = {
854          c = [[
855        ("static" @keyword
856         (#set! conceal "R"))
857
858        ((identifier) @Identifier
859         (#set! conceal "")
860         (#eq? @Identifier "lstate"))
861
862        ((call_expression
863            function: (identifier) @function
864            arguments: (argument_list) @arguments)
865         (#eq? @function "multiqueue_put")
866         (#set! @function conceal "V"))
867      ]],
868        },
869      })
870    end)
871
872    screen:expect({
873      grid = [[
874        /// Schedule Lua callback on main loop's event queue             |
875        {15:R} int nlua_schedule(lua_State *const )                           |
876        {                                                                |
877          if (lua_type(, 1) != LUA_TFUNCTION                             |
878              ||  != ) {                                                 |
879            lua_pushliteral(, "vim.schedule: expected function");        |
880            return lua_error();                                          |
881          }                                                              |
882                                                                         |
883          LuaRef cb = nlua_ref(, 1);                                     |
884                                                                         |
885          {25:V}(main_loop.events, nlua_schedule_event,                       |
886                         1, (void *)(ptrdiff_t)cb);                      |
887          return 0;                                                      |
888        ^}                                                                |
889        {1:~                                                                }|*2
890                                                                         |
891      ]],
892    })
893  end)
894
895  it('supports @noconceal', function()
896    insert([[
897      int foo = bar;
898    ]])
899
900    exec_lua(function()
901      vim.opt.cole = 2
902      local parser = vim.treesitter.get_parser(0, 'c')
903      vim.treesitter.highlighter.new(parser, {
904        queries = {
905          c = [[
906        ((identifier) @conceal
907         (#set! conceal "X"))
908
909        ((identifier) @noconceal
910         (#eq? @noconceal "bar"))
911      ]],
912        },
913      })
914    end)
915
916    screen:expect({
917      grid = [[
918        int {14:X} = bar;                                                     |
919        ^                                                                 |
920        {1:~                                                                }|*15
921                                                                         |
922      ]],
923    })
924  end)
925
926  it('@foo.bar groups has the correct fallback behavior', function()
927    local get_hl = function(name)
928      return api.nvim_get_hl_by_name(name, 1).foreground
929    end
930    api.nvim_set_hl(0, '@foo', { fg = 1 })
931    api.nvim_set_hl(0, '@foo.bar', { fg = 2 })
932    api.nvim_set_hl(0, '@foo.bar.baz', { fg = 3 })
933
934    eq(1, get_hl '@foo')
935    eq(1, get_hl '@foo.a.b.c.d')
936    eq(2, get_hl '@foo.bar')
937    eq(2, get_hl '@foo.bar.a.b.c.d')
938    eq(3, get_hl '@foo.bar.baz')
939    eq(3, get_hl '@foo.bar.baz.d')
940
941    -- lookup is case insensitive
942    eq(2, get_hl '@FOO.BAR.SPAM')
943
944    api.nvim_set_hl(0, '@foo.missing.exists', { fg = 3 })
945    eq(1, get_hl '@foo.missing')
946    eq(3, get_hl '@foo.missing.exists')
947    eq(3, get_hl '@foo.missing.exists.bar')
948    eq(nil, get_hl '@total.nonsense.but.a.lot.of.dots')
949  end)
950
951  it('supports multiple nodes assigned to the same capture #17060', function()
952    insert([[
953      int x = 4;
954      int y = 5;
955      int z = 6;
956    ]])
957
958    exec_lua(function()
959      local query = '((declaration)+ @string)'
960      vim.treesitter.query.set('c', 'highlights', query)
961      vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
962    end)
963
964    screen:expect({
965      grid = [[
966        {26:int x = 4;}                                                       |
967        {26:int y = 5;}                                                       |
968        {26:int z = 6;}                                                       |
969        ^                                                                 |
970        {1:~                                                                }|*13
971                                                                         |
972      ]],
973    })
974  end)
975
976  it('gives higher priority to more specific captures #27895', function()
977    insert([[
978      void foo(int *bar);
979    ]])
980
981    local query = [[
982      "*" @operator
983
984      (parameter_declaration
985        declarator: (pointer_declarator) @variable.parameter)
986    ]]
987
988    exec_lua(function()
989      vim.treesitter.query.set('c', 'highlights', query)
990      vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
991    end)
992
993    screen:expect({
994      grid = [[
995        void foo(int {15:*}{25:bar});                                              |
996        ^                                                                 |
997        {1:~                                                                }|*15
998                                                                         |
999      ]],
1000    })
1001  end)
1002
1003  it('highlights applied to first line of closed fold', function()
1004    insert(hl_text_c)
1005    exec_lua(function()
1006      vim.treesitter.query.set('c', 'highlights', hl_query_c)
1007      vim.treesitter.highlighter.new(vim.treesitter.get_parser(0, 'c'))
1008    end)
1009    feed('ggjzfj')
1010    command('set foldtext=')
1011    screen:add_extra_attr_ids({
1012      [100] = {
1013        bold = true,
1014        background = Screen.colors.LightGray,
1015        foreground = Screen.colors.SeaGreen4,
1016      },
1017      [101] = { background = Screen.colors.LightGray, foreground = Screen.colors.DarkCyan },
1018    })
1019    screen:expect({
1020      grid = [[
1021        {18:/// Schedule Lua callback on main loop's event queue}             |
1022        {100:^static}{13: }{100:int}{13: }{101:nlua_schedule}{13:(}{100:lua_State}{13: *}{100:const}{13: lstate)················}|
1023          {15:if} ({25:lua_type}(lstate, {26:1}) != {26:LUA_TFUNCTION}                       |
1024              || {19:lstate} != {19:lstate}) {                                     |
1025            {25:lua_pushliteral}(lstate, {26:"vim.schedule: expected function"});  |
1026            {15:return} {25:lua_error}(lstate);                                    |
1027          }                                                              |
1028                                                                         |
1029          {29:LuaRef} cb = {25:nlua_ref}(lstate, {26:1});                               |
1030                                                                         |
1031          multiqueue_put(main_loop.events, {25:nlua_schedule_event},          |
1032                         {26:1}, ({6:void} *)({6:ptrdiff_t})cb);                      |
1033          {15:return} {26:0};                                                      |
1034        }                                                                |
1035        {1:~                                                                }|*3
1036                                                                         |
1037      ]],
1038    })
1039  end)
1040
1041  it('#35575', function()
1042    -- Window size is 14x14, and first string literal ends at byte 14
1043    -- See: https://github.com/neovim/neovim/pull/35587
1044    screen:try_resize(14, 15)
1045
1046    exec_lua(function()
1047      local line = 'A a="\240\157\158\140\240\157\158\140" "aaaaaaaaaaaaaaaaaaaaaaaa";'
1048      vim.api.nvim_buf_set_lines(0, 0, -1, true, { line })
1049      vim.cmd('set nowrap')
1050      vim.treesitter.query.set('c', 'highlights', hl_query_c)
1051      vim.treesitter.start(0, 'c')
1052    end)
1053
1054    screen:expect([[
1055      {6:^A} a={26:"𝞌𝞌"} {26:"aaaa}|
1056      {1:~             }|*13
1057                    |
1058    ]])
1059  end)
1060end)
1061
1062describe('treesitter highlighting (lua)', function()
1063  local screen
1064
1065  before_each(function()
1066    clear()
1067    screen = Screen.new(65, 18)
1068  end)
1069
1070  it('supports language injections', function()
1071    insert [[
1072      local ffi = require('ffi')
1073      ffi.cdef("int (*fun)(int, char *);")
1074    ]]
1075
1076    exec_lua(function()
1077      vim.bo.filetype = 'lua'
1078      vim.treesitter.start()
1079    end)
1080
1081    screen:expect({
1082      grid = [[
1083        {15:local} {25:ffi} {15:=} {16:require(}{26:'ffi'}{16:)}                                       |
1084        {25:ffi}{16:.}{25:cdef}{16:(}{26:"}{16:int}{26: }{16:(}{15:*}{26:fun}{16:)(int,}{26: }{16:char}{26: }{15:*}{16:);}{26:"}{16:)}                             |
1085        ^                                                                 |
1086        {1:~                                                                }|*14
1087                                                                         |
1088      ]],
1089    })
1090  end)
1091
1092  it('removes outdated highlights', function()
1093    insert('-- int main() {}' .. string.rep("\nprint('test')", 20) .. '\n-- int other() {}')
1094
1095    exec_lua(function()
1096      vim.cmd.norm('gg')
1097      vim.treesitter.query.set(
1098        'lua',
1099        'injections',
1100        [[((comment_content) @injection.content
1101            (#set! injection.combined)
1102            (#set! injection.language "c"))]]
1103      )
1104      vim.bo.filetype = 'lua'
1105      vim.treesitter.start()
1106    end)
1107
1108    screen:expect([[
1109      {18:^-- }{16:int}{18: }{25:main}{16:()}{18: }{16:{}}                                                 |
1110      {16:print(}{26:'test'}{16:)}                                                    |*16
1111                                                                       |
1112    ]])
1113
1114    exec_lua(function()
1115      vim.cmd.norm('gg0dw')
1116    end)
1117
1118    screen:expect([[
1119      {25:^int} {25:main}{16:()} {16:{}}                                                    |
1120      {16:print(}{26:'test'}{16:)}                                                    |*16
1121                                                                       |
1122    ]])
1123  end)
1124end)
1125
1126describe('treesitter highlighting (help)', function()
1127  local screen
1128
1129  before_each(function()
1130    clear()
1131    screen = Screen.new(40, 6)
1132  end)
1133
1134  it('defaults in vimdoc/highlights.scm', function()
1135    -- Avoid regressions when syncing upstream vimdoc queries.
1136
1137    insert [[
1138    ==============================================================================
1139    NVIM DOCUMENTATION
1140
1141    ------------------------------------------------------------------------------
1142    ABOUT NVIM                                                     *tag-1* *tag-2*
1143
1144    |news|			News
1145    |nvim|			NVim
1146    ]]
1147
1148    feed('gg')
1149    exec_lua(function()
1150      vim.wo.wrap = false
1151      vim.bo.filetype = 'help'
1152      vim.treesitter.start()
1153    end)
1154
1155    screen:add_extra_attr_ids({
1156      [100] = { nocombine = true, underdouble = true },
1157      [101] = { foreground = Screen.colors.Fuchsia, bold = true },
1158      [102] = { underline = true, nocombine = true },
1159    })
1160    screen:expect({
1161      grid = [[
1162        {100:^========================================}|
1163        {101:NVIM DOCUMENTATION}                      |
1164                                                |
1165        {102:----------------------------------------}|
1166        {101:ABOUT NVIM}                              |
1167                                                |
1168      ]],
1169    })
1170  end)
1171
1172  it('correctly redraws added/removed injections', function()
1173    insert [[
1174    >ruby
1175      -- comment
1176      local this_is = 'actually_lua'
1177    <
1178    ]]
1179
1180    exec_lua(function()
1181      vim.bo.filetype = 'help'
1182      vim.treesitter.start()
1183    end)
1184
1185    screen:expect({
1186      grid = [[
1187        {18:>}{15:ruby}                                   |
1188        {18:  -- comment}                            |
1189        {18:  local this_is = 'actually_lua'}        |
1190        {18:<}                                       |
1191        ^                                        |
1192                                                |
1193      ]],
1194    })
1195
1196    n.api.nvim_buf_set_text(0, 0, 1, 0, 5, { 'lua' })
1197
1198    screen:expect({
1199      grid = [[
1200        {18:>}{15:lua}                                    |
1201        {18:  -- comment}                            |
1202        {18:  }{15:local}{18: }{25:this_is}{18: }{15:=}{18: }{26:'actually_lua'}        |
1203        {18:<}                                       |
1204        ^                                        |
1205                                                |
1206      ]],
1207    })
1208
1209    n.api.nvim_buf_set_text(0, 0, 1, 0, 4, { 'ruby' })
1210
1211    screen:expect({
1212      grid = [[
1213        {18:>}{15:ruby}                                   |
1214        {18:  -- comment}                            |
1215        {18:  local this_is = 'actually_lua'}        |
1216        {18:<}                                       |
1217        ^                                        |
1218                                                |
1219      ]],
1220    })
1221  end)
1222
1223  it('correctly redraws injections subpriorities', function()
1224    -- The top level string node will be highlighted first
1225    -- with an extmark spanning multiple lines.
1226    -- When the next line is drawn, which includes an injection,
1227    -- make sure the highlight appears above the base tree highlight
1228
1229    insert([=[
1230    local s = [[
1231      local also = lua
1232    ]]
1233    ]=])
1234
1235    exec_lua(function()
1236      local parser = vim.treesitter.get_parser(0, 'lua', {
1237        injections = {
1238          lua = '(string content: (_) @injection.content (#set! injection.language lua))',
1239        },
1240      })
1241
1242      vim.treesitter.highlighter.new(parser)
1243    end)
1244
1245    screen:expect({
1246      grid = [=[
1247        {15:local} {25:s} {15:=} {26:[[}                            |
1248        {26:  }{15:local}{26: }{25:also}{26: }{15:=}{26: }{25:lua}                      |
1249        {26:]]}                                      |
1250        ^                                        |
1251        {1:~                                       }|
1252                                                |
1253      ]=],
1254    })
1255  end)
1256end)
1257
1258describe('treesitter highlighting (nested injections)', function()
1259  local screen --- @type test.functional.ui.screen
1260
1261  before_each(function()
1262    clear()
1263    screen = Screen.new(80, 7)
1264  end)
1265
1266  it('correctly redraws nested injections (GitHub #25252)', function()
1267    insert [=[
1268function foo() print("Lua!") end
1269
1270local lorem = {
1271    ipsum = {},
1272    bar = {},
1273}
1274vim.cmd([[
1275    augroup RustLSP
1276    autocmd CursorHold silent! lua vim.lsp.buf.document_highlight()
1277    augroup END
1278]])
1279    ]=]
1280
1281    exec_lua(function()
1282      vim.opt.scrolloff = 0
1283      vim.bo.filetype = 'lua'
1284      vim.treesitter.start()
1285    end)
1286
1287    -- invalidate the language tree
1288    feed('ggi--[[<ESC>04x')
1289
1290    screen:expect({
1291      grid = [[
1292        {15:^function} {25:foo}{16:()} {16:print(}{26:"Lua!"}{16:)} {15:end}                                                |
1293                                                                                        |
1294        {15:local} {25:lorem} {15:=} {16:{}                                                                 |
1295            {25:ipsum} {15:=} {16:{},}                                                                 |
1296            {25:bar} {15:=} {16:{},}                                                                   |
1297        {16:}}                                                                               |
1298                                                                                        |
1299      ]],
1300    })
1301
1302    -- spam newline insert/delete to invalidate Lua > Vim > Lua region
1303    feed('3jo<ESC>ddko<ESC>ddko<ESC>ddko<ESC>ddk0')
1304
1305    screen:expect({
1306      grid = [[
1307        {15:function} {25:foo}{16:()} {16:print(}{26:"Lua!"}{16:)} {15:end}                                                |
1308                                                                                        |
1309        {15:local} {25:lorem} {15:=} {16:{}                                                                 |
1310        ^    {25:ipsum} {15:=} {16:{},}                                                                 |
1311            {25:bar} {15:=} {16:{},}                                                                   |
1312        {16:}}                                                                               |
1313                                                                                        |
1314      ]],
1315    })
1316  end)
1317end)
1318
1319describe('treesitter highlighting (markdown)', function()
1320  local screen
1321
1322  before_each(function()
1323    clear()
1324    screen = Screen.new(40, 6)
1325    exec_lua(function()
1326      vim.bo.filetype = 'markdown'
1327      vim.treesitter.start()
1328    end)
1329  end)
1330
1331  it('supports hyperlinks', function()
1332    local url = 'https://example.com'
1333    insert(string.format('[This link text](%s) is a hyperlink.', url))
1334    screen:add_extra_attr_ids({
1335      [100] = { foreground = Screen.colors.DarkCyan, url = 'https://example.com' },
1336      [101] = {
1337        foreground = Screen.colors.SlateBlue,
1338        url = 'https://example.com',
1339        underline = true,
1340      },
1341    })
1342    screen:expect({
1343      grid = [[
1344        {100:[This link text](}{101:https://example.com}{100:)} is|
1345         a hyperlink^.                           |
1346        {1:~                                       }|*3
1347                                                |
1348      ]],
1349    })
1350  end)
1351
1352  local code_block = [[
1353- $f(0)=\sum_{k=1}^{\infty}\frac{2}{\pi^{2}k^{2}}+\lim_{w \to 0}x$.
1354
1355```c
1356printf('Hello World!');
1357```
1358    ]]
1359
1360  it('works with spellchecked and smoothscrolled topline', function()
1361    insert(code_block)
1362    command('set spell smoothscroll')
1363    feed('gg<C-E>')
1364    screen:add_extra_attr_ids({ [100] = { undercurl = true, special = Screen.colors.Red } })
1365    screen:expect({
1366      grid = [[
1367        {1:<<<}k^{2}}+\{100:lim}_{w \to 0}x$^.             |
1368                                                |
1369        {18:```}{15:c}                                    |
1370        {25:printf}{16:(}{26:'Hello World!'}{16:);}                 |
1371        {18:```}                                     |
1372                                                |
1373      ]],
1374    })
1375  end)
1376
1377  it('works with concealed lines', function()
1378    insert(code_block)
1379    screen:expect({
1380      grid = [[
1381                                                |
1382        {18:```}{15:c}                                    |
1383        {25:printf}{16:(}{26:'Hello World!'}{16:);}                 |
1384        {18:```}                                     |
1385        ^                                        |
1386                                                |
1387      ]],
1388    })
1389    feed('ggj')
1390    command('set number conceallevel=3')
1391    screen:expect({
1392      grid = [[
1393        {8:  1 }{16:- }$f(0)=\sum_{k=1}^{\infty}\frac{2}{|
1394        {8:    }\pi^{2}k^{2}}+\lim_{w \to 0}x$.     |
1395        {8:  2 }^                                    |
1396        {8:  4 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1397        {8:  6 }                                    |
1398                                                |
1399      ]],
1400    })
1401    feed('j')
1402    screen:expect({
1403      grid = [[
1404        {8:  1 }{16:- }$f(0)=\sum_{k=1}^{\infty}\frac{2}{|
1405        {8:    }\pi^{2}k^{2}}+\lim_{w \to 0}x$.     |
1406        {8:  2 }                                    |
1407        {8:  3 }{18:^```}{15:c}                                |
1408        {8:  4 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1409                                                |
1410      ]],
1411    })
1412    feed('j')
1413    screen:expect({
1414      grid = [[
1415        {8:  1 }{16:- }$f(0)=\sum_{k=1}^{\infty}\frac{2}{|
1416        {8:    }\pi^{2}k^{2}}+\lim_{w \to 0}x$.     |
1417        {8:  2 }                                    |
1418        {8:  4 }{25:^printf}{16:(}{26:'Hello World!'}{16:);}             |
1419        {8:  6 }                                    |
1420                                                |
1421      ]],
1422    })
1423    feed('j')
1424    screen:expect({
1425      grid = [[
1426        {8:  1 }{16:- }$f(0)=\sum_{k=1}^{\infty}\frac{2}{|
1427        {8:    }\pi^{2}k^{2}}+\lim_{w \to 0}x$.     |
1428        {8:  2 }                                    |
1429        {8:  4 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1430        {8:  5 }{18:^```}                                 |
1431                                                |
1432      ]],
1433    })
1434    -- Concealed lines highlight until changed botline
1435    screen:try_resize(screen._width, 16)
1436    feed('y3k30P:<Esc><C-F><C-B>')
1437    screen:expect([[
1438      {8:  1 }{16:- }$f(0)=\sum_{k=1}^{\infty}\frac{2}{|
1439      {8:    }\pi^{2}k^{2}}+\lim_{w \to 0}x$.     |
1440      {8:  2 }                                    |
1441      {8:  4 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1442      {8:  6 }                                    |
1443      {8:  8 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1444      {8: 10 }                                    |
1445      {8: 12 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1446      {8: 14 }                                    |
1447      {8: 16 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1448      {8: 18 }                                    |
1449      {8: 20 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1450      {8: 22 }                                    |
1451      {8: 24 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1452      {8: 25 }{18:^```}                                 |
1453                                              |
1454    ]])
1455    feed('G')
1456    screen:expect([[
1457      {8: 98 }                                    |
1458      {8:100 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1459      {8:102 }                                    |
1460      {8:104 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1461      {8:106 }                                    |
1462      {8:108 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1463      {8:110 }                                    |
1464      {8:112 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1465      {8:114 }                                    |
1466      {8:116 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1467      {8:118 }                                    |
1468      {8:120 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1469      {8:122 }                                    |
1470      {8:124 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1471      {8:126 }^                                    |
1472                                              |
1473    ]])
1474    feed('ggdj')
1475    command('set concealcursor=n')
1476    screen:expect([[
1477      {8:  2 }{25:^printf}{16:(}{26:'Hello World!'}{16:);}             |
1478      {8:  4 }                                    |
1479      {8:  6 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1480      {8:  8 }                                    |
1481      {8: 10 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1482      {8: 12 }                                    |
1483      {8: 14 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1484      {8: 16 }                                    |
1485      {8: 18 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1486      {8: 20 }                                    |
1487      {8: 22 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1488      {8: 24 }                                    |
1489      {8: 26 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1490      {8: 28 }                                    |
1491      {8: 30 }{25:printf}{16:(}{26:'Hello World!'}{16:);}             |
1492                                              |
1493    ]])
1494    exec_lua(function()
1495      vim.api.nvim_buf_set_lines(0, 0, -1, false, {})
1496      assert(vim.api.nvim_win_text_height(0, {}).all == 1, 'line concealed')
1497    end)
1498  end)
1499
1500  it('conceals backslash in hard_line_break/backslash_escape', function()
1501    command('set concealcursor=n')
1502    command('set conceallevel=2')
1503    insert('Hello\\\nWorld\nHello\\. World')
1504    screen:expect({
1505      grid = [[
1506        Hello                                   |
1507        World                                   |
1508        Hello. Worl^d                            |
1509        {1:~                                       }|*2
1510                                                |
1511      ]],
1512    })
1513  end)
1514end)
1515
1516it('starting and stopping treesitter highlight in init.lua works #29541', function()
1517  t.write_file(
1518    'Xinit.lua',
1519    [[
1520      vim.bo.ft = 'c'
1521      vim.treesitter.start()
1522      vim.treesitter.stop()
1523    ]]
1524  )
1525  finally(function()
1526    os.remove('Xinit.lua')
1527  end)
1528  clear({ args = { '-u', 'Xinit.lua' } })
1529  eq('', api.nvim_get_vvar('errmsg'))
1530
1531  local screen = Screen.new(65, 18)
1532  fn.setreg('r', hl_text_c)
1533  feed('i<C-R><C-O>r<Esc>gg')
1534  -- legacy syntax highlighting is used
1535  screen:expect(hl_grid_legacy_c)
1536end)
1537
1538it('no nil index for missing highlight query', function()
1539  clear()
1540  local cqueries = t.paths.test_source_path .. '/runtime/queries/c/'
1541  os.rename(cqueries .. 'highlights.scm', cqueries .. '_highlights.scm')
1542  finally(function()
1543    os.rename(cqueries .. '_highlights.scm', cqueries .. 'highlights.scm')
1544  end)
1545  exec_lua([[
1546    local parser = vim.treesitter.get_parser(0, 'c')
1547    vim.treesitter.highlighter.new(parser)
1548  ]])
1549end)
1550
1551it('spell navigation correctly wraps back to the first line (Row 0) #36970', function()
1552  clear()
1553  insert([[
1554mispelledone
1555mispelledtwo]])
1556
1557  command('set spell')
1558  command('set wrapscan')
1559  exec_lua(function()
1560    vim.treesitter.start(0, 'markdown')
1561  end)
1562
1563  api.nvim_win_set_cursor(0, { 2, 0 })
1564
1565  feed(']s')
1566
1567  local pos = api.nvim_win_get_cursor(0)
1568  eq(1, pos[1], 'Should have wrapped back to Line 1')
1569end)
1570
1571it('conceals lines contributed by an injected tree', function()
1572  clear()
1573  command('set conceallevel=3')
1574
1575  -- Measured without an intervening redraw, so that the conceal_line callback
1576  -- is the thing that has to parse the injection. The outer ~~~ fences come
1577  -- from the root tree, the inner ``` fences from the markdown tree injected
1578  -- into it; all four carry conceal_lines, leaving "filler", "print(1)" and
1579  -- "tail" on screen.
1580  eq(
1581    3,
1582    exec_lua(function()
1583      vim.api.nvim_buf_set_lines(0, 0, -1, false, {
1584        'filler',
1585        '~~~markdown',
1586        '```lua',
1587        'print(1)',
1588        '```',
1589        '~~~',
1590        'tail',
1591      })
1592      vim.treesitter.start(0, 'markdown')
1593      return vim.api.nvim_win_text_height(0, {}).all
1594    end)
1595  )
1596end)
1597
1598describe('treesitter get_captures', function()
1599  local function captures(start, stop)
1600    local result = exec_lua(function()
1601      return vim.treesitter.get_captures(0, start, stop)
1602    end)
1603    return vim.tbl_map(function(c)
1604      return { c.capture, c.lang, c.row, c.col, c.end_row, c.end_col }
1605    end, result)
1606  end
1607
1608  before_each(function()
1609    clear()
1610    exec_lua(function()
1611      vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'local abc = 123', 'local def = 456' })
1612      vim.treesitter.query.set('lua', 'highlights', '(identifier) @variable (number) @number')
1613      vim.treesitter.start(0, 'lua')
1614      vim.treesitter.get_parser():parse(true)
1615    end)
1616  end)
1617
1618  it('returns overlapping captures with exclusive ends', function()
1619    eq({ { 'variable', 'lua', 0, 6, 0, 9 } }, captures({ 0, 7 }))
1620    eq({}, captures({ 0, 9 }))
1621    eq({ { 'variable', 'lua', 0, 6, 0, 9 } }, captures({ 0, 7 }, { 0, 8 }))
1622    eq({}, captures({ 0, 9 }, { 0, 12 }))
1623    eq({}, captures({ 0, 7 }, { 0, 7 }))
1624  end)
1625
1626  it('accepts row endpoints and excludes the stop row', function()
1627    eq({ { 'variable', 'lua', 0, 6, 0, 9 }, { 'number', 'lua', 0, 12, 0, 15 } }, captures(0, 1))
1628    eq(captures(0, 1), captures(0))
1629    eq({}, captures(0, 0))
1630    eq(captures(0, 1), captures({ 0, 0 }, 1))
1631    eq({
1632      { 'variable', 'lua', 0, 6, 0, 9 },
1633      { 'number', 'lua', 0, 12, 0, 15 },
1634      { 'variable', 'lua', 1, 6, 1, 9 },
1635    }, captures(0, { 1, 7 }))
1636  end)
1637
1638  it('includes injected captures outside the parsed viewport', function()
1639    exec_lua(function()
1640      vim.api.nvim_set_current_buf(vim.api.nvim_create_buf(false, true))
1641      local lines = {}
1642      for row = 1, 100 do
1643        lines[row] = 'local s = "int abc;"'
1644      end
1645      vim.api.nvim_buf_set_lines(0, 0, -1, false, lines)
1646      vim.treesitter.query.set(
1647        'lua',
1648        'injections',
1649        '((string_content) @injection.content (#set! injection.language "c"))'
1650      )
1651      vim.treesitter.query.set('c', 'highlights', '(identifier) @variable')
1652      vim.treesitter.start(0, 'lua')
1653      vim.treesitter.get_parser():parse({ 0, 10 })
1654    end)
1655    eq({ { 'variable', 'c', 99, 15, 99, 18 } }, captures({ 99, 16 }, { 99, 17 }))
1656    eq({}, captures({ 99, 18 }, { 99, 19 }))
1657  end)
1658end)