robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
101.7 KiB3059 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, after_each, setup, teardown, finally =
6  t.describe, t.it, t.before_each, t.after_each, t.setup, t.teardown, t.finally
7local clear = n.clear
8local eq = t.eq
9local ok = t.ok
10local describe_lua_and_rpc = n.describe_lua_and_rpc(describe)
11local api = n.api
12local fn = n.fn
13local request = n.request
14local exec, exec_lua = n.exec, n.exec_lua
15local insert = n.insert
16local NIL = vim.NIL
17local command = n.command
18local feed = n.feed
19local pcall_err = t.pcall_err
20local assert_alive = n.assert_alive
21
22describe('api/buf', function()
23  before_each(clear)
24
25  -- access deprecated functions
26  local function curbuf_depr(method, ...)
27    return request('buffer_' .. method, 0, ...)
28  end
29
30  describe('nvim_buf_set_lines, nvim_buf_line_count', function()
31    it('deprecated forms', function()
32      eq(1, curbuf_depr('line_count'))
33      curbuf_depr('insert', -1, { 'line' })
34      eq(2, curbuf_depr('line_count'))
35      curbuf_depr('insert', -1, { 'line' })
36      eq(3, curbuf_depr('line_count'))
37      curbuf_depr('del_line', -1)
38      eq(2, curbuf_depr('line_count'))
39      curbuf_depr('del_line', -1)
40      curbuf_depr('del_line', -1)
41      -- There's always at least one line
42      eq(1, curbuf_depr('line_count'))
43    end)
44
45    it("doesn't crash just after set undolevels=1 #24894", function()
46      local buf = api.nvim_create_buf(false, true)
47      api.nvim_set_option_value('undolevels', -1, { buf = buf })
48      api.nvim_buf_set_lines(buf, 0, 1, false, {})
49
50      assert_alive()
51    end)
52
53    it('cursor position is maintained after lines are inserted #9961', function()
54      -- replace the buffer contents with these three lines.
55      api.nvim_buf_set_lines(0, 0, -1, true, { 'line1', 'line2', 'line3', 'line4' })
56      -- Set the current cursor to {3, 2}.
57      api.nvim_win_set_cursor(0, { 3, 2 })
58
59      -- add 2 lines and delete 1 line above the current cursor position.
60      api.nvim_buf_set_lines(0, 1, 2, true, { 'line5', 'line6' })
61      -- check the current set of lines in the buffer.
62      eq({ 'line1', 'line5', 'line6', 'line3', 'line4' }, api.nvim_buf_get_lines(0, 0, -1, true))
63      -- cursor should be moved below by 1 line.
64      eq({ 4, 2 }, api.nvim_win_get_cursor(0))
65
66      -- add a line after the current cursor position.
67      api.nvim_buf_set_lines(0, 5, 5, true, { 'line7' })
68      -- check the current set of lines in the buffer.
69      eq(
70        { 'line1', 'line5', 'line6', 'line3', 'line4', 'line7' },
71        api.nvim_buf_get_lines(0, 0, -1, true)
72      )
73      -- cursor position is unchanged.
74      eq({ 4, 2 }, api.nvim_win_get_cursor(0))
75
76      -- overwrite current cursor line.
77      api.nvim_buf_set_lines(0, 3, 5, true, { 'line8', 'line9' })
78      -- check the current set of lines in the buffer.
79      eq(
80        { 'line1', 'line5', 'line6', 'line8', 'line9', 'line7' },
81        api.nvim_buf_get_lines(0, 0, -1, true)
82      )
83      -- cursor position is unchanged.
84      eq({ 4, 2 }, api.nvim_win_get_cursor(0))
85
86      -- delete current cursor line.
87      api.nvim_buf_set_lines(0, 3, 5, true, {})
88      -- check the current set of lines in the buffer.
89      eq({ 'line1', 'line5', 'line6', 'line7' }, api.nvim_buf_get_lines(0, 0, -1, true))
90      -- cursor position is unchanged.
91      eq({ 4, 2 }, api.nvim_win_get_cursor(0))
92    end)
93
94    it('cursor position is maintained in non-current window', function()
95      api.nvim_buf_set_lines(0, 0, -1, true, { 'line1', 'line2', 'line3', 'line4' })
96      api.nvim_win_set_cursor(0, { 3, 2 })
97      local win = api.nvim_get_current_win()
98      local buf = api.nvim_get_current_buf()
99
100      command('new')
101
102      api.nvim_buf_set_lines(buf, 1, 2, true, { 'line5', 'line6' })
103      eq({ 'line1', 'line5', 'line6', 'line3', 'line4' }, api.nvim_buf_get_lines(buf, 0, -1, true))
104      eq({ 4, 2 }, api.nvim_win_get_cursor(win))
105    end)
106
107    it('cursor position is maintained in TWO non-current windows', function()
108      api.nvim_buf_set_lines(0, 0, -1, true, { 'line1', 'line2', 'line3', 'line4' })
109      api.nvim_win_set_cursor(0, { 3, 2 })
110      local win = api.nvim_get_current_win()
111      local buf = api.nvim_get_current_buf()
112
113      command('split')
114      api.nvim_win_set_cursor(0, { 4, 2 })
115      local win2 = api.nvim_get_current_win()
116
117      -- set current window to third one with another buffer
118      command('new')
119
120      api.nvim_buf_set_lines(buf, 1, 2, true, { 'line5', 'line6' })
121      eq({ 'line1', 'line5', 'line6', 'line3', 'line4' }, api.nvim_buf_get_lines(buf, 0, -1, true))
122      eq({ 4, 2 }, api.nvim_win_get_cursor(win))
123      eq({ 5, 2 }, api.nvim_win_get_cursor(win2))
124    end)
125
126    it('cursor position is maintained consistently with viewport', function()
127      local screen = Screen.new(20, 12)
128
129      local lines = { 'line1', 'line2', 'line3', 'line4', 'line5', 'line6' }
130      local buf = api.nvim_get_current_buf()
131
132      api.nvim_buf_set_lines(buf, 0, -1, true, lines)
133
134      command('6')
135      command('new')
136      screen:expect {
137        grid = [[
138        ^                    |
139        {1:~                   }|*4
140        {3:[No Name]           }|
141        line5               |
142        line6               |
143        {1:~                   }|*2
144        {2:[No Name] [+]       }|
145                            |
146      ]],
147      }
148
149      lines[5] = 'boogalo 5'
150      api.nvim_buf_set_lines(buf, 0, -1, true, lines)
151      screen:expect {
152        grid = [[
153        ^                    |
154        {1:~                   }|*4
155        {3:[No Name]           }|
156        boogalo 5           |
157        line6               |
158        {1:~                   }|*2
159        {2:[No Name] [+]       }|
160                            |
161      ]],
162      }
163
164      command('wincmd w')
165      screen:expect {
166        grid = [[
167                            |
168        {1:~                   }|*4
169        {2:[No Name]           }|
170        boogalo 5           |
171        ^line6               |
172        {1:~                   }|*2
173        {3:[No Name] [+]       }|
174                            |
175      ]],
176      }
177    end)
178
179    it('line_count has defined behaviour for unloaded buffers', function()
180      -- we'll need to know our bufnr for when it gets unloaded
181      local bufnr = api.nvim_get_current_buf()
182      -- replace the buffer contents with these three lines
183      api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'line1', 'line2', 'line3', 'line4' })
184      -- check the line count is correct
185      eq(4, api.nvim_buf_line_count(bufnr))
186      -- force unload the buffer (this will discard changes)
187      command('new')
188      command('bunload! ' .. bufnr)
189      -- line count for an unloaded buffer should always be 0
190      eq(0, api.nvim_buf_line_count(bufnr))
191    end)
192
193    it('get_lines and get_text has defined behaviour for unloaded buffers', function()
194      -- we'll need to know our bufnr for when it gets unloaded
195      local bufnr = api.nvim_get_current_buf()
196      -- replace the buffer contents with these three lines
197      api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'line1', 'line2', 'line3', 'line4' })
198      -- confirm that getting lines works
199      eq({ 'line2', 'line3' }, api.nvim_buf_get_lines(bufnr, 1, 3, true))
200      -- force unload the buffer (this will discard changes)
201      command('new')
202      command('bunload! ' .. bufnr)
203      -- attempting to get lines now always gives empty list
204      eq({}, api.nvim_buf_get_lines(bufnr, 1, 3, true))
205      -- it's impossible to get out-of-bounds errors for an unloaded buffer
206      eq({}, api.nvim_buf_get_lines(bufnr, 8888, 9999, true))
207      eq({}, api.nvim_buf_get_text(bufnr, 8888, 1000, 9999, 2000, {}))
208      -- The Lua path (vim.api) must also return an empty table, not nil. #39833 #39851
209      eq(
210        { 'table', {} },
211        exec_lua(function()
212          local r = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
213          return { type(r), r }
214        end)
215      )
216      eq(
217        { 'table', {} },
218        exec_lua(function()
219          local r = vim.api.nvim_buf_get_text(bufnr, 0, 0, -1, 0, {})
220          return { type(r), r }
221        end)
222      )
223    end)
224
225    describe('handles topline', function()
226      local screen
227      before_each(function()
228        screen = Screen.new(20, 12)
229        api.nvim_buf_set_lines(
230          0,
231          0,
232          -1,
233          true,
234          { 'aaa', 'bbb', 'ccc', 'ddd', 'www', 'xxx', 'yyy', 'zzz' }
235        )
236        api.nvim_set_option_value('modified', false, {})
237      end)
238
239      it('of current window', function()
240        local win = api.nvim_get_current_win()
241        local buf = api.nvim_get_current_buf()
242
243        command('new | wincmd w')
244        api.nvim_win_set_cursor(win, { 8, 0 })
245
246        screen:expect {
247          grid = [[
248                              |
249          {1:~                   }|*4
250          {2:[No Name]           }|
251          www                 |
252          xxx                 |
253          yyy                 |
254          ^zzz                 |
255          {3:[No Name]           }|
256                              |
257        ]],
258        }
259
260        api.nvim_buf_set_lines(buf, 0, 2, true, { 'aaabbb' })
261        screen:expect {
262          grid = [[
263                              |
264          {1:~                   }|*4
265          {2:[No Name]           }|
266          www                 |
267          xxx                 |
268          yyy                 |
269          ^zzz                 |
270          {3:[No Name] [+]       }|
271                              |
272        ]],
273        }
274
275        -- replacing topline keeps it the topline
276        api.nvim_buf_set_lines(buf, 3, 4, true, { 'wwweeee' })
277        screen:expect {
278          grid = [[
279                              |
280          {1:~                   }|*4
281          {2:[No Name]           }|
282          wwweeee             |
283          xxx                 |
284          yyy                 |
285          ^zzz                 |
286          {3:[No Name] [+]       }|
287                              |
288        ]],
289        }
290
291        -- inserting just before topline does not scroll up if cursor would be moved
292        api.nvim_buf_set_lines(buf, 3, 3, true, { 'mmm' })
293        screen:expect {
294          grid = [[
295                              |
296          {1:~                   }|*4
297          {2:[No Name]           }|
298          wwweeee             |
299          xxx                 |
300          yyy                 |
301          ^zzz                 |
302          {3:[No Name] [+]       }|
303                              |
304        ]],
305          unchanged = true,
306        }
307
308        api.nvim_win_set_cursor(0, { 7, 0 })
309        screen:expect {
310          grid = [[
311                              |
312          {1:~                   }|*4
313          {2:[No Name]           }|
314          wwweeee             |
315          xxx                 |
316          ^yyy                 |
317          zzz                 |
318          {3:[No Name] [+]       }|
319                              |
320        ]],
321        }
322
323        api.nvim_buf_set_lines(buf, 4, 4, true, { 'mmmeeeee' })
324        screen:expect {
325          grid = [[
326                              |
327          {1:~                   }|*4
328          {2:[No Name]           }|
329          mmmeeeee            |
330          wwweeee             |
331          xxx                 |
332          ^yyy                 |
333          {3:[No Name] [+]       }|
334                              |
335        ]],
336        }
337      end)
338
339      it('of non-current window', function()
340        local win = api.nvim_get_current_win()
341        local buf = api.nvim_get_current_buf()
342
343        command('new')
344        api.nvim_win_set_cursor(win, { 8, 0 })
345
346        screen:expect {
347          grid = [[
348          ^                    |
349          {1:~                   }|*4
350          {3:[No Name]           }|
351          www                 |
352          xxx                 |
353          yyy                 |
354          zzz                 |
355          {2:[No Name]           }|
356                              |
357        ]],
358        }
359
360        api.nvim_buf_set_lines(buf, 0, 2, true, { 'aaabbb' })
361        screen:expect {
362          grid = [[
363          ^                    |
364          {1:~                   }|*4
365          {3:[No Name]           }|
366          www                 |
367          xxx                 |
368          yyy                 |
369          zzz                 |
370          {2:[No Name] [+]       }|
371                              |
372        ]],
373        }
374
375        -- replacing topline keeps it the topline
376        api.nvim_buf_set_lines(buf, 3, 4, true, { 'wwweeee' })
377        screen:expect {
378          grid = [[
379          ^                    |
380          {1:~                   }|*4
381          {3:[No Name]           }|
382          wwweeee             |
383          xxx                 |
384          yyy                 |
385          zzz                 |
386          {2:[No Name] [+]       }|
387                              |
388        ]],
389        }
390
391        api.nvim_buf_set_lines(buf, 3, 3, true, { 'mmm' })
392        screen:expect {
393          grid = [[
394          ^                    |
395          {1:~                   }|*4
396          {3:[No Name]           }|
397          wwweeee             |
398          xxx                 |
399          yyy                 |
400          zzz                 |
401          {2:[No Name] [+]       }|
402                              |
403        ]],
404          unchanged = true,
405        }
406      end)
407
408      it('of split windows with same buffer', function()
409        local win = api.nvim_get_current_win()
410        local buf = api.nvim_get_current_buf()
411
412        command('split')
413        api.nvim_win_set_cursor(win, { 8, 0 })
414        api.nvim_win_set_cursor(0, { 1, 0 })
415
416        screen:expect {
417          grid = [[
418          ^aaa                 |
419          bbb                 |
420          ccc                 |
421          ddd                 |
422          www                 |
423          {3:[No Name]           }|
424          www                 |
425          xxx                 |
426          yyy                 |
427          zzz                 |
428          {2:[No Name]           }|
429                              |
430        ]],
431        }
432        api.nvim_buf_set_lines(buf, 0, 2, true, { 'aaabbb' })
433
434        screen:expect {
435          grid = [[
436          ^aaabbb              |
437          ccc                 |
438          ddd                 |
439          www                 |
440          xxx                 |
441          {3:[No Name] [+]       }|
442          www                 |
443          xxx                 |
444          yyy                 |
445          zzz                 |
446          {2:[No Name] [+]       }|
447                              |
448        ]],
449        }
450
451        -- replacing topline keeps it the topline
452        api.nvim_buf_set_lines(buf, 3, 4, true, { 'wwweeee' })
453        screen:expect {
454          grid = [[
455          ^aaabbb              |
456          ccc                 |
457          ddd                 |
458          wwweeee             |
459          xxx                 |
460          {3:[No Name] [+]       }|
461          wwweeee             |
462          xxx                 |
463          yyy                 |
464          zzz                 |
465          {2:[No Name] [+]       }|
466                              |
467        ]],
468        }
469
470        api.nvim_buf_set_lines(buf, 3, 3, true, { 'mmm' })
471        screen:expect {
472          grid = [[
473          ^aaabbb              |
474          ccc                 |
475          ddd                 |
476          mmm                 |
477          wwweeee             |
478          {3:[No Name] [+]       }|
479          wwweeee             |
480          xxx                 |
481          yyy                 |
482          zzz                 |
483          {2:[No Name] [+]       }|
484                              |
485        ]],
486        }
487      end)
488
489      describe('of current window when', function()
490        before_each(function()
491          command('new | wincmd w | setlocal modified')
492          feed('Gk')
493          screen:expect([[
494                                |
495            {1:~                   }|*4
496            {2:[No Name]           }|
497            www                 |
498            xxx                 |
499            ^yyy                 |
500            zzz                 |
501            {3:[No Name] [+]       }|
502                                |
503          ]])
504        end)
505
506        it('deleting 3 lines around topline', function()
507          api.nvim_buf_set_lines(0, 3, 6, true, {})
508          screen:expect([[
509                                |
510            {1:~                   }|*4
511            {2:[No Name]           }|
512            ccc                 |
513            ^yyy                 |
514            zzz                 |
515            {1:~                   }|
516            {3:[No Name] [+]       }|
517                                |
518          ]])
519          eq(5, api.nvim_buf_line_count(0))
520        end)
521
522        it('deleting 3 lines around the line just before topline', function()
523          api.nvim_buf_set_lines(0, 2, 5, true, {})
524          screen:expect([[
525                                |
526            {1:~                   }|*4
527            {2:[No Name]           }|
528            bbb                 |
529            xxx                 |
530            ^yyy                 |
531            zzz                 |
532            {3:[No Name] [+]       }|
533                                |
534          ]])
535          eq(5, api.nvim_buf_line_count(0))
536        end)
537
538        for count = 1, 4 do
539          it(('deleting %d lines just before topline'):format(count), function()
540            api.nvim_buf_set_lines(0, 4 - count, 4, true, {})
541            screen:expect_unchanged()
542            eq(8 - count, api.nvim_buf_line_count(0))
543          end)
544
545          it(('replacing %d lines just before topline with 2 lines'):format(count), function()
546            api.nvim_buf_set_lines(0, 4 - count, 4, true, { 'eee', 'fff' })
547            screen:expect_unchanged()
548            eq(8 - count + 2, api.nvim_buf_line_count(0))
549          end)
550        end
551
552        for count = 1, 3 do
553          it(('deleting %d lines far before topline'):format(count), function()
554            api.nvim_buf_set_lines(0, 0, count, true, {})
555            screen:expect_unchanged()
556            eq(8 - count, api.nvim_buf_line_count(0))
557          end)
558
559          it(('replacing %d lines far before topline with 2 lines'):format(count), function()
560            api.nvim_buf_set_lines(0, 0, count, true, { 'eee', 'fff' })
561            screen:expect_unchanged()
562            eq(8 - count + 2, api.nvim_buf_line_count(0))
563          end)
564        end
565      end)
566    end)
567
568    it('handles clearing out non-current buffer #24911', function()
569      local buf = api.nvim_get_current_buf()
570      api.nvim_buf_set_lines(buf, 0, -1, true, { 'aaa', 'bbb', 'ccc' })
571      command('new')
572
573      api.nvim_buf_set_lines(0, 0, -1, true, { 'xxx', 'yyy', 'zzz' })
574
575      api.nvim_buf_set_lines(buf, 0, -1, true, {})
576      eq({ 'xxx', 'yyy', 'zzz' }, api.nvim_buf_get_lines(0, 0, -1, true))
577      eq({ '' }, api.nvim_buf_get_lines(buf, 0, -1, true))
578    end)
579  end)
580
581  describe('deprecated: {get,set,del}_line', function()
582    it('works', function()
583      eq('', curbuf_depr('get_line', 0))
584      curbuf_depr('set_line', 0, 'line1')
585      eq('line1', curbuf_depr('get_line', 0))
586      curbuf_depr('set_line', 0, 'line2')
587      eq('line2', curbuf_depr('get_line', 0))
588      curbuf_depr('del_line', 0)
589      eq('', curbuf_depr('get_line', 0))
590    end)
591
592    it('get_line: out-of-bounds is an error', function()
593      curbuf_depr('set_line', 0, 'line1.a')
594      eq(1, curbuf_depr('line_count')) -- sanity
595      eq(false, pcall(curbuf_depr, 'get_line', 1))
596      eq(false, pcall(curbuf_depr, 'get_line', -2))
597    end)
598
599    it('set_line, del_line: out-of-bounds is an error', function()
600      curbuf_depr('set_line', 0, 'line1.a')
601      eq(false, pcall(curbuf_depr, 'set_line', 1, 'line1.b'))
602      eq(false, pcall(curbuf_depr, 'set_line', -2, 'line1.b'))
603      eq(false, pcall(curbuf_depr, 'del_line', 2))
604      eq(false, pcall(curbuf_depr, 'del_line', -3))
605    end)
606
607    it('can handle NULs', function()
608      curbuf_depr('set_line', 0, 'ab\0cd')
609      eq('ab\0cd', curbuf_depr('get_line', 0))
610    end)
611  end)
612
613  describe('deprecated: {get,set}_line_slice', function()
614    it('get_line_slice: out-of-bounds returns empty array', function()
615      curbuf_depr('set_line_slice', 0, 0, true, true, { 'a', 'b', 'c' })
616      eq({ 'a', 'b', 'c' }, curbuf_depr('get_line_slice', 0, 2, true, true)) --sanity
617
618      eq({}, curbuf_depr('get_line_slice', 2, 3, false, true))
619      eq({}, curbuf_depr('get_line_slice', 3, 9, true, true))
620      eq({}, curbuf_depr('get_line_slice', 3, -1, true, true))
621      eq({}, curbuf_depr('get_line_slice', -3, -4, false, true))
622      eq({}, curbuf_depr('get_line_slice', -4, -5, true, true))
623    end)
624
625    it('set_line_slice: out-of-bounds extends past end', function()
626      curbuf_depr('set_line_slice', 0, 0, true, true, { 'a', 'b', 'c' })
627      eq({ 'a', 'b', 'c' }, curbuf_depr('get_line_slice', 0, 2, true, true)) --sanity
628
629      eq({ 'c' }, curbuf_depr('get_line_slice', -1, 4, true, true))
630      eq({ 'a', 'b', 'c' }, curbuf_depr('get_line_slice', 0, 5, true, true))
631      curbuf_depr('set_line_slice', 4, 5, true, true, { 'd' })
632      eq({ 'a', 'b', 'c', 'd' }, curbuf_depr('get_line_slice', 0, 5, true, true))
633      curbuf_depr('set_line_slice', -4, -5, true, true, { 'e' })
634      eq({ 'e', 'a', 'b', 'c', 'd' }, curbuf_depr('get_line_slice', 0, 5, true, true))
635    end)
636
637    it('works', function()
638      eq({ '' }, curbuf_depr('get_line_slice', 0, -1, true, true))
639      -- Replace buffer
640      curbuf_depr('set_line_slice', 0, -1, true, true, { 'a', 'b', 'c' })
641      eq({ 'a', 'b', 'c' }, curbuf_depr('get_line_slice', 0, -1, true, true))
642      eq({ 'b', 'c' }, curbuf_depr('get_line_slice', 1, -1, true, true))
643      eq({ 'b' }, curbuf_depr('get_line_slice', 1, 2, true, false))
644      eq({}, curbuf_depr('get_line_slice', 1, 1, true, false))
645      eq({ 'a', 'b' }, curbuf_depr('get_line_slice', 0, -1, true, false))
646      eq({ 'b' }, curbuf_depr('get_line_slice', 1, -1, true, false))
647      eq({ 'b', 'c' }, curbuf_depr('get_line_slice', -2, -1, true, true))
648      curbuf_depr('set_line_slice', 1, 2, true, false, { 'a', 'b', 'c' })
649      eq({ 'a', 'a', 'b', 'c', 'c' }, curbuf_depr('get_line_slice', 0, -1, true, true))
650      curbuf_depr('set_line_slice', -1, -1, true, true, { 'a', 'b', 'c' })
651      eq({ 'a', 'a', 'b', 'c', 'a', 'b', 'c' }, curbuf_depr('get_line_slice', 0, -1, true, true))
652      curbuf_depr('set_line_slice', 0, -3, true, false, {})
653      eq({ 'a', 'b', 'c' }, curbuf_depr('get_line_slice', 0, -1, true, true))
654      curbuf_depr('set_line_slice', 0, -1, true, true, {})
655      eq({ '' }, curbuf_depr('get_line_slice', 0, -1, true, true))
656    end)
657  end)
658
659  describe_lua_and_rpc('nvim_buf_get_lines, nvim_buf_set_lines', function(lua_or_rpc)
660    local function get_lines(...)
661      return lua_or_rpc.nvim_buf_get_lines(0, ...)
662    end
663
664    local function set_lines(...)
665      return lua_or_rpc.nvim_buf_set_lines(0, ...)
666    end
667
668    local function line_count()
669      return lua_or_rpc.nvim_buf_line_count(0)
670    end
671
672    it('fails correctly when input is not valid', function()
673      eq(1, lua_or_rpc.nvim_buf_get_number(0))
674      eq(
675        [['replacement string' item contains newlines]],
676        pcall_err(lua_or_rpc.nvim_buf_set_lines, 1, 1, 2, false, { 'b\na' })
677      )
678    end)
679
680    it("fails if 'nomodifiable'", function()
681      command('set nomodifiable')
682      eq(
683        [[Buffer is not 'modifiable']],
684        pcall_err(lua_or_rpc.nvim_buf_set_lines, 1, 1, 2, false, { 'a', 'b' })
685      )
686    end)
687
688    it('has correct line_count when inserting and deleting', function()
689      eq(1, line_count())
690      set_lines(-1, -1, true, { 'line' })
691      eq(2, line_count())
692      set_lines(-1, -1, true, { 'line' })
693      eq(3, line_count())
694      set_lines(-2, -1, true, {})
695      eq(2, line_count())
696      set_lines(-2, -1, true, {})
697      set_lines(-2, -1, true, {})
698      -- There's always at least one line
699      eq(1, line_count())
700    end)
701
702    it('can get, set and delete a single line', function()
703      eq({ '' }, get_lines(0, 1, true))
704      set_lines(0, 1, true, { 'line1' })
705      eq({ 'line1' }, get_lines(0, 1, true))
706      set_lines(0, 1, true, { 'line2' })
707      eq({ 'line2' }, get_lines(0, 1, true))
708      set_lines(0, 1, true, {})
709      eq({ '' }, get_lines(0, 1, true))
710    end)
711
712    it('can get a single line with strict indexing', function()
713      set_lines(0, 1, true, { 'line1.a' })
714      eq(1, line_count()) -- sanity
715      eq('Index out of bounds', pcall_err(get_lines, 1, 2, true))
716      eq('Index out of bounds', pcall_err(get_lines, -3, -2, true))
717    end)
718
719    it('can get a single line with non-strict indexing', function()
720      set_lines(0, 1, true, { 'line1.a' })
721      eq(1, line_count()) -- sanity
722      eq({}, get_lines(1, 2, false))
723      eq({}, get_lines(-3, -2, false))
724    end)
725
726    it('can set and delete a single line with strict indexing', function()
727      set_lines(0, 1, true, { 'line1.a' })
728      eq('Index out of bounds', pcall_err(set_lines, 1, 2, true, { 'line1.b' }))
729      eq('Index out of bounds', pcall_err(set_lines, -3, -2, true, { 'line1.c' }))
730      eq({ 'line1.a' }, get_lines(0, -1, true))
731      eq('Index out of bounds', pcall_err(set_lines, 1, 2, true, {}))
732      eq('Index out of bounds', pcall_err(set_lines, -3, -2, true, {}))
733      eq({ 'line1.a' }, get_lines(0, -1, true))
734    end)
735
736    it('can set and delete a single line with non-strict indexing', function()
737      set_lines(0, 1, true, { 'line1.a' })
738      set_lines(1, 2, false, { 'line1.b' })
739      set_lines(-4, -3, false, { 'line1.c' })
740      eq({ 'line1.c', 'line1.a', 'line1.b' }, get_lines(0, -1, true))
741      set_lines(3, 4, false, {})
742      set_lines(-5, -4, false, {})
743      eq({ 'line1.c', 'line1.a', 'line1.b' }, get_lines(0, -1, true))
744    end)
745
746    it('can handle NULs', function()
747      set_lines(0, 1, true, { 'ab\0cd' })
748      eq({ 'ab\0cd' }, get_lines(0, -1, true))
749    end)
750
751    it('works with multiple lines', function()
752      eq({ '' }, get_lines(0, -1, true))
753      -- Replace buffer
754      for _, mode in pairs({ false, true }) do
755        set_lines(0, -1, mode, { 'a', 'b', 'c' })
756        eq({ 'a', 'b', 'c' }, get_lines(0, -1, mode))
757        eq({ 'b', 'c' }, get_lines(1, -1, mode))
758        eq({ 'b' }, get_lines(1, 2, mode))
759        eq({}, get_lines(1, 1, mode))
760        eq({ 'a', 'b' }, get_lines(0, -2, mode))
761        eq({ 'b' }, get_lines(1, -2, mode))
762        eq({ 'b', 'c' }, get_lines(-3, -1, mode))
763        set_lines(1, 2, mode, { 'a', 'b', 'c' })
764        eq({ 'a', 'a', 'b', 'c', 'c' }, get_lines(0, -1, mode))
765        set_lines(-2, -1, mode, { 'a', 'b', 'c' })
766        eq({ 'a', 'a', 'b', 'c', 'a', 'b', 'c' }, get_lines(0, -1, mode))
767        set_lines(0, -4, mode, {})
768        eq({ 'a', 'b', 'c' }, get_lines(0, -1, mode))
769        set_lines(0, -1, mode, {})
770        eq({ '' }, get_lines(0, -1, mode))
771      end
772    end)
773
774    it('can get line ranges with non-strict indexing', function()
775      set_lines(0, -1, true, { 'a', 'b', 'c' })
776      eq({ 'a', 'b', 'c' }, get_lines(0, -1, true)) --sanity
777
778      eq({}, get_lines(3, 4, false))
779      eq({}, get_lines(3, 10, false))
780      eq({}, get_lines(-5, -5, false))
781      eq({}, get_lines(3, -1, false))
782      eq({}, get_lines(-3, -4, false))
783    end)
784
785    it('can get line ranges with strict indexing', function()
786      set_lines(0, -1, true, { 'a', 'b', 'c' })
787      eq({ 'a', 'b', 'c' }, get_lines(0, -1, true)) --sanity
788
789      eq('Index out of bounds', pcall_err(get_lines, 3, 4, true))
790      eq('Index out of bounds', pcall_err(get_lines, 3, 10, true))
791      eq('Index out of bounds', pcall_err(get_lines, -5, -5, true))
792      -- empty or inverted ranges are not errors
793      eq({}, get_lines(3, -1, true))
794      eq({}, get_lines(-3, -4, true))
795    end)
796
797    it('set_lines: out-of-bounds can extend past end', function()
798      set_lines(0, -1, true, { 'a', 'b', 'c' })
799      eq({ 'a', 'b', 'c' }, get_lines(0, -1, true)) --sanity
800
801      eq({ 'c' }, get_lines(-2, 5, false))
802      eq({ 'a', 'b', 'c' }, get_lines(0, 6, false))
803      eq('Index out of bounds', pcall_err(set_lines, 4, 6, true, { 'd' }))
804      set_lines(4, 6, false, { 'd' })
805      eq({ 'a', 'b', 'c', 'd' }, get_lines(0, -1, true))
806      eq('Index out of bounds', pcall_err(set_lines, -6, -6, true, { 'e' }))
807      set_lines(-6, -6, false, { 'e' })
808      eq({ 'e', 'a', 'b', 'c', 'd' }, get_lines(0, -1, true))
809    end)
810
811    it('set_lines on alternate buffer does not access invalid line (E315)', function()
812      command('set hidden')
813      insert('Initial file')
814      command('enew')
815      insert([[
816      More
817      Lines
818      Than
819      In
820      The
821      Other
822      Buffer]])
823      command('$')
824      eq(true, pcall(api.nvim_buf_set_lines, 0, 0, 1, false, { 'test' }))
825    end)
826
827    it("set_lines of invisible buffer doesn't move cursor in current window", function()
828      local screen = Screen.new(20, 5)
829
830      insert([[
831        Who would win?
832        A real window
833        with proper text]])
834      local buf = lua_or_rpc.nvim_create_buf(false, true)
835      screen:expect([[
836        Who would win?      |
837        A real window       |
838        with proper tex^t    |
839        {1:~                   }|
840                            |
841      ]])
842
843      lua_or_rpc.nvim_buf_set_lines(buf, 0, -1, true, { 'or some', 'scratchy text' })
844      feed('i') -- provoke redraw
845      screen:expect([[
846        Who would win?      |
847        A real window       |
848        with proper tex^t    |
849        {1:~                   }|
850        {5:-- INSERT --}        |
851      ]])
852    end)
853
854    it('set_lines on hidden buffer preserves "previous window" #9741', function()
855      insert([[
856        visible buffer line 1
857        line 2
858      ]])
859      local hiddenbuf = lua_or_rpc.nvim_create_buf(false, true)
860      command('vsplit')
861      command('vsplit')
862      feed('<c-w>l<c-w>l<c-w>l')
863      eq(3, fn.winnr())
864      feed('<c-w>h')
865      eq(2, fn.winnr())
866      lua_or_rpc.nvim_buf_set_lines(hiddenbuf, 0, -1, true, { 'hidden buffer line 1', 'line 2' })
867      feed('<c-w>p')
868      eq(3, fn.winnr())
869    end)
870
871    it('set_lines on unloaded buffer #8659 #22670', function()
872      local bufnr = api.nvim_get_current_buf()
873      lua_or_rpc.nvim_buf_set_lines(bufnr, 0, -1, false, { 'a', 'b', 'c' })
874      lua_or_rpc.nvim_buf_set_name(bufnr, 'set_lines')
875      finally(function()
876        os.remove('set_lines')
877      end)
878      command('write!')
879      command('new')
880      command('bunload! ' .. bufnr)
881      local new_bufnr = fn.bufnr('set_lines', true)
882      lua_or_rpc.nvim_buf_set_lines(new_bufnr, 0, -1, false, {})
883      eq({ '' }, lua_or_rpc.nvim_buf_get_lines(new_bufnr, 0, -1, false))
884      eq(true, api.nvim_buf_is_loaded(new_bufnr))
885    end)
886  end)
887
888  describe('nvim_buf_set_text', function()
889    local function get_lines(...)
890      return api.nvim_buf_get_lines(0, ...)
891    end
892
893    local function set_text(...)
894      return api.nvim_buf_set_text(0, ...)
895    end
896
897    it('works', function()
898      insert([[
899      hello foo!
900      text
901      ]])
902
903      eq({ 'hello foo!' }, get_lines(0, 1, true))
904
905      -- can replace a single word
906      set_text(0, 6, 0, 9, { 'world' })
907      eq({ 'hello world!', 'text' }, get_lines(0, 2, true))
908
909      -- can insert text
910      set_text(0, 0, 0, 0, { 'well ' })
911      eq({ 'well hello world!', 'text' }, get_lines(0, 2, true))
912
913      -- can delete text
914      set_text(0, 0, 0, 5, { '' })
915      eq({ 'hello world!', 'text' }, get_lines(0, 2, true))
916
917      -- can replace with multiple lines
918      set_text(0, 6, 0, 11, { 'foo', 'wo', 'more' })
919      eq({ 'hello foo', 'wo', 'more!', 'text' }, get_lines(0, 4, true))
920
921      -- will join multiple lines if needed
922      set_text(0, 6, 3, 4, { 'bar' })
923      eq({ 'hello bar' }, get_lines(0, 1, true))
924
925      -- can use negative line numbers
926      set_text(-2, 0, -2, 5, { 'goodbye' })
927      eq({ 'goodbye bar', '' }, get_lines(0, -1, true))
928
929      set_text(-1, 0, -1, 0, { 'text' })
930      eq({ 'goodbye bar', 'text' }, get_lines(0, 2, true))
931
932      -- can append to a line
933      set_text(1, 4, -1, 4, { ' and', 'more' })
934      eq({ 'goodbye bar', 'text and', 'more' }, get_lines(0, 3, true))
935
936      -- can use negative column numbers
937      set_text(0, -5, 0, -1, { '!' })
938      eq({ 'goodbye!' }, get_lines(0, 1, true))
939    end)
940
941    it('works with undo', function()
942      insert([[
943        hello world!
944        foo bar
945        ]])
946
947      -- setting text
948      set_text(0, 0, 0, 0, { 'well ' })
949      feed('u')
950      eq({ 'hello world!' }, get_lines(0, 1, true))
951
952      -- deleting text
953      set_text(0, 0, 0, 6, { '' })
954      feed('u')
955      eq({ 'hello world!' }, get_lines(0, 1, true))
956
957      -- inserting newlines
958      set_text(0, 0, 0, 0, { 'hello', 'mr ' })
959      feed('u')
960      eq({ 'hello world!' }, get_lines(0, 1, true))
961
962      -- deleting newlines
963      set_text(0, 0, 1, 4, { 'hello' })
964      feed('u')
965      eq({ 'hello world!' }, get_lines(0, 1, true))
966    end)
967
968    it('updates the cursor position', function()
969      insert([[
970      hello world!
971      ]])
972
973      -- position the cursor on `!`
974      api.nvim_win_set_cursor(0, { 1, 11 })
975      -- replace 'world' with 'foo'
976      set_text(0, 6, 0, 11, { 'foo' })
977      eq('hello foo!', curbuf_depr('get_line', 0))
978      -- cursor should be moved left by two columns (replacement is shorter by 2 chars)
979      eq({ 1, 9 }, api.nvim_win_get_cursor(0))
980
981      -- changelist entry reflects the edit column #28618
982      local changes = fn.getchangelist()[1]
983      eq(6, changes[#changes].col)
984    end)
985
986    it('updates the cursor position in non-current window', function()
987      insert([[
988      hello world!]])
989
990      -- position the cursor on `!`
991      api.nvim_win_set_cursor(0, { 1, 11 })
992
993      local win = api.nvim_get_current_win()
994      local buf = api.nvim_get_current_buf()
995
996      command('new')
997
998      -- replace 'world' with 'foo'
999      api.nvim_buf_set_text(buf, 0, 6, 0, 11, { 'foo' })
1000      eq({ 'hello foo!' }, api.nvim_buf_get_lines(buf, 0, -1, true))
1001      -- cursor should be moved left by two columns (replacement is shorter by 2 chars)
1002      eq({ 1, 9 }, api.nvim_win_get_cursor(win))
1003    end)
1004
1005    it('updates the cursor position in TWO non-current windows', function()
1006      insert([[
1007      hello world!]])
1008
1009      -- position the cursor on `!`
1010      api.nvim_win_set_cursor(0, { 1, 11 })
1011      local win = api.nvim_get_current_win()
1012      local buf = api.nvim_get_current_buf()
1013
1014      command('split')
1015      local win2 = api.nvim_get_current_win()
1016      -- position the cursor on `w`
1017      api.nvim_win_set_cursor(0, { 1, 6 })
1018
1019      command('new')
1020
1021      -- replace 'hello' with 'foo'
1022      api.nvim_buf_set_text(buf, 0, 0, 0, 5, { 'foo' })
1023      eq({ 'foo world!' }, api.nvim_buf_get_lines(buf, 0, -1, true))
1024
1025      -- both cursors should be moved left by two columns (replacement is shorter by 2 chars)
1026      eq({ 1, 9 }, api.nvim_win_get_cursor(win))
1027      eq({ 1, 4 }, api.nvim_win_get_cursor(win2))
1028    end)
1029
1030    it('keep visual select position #29558', function()
1031      insert([[1234]])
1032      api.nvim_win_set_cursor(0, { 1, 1 })
1033      feed('vl')
1034      exec_lua([[
1035        vim.defer_fn(function() vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { '0' }) end, 50)
1036        vim.wait(80)
1037      ]])
1038      local mode = api.nvim_get_mode().mode
1039      eq({ '23' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1040      eq({ 'v', { '01234' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1041      feed('<ESC>')
1042
1043      api.nvim_buf_set_lines(0, 0, -1, false, { '1', '2', '3' })
1044      api.nvim_win_set_cursor(0, { 2, 0 })
1045      feed('v')
1046      exec_lua([[
1047        vim.defer_fn(function() vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { '0', '' }) end, 50)
1048        vim.wait(80)
1049      ]])
1050      mode = api.nvim_get_mode().mode
1051      eq({ '2' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1052      eq({ 'v', { '0', '1', '2', '3' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1053      feed('<ESC>')
1054
1055      api.nvim_buf_set_lines(0, 0, -1, false, { '1', '2' })
1056      api.nvim_win_set_cursor(0, { 1, 0 })
1057      feed('vj')
1058      exec_lua([[
1059        vim.defer_fn(function() vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { '0' }) end, 50)
1060        vim.wait(80)
1061      ]])
1062      mode = api.nvim_get_mode().mode
1063      eq({ '1', '2' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1064      eq({ 'v', { '01', '2' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1065      feed('<ESC>')
1066
1067      api.nvim_buf_set_lines(0, 0, -1, false, { '123' })
1068      api.nvim_win_set_cursor(0, { 1, 1 })
1069      feed('v')
1070      exec_lua([[
1071        vim.defer_fn(function() vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { '', '' }) end, 50)
1072        vim.wait(80)
1073      ]])
1074      mode = api.nvim_get_mode().mode
1075      eq({ '2' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1076      eq({ 'v', { '', '123' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1077      feed('<ESC>')
1078
1079      -- Visual block mode
1080      api.nvim_buf_set_lines(0, 0, -1, false, { '123', '456' })
1081      api.nvim_win_set_cursor(0, { 1, 0 })
1082      feed('<C-v>jl')
1083      exec_lua([[
1084        vim.defer_fn(function() vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { '0' }) end, 50)
1085        vim.wait(80)
1086      ]])
1087      mode = api.nvim_get_mode().mode
1088      eq({ '01', '45' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1089      eq(
1090        { string.char(0x16), { '0123', '456' } },
1091        { mode, api.nvim_buf_get_lines(0, 0, -1, false) }
1092      )
1093      feed('<ESC>')
1094      -- also test nvim_buf_set_lines inserts line above visual selection
1095      api.nvim_buf_set_lines(0, 0, -1, false, { '1', '2', '3' })
1096      api.nvim_win_set_cursor(0, { 2, 0 })
1097      feed('v')
1098      exec_lua([[
1099        vim.defer_fn(function() vim.api.nvim_buf_set_lines(0, 0, 0, false, { 'new' }) end, 50)
1100        vim.wait(80)
1101      ]])
1102      mode = api.nvim_get_mode().mode
1103      eq({ '2' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1104      eq({ 'v', { 'new', '1', '2', '3' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1105      feed('<ESC>')
1106
1107      api.nvim_buf_set_lines(0, 0, -1, false, { '1234' })
1108      api.nvim_win_set_cursor(0, { 1, 1 })
1109      feed('vl')
1110      exec_lua([[
1111        vim.defer_fn(function()
1112          vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { '0', 'foo' })
1113        end, 50)
1114        vim.wait(80)
1115      ]])
1116      mode = api.nvim_get_mode().mode
1117      eq({ '23' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1118      eq({ 'v', { '0', 'foo1234' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1119      feed('<ESC>')
1120
1121      api.nvim_buf_set_lines(0, 0, -1, false, { '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' })
1122      api.nvim_win_set_cursor(0, { 8, 0 })
1123      feed('v')
1124      exec_lua([[
1125        vim.defer_fn(function() vim.api.nvim_buf_set_lines(0, 0, 5, false, {}) end, 50)
1126        vim.wait(80)
1127      ]])
1128      mode = api.nvim_get_mode().mode
1129      eq({ '8' }, fn.getregion(fn.getpos('.'), fn.getpos('v'), { type = mode }))
1130      eq({ 'v', { '6', '7', '8', '9', '10' } }, { mode, api.nvim_buf_get_lines(0, 0, -1, false) })
1131      feed('<ESC>')
1132    end)
1133
1134    describe('when text is being added right at cursor position #22526', function()
1135      it('updates the cursor position in NORMAL mode', function()
1136        insert([[
1137        abcd]])
1138
1139        -- position the cursor on 'c'
1140        api.nvim_win_set_cursor(0, { 1, 2 })
1141        -- add 'xxx' before 'c'
1142        set_text(0, 2, 0, 2, { 'xxx' })
1143        eq({ 'abxxxcd' }, get_lines(0, -1, true))
1144        -- cursor should be on 'c'
1145        eq({ 1, 5 }, api.nvim_win_get_cursor(0))
1146      end)
1147
1148      it('updates the cursor position only in non-current window when in INSERT mode', function()
1149        insert([[
1150        abcd]])
1151
1152        -- position the cursor on 'c'
1153        api.nvim_win_set_cursor(0, { 1, 2 })
1154        -- open vertical split
1155        feed('<c-w>v')
1156        -- get into INSERT mode to treat cursor
1157        -- as being after 'b', not on 'c'
1158        feed('i')
1159        -- add 'xxx' between 'b' and 'c'
1160        set_text(0, 2, 0, 2, { 'xxx' })
1161        eq({ 'abxxxcd' }, get_lines(0, -1, true))
1162        -- in the current window cursor should stay after 'b'
1163        eq({ 1, 2 }, api.nvim_win_get_cursor(0))
1164        -- quit INSERT mode
1165        feed('<esc>')
1166        -- close current window
1167        feed('<c-w>c')
1168        -- in another window cursor should be on 'c'
1169        eq({ 1, 5 }, api.nvim_win_get_cursor(0))
1170      end)
1171    end)
1172
1173    describe('when text is being deleted right at cursor position', function()
1174      it('leaves cursor at the same position in NORMAL mode', function()
1175        insert([[
1176        abcd]])
1177
1178        -- position the cursor on 'b'
1179        api.nvim_win_set_cursor(0, { 1, 1 })
1180        -- delete 'b'
1181        set_text(0, 1, 0, 2, {})
1182        eq({ 'acd' }, get_lines(0, -1, true))
1183        -- cursor is now on 'c'
1184        eq({ 1, 1 }, api.nvim_win_get_cursor(0))
1185      end)
1186
1187      it('maintains INSERT-mode cursor position current/non-current window', function()
1188        insert([[
1189        abcd]])
1190
1191        -- position the cursor on 'b'
1192        api.nvim_win_set_cursor(0, { 1, 1 })
1193        -- open vertical split
1194        feed('<c-w>v')
1195        -- get into INSERT mode to treat cursor
1196        -- as being after 'a', not on 'b'
1197        feed('i')
1198        -- delete 'b'
1199        set_text(0, 1, 0, 2, {})
1200        eq({ 'acd' }, get_lines(0, -1, true))
1201        -- cursor in the current window should stay after 'a'
1202        eq({ 1, 1 }, api.nvim_win_get_cursor(0))
1203        -- quit INSERT mode
1204        feed('<esc>')
1205        -- close current window
1206        feed('<c-w>c')
1207        -- cursor in non-current window should stay on 'c'
1208        eq({ 1, 1 }, api.nvim_win_get_cursor(0))
1209      end)
1210    end)
1211
1212    describe('when cursor is inside replaced row range', function()
1213      it('maintains cursor position if at start_row, but before start_col', function()
1214        insert([[
1215        This should be first
1216        then there is a line we do not want
1217        and finally the last one]])
1218
1219        -- position the cursor on ' ' before 'first'
1220        api.nvim_win_set_cursor(0, { 1, 14 })
1221
1222        set_text(0, 15, 2, 11, {
1223          'the line we do not want',
1224          'but hopefully',
1225        })
1226
1227        eq({
1228          'This should be the line we do not want',
1229          'but hopefully the last one',
1230        }, get_lines(0, -1, true))
1231        -- cursor should stay at the same position
1232        eq({ 1, 14 }, api.nvim_win_get_cursor(0))
1233      end)
1234
1235      it('maintains cursor position if at start_row and column is still valid', function()
1236        insert([[
1237        This should be first
1238        then there is a line we do not want
1239        and finally the last one]])
1240
1241        -- position the cursor on 'f' in 'first'
1242        api.nvim_win_set_cursor(0, { 1, 15 })
1243
1244        set_text(0, 15, 2, 11, {
1245          'the line we do not want',
1246          'but hopefully',
1247        })
1248
1249        eq({
1250          'This should be the line we do not want',
1251          'but hopefully the last one',
1252        }, get_lines(0, -1, true))
1253        -- cursor should stay at the same position
1254        eq({ 1, 15 }, api.nvim_win_get_cursor(0))
1255      end)
1256
1257      it('adjusts cursor column to keep it valid if start_row got smaller', function()
1258        insert([[
1259        This should be first
1260        then there is a line we do not want
1261        and finally the last one]])
1262
1263        -- position the cursor on 't' in 'first'
1264        api.nvim_win_set_cursor(0, { 1, 19 })
1265
1266        local cursor = exec_lua([[
1267          vim.api.nvim_buf_set_text(0, 0, 15, 2, 24, {'last'})
1268          return vim.api.nvim_win_get_cursor(0)
1269        ]])
1270
1271        eq({ 'This should be last' }, get_lines(0, -1, true))
1272        -- cursor should end up on 't' in 'last'
1273        eq({ 1, 18 }, api.nvim_win_get_cursor(0))
1274        -- immediate call to nvim_win_get_cursor should have returned the same position
1275        eq({ 1, 18 }, cursor)
1276      end)
1277
1278      it('adjusts cursor column to keep it valid if start_row decreased in INSERT mode', function()
1279        insert([[
1280        This should be first
1281        then there is a line we do not want
1282        and finally the last one]])
1283
1284        -- position the cursor on 't' in 'first'
1285        api.nvim_win_set_cursor(0, { 1, 19 })
1286        -- enter INSERT mode to treat cursor as being after 't'
1287        feed('a')
1288
1289        local cursor = exec_lua([[
1290          vim.api.nvim_buf_set_text(0, 0, 15, 2, 24, {'last'})
1291          return vim.api.nvim_win_get_cursor(0)
1292        ]])
1293
1294        eq({ 'This should be last' }, get_lines(0, -1, true))
1295        -- cursor should end up after 't' in 'last'
1296        eq({ 1, 19 }, api.nvim_win_get_cursor(0))
1297        -- immediate call to nvim_win_get_cursor should have returned the same position
1298        eq({ 1, 19 }, cursor)
1299      end)
1300
1301      it('adjusts cursor to valid column in row after start_row if it got smaller', function()
1302        insert([[
1303        This should be first
1304        then there is a line we do not want
1305        and finally the last one]])
1306
1307        -- position the cursor on 'w' in 'want'
1308        api.nvim_win_set_cursor(0, { 2, 31 })
1309
1310        local cursor = exec_lua([[
1311          vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1312            '1',
1313            'then 2',
1314            'and then',
1315          })
1316          return vim.api.nvim_win_get_cursor(0)
1317        ]])
1318
1319        eq({
1320          'This should be 1',
1321          'then 2',
1322          'and then the last one',
1323        }, get_lines(0, -1, true))
1324        -- cursor column should end up at the end of a row
1325        eq({ 2, 5 }, api.nvim_win_get_cursor(0))
1326        -- immediate call to nvim_win_get_cursor should have returned the same position
1327        eq({ 2, 5 }, cursor)
1328      end)
1329
1330      it(
1331        'adjusts cursor to valid column in row after start_row if it got smaller in INSERT mode',
1332        function()
1333          insert([[
1334        This should be first
1335        then there is a line we do not want
1336        and finally the last one]])
1337
1338          -- position the cursor on 'w' in 'want'
1339          api.nvim_win_set_cursor(0, { 2, 31 })
1340          -- enter INSERT mode
1341          feed('a')
1342
1343          local cursor = exec_lua([[
1344          vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1345            '1',
1346            'then 2',
1347            'and then',
1348          })
1349          return vim.api.nvim_win_get_cursor(0)
1350        ]])
1351
1352          eq({
1353            'This should be 1',
1354            'then 2',
1355            'and then the last one',
1356          }, get_lines(0, -1, true))
1357          -- cursor column should end up at the end of a row
1358          eq({ 2, 6 }, api.nvim_win_get_cursor(0))
1359          -- immediate call to nvim_win_get_cursor should have returned the same position
1360          eq({ 2, 6 }, cursor)
1361        end
1362      )
1363
1364      it('adjusts cursor line and column to keep it inside replacement range', function()
1365        insert([[
1366        This should be first
1367        then there is a line we do not want
1368        and finally the last one]])
1369
1370        -- position the cursor on 'n' in 'finally'
1371        api.nvim_win_set_cursor(0, { 3, 6 })
1372
1373        local cursor = exec_lua([[
1374          vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1375            'the line we do not want',
1376            'but hopefully',
1377          })
1378          return vim.api.nvim_win_get_cursor(0)
1379        ]])
1380
1381        eq({
1382          'This should be the line we do not want',
1383          'but hopefully the last one',
1384        }, get_lines(0, -1, true))
1385        -- cursor should end up on 'y' in 'hopefully'
1386        -- to stay in the range, because it got smaller
1387        eq({ 2, 12 }, api.nvim_win_get_cursor(0))
1388        -- immediate call to nvim_win_get_cursor should have returned the same position
1389        eq({ 2, 12 }, cursor)
1390      end)
1391
1392      it('adjusts cursor line and column if replacement is empty', function()
1393        insert([[
1394        This should be first
1395        then there is a line we do not want
1396        and finally the last one]])
1397
1398        -- position the cursor on 'r' in 'there'
1399        api.nvim_win_set_cursor(0, { 2, 8 })
1400
1401        local cursor = exec_lua([[
1402          vim.api.nvim_buf_set_text(0, 0, 15, 2, 12, {})
1403          return vim.api.nvim_win_get_cursor(0)
1404        ]])
1405
1406        eq({ 'This should be the last one' }, get_lines(0, -1, true))
1407        -- cursor should end up on the next column after deleted range
1408        eq({ 1, 15 }, api.nvim_win_get_cursor(0))
1409        -- immediate call to nvim_win_get_cursor should have returned the same position
1410        eq({ 1, 15 }, cursor)
1411      end)
1412
1413      it('adjusts cursor line and column if replacement is empty and start_col == 0', function()
1414        insert([[
1415        This should be first
1416        then there is a line we do not want
1417        and finally the last one]])
1418
1419        -- position the cursor on 'r' in 'there'
1420        api.nvim_win_set_cursor(0, { 2, 8 })
1421
1422        local cursor = exec_lua([[
1423          vim.api.nvim_buf_set_text(0, 0, 0, 2, 4, {})
1424          return vim.api.nvim_win_get_cursor(0)
1425        ]])
1426
1427        eq({ 'finally the last one' }, get_lines(0, -1, true))
1428        -- cursor should end up in column 0
1429        eq({ 1, 0 }, api.nvim_win_get_cursor(0))
1430        -- immediate call to nvim_win_get_cursor should have returned the same position
1431        eq({ 1, 0 }, cursor)
1432      end)
1433
1434      it('adjusts cursor column if replacement ends at cursor row, after cursor column', function()
1435        insert([[
1436        This should be first
1437        then there is a line we do not want
1438        and finally the last one]])
1439
1440        -- position the cursor on 'y' in 'finally'
1441        api.nvim_win_set_cursor(0, { 3, 10 })
1442        set_text(0, 15, 2, 11, { '1', 'this 2', 'and then' })
1443
1444        eq({
1445          'This should be 1',
1446          'this 2',
1447          'and then the last one',
1448        }, get_lines(0, -1, true))
1449        -- cursor should end up on 'n' in 'then'
1450        eq({ 3, 7 }, api.nvim_win_get_cursor(0))
1451      end)
1452
1453      it(
1454        'adjusts cursor column if replacement ends at cursor row, at cursor column in INSERT mode',
1455        function()
1456          insert([[
1457        This should be first
1458        then there is a line we do not want
1459        and finally the last one]])
1460
1461          -- position the cursor on 'y' at 'finally'
1462          api.nvim_win_set_cursor(0, { 3, 10 })
1463          -- enter INSERT mode to treat cursor as being between 'l' and 'y'
1464          feed('i')
1465          set_text(0, 15, 2, 11, { '1', 'this 2', 'and then' })
1466
1467          eq({
1468            'This should be 1',
1469            'this 2',
1470            'and then the last one',
1471          }, get_lines(0, -1, true))
1472          -- cursor should end up after 'n' in 'then'
1473          eq({ 3, 8 }, api.nvim_win_get_cursor(0))
1474        end
1475      )
1476
1477      it('adjusts cursor column if replacement is inside of a single line', function()
1478        insert([[
1479        This should be first
1480        then there is a line we do not want
1481        and finally the last one]])
1482
1483        -- position the cursor on 'y' in 'finally'
1484        api.nvim_win_set_cursor(0, { 3, 10 })
1485        set_text(2, 4, 2, 11, { 'then' })
1486
1487        eq({
1488          'This should be first',
1489          'then there is a line we do not want',
1490          'and then the last one',
1491        }, get_lines(0, -1, true))
1492        -- cursor should end up on 'n' in 'then'
1493        eq({ 3, 7 }, api.nvim_win_get_cursor(0))
1494      end)
1495
1496      it('does not move cursor column after end of a line', function()
1497        insert([[
1498        This should be the only line here
1499        !!!]])
1500
1501        -- position cursor on the last '1'
1502        api.nvim_win_set_cursor(0, { 2, 2 })
1503
1504        local cursor = exec_lua([[
1505          vim.api.nvim_buf_set_text(0, 0, 33, 1, 3, {})
1506          return vim.api.nvim_win_get_cursor(0)
1507        ]])
1508
1509        eq({ 'This should be the only line here' }, get_lines(0, -1, true))
1510        -- cursor should end up on '!'
1511        eq({ 1, 32 }, api.nvim_win_get_cursor(0))
1512        -- immediate call to nvim_win_get_cursor should have returned the same position
1513        eq({ 1, 32 }, cursor)
1514      end)
1515
1516      it('does not move cursor column before start of a line', function()
1517        insert('\n!!!')
1518
1519        -- position cursor on the last '1'
1520        api.nvim_win_set_cursor(0, { 2, 2 })
1521
1522        local cursor = exec_lua([[
1523          vim.api.nvim_buf_set_text(0, 0, 0, 1, 3, {})
1524          return vim.api.nvim_win_get_cursor(0)
1525        ]])
1526
1527        eq({ '' }, get_lines(0, -1, true))
1528        -- cursor should end up on '!'
1529        eq({ 1, 0 }, api.nvim_win_get_cursor(0))
1530        -- immediate call to nvim_win_get_cursor should have returned the same position
1531        eq({ 1, 0 }, cursor)
1532      end)
1533
1534      describe('with virtualedit', function()
1535        it('adjusts cursor line/col to keep inside replacement range if not after eol', function()
1536          insert([[
1537          This should be first
1538          then there is a line we do not want
1539          and finally the last one]])
1540
1541          -- position cursor on 't' in 'want'
1542          api.nvim_win_set_cursor(0, { 2, 34 })
1543          -- turn on virtualedit
1544          command('set virtualedit=all')
1545
1546          local cursor = exec_lua([[
1547            vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1548              'the line we do not want',
1549              'but hopefully',
1550            })
1551            return vim.api.nvim_win_get_cursor(0)
1552          ]])
1553
1554          eq({
1555            'This should be the line we do not want',
1556            'but hopefully the last one',
1557          }, get_lines(0, -1, true))
1558          -- cursor should end up on 'y' in 'hopefully'
1559          -- to stay in the range
1560          eq({ 2, 12 }, api.nvim_win_get_cursor(0))
1561          -- immediate call to nvim_win_get_cursor should have returned the same position
1562          eq({ 2, 12 }, cursor)
1563          -- coladd should be 0
1564          eq(0, fn.winsaveview().coladd)
1565        end)
1566
1567        it('does not change cursor screen column when cursor >EOL and row got shorter', function()
1568          insert([[
1569          This should be first
1570          then there is a line we do not want
1571          and finally the last one]])
1572
1573          -- position cursor on 't' in 'want'
1574          api.nvim_win_set_cursor(0, { 2, 34 })
1575          -- turn on virtualedit
1576          command('set virtualedit=all')
1577          -- move cursor after eol
1578          fn.winrestview({ coladd = 5 })
1579
1580          local cursor = exec_lua([[
1581            vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1582              'the line we do not want',
1583              'but hopefully',
1584            })
1585            return vim.api.nvim_win_get_cursor(0)
1586          ]])
1587
1588          eq({
1589            'This should be the line we do not want',
1590            'but hopefully the last one',
1591          }, get_lines(0, -1, true))
1592          -- cursor should end up at eol of a new row
1593          eq({ 2, 26 }, api.nvim_win_get_cursor(0))
1594          -- immediate call to nvim_win_get_cursor should have returned the same position
1595          eq({ 2, 26 }, cursor)
1596          -- coladd should be increased so that cursor stays in the same screen column
1597          eq(13, fn.winsaveview().coladd)
1598        end)
1599
1600        it(
1601          'does not change cursor screen column when cursor is after eol and row got longer',
1602          function()
1603            insert([[
1604          This should be first
1605          then there is a line we do not want
1606          and finally the last one]])
1607
1608            -- position cursor on 't' in 'first'
1609            api.nvim_win_set_cursor(0, { 1, 19 })
1610            -- turn on virtualedit
1611            command('set virtualedit=all')
1612            -- move cursor after eol
1613            fn.winrestview({ coladd = 21 })
1614
1615            local cursor = exec_lua([[
1616            vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1617              'the line we do not want',
1618              'but hopefully',
1619            })
1620            return vim.api.nvim_win_get_cursor(0)
1621          ]])
1622
1623            eq({
1624              'This should be the line we do not want',
1625              'but hopefully the last one',
1626            }, get_lines(0, -1, true))
1627            -- cursor should end up at eol of a new row
1628            eq({ 1, 38 }, api.nvim_win_get_cursor(0))
1629            -- immediate call to nvim_win_get_cursor should have returned the same position
1630            eq({ 1, 38 }, cursor)
1631            -- coladd should be increased so that cursor stays in the same screen column
1632            eq(2, fn.winsaveview().coladd)
1633          end
1634        )
1635
1636        it(
1637          'does not change cursor screen column when cursor is after eol and row extended past cursor column',
1638          function()
1639            insert([[
1640          This should be first
1641          then there is a line we do not want
1642          and finally the last one]])
1643
1644            -- position cursor on 't' in 'first'
1645            api.nvim_win_set_cursor(0, { 1, 19 })
1646            -- turn on virtualedit
1647            command('set virtualedit=all')
1648            -- move cursor after eol just a bit
1649            fn.winrestview({ coladd = 3 })
1650
1651            local cursor = exec_lua([[
1652            vim.api.nvim_buf_set_text(0, 0, 15, 2, 11, {
1653              'the line we do not want',
1654              'but hopefully',
1655            })
1656            return vim.api.nvim_win_get_cursor(0)
1657          ]])
1658
1659            eq({
1660              'This should be the line we do not want',
1661              'but hopefully the last one',
1662            }, get_lines(0, -1, true))
1663            -- cursor should stay at the same screen column
1664            eq({ 1, 22 }, api.nvim_win_get_cursor(0))
1665            -- immediate call to nvim_win_get_cursor should have returned the same position
1666            eq({ 1, 22 }, cursor)
1667            -- coladd should become 0
1668            eq(0, fn.winsaveview().coladd)
1669          end
1670        )
1671
1672        it(
1673          'does not change cursor screen column when cursor is after eol and row range decreased',
1674          function()
1675            insert([[
1676          This should be first
1677          then there is a line we do not want
1678          and one more
1679          and finally the last one]])
1680
1681            -- position cursor on 'e' in 'more'
1682            api.nvim_win_set_cursor(0, { 3, 11 })
1683            -- turn on virtualedit
1684            command('set virtualedit=all')
1685            -- move cursor after eol
1686            fn.winrestview({ coladd = 28 })
1687
1688            local cursor = exec_lua([[
1689            vim.api.nvim_buf_set_text(0, 0, 15, 3, 11, {
1690              'the line we do not want',
1691              'but hopefully',
1692            })
1693            return vim.api.nvim_win_get_cursor(0)
1694          ]])
1695
1696            eq({
1697              'This should be the line we do not want',
1698              'but hopefully the last one',
1699            }, get_lines(0, -1, true))
1700            -- cursor should end up at eol of a new row
1701            eq({ 2, 26 }, api.nvim_win_get_cursor(0))
1702            -- immediate call to nvim_win_get_cursor should have returned the same position
1703            eq({ 2, 26 }, cursor)
1704            -- coladd should be increased so that cursor stays in the same screen column
1705            eq(13, fn.winsaveview().coladd)
1706          end
1707        )
1708      end)
1709    end)
1710
1711    describe('when cursor is at end_row and after end_col', function()
1712      it('adjusts cursor column when only a newline is added or deleted', function()
1713        insert([[
1714        first line
1715        second
1716         line]])
1717
1718        -- position the cursor on 'i'
1719        api.nvim_win_set_cursor(0, { 3, 2 })
1720        set_text(1, 6, 2, 0, {})
1721        eq({ 'first line', 'second line' }, get_lines(0, -1, true))
1722        -- cursor should stay on 'i'
1723        eq({ 2, 8 }, api.nvim_win_get_cursor(0))
1724
1725        -- add a newline back
1726        set_text(1, 6, 1, 6, { '', '' })
1727        eq({ 'first line', 'second', ' line' }, get_lines(0, -1, true))
1728        -- cursor should return back to the original position
1729        eq({ 3, 2 }, api.nvim_win_get_cursor(0))
1730      end)
1731
1732      it(
1733        'adjusts cursor column if the range is not bound to either start or end of a line',
1734        function()
1735          insert([[
1736        This should be first
1737        then there is a line we do not want
1738        and finally the last one]])
1739
1740          -- position the cursor on 'h' in 'the'
1741          api.nvim_win_set_cursor(0, { 3, 13 })
1742          set_text(0, 14, 2, 11, {})
1743          eq({ 'This should be the last one' }, get_lines(0, -1, true))
1744          -- cursor should stay on 'h'
1745          eq({ 1, 16 }, api.nvim_win_get_cursor(0))
1746          -- add deleted lines back
1747          set_text(0, 14, 0, 14, {
1748            ' first',
1749            'then there is a line we do not want',
1750            'and finally',
1751          })
1752          eq({
1753            'This should be first',
1754            'then there is a line we do not want',
1755            'and finally the last one',
1756          }, get_lines(0, -1, true))
1757          -- cursor should return back to the original position
1758          eq({ 3, 13 }, api.nvim_win_get_cursor(0))
1759        end
1760      )
1761
1762      it(
1763        'adjusts cursor column if replacing lines in range, not just deleting and adding',
1764        function()
1765          insert([[
1766        This should be first
1767        then there is a line we do not want
1768        and finally the last one]])
1769
1770          -- position the cursor on 's' in 'last'
1771          api.nvim_win_set_cursor(0, { 3, 18 })
1772          set_text(0, 15, 2, 11, {
1773            'the line we do not want',
1774            'but hopefully',
1775          })
1776
1777          eq({
1778            'This should be the line we do not want',
1779            'but hopefully the last one',
1780          }, get_lines(0, -1, true))
1781          -- cursor should stay on 's'
1782          eq({ 2, 20 }, api.nvim_win_get_cursor(0))
1783
1784          set_text(0, 15, 1, 13, {
1785            'first',
1786            'then there is a line we do not want',
1787            'and finally',
1788          })
1789
1790          eq({
1791            'This should be first',
1792            'then there is a line we do not want',
1793            'and finally the last one',
1794          }, get_lines(0, -1, true))
1795          -- cursor should return back to the original position
1796          eq({ 3, 18 }, api.nvim_win_get_cursor(0))
1797        end
1798      )
1799
1800      it('does not move cursor column after end of a line', function()
1801        insert([[
1802        This should be the only line here
1803        ]])
1804
1805        -- position cursor at the empty line
1806        api.nvim_win_set_cursor(0, { 2, 0 })
1807
1808        local cursor = exec_lua([[
1809          vim.api.nvim_buf_set_text(0, 0, 33, 1, 0, {'!'})
1810          return vim.api.nvim_win_get_cursor(0)
1811        ]])
1812
1813        eq({ 'This should be the only line here!' }, get_lines(0, -1, true))
1814        -- cursor should end up on '!'
1815        eq({ 1, 33 }, api.nvim_win_get_cursor(0))
1816        -- immediate call to nvim_win_get_cursor should have returned the same position
1817        eq({ 1, 33 }, cursor)
1818      end)
1819
1820      it('does not move cursor column before start of a line', function()
1821        insert('\n')
1822
1823        eq({ '', '' }, get_lines(0, -1, true))
1824
1825        -- position cursor on the last '1'
1826        api.nvim_win_set_cursor(0, { 2, 2 })
1827
1828        local cursor = exec_lua([[
1829          vim.api.nvim_buf_set_text(0, 0, 0, 1, 0, {''})
1830          return vim.api.nvim_win_get_cursor(0)
1831        ]])
1832
1833        eq({ '' }, get_lines(0, -1, true))
1834        -- cursor should end up on '!'
1835        eq({ 1, 0 }, api.nvim_win_get_cursor(0))
1836        -- immediate call to nvim_win_get_cursor should have returned the same position
1837        eq({ 1, 0 }, cursor)
1838      end)
1839    end)
1840
1841    it('can handle NULs', function()
1842      set_text(0, 0, 0, 0, { 'ab\0cd' })
1843      eq('ab\0cd', curbuf_depr('get_line', 0))
1844    end)
1845
1846    it('adjusts extmarks', function()
1847      local ns = api.nvim_create_namespace('my-fancy-plugin')
1848      insert([[
1849      foo bar
1850      baz
1851      ]])
1852      local id1 = api.nvim_buf_set_extmark(0, ns, 0, 1, {})
1853      local id2 = api.nvim_buf_set_extmark(0, ns, 0, 7, {})
1854      local id3 = api.nvim_buf_set_extmark(0, ns, 1, 1, {})
1855      set_text(0, 4, 0, 7, { 'q' })
1856
1857      eq({ 'foo q', 'baz' }, get_lines(0, 2, true))
1858      -- mark before replacement point is unaffected
1859      eq({ 0, 1 }, api.nvim_buf_get_extmark_by_id(0, ns, id1, {}))
1860      -- mark gets shifted back because the replacement was shorter
1861      eq({ 0, 5 }, api.nvim_buf_get_extmark_by_id(0, ns, id2, {}))
1862      -- mark on the next line is unaffected
1863      eq({ 1, 1 }, api.nvim_buf_get_extmark_by_id(0, ns, id3, {}))
1864
1865      -- replacing the text spanning two lines will adjust the mark on the next line
1866      set_text(0, 3, 1, 3, { 'qux' })
1867      eq({ 'fooqux', '' }, get_lines(0, 2, true))
1868      eq({ 0, 6 }, api.nvim_buf_get_extmark_by_id(0, ns, id3, {}))
1869      -- but mark before replacement point is still unaffected
1870      eq({ 0, 1 }, api.nvim_buf_get_extmark_by_id(0, ns, id1, {}))
1871      -- and the mark in the middle was shifted to the end of the insertion
1872      eq({ 0, 6 }, api.nvim_buf_get_extmark_by_id(0, ns, id2, {}))
1873
1874      -- marks should be put back into the same place after undoing
1875      set_text(0, 0, 0, 2, { '' })
1876      feed('u')
1877      eq({ 0, 1 }, api.nvim_buf_get_extmark_by_id(0, ns, id1, {}))
1878      eq({ 0, 6 }, api.nvim_buf_get_extmark_by_id(0, ns, id2, {}))
1879      eq({ 0, 6 }, api.nvim_buf_get_extmark_by_id(0, ns, id3, {}))
1880
1881      -- marks should be shifted over by the correct number of bytes for multibyte
1882      -- chars
1883      set_text(0, 0, 0, 0, { 'Ø' })
1884      eq({ 0, 3 }, api.nvim_buf_get_extmark_by_id(0, ns, id1, {}))
1885      eq({ 0, 8 }, api.nvim_buf_get_extmark_by_id(0, ns, id2, {}))
1886      eq({ 0, 8 }, api.nvim_buf_get_extmark_by_id(0, ns, id3, {}))
1887    end)
1888
1889    it('correctly marks changed region for redraw #13890', function()
1890      local screen = Screen.new(20, 5)
1891
1892      insert([[
1893      AAA
1894      BBB
1895      ]])
1896
1897      api.nvim_buf_set_text(0, 0, 0, 1, 3, { 'XXX', 'YYY' })
1898
1899      screen:expect([[
1900        XXX                 |
1901        YYY                 |
1902        ^                    |
1903        {1:~                   }|
1904                            |
1905      ]])
1906    end)
1907
1908    it('errors on out-of-range', function()
1909      insert([[
1910      hello foo!
1911      text]])
1912      eq("Invalid 'start_row': out of range", pcall_err(set_text, 2, 0, 3, 0, {}))
1913      eq("Invalid 'start_row': out of range", pcall_err(set_text, -3, 0, 0, 0, {}))
1914      eq("Invalid 'end_row': out of range", pcall_err(set_text, 0, 0, 2, 0, {}))
1915      eq("Invalid 'end_row': out of range", pcall_err(set_text, 0, 0, -3, 0, {}))
1916      eq("Invalid 'start_col': out of range", pcall_err(set_text, 1, 5, 1, 5, {}))
1917      eq("Invalid 'end_col': out of range", pcall_err(set_text, 1, 0, 1, 5, {}))
1918    end)
1919
1920    it('errors when start is greater than end', function()
1921      insert([[
1922      hello foo!
1923      text]])
1924      eq("'start' is higher than 'end'", pcall_err(set_text, 1, 0, 0, 0, {}))
1925      eq("'start' is higher than 'end'", pcall_err(set_text, 0, 1, 0, 0, {}))
1926    end)
1927
1928    it('no heap-use-after-free when called consecutively #19643', function()
1929      set_text(0, 0, 0, 0, { 'one', '', '', 'two' })
1930      eq({ 'one', '', '', 'two' }, get_lines(0, 4, true))
1931      api.nvim_win_set_cursor(0, { 1, 0 })
1932      exec_lua([[
1933        vim.api.nvim_buf_set_text(0, 0, 3, 1, 0, {''})
1934        vim.api.nvim_buf_set_text(0, 0, 3, 1, 0, {''})
1935      ]])
1936      eq({ 'one', 'two' }, get_lines(0, 2, true))
1937    end)
1938
1939    it('auto-loads unloaded buffer', function()
1940      local new_bufnr = fn.bufnr('set_text', true)
1941      eq(false, api.nvim_buf_is_loaded(new_bufnr))
1942      api.nvim_buf_set_text(new_bufnr, 0, 0, 0, -1, { 'foo' })
1943      eq(true, api.nvim_buf_is_loaded(new_bufnr))
1944      eq({ 'foo' }, api.nvim_buf_get_lines(new_bufnr, 0, -1, false))
1945    end)
1946
1947    describe('handles topline', function()
1948      local screen
1949      before_each(function()
1950        screen = Screen.new(20, 12)
1951        api.nvim_buf_set_lines(
1952          0,
1953          0,
1954          -1,
1955          true,
1956          { 'aaa', 'bbb', 'ccc', 'ddd', 'www', 'xxx', 'yyy', 'zzz' }
1957        )
1958        api.nvim_set_option_value('modified', false, {})
1959      end)
1960
1961      it('of current window', function()
1962        local win = api.nvim_get_current_win()
1963        local buf = api.nvim_get_current_buf()
1964
1965        command('new | wincmd w')
1966        api.nvim_win_set_cursor(win, { 8, 0 })
1967
1968        screen:expect {
1969          grid = [[
1970                              |
1971          {1:~                   }|*4
1972          {2:[No Name]           }|
1973          www                 |
1974          xxx                 |
1975          yyy                 |
1976          ^zzz                 |
1977          {3:[No Name]           }|
1978                              |
1979        ]],
1980        }
1981        api.nvim_buf_set_text(buf, 0, 3, 1, 0, { 'X' })
1982
1983        screen:expect {
1984          grid = [[
1985                              |
1986          {1:~                   }|*4
1987          {2:[No Name]           }|
1988          www                 |
1989          xxx                 |
1990          yyy                 |
1991          ^zzz                 |
1992          {3:[No Name] [+]       }|
1993                              |
1994        ]],
1995        }
1996      end)
1997
1998      it('of non-current window', function()
1999        local win = api.nvim_get_current_win()
2000        local buf = api.nvim_get_current_buf()
2001
2002        command('new')
2003        api.nvim_win_set_cursor(win, { 8, 0 })
2004
2005        screen:expect {
2006          grid = [[
2007          ^                    |
2008          {1:~                   }|*4
2009          {3:[No Name]           }|
2010          www                 |
2011          xxx                 |
2012          yyy                 |
2013          zzz                 |
2014          {2:[No Name]           }|
2015                              |
2016        ]],
2017        }
2018
2019        api.nvim_buf_set_text(buf, 0, 3, 1, 0, { 'X' })
2020        screen:expect {
2021          grid = [[
2022          ^                    |
2023          {1:~                   }|*4
2024          {3:[No Name]           }|
2025          www                 |
2026          xxx                 |
2027          yyy                 |
2028          zzz                 |
2029          {2:[No Name] [+]       }|
2030                              |
2031        ]],
2032        }
2033      end)
2034
2035      it('of split windows with same buffer', function()
2036        local win = api.nvim_get_current_win()
2037        local buf = api.nvim_get_current_buf()
2038
2039        command('split')
2040        api.nvim_win_set_cursor(win, { 8, 0 })
2041        api.nvim_win_set_cursor(0, { 1, 1 })
2042
2043        screen:expect {
2044          grid = [[
2045          a^aa                 |
2046          bbb                 |
2047          ccc                 |
2048          ddd                 |
2049          www                 |
2050          {3:[No Name]           }|
2051          www                 |
2052          xxx                 |
2053          yyy                 |
2054          zzz                 |
2055          {2:[No Name]           }|
2056                              |
2057        ]],
2058        }
2059        api.nvim_buf_set_text(buf, 0, 3, 1, 0, { 'X' })
2060
2061        screen:expect {
2062          grid = [[
2063          a^aaXbbb             |
2064          ccc                 |
2065          ddd                 |
2066          www                 |
2067          xxx                 |
2068          {3:[No Name] [+]       }|
2069          www                 |
2070          xxx                 |
2071          yyy                 |
2072          zzz                 |
2073          {2:[No Name] [+]       }|
2074                              |
2075        ]],
2076        }
2077      end)
2078
2079      describe('of current window when', function()
2080        before_each(function()
2081          command('new | wincmd w | setlocal modified')
2082          feed('Gk')
2083          screen:expect([[
2084                                |
2085            {1:~                   }|*4
2086            {2:[No Name]           }|
2087            www                 |
2088            xxx                 |
2089            ^yyy                 |
2090            zzz                 |
2091            {3:[No Name] [+]       }|
2092                                |
2093          ]])
2094        end)
2095
2096        it('deleting 3 lines around topline', function()
2097          api.nvim_buf_set_text(0, 3, 0, 6, 0, {})
2098          screen:expect([[
2099                                |
2100            {1:~                   }|*4
2101            {2:[No Name]           }|
2102            ccc                 |
2103            ^yyy                 |
2104            zzz                 |
2105            {1:~                   }|
2106            {3:[No Name] [+]       }|
2107                                |
2108          ]])
2109          eq(5, api.nvim_buf_line_count(0))
2110        end)
2111
2112        it('deleting 3 lines around the line just before topline', function()
2113          api.nvim_buf_set_text(0, 2, 0, 5, 0, {})
2114          screen:expect([[
2115                                |
2116            {1:~                   }|*4
2117            {2:[No Name]           }|
2118            bbb                 |
2119            xxx                 |
2120            ^yyy                 |
2121            zzz                 |
2122            {3:[No Name] [+]       }|
2123                                |
2124          ]])
2125          eq(5, api.nvim_buf_line_count(0))
2126        end)
2127
2128        for count = 1, 4 do
2129          it(('deleting %d lines just before topline'):format(count), function()
2130            api.nvim_buf_set_text(0, 4 - count, 0, 4, 0, {})
2131            screen:expect_unchanged()
2132            eq(8 - count, api.nvim_buf_line_count(0))
2133          end)
2134
2135          describe(('replacing %d lines just before topline with 2 lines'):format(count), function()
2136            it('including final newline', function()
2137              api.nvim_buf_set_text(0, 4 - count, 0, 4, 0, { 'eee', 'fff', '' })
2138              screen:expect_unchanged()
2139              eq(8 - count + 2, api.nvim_buf_line_count(0))
2140            end)
2141
2142            it('excluding final newline', function()
2143              api.nvim_buf_set_text(0, 4 - count, 0, 3, -1, { 'eee', 'fff' })
2144              screen:expect_unchanged()
2145              eq(8 - count + 2, api.nvim_buf_line_count(0))
2146            end)
2147          end)
2148        end
2149
2150        for count = 1, 3 do
2151          it(('deleting %d lines far before topline'):format(count), function()
2152            api.nvim_buf_set_text(0, 0, 0, count, 0, {})
2153            screen:expect_unchanged()
2154            eq(8 - count, api.nvim_buf_line_count(0))
2155          end)
2156
2157          describe(('replacing %d lines far before topline with 2 lines'):format(count), function()
2158            it('including final newline', function()
2159              api.nvim_buf_set_text(0, 0, 0, count, 0, { 'eee', 'fff', '' })
2160              screen:expect_unchanged()
2161              eq(8 - count + 2, api.nvim_buf_line_count(0))
2162            end)
2163
2164            it('excluding final newline', function()
2165              api.nvim_buf_set_text(0, 0, 0, count - 1, -1, { 'eee', 'fff' })
2166              screen:expect_unchanged()
2167              eq(8 - count + 2, api.nvim_buf_line_count(0))
2168            end)
2169          end)
2170        end
2171
2172        describe('replacing topline', function()
2173          describe('with 1 line', function()
2174            local s1 = [[
2175                                  |
2176              {1:~                   }|*4
2177              {2:[No Name]           }|
2178              eee                 |
2179              xxx                 |
2180              ^yyy                 |
2181              zzz                 |
2182              {3:[No Name] [+]       }|
2183                                  |
2184            ]]
2185            it('including final newline', function()
2186              api.nvim_buf_set_text(0, 4, 0, 5, 0, { 'eee', '' })
2187              screen:expect(s1)
2188            end)
2189            it('excluding final newline', function()
2190              api.nvim_buf_set_text(0, 4, 0, 4, -1, { 'eee' })
2191              screen:expect(s1)
2192            end)
2193          end)
2194
2195          describe('with 2 lines', function()
2196            local s2 = [[
2197                                  |
2198              {1:~                   }|*4
2199              {2:[No Name]           }|
2200              eee                 |
2201              fff                 |
2202              xxx                 |
2203              ^yyy                 |
2204              {3:[No Name] [+]       }|
2205                                  |
2206            ]]
2207            it('including final newline', function()
2208              api.nvim_buf_set_text(0, 4, 0, 5, 0, { 'eee', 'fff', '' })
2209              screen:expect(s2)
2210            end)
2211            it('excluding final newline', function()
2212              api.nvim_buf_set_text(0, 4, 0, 4, -1, { 'eee', 'fff' })
2213              screen:expect(s2)
2214            end)
2215          end)
2216        end)
2217
2218        it('inserting at start of topline', function()
2219          api.nvim_buf_set_text(0, 4, 0, 4, 0, { 'X', '' })
2220          screen:expect([[
2221                                |
2222            {1:~                   }|*4
2223            {2:[No Name]           }|
2224            X                   |
2225            www                 |
2226            xxx                 |
2227            ^yyy                 |
2228            {3:[No Name] [+]       }|
2229                                |
2230          ]])
2231        end)
2232      end)
2233    end)
2234  end)
2235
2236  describe_lua_and_rpc('nvim_buf_get_text', function(lua_or_rpc)
2237    local get_text = lua_or_rpc.nvim_buf_get_text
2238    before_each(function()
2239      insert([[
2240      hello foo!
2241      text
2242      more]])
2243    end)
2244
2245    it('works', function()
2246      eq({ 'hello' }, get_text(0, 0, 0, 0, 5, {}))
2247      eq({ 'hello foo!' }, get_text(0, 0, 0, 0, 42, {}))
2248      eq({ 'foo!' }, get_text(0, 0, 6, 0, 10, {}))
2249      eq({ 'foo!', 'tex' }, get_text(0, 0, 6, 1, 3, {}))
2250      eq({ 'foo!', 'tex' }, get_text(0, -3, 6, -2, 3, {}))
2251      eq({ '' }, get_text(0, 0, 18, 0, 20, {}))
2252      eq({ 'ext' }, get_text(0, -2, 1, -2, 4, {}))
2253      eq({ 'hello foo!', 'text', 'm' }, get_text(0, 0, 0, 2, 1, {}))
2254      eq({ 'hello foo!' }, get_text(0, 0, -987654321, 0, 987654321, {}))
2255      eq({ '' }, get_text(0, 0, -15, 0, -20, {}))
2256    end)
2257
2258    it('errors on out-of-range', function()
2259      eq('Index out of bounds', pcall_err(get_text, 0, 2, 0, 4, 0, {}))
2260      eq('Index out of bounds', pcall_err(get_text, 0, -4, 0, 0, 0, {}))
2261      eq('Index out of bounds', pcall_err(get_text, 0, 0, 0, 3, 0, {}))
2262      eq('Index out of bounds', pcall_err(get_text, 0, 0, 0, -4, 0, {}))
2263      -- no ml_get errors should happen #19017
2264      eq('', api.nvim_get_vvar('errmsg'))
2265    end)
2266
2267    it('errors when start is greater than end', function()
2268      eq("'start' is higher than 'end'", pcall_err(get_text, 0, 1, 0, 0, 0, {}))
2269      eq('start_col must be less than or equal to end_col', pcall_err(get_text, 0, 0, 1, 0, 0, {}))
2270    end)
2271  end)
2272
2273  describe('nvim_buf_get_offset', function()
2274    local get_offset = api.nvim_buf_get_offset
2275    it('works', function()
2276      api.nvim_buf_set_lines(0, 0, -1, true, { 'Some\r', 'exa\000mple', '', 'buf\rfer', 'text' })
2277      eq(5, api.nvim_buf_line_count(0))
2278      eq(0, get_offset(0, 0))
2279      eq(6, get_offset(0, 1))
2280      eq(15, get_offset(0, 2))
2281      eq(16, get_offset(0, 3))
2282      eq(24, get_offset(0, 4))
2283      eq(29, get_offset(0, 5))
2284      eq('Index out of bounds', pcall_err(get_offset, 0, 6))
2285      eq('Index out of bounds', pcall_err(get_offset, 0, -1))
2286
2287      api.nvim_set_option_value('eol', false, {})
2288      api.nvim_set_option_value('fixeol', false, {})
2289      eq(28, get_offset(0, 5))
2290
2291      -- fileformat is ignored
2292      api.nvim_set_option_value('fileformat', 'dos', {})
2293      eq(0, get_offset(0, 0))
2294      eq(6, get_offset(0, 1))
2295      eq(15, get_offset(0, 2))
2296      eq(16, get_offset(0, 3))
2297      eq(24, get_offset(0, 4))
2298      eq(28, get_offset(0, 5))
2299      api.nvim_set_option_value('eol', true, {})
2300      eq(29, get_offset(0, 5))
2301
2302      command('set hidden')
2303      command('enew')
2304      eq(6, api.nvim_buf_get_offset(1, 1))
2305      command('bunload! 1')
2306      eq(-1, api.nvim_buf_get_offset(1, 1))
2307      eq(-1, api.nvim_buf_get_offset(1, 0))
2308    end)
2309
2310    it('works in empty buffer', function()
2311      eq(0, get_offset(0, 0))
2312      eq(1, get_offset(0, 1))
2313      eq(-1, fn.line2byte('$'))
2314    end)
2315
2316    it('works in buffer with one line inserted', function()
2317      feed('itext')
2318      eq(0, get_offset(0, 0))
2319      eq(5, get_offset(0, 1))
2320    end)
2321  end)
2322
2323  describe('nvim_buf_get_var, nvim_buf_set_var, nvim_buf_del_var', function()
2324    it('works', function()
2325      api.nvim_buf_set_var(0, 'lua', { 1, 2, { ['3'] = 1 } })
2326      eq({ 1, 2, { ['3'] = 1 } }, api.nvim_buf_get_var(0, 'lua'))
2327      eq({ 1, 2, { ['3'] = 1 } }, api.nvim_eval('b:lua'))
2328      eq(1, fn.exists('b:lua'))
2329      api.nvim_buf_del_var(0, 'lua')
2330      eq(0, fn.exists('b:lua'))
2331      eq('Key not found: lua', pcall_err(api.nvim_buf_del_var, 0, 'lua'))
2332      api.nvim_buf_set_var(0, 'lua', 1)
2333      command('lockvar b:lua')
2334      eq('Key is locked: lua', pcall_err(api.nvim_buf_del_var, 0, 'lua'))
2335      eq('Key is locked: lua', pcall_err(api.nvim_buf_set_var, 0, 'lua', 1))
2336      eq('Key is read-only: changedtick', pcall_err(api.nvim_buf_del_var, 0, 'changedtick'))
2337      eq('Key is read-only: changedtick', pcall_err(api.nvim_buf_set_var, 0, 'changedtick', 1))
2338    end)
2339  end)
2340
2341  describe('nvim_buf_get_changedtick', function()
2342    it('works', function()
2343      eq(2, api.nvim_buf_get_changedtick(0))
2344      api.nvim_buf_set_lines(0, 0, 1, false, { 'abc\0', '\0def', 'ghi' })
2345      eq(3, api.nvim_buf_get_changedtick(0))
2346      eq(3, api.nvim_buf_get_var(0, 'changedtick'))
2347    end)
2348
2349    it('buffer_set_var returns the old value', function()
2350      local val1 = { 1, 2, { ['3'] = 1 } }
2351      local val2 = { 4, 7 }
2352      eq(NIL, request('buffer_set_var', 0, 'lua', val1))
2353      eq(val1, request('buffer_set_var', 0, 'lua', val2))
2354    end)
2355
2356    it('buffer_del_var returns the old value', function()
2357      local val1 = { 1, 2, { ['3'] = 1 } }
2358      local val2 = { 4, 7 }
2359      eq(NIL, request('buffer_set_var', 0, 'lua', val1))
2360      eq(val1, request('buffer_set_var', 0, 'lua', val2))
2361      eq(val2, request('buffer_del_var', 0, 'lua'))
2362    end)
2363  end)
2364
2365  describe('nvim_get_option_value, nvim_set_option_value', function()
2366    it('works', function()
2367      eq(8, api.nvim_get_option_value('shiftwidth', {}))
2368      api.nvim_set_option_value('shiftwidth', 4, {})
2369      eq(4, api.nvim_get_option_value('shiftwidth', {}))
2370      -- global-local option
2371      api.nvim_set_option_value('define', 'test', { buf = 0 })
2372      eq('test', api.nvim_get_option_value('define', { buf = 0 }))
2373      -- Doesn't change the global value
2374      eq('', api.nvim_get_option_value('define', { scope = 'global' }))
2375    end)
2376
2377    it('returns values for unset local options', function()
2378      -- 'undolevels' is only set to its "unset" value when a new buffer is
2379      -- created
2380      command('enew')
2381      eq(-123456, api.nvim_get_option_value('undolevels', { buf = 0 }))
2382    end)
2383  end)
2384
2385  describe('nvim_buf_get_name, nvim_buf_set_name', function()
2386    it('works', function()
2387      command('new')
2388      eq('', api.nvim_buf_get_name(0))
2389      local new_name = api.nvim_eval('resolve(tempname())')
2390      api.nvim_buf_set_name(0, new_name)
2391      eq(new_name, api.nvim_buf_get_name(0))
2392      command('w!')
2393      eq(1, fn.filereadable(new_name))
2394      os.remove(new_name)
2395    end)
2396
2397    it('directory buffer-name always ends with slash', function()
2398      local cwd = t.fix_slashes(fn.getcwd())
2399      local dir = 'Xtest_dir_name'
2400      t.mkdir(dir)
2401      finally(function()
2402        n.rmdir(dir)
2403      end)
2404      api.nvim_buf_set_name(0, dir)
2405      eq(cwd .. '/' .. dir .. '/', t.fix_slashes(api.nvim_buf_get_name(0)))
2406    end)
2407
2408    it('directory buffer-name preserves symbolic link path', function()
2409      t.skip(t.is_os('win'), 'N/A for Windows')
2410      local cwd = t.fix_slashes(fn.getcwd())
2411      local target = 'Xtest_dir_target'
2412      local link = 'Xtest_dir_link'
2413      t.mkdir(target)
2414      assert(vim.uv.fs_symlink(assert(vim.uv.fs_realpath(target)), link, { dir = true }))
2415      finally(function()
2416        os.remove(link)
2417        n.rmdir(target)
2418      end)
2419      api.nvim_buf_set_name(0, link .. '/')
2420      eq(cwd .. '/' .. link .. '/', t.fix_slashes(api.nvim_buf_get_name(0)))
2421    end)
2422
2423    it('allows URI buffer names that differ by a trailing slash', function()
2424      api.nvim_buf_set_name(0, 'test://example')
2425      local trailing_slash = api.nvim_create_buf(true, false)
2426      api.nvim_buf_set_name(trailing_slash, 'test://example/')
2427
2428      eq('test://example', api.nvim_buf_get_name(0))
2429      eq('test://example/', api.nvim_buf_get_name(trailing_slash))
2430    end)
2431
2432    describe("with 'autochdir'", function()
2433      local topdir
2434      local oldbuf
2435      local newbuf
2436
2437      before_each(function()
2438        command('set shellslash')
2439        topdir = fn.getcwd()
2440        t.mkdir(topdir .. '/Xacd')
2441
2442        oldbuf = api.nvim_get_current_buf()
2443        command('vnew')
2444        newbuf = api.nvim_get_current_buf()
2445        command('set autochdir')
2446      end)
2447
2448      after_each(function()
2449        n.rmdir(topdir .. '/Xacd')
2450      end)
2451
2452      it('does not change cwd with non-current buffer', function()
2453        api.nvim_buf_set_name(oldbuf, topdir .. '/Xacd/foo.txt')
2454        eq(topdir, fn.getcwd())
2455      end)
2456
2457      it('changes cwd with current buffer', function()
2458        api.nvim_buf_set_name(newbuf, topdir .. '/Xacd/foo.txt')
2459        eq(topdir .. '/Xacd', fn.getcwd())
2460      end)
2461    end)
2462  end)
2463
2464  describe('nvim_buf_is_loaded', function()
2465    it('works', function()
2466      -- record our buffer number for when we unload it
2467      local bufnr = api.nvim_get_current_buf()
2468      -- api should report that the buffer is loaded
2469      ok(api.nvim_buf_is_loaded(bufnr))
2470      -- hide the current buffer by switching to a new empty buffer
2471      -- Careful! we need to modify the buffer first or vim will just reuse it
2472      api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'line1' })
2473      command('hide enew')
2474      -- confirm the buffer is hidden, but still loaded
2475      local infolist = api.nvim_eval('getbufinfo(' .. bufnr .. ')')
2476      eq(1, #infolist)
2477      eq(1, infolist[1].hidden)
2478      eq(1, infolist[1].loaded)
2479      -- now force unload the buffer
2480      command('bunload! ' .. bufnr)
2481      -- confirm the buffer is unloaded
2482      infolist = api.nvim_eval('getbufinfo(' .. bufnr .. ')')
2483      eq(0, infolist[1].loaded)
2484      -- nvim_buf_is_loaded() should also report the buffer as unloaded
2485      eq(false, api.nvim_buf_is_loaded(bufnr))
2486    end)
2487  end)
2488
2489  describe('nvim_buf_is_valid', function()
2490    it('works', function()
2491      command('new')
2492      local b = api.nvim_get_current_buf()
2493      ok(api.nvim_buf_is_valid(b))
2494      command('bw!')
2495      ok(not api.nvim_buf_is_valid(b))
2496    end)
2497  end)
2498
2499  describe('nvim_buf_delete', function()
2500    it('allows for just deleting', function()
2501      command('new')
2502      local b = api.nvim_get_current_buf()
2503      ok(api.nvim_buf_is_valid(b))
2504      api.nvim_buf_delete(b, {})
2505      ok(not api.nvim_buf_is_loaded(b))
2506      ok(not api.nvim_buf_is_valid(b))
2507    end)
2508
2509    it('allows for just unloading', function()
2510      command('new')
2511      local b = api.nvim_get_current_buf()
2512      ok(api.nvim_buf_is_valid(b))
2513      api.nvim_buf_delete(b, { unload = true })
2514      ok(not api.nvim_buf_is_loaded(b))
2515      ok(api.nvim_buf_is_valid(b))
2516    end)
2517
2518    it('does not crash if WinClosed closes the next tabpage #40852', function()
2519      exec_lua(function()
2520        vim.cmd.tabnew()
2521        vim.api.nvim_create_autocmd('WinClosed', {
2522          callback = function()
2523            pcall(vim.api.nvim_win_close, 0, true)
2524          end,
2525        })
2526        local bufs = vim.api.nvim_list_bufs()
2527        vim.api.nvim_buf_delete(bufs[#bufs - 1], { force = true })
2528      end)
2529      assert_alive()
2530    end)
2531  end)
2532
2533  describe('nvim_buf_get_mark', function()
2534    it('works', function()
2535      api.nvim_buf_set_lines(0, -1, -1, true, { 'a', 'bit of', 'text' })
2536      api.nvim_win_set_cursor(0, { 3, 4 })
2537      command('mark v')
2538      eq({ 3, 0 }, api.nvim_buf_get_mark(0, 'v'))
2539    end)
2540  end)
2541
2542  describe('nvim_buf_set_mark', function()
2543    it('works with buffer local marks', function()
2544      api.nvim_buf_set_lines(0, -1, -1, true, { 'a', 'bit of', 'text' })
2545      eq(true, api.nvim_buf_set_mark(0, 'z', 1, 1, {}))
2546      eq({ 1, 1 }, api.nvim_buf_get_mark(0, 'z'))
2547      eq({ 0, 1, 2, 0 }, fn.getpos("'z"))
2548    end)
2549    it('works with file/uppercase marks', function()
2550      api.nvim_buf_set_lines(0, -1, -1, true, { 'a', 'bit of', 'text' })
2551      eq(true, api.nvim_buf_set_mark(0, 'Z', 3, 2, {}))
2552      eq({ 3, 2 }, api.nvim_buf_get_mark(0, 'Z'))
2553      eq({ api.nvim_get_current_buf(), 3, 3, 0 }, fn.getpos("'Z"))
2554    end)
2555    it('fails when invalid marks names are used', function()
2556      eq(false, pcall(api.nvim_buf_set_mark, 0, '!', 1, 0, {}))
2557      eq(false, pcall(api.nvim_buf_set_mark, 0, 'fail', 1, 0, {}))
2558    end)
2559    it('fails when invalid buffer number is used', function()
2560      eq(false, pcall(api.nvim_buf_set_mark, 99, 'a', 1, 1, {}))
2561    end)
2562    it('auto-loads unloaded buffer', function()
2563      local new_bufnr = fn.bufnr('set_mark', true)
2564      eq(false, api.nvim_buf_is_loaded(new_bufnr))
2565      eq(true, api.nvim_buf_set_mark(new_bufnr, 'A', 0, 0, {}))
2566      eq(true, api.nvim_buf_is_loaded(new_bufnr))
2567      eq({ 0, 0 }, api.nvim_buf_get_mark(new_bufnr, 'A'))
2568    end)
2569  end)
2570
2571  describe('nvim_buf_del_mark', function()
2572    it('works with buffer local marks', function()
2573      api.nvim_buf_set_lines(0, -1, -1, true, { 'a', 'bit of', 'text' })
2574      api.nvim_buf_set_mark(0, 'z', 3, 1, {})
2575      eq(true, api.nvim_buf_del_mark(0, 'z'))
2576      eq({ 0, 0 }, api.nvim_buf_get_mark(0, 'z'))
2577    end)
2578    it('works with file/uppercase marks', function()
2579      api.nvim_buf_set_lines(0, -1, -1, true, { 'a', 'bit of', 'text' })
2580      api.nvim_buf_set_mark(0, 'Z', 3, 3, {})
2581      eq(true, api.nvim_buf_del_mark(0, 'Z'))
2582      eq({ 0, 0 }, api.nvim_buf_get_mark(0, 'Z'))
2583    end)
2584    it('returns false in marks not set in this buffer', function()
2585      local abuf = api.nvim_create_buf(false, true)
2586      api.nvim_buf_set_lines(abuf, -1, -1, true, { 'a', 'bit of', 'text' })
2587      api.nvim_buf_set_mark(abuf, 'A', 2, 2, {})
2588      eq(false, api.nvim_buf_del_mark(0, 'A'))
2589      eq({ 2, 2 }, api.nvim_buf_get_mark(abuf, 'A'))
2590    end)
2591    it('returns false if mark was not deleted', function()
2592      api.nvim_buf_set_lines(0, -1, -1, true, { 'a', 'bit of', 'text' })
2593      api.nvim_buf_set_mark(0, 'z', 3, 1, {})
2594      eq(true, api.nvim_buf_del_mark(0, 'z'))
2595      eq(false, api.nvim_buf_del_mark(0, 'z')) -- Mark was already deleted
2596    end)
2597    it('fails when invalid marks names are used', function()
2598      eq(false, pcall(api.nvim_buf_del_mark, 0, '!'))
2599      eq(false, pcall(api.nvim_buf_del_mark, 0, 'fail'))
2600    end)
2601    it('fails when invalid buffer number is used', function()
2602      eq(false, pcall(api.nvim_buf_del_mark, 99, 'a'))
2603    end)
2604  end)
2605
2606  describe('nvim_buf_call', function()
2607    it('window keeps the buffer when the callback closes the original window', function()
2608      local origin = api.nvim_get_current_win()
2609      local other_buf = api.nvim_create_buf(true, false)
2610      local other_win = api.nvim_open_win(other_buf, false, { split = 'right' })
2611      exec_lua(function()
2612        vim.api.nvim_buf_call(other_buf, function()
2613          vim.api.nvim_win_close(origin, true)
2614          vim.cmd('enew') -- switch the context window away from other_buf
2615        end)
2616      end)
2617      -- Original window is gone: stay in the nvim_buf_call window, but buffer is restored.
2618      eq(other_win, api.nvim_get_current_win())
2619      eq(other_buf, api.nvim_win_get_buf(other_win))
2620    end)
2621
2622    it('preserves visual-mode, unless the callback ended it', function()
2623      -- Same-buffer: Visual survives untouched.
2624      command('normal! v')
2625      exec_lua('vim.api.nvim_buf_call(0, function() end)')
2626      eq('v', fn.mode())
2627      -- The callback ends Visual mode: it must STAY ended.
2628      exec_lua([[vim.api.nvim_buf_call(0, function() vim.cmd('normal! \27') end)]])
2629      eq('n', fn.mode())
2630    end)
2631
2632    it('supports multiple returns', function()
2633      local curbuf = api.nvim_get_current_buf()
2634      local other = api.nvim_create_buf(false, true)
2635      exec_lua(function()
2636        function with_len(...)
2637          return select('#', ...), { ... }
2638        end
2639        function test(fn)
2640          local len, res = with_len(vim.api.nvim_buf_call(other, fn))
2641          -- convert to serializable vim.NIL
2642          for i = 1, len do
2643            if res[i] == nil then
2644              res[i] = vim.NIL
2645            end
2646          end
2647          return res
2648        end
2649      end)
2650
2651      eq(
2652        { other },
2653        exec_lua(function()
2654          return test(function()
2655            return vim.api.nvim_get_current_buf()
2656          end)
2657        end)
2658      )
2659      eq(curbuf, api.nvim_get_current_buf())
2660      eq(
2661        { other, vim.NIL },
2662        exec_lua(function()
2663          return test(function()
2664            return vim.api.nvim_get_current_buf(), nil
2665          end)
2666        end)
2667      )
2668
2669      eq(
2670        { 6, 7 },
2671        exec_lua(function()
2672          return test(function()
2673            return 6, 7
2674          end)
2675        end)
2676      )
2677      eq(
2678        { 6, vim.NIL, 7 },
2679        exec_lua(function()
2680          return test(function()
2681            return 6, nil, 7
2682          end)
2683        end)
2684      )
2685      eq(
2686        {},
2687        exec_lua(function()
2688          return test(function() end)
2689        end)
2690      )
2691      eq(
2692        { vim.NIL },
2693        exec_lua(function()
2694          return test(function()
2695            return nil
2696          end)
2697        end)
2698      )
2699    end)
2700
2701    it('propagates return values when called from a coroutine #39834', function()
2702      local other = api.nvim_create_buf(false, true)
2703      eq(
2704        { other, vim.NIL, 42 },
2705        exec_lua(function()
2706          local out
2707          local co = coroutine.create(function()
2708            local function pack(...)
2709              local r = { ... }
2710              for i = 1, select('#', ...) do
2711                if r[i] == nil then
2712                  r[i] = vim.NIL
2713                end
2714              end
2715              return r
2716            end
2717            out = pack(vim.api.nvim_buf_call(other, function()
2718              return vim.api.nvim_get_current_buf(), nil, 42
2719            end))
2720          end)
2721          assert(coroutine.resume(co))
2722          return out
2723        end)
2724      )
2725    end)
2726
2727    it('can access buf options', function()
2728      local buf1 = api.nvim_get_current_buf()
2729      local buf2 = exec_lua [[
2730        buf2 = vim.api.nvim_create_buf(false, true)
2731        return buf2
2732      ]]
2733
2734      eq(false, api.nvim_get_option_value('autoindent', { buf = buf1 }))
2735      eq(false, api.nvim_get_option_value('autoindent', { buf = buf2 }))
2736
2737      local val = exec_lua [[
2738        return vim.api.nvim_buf_call(buf2, function()
2739          vim.cmd "set autoindent"
2740          return vim.api.nvim_get_current_buf()
2741        end)
2742      ]]
2743
2744      eq(false, api.nvim_get_option_value('autoindent', { buf = buf1 }))
2745      eq(true, api.nvim_get_option_value('autoindent', { buf = buf2 }))
2746      eq(buf1, api.nvim_get_current_buf())
2747      eq(buf2, val)
2748    end)
2749
2750    it('does not cause ml_get errors with invalid visual selection', function()
2751      -- Should be fixed by vim-patch:8.2.4028.
2752      exec_lua [[
2753        local api = vim.api
2754        local t = function(s) return api.nvim_replace_termcodes(s, true, true, true) end
2755        api.nvim_buf_set_lines(0, 0, -1, true, {"a", "b", "c"})
2756        api.nvim_feedkeys(t "G<C-V>", "txn", false)
2757        api.nvim_buf_call(api.nvim_create_buf(false, true), function() vim.cmd "redraw" end)
2758      ]]
2759    end)
2760
2761    it('can be nested crazily with hidden buffers', function()
2762      eq(
2763        true,
2764        exec_lua([[
2765        local function scratch_buf_call(fn)
2766          local buf = vim.api.nvim_create_buf(false, true)
2767          vim.api.nvim_set_option_value('cindent', true, {buf = buf})
2768          return vim.api.nvim_buf_call(buf, function()
2769            return vim.api.nvim_get_current_buf() == buf
2770              and vim.api.nvim_get_option_value('cindent', {buf = buf})
2771              and fn()
2772          end) and vim.api.nvim_buf_delete(buf, {}) == nil
2773        end
2774
2775        return scratch_buf_call(function()
2776          return scratch_buf_call(function()
2777            return scratch_buf_call(function()
2778              return scratch_buf_call(function()
2779                return scratch_buf_call(function()
2780                  return scratch_buf_call(function()
2781                    return scratch_buf_call(function()
2782                      return scratch_buf_call(function()
2783                        return scratch_buf_call(function()
2784                          return scratch_buf_call(function()
2785                            return scratch_buf_call(function()
2786                              return scratch_buf_call(function()
2787                                return true
2788                              end)
2789                            end)
2790                          end)
2791                        end)
2792                      end)
2793                    end)
2794                  end)
2795                end)
2796              end)
2797            end)
2798          end)
2799        end)
2800      ]])
2801      )
2802    end)
2803
2804    it('can return values by reference', function()
2805      eq(
2806        { 4, 7 },
2807        exec_lua [[
2808        local val = {4, 10}
2809        local ref = vim.api.nvim_buf_call(0, function() return val end)
2810        ref[2] = 7
2811        return val
2812      ]]
2813      )
2814    end)
2815
2816    it('can get Visual selection in current buffer #34162', function()
2817      insert('foo bar baz')
2818      feed('gg0fbvtb')
2819      local text = exec_lua([[
2820        return vim.api.nvim_buf_call(0, function()
2821          return vim.fn.getregion(vim.fn.getpos('.'), vim.fn.getpos('v'))
2822        end)
2823      ]])
2824      eq({ 'bar ' }, text)
2825    end)
2826  end)
2827end)
2828
2829describe('path sep in ffname/sfname #39382,', function()
2830  if not t.is_os('win') then
2831    return
2832  end
2833
2834  local cwd, files = vim.uv.cwd(), {}
2835  local expected_cwd = vim.fs.normalize(cwd)
2836  for i = 1, 3 do
2837    files[i] = ([[%s\Xtest\file%s]]):format(cwd, i)
2838  end
2839
2840  local sfname_eq = function(expected, nr)
2841    command(('buffer %s'):format(nr or ''))
2842    eq(expected, api.nvim_eval_statusline('%f', {}).str)
2843  end
2844
2845  setup(function()
2846    t.mkdir('Xtest')
2847  end)
2848
2849  teardown(function()
2850    n.rmdir('Xtest')
2851  end)
2852
2853  before_each(function()
2854    clear()
2855  end)
2856
2857  it('normalizes startup file arguments', function()
2858    clear { args = files }
2859    for i = 1, 3 do
2860      eq(('%s/Xtest/file%s'):format(expected_cwd, i), api.nvim_buf_get_name(i))
2861      sfname_eq(('Xtest/file%s'):format(i), i)
2862    end
2863  end)
2864
2865  it('normalizes :next arguments (FILES flag)', function()
2866    command(('next %s'):format(table.concat(files, ' ')))
2867    for i = 1, 3 do
2868      eq(('%s/Xtest/file%s'):format(expected_cwd, i), api.nvim_buf_get_name(i))
2869      sfname_eq(('%s/Xtest/file%s'):format(expected_cwd, i), i)
2870    end
2871  end)
2872
2873  it('normalizes :edit arguments (FILE1 flag)', function()
2874    -- tilde prefix
2875    command([[edit ~\foo\bar]])
2876    eq(('%s/foo/bar'):format(fn.getenv('HOME')), api.nvim_buf_get_name(0))
2877    sfname_eq('~/foo/bar')
2878
2879    -- absolute path
2880    command(('edit %s'):format(files[1]))
2881    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(0))
2882    sfname_eq(('%s/Xtest/file1'):format(expected_cwd))
2883  end)
2884
2885  it('normalizes bufadd() arguments', function()
2886    local n = fn.bufadd(files[1])
2887    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(n))
2888    sfname_eq(('%s/Xtest/file1'):format(expected_cwd), n)
2889  end)
2890
2891  it('normalizes bufnr() arguments', function()
2892    local n = fn.bufnr(files[1], 1)
2893    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(n))
2894    sfname_eq(('%s/Xtest/file1'):format(expected_cwd), n)
2895  end)
2896
2897  it('normalizes temp paths, <afile> and <amatch> for :diffpatch', function()
2898    t.write_file('Xtest/patch', [[diff file]])
2899    t.write_file('Xtest/test.txt', [[input file]])
2900    command('edit Xtest/test.txt')
2901    exec([[
2902      fun MyPatch()
2903        call writefile(['output file'], v:fname_out)
2904      endfunc
2905      set patchexpr=MyPatch()
2906    ]])
2907    exec_lua([[
2908      vim.api.nvim_create_autocmd('BufAdd', {
2909        pattern = '*',
2910        callback = function(ev)
2911          vim.g.test_file = ev.file
2912          vim.g.test_match = ev.match
2913        end
2914      })
2915    ]])
2916    command('diffpatch Xtest/patch')
2917    eq(('%s/Xtest/test.txt.new'):format(expected_cwd), api.nvim_buf_get_name(0))
2918    sfname_eq('Xtest/test.txt.new')
2919    local tmp = fn.getenv('TMPDIR')
2920    local afile = fn.eval('g:test_file') ---@type string
2921    local amatch = fn.eval('g:test_match') ---@type string
2922    t.matches(tmp, afile, true)
2923    t.not_matches('\\', afile, true)
2924    t.matches(tmp, amatch, true)
2925    t.not_matches('\\', amatch, true)
2926  end)
2927
2928  it('normalizes :find results', function()
2929    t.write_file('Xtest/file1', '')
2930    command([[find Xtest\file1]])
2931    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(0))
2932    sfname_eq('Xtest/file1')
2933
2934    -- 'findfunc'
2935    exec(([[
2936      func FindFile(cmdarg, cmdcomplete)
2937        return  ['%s']
2938      endfunc
2939      set findfunc=FindFile
2940    ]]):format(files[2]))
2941    command([[find file2]])
2942    eq(('%s/Xtest/file2'):format(expected_cwd), api.nvim_buf_get_name(0))
2943    sfname_eq(('%s/Xtest/file2'):format(expected_cwd))
2944  end)
2945
2946  it('normalizes :scriptnames arguments', function()
2947    command(('scriptnames %s'):format(files[1]))
2948    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(0))
2949    sfname_eq(('%s/Xtest/file1'):format(expected_cwd))
2950  end)
2951
2952  it('normalizes gf targets', function()
2953    t.write_file('Xtest/file1', '')
2954    feed(('i%s<Esc>0gf'):format(files[1]))
2955    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(0))
2956    sfname_eq(('%s/Xtest/file1'):format(expected_cwd))
2957    command('bw')
2958    feed('<C-W>f')
2959    eq(('%s/Xtest/file1'):format(expected_cwd), api.nvim_buf_get_name(0))
2960    sfname_eq(('%s/Xtest/file1'):format(expected_cwd))
2961  end)
2962
2963  it('normalizes macro definition targets and completions', function()
2964    t.mkdir('Xtest/sub')
2965    t.write_file(
2966      'Xtest/sub/bar.h',
2967      [[
2968      #define MIN 0;
2969      #define MAX 10;
2970    ]]
2971    )
2972    t.write_file(
2973      'Xtest/foo.c',
2974      [[
2975      #include "sub\bar.h";
2976      void main() {
2977        int i = MIN;
2978      }
2979    ]]
2980    )
2981    local screen = Screen.new(30, 10)
2982    command([[set include=^\\s*#\\s*include]])
2983    command([[set define=^\\s*#\\s*define]])
2984    command('e Xtest/foo.c')
2985    command('djump MIN')
2986    eq(('%s/Xtest/sub/bar.h'):format(expected_cwd), api.nvim_buf_get_name(0))
2987    sfname_eq('Xtest/sub/bar.h')
2988    command('bw')
2989    feed('/MIN<CR>lxxi<C-x><C-d>')
2990    screen:expect({
2991      any = {
2992        'MIN Xtest/sub/bar.h',
2993        'MAX Xtest/sub/bar.h',
2994      },
2995    })
2996  end)
2997
2998  it('normalizes tag targets', function()
2999    t.write_file(
3000      'Xtest/tags',
3001      [[
3002      main	.\\foo.c	/^void main() /;"	f	typeref:typename:void
3003      main2	$DIR\foo.c	/^void main2() /;"	f	typeref:typename:void
3004      main3	./foo.c	/^void main3() /;"	f	typeref:typename:void
3005    ]]
3006    )
3007    t.write_file(
3008      'Xtest/foo.c',
3009      [[
3010      void main() {}
3011      void main2() {};
3012      void main3() {};
3013    ]]
3014    )
3015
3016    command('cd Xtest')
3017    command('tjump main')
3018    eq(('%s/Xtest/foo.c'):format(expected_cwd), api.nvim_buf_get_name(0))
3019    sfname_eq('.//foo.c')
3020
3021    command('bw')
3022    fn.setenv('DIR', ([[%s\Xtest]]):format(cwd))
3023    command('tjump main2')
3024    eq(('%s/Xtest/foo.c'):format(expected_cwd), api.nvim_buf_get_name(0))
3025    sfname_eq(('%s/Xtest/foo.c'):format(expected_cwd))
3026
3027    command('bw')
3028    command('tjump main3')
3029    eq(('%s/Xtest/foo.c'):format(expected_cwd), api.nvim_buf_get_name(0))
3030    sfname_eq('./foo.c')
3031  end)
3032
3033  it('normalizes quickfix targets', function()
3034    t.write_file(
3035      'Xtest/error',
3036      [[
3037      foo.c
3038      .\Xtest\foo.c(3): error C2143: syntax error: missing ';' before 'return'
3039    ]]
3040    )
3041    local screen = Screen.new(40, 10)
3042    command('cg Xtest/error')
3043    command('copen')
3044    screen:expect({
3045      any = './Xtest/foo.c',
3046    })
3047    feed('<CR>')
3048    eq(('%s/Xtest/foo.c'):format(expected_cwd), api.nvim_buf_get_name(0))
3049    sfname_eq('./Xtest/foo.c')
3050  end)
3051
3052  it('preserves backslashes in URIs', function()
3053    local exe_path = fn.exepath('cmd')
3054    t.not_matches('/', exe_path, true)
3055    command(('e term://%s'):format(exe_path))
3056    t.matches(exe_path, api.nvim_buf_get_name(0), true)
3057    t.matches(exe_path, api.nvim_eval_statusline('%f', {}).str, true)
3058  end)
3059end)