robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
57.8 KiB1859 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, pending = t.describe, t.it, t.before_each, t.pending
6local fn = n.fn
7local api = n.api
8local command = n.command
9local eq = t.eq
10local exec_lua = n.exec_lua
11local exec_capture = n.exec_capture
12local matches = t.matches
13local pcall_err = t.pcall_err
14
15describe('vim._with', function()
16  before_each(function()
17    n.clear()
18    exec_lua([[
19      _G.fn = vim.fn
20      _G.api = vim.api
21
22      _G.setup_buffers = function()
23        return api.nvim_create_buf(false, true), api.nvim_get_current_buf()
24      end
25
26      _G.setup_windows = function()
27        local other_win = api.nvim_get_current_win()
28        vim.cmd.new()
29        return other_win, api.nvim_get_current_win()
30      end
31    ]])
32  end)
33
34  local assert_events_trigger = function()
35    local out = exec_lua [[
36      -- Needs three global values defined:
37      -- - `test_events` - array of events which are tested.
38      -- - `test_context` - context to be tested.
39      -- - `test_trig_event` - callable triggering at least one tested event.
40      _G.n_events = 0
41      local opts = { callback = function() _G.n_events = _G.n_events + 1 end }
42      api.nvim_create_autocmd(_G.test_events, opts)
43
44      local context = { bo = { commentstring = '-- %s' } }
45
46      -- Should not trigger events on its own
47      vim._with(_G.test_context, function() end)
48      local is_no_events = _G.n_events == 0
49
50      -- Should trigger events if specifically asked inside callback
51      local is_events = vim._with(_G.test_context, function()
52        _G.test_trig_event()
53        return _G.n_events > 0
54      end)
55      return { is_no_events, is_events }
56    ]]
57    eq({ true, true }, out)
58  end
59
60  describe('`bo` context', function()
61    before_each(function()
62      exec_lua [[
63        _G.other_buf, _G.cur_buf = setup_buffers()
64
65        -- 'commentstring' is local to buffer and string
66        vim.bo[other_buf].commentstring = '## %s'
67        vim.bo[cur_buf].commentstring = '// %s'
68        vim.go.commentstring = '$$ %s'
69
70        -- 'undolevels' is global or local to buffer (global-local) and number
71        vim.bo[other_buf].undolevels = 100
72        vim.bo[cur_buf].undolevels = 250
73        vim.go.undolevels = 500
74
75        -- 'autoread' is global or local to buffer (global-local) and boolean
76        vim.bo[other_buf].autoread = false
77        vim.bo[cur_buf].autoread = false
78        vim.go.autoread = true
79
80        _G.get_state = function()
81          return {
82            bo = {
83              cms_cur = vim.bo[cur_buf].commentstring,
84              cms_other = vim.bo[other_buf].commentstring,
85              ul_cur = vim.bo[cur_buf].undolevels,
86              ul_other = vim.bo[other_buf].undolevels,
87              ar_cur = vim.bo[cur_buf].autoread,
88              ar_other = vim.bo[other_buf].autoread,
89            },
90            go = {
91              cms = vim.go.commentstring,
92              ul = vim.go.undolevels,
93              ar = vim.go.autoread,
94            },
95          }
96        end
97      ]]
98    end)
99
100    it('works', function()
101      local out = exec_lua [[
102        local context = { bo = { commentstring = '-- %s', undolevels = 0, autoread = true } }
103
104        local before = get_state()
105        local inner = vim._with(context, function()
106          assert(api.nvim_get_current_buf() == cur_buf)
107          return get_state()
108        end)
109
110        return { before = before, inner = inner, after = get_state() }
111      ]]
112
113      eq({
114        bo = {
115          cms_cur = '-- %s',
116          cms_other = '## %s',
117          ul_cur = 0,
118          ul_other = 100,
119          ar_cur = true,
120          ar_other = false,
121        },
122        go = { cms = '$$ %s', ul = 500, ar = true },
123      }, out.inner)
124      eq(out.before, out.after)
125    end)
126
127    it('sets options in `buf` context', function()
128      local out = exec_lua [[
129        local context = { buf = other_buf, bo = { commentstring = '-- %s', undolevels = 0, autoread = true } }
130
131        local before = get_state()
132        local inner = vim._with(context, function()
133          assert(api.nvim_get_current_buf() == other_buf)
134          return get_state()
135        end)
136
137        return { before = before, inner = inner, after = get_state() }
138      ]]
139
140      eq({
141        bo = {
142          cms_cur = '// %s',
143          cms_other = '-- %s',
144          ul_cur = 250,
145          ul_other = 0,
146          ar_cur = false,
147          ar_other = true,
148        },
149        go = { cms = '$$ %s', ul = 500, ar = true },
150      }, out.inner)
151      eq(out.before, out.after)
152    end)
153
154    it('restores only options from context', function()
155      local out = exec_lua [[
156        local context = { bo = { commentstring = '-- %s' } }
157
158        local inner = vim._with(context, function()
159          assert(api.nvim_get_current_buf() == cur_buf)
160          vim.bo[cur_buf].undolevels = 750
161          vim.bo[cur_buf].commentstring = '!! %s'
162          return get_state()
163        end)
164
165        return { inner = inner, after = get_state() }
166      ]]
167
168      eq({
169        bo = {
170          cms_cur = '!! %s',
171          cms_other = '## %s',
172          ul_cur = 750,
173          ul_other = 100,
174          ar_cur = false,
175          ar_other = false,
176        },
177        go = { cms = '$$ %s', ul = 500, ar = true },
178      }, out.inner)
179      eq({
180        bo = {
181          cms_cur = '// %s',
182          cms_other = '## %s',
183          ul_cur = 750,
184          ul_other = 100,
185          ar_cur = false,
186          ar_other = false,
187        },
188        go = { cms = '$$ %s', ul = 500, ar = true },
189      }, out.after)
190    end)
191
192    it('does not trigger events', function()
193      exec_lua [[
194        _G.test_events = { 'BufEnter', 'BufLeave', 'BufWinEnter', 'BufWinLeave' }
195        _G.test_context = { bo = { commentstring = '-- %s' } }
196        _G.test_trig_event = function() vim.cmd.new() end
197      ]]
198      assert_events_trigger()
199    end)
200
201    it('can be nested', function()
202      local out = exec_lua [[
203        local before, before_inner, after_inner = get_state(), nil, nil
204        vim._with({ bo = { commentstring = '-- %s', undolevels = 0, autoread = true } }, function()
205          before_inner = get_state()
206          inner = vim._with({ bo = { commentstring = '!! %s', autoread = false } }, get_state)
207          after_inner = get_state()
208        end)
209        return {
210          before = before, before_inner = before_inner,
211          inner = inner,
212          after_inner = after_inner, after = get_state(),
213        }
214      ]]
215      eq('!! %s', out.inner.bo.cms_cur)
216      eq(0, out.inner.bo.ul_cur)
217      eq(false, out.inner.bo.ar_cur)
218      eq(out.before_inner, out.after_inner)
219      eq(out.before, out.after)
220    end)
221  end)
222
223  describe('`buf` context', function()
224    it('works', function()
225      local out = exec_lua [[
226        local other_buf, cur_buf = setup_buffers()
227        local inner = vim._with({ buf = other_buf }, function()
228          return api.nvim_get_current_buf()
229        end)
230        return { inner == other_buf, api.nvim_get_current_buf() == cur_buf }
231      ]]
232      eq({ true, true }, out)
233    end)
234
235    it('does not trigger events', function()
236      exec_lua [[
237        _G.test_events = { 'BufEnter', 'BufLeave', 'BufWinEnter', 'BufWinLeave' }
238        _G.test_context = { buf = other_buf }
239        _G.test_trig_event = function() vim.cmd.new() end
240      ]]
241      assert_events_trigger()
242    end)
243
244    it('can access buffer options', function()
245      local out = exec_lua [[
246        other_buf, cur_buf = setup_buffers()
247        vim.bo[other_buf].commentstring = '## %s'
248        vim.bo[cur_buf].commentstring = '// %s'
249
250        vim._with({ buf = other_buf }, function()
251          vim.cmd.set('commentstring=--\\ %s')
252        end)
253
254        return vim.bo[other_buf].commentstring == '-- %s' and
255          vim.bo[cur_buf].commentstring == '// %s'
256      ]]
257      eq(true, out)
258    end)
259
260    it('works with different kinds of buffers', function()
261      exec_lua [[
262        local assert_buf = function(buf)
263          vim._with({ buf = buf }, function()
264            assert(api.nvim_get_current_buf() == buf)
265          end)
266        end
267
268        -- Current
269        assert_buf(api.nvim_get_current_buf())
270
271        local buf = api.nvim_get_current_buf()
272        vim._with({ buf = 0 }, function()
273          assert(api.nvim_get_current_buf() == buf)
274        end)
275        assert(api.nvim_get_current_buf() == buf)
276
277        -- Hidden listed
278        local listed = api.nvim_create_buf(true, true)
279        assert_buf(listed)
280
281        -- Visible
282        local other_win, cur_win = setup_windows()
283        api.nvim_win_set_buf(other_win, listed)
284        assert_buf(listed)
285
286        -- Shown but not visible
287        vim.cmd.tabnew()
288        assert_buf(listed)
289
290        -- Shown in several windows
291        api.nvim_win_set_buf(0, listed)
292        assert_buf(listed)
293
294        -- Shown in floating window
295        local float_buf = api.nvim_create_buf(false, true)
296        local config = { relative = 'editor', row = 1, col = 1, width = 5, height = 5 }
297        api.nvim_open_win(float_buf, false, config)
298        assert_buf(float_buf)
299      ]]
300    end)
301
302    it('does not cause ml_get errors with invalid visual selection', function()
303      exec_lua [[
304        api.nvim_buf_set_lines(0, 0, -1, true, { 'a', 'b', 'c' })
305        api.nvim_feedkeys(vim.keycode('G<C-V>'), 'txn', false)
306        local other_buf, _ = setup_buffers()
307        vim._with({ buf = buf }, function() vim.cmd.redraw() end)
308      ]]
309    end)
310
311    it('can be nested', function()
312      exec_lua [[
313        local other_buf, cur_buf = setup_buffers()
314        vim._with({ buf = other_buf }, function()
315          assert(api.nvim_get_current_buf() == other_buf)
316          inner = vim._with({ buf = cur_buf }, function()
317            assert(api.nvim_get_current_buf() == cur_buf)
318          end)
319          assert(api.nvim_get_current_buf() == other_buf)
320        end)
321        assert(api.nvim_get_current_buf() == cur_buf)
322      ]]
323    end)
324
325    it('can be nested crazily with hidden buffers', function()
326      local out = exec_lua([[
327        local n = 0
328        local function with_recursive_nested_bufs()
329          n = n + 1
330          if n > 20 then return true end
331
332          local other_buf, _ = setup_buffers()
333          vim.bo[other_buf].commentstring = '## %s'
334          local callback = function()
335            return api.nvim_get_current_buf() == other_buf
336              and vim.bo[other_buf].commentstring == '## %s'
337              and with_recursive_nested_bufs()
338          end
339          return vim._with({ buf = other_buf }, callback) and
340            api.nvim_buf_delete(other_buf, {}) == nil
341        end
342
343        return with_recursive_nested_bufs()
344      ]])
345      eq(true, out)
346    end)
347
348    it('keeps ":bcd" on the target buffer', function()
349      local out = exec_lua [[
350        local other_buf, cur_buf = setup_buffers()
351        local err_buf = api.nvim_create_buf(false, true)
352        local cwd = fn.getcwd()
353        local dir = vim.fs.joinpath(cwd, 'test')
354        vim._with({ buf = other_buf }, function() vim.cmd.bcd(dir) end)
355        pcall(vim._with, { buf = err_buf }, function()
356          vim.cmd.bcd(dir)
357          error('oops')
358        end)
359        return {
360          fn.haslocaldir(-1, -1, other_buf),
361          fn.haslocaldir(-1, -1, err_buf),
362          fn.haslocaldir(-1, -1, cur_buf),
363          fn.getcwd() == cwd,  -- Caller's CWD is unaffected: the target is not current.
364        }
365      ]]
366      eq({ 1, 1, 0, true }, out)
367    end)
368  end)
369
370  describe('`cwd` context', function()
371    it('works', function()
372      local out = exec_lua [[
373        local cwd = vim.uv.cwd()
374        local temp_cwd = vim.fs.joinpath(cwd, 'test')
375        local test_cwd
376        vim._with({ cwd = temp_cwd }, function() test_cwd = vim.uv.cwd() end)
377        -- Use `fs_realpath` to resolve symlinks from how tests are set up
378        return { vim.uv.cwd() == cwd, vim.uv.fs_realpath(test_cwd) == vim.uv.fs_realpath(temp_cwd) }
379      ]]
380      eq({ true, true }, out)
381    end)
382
383    it('can be nested', function()
384      local out = exec_lua [[
385        local cwd = vim.uv.cwd()
386        local temp_cwd = vim.fs.joinpath(cwd, 'test')
387        local temp_cwd2 = vim.fs.joinpath(cwd, 'src')
388        local test_cwd_before, test_cwd, test_cwd_after
389        vim._with({ cwd = temp_cwd }, function()
390          test_cwd_before = vim.uv.cwd()
391          vim._with({ cwd = temp_cwd2 }, function()
392            test_cwd = vim.uv.cwd()
393          end)
394          test_cwd_after = vim.uv.cwd()
395        end)
396        return {
397          vim.uv.cwd() == cwd,
398          vim.uv.fs_realpath(test_cwd_before) == vim.uv.fs_realpath(temp_cwd),
399          vim.uv.fs_realpath(test_cwd) == vim.uv.fs_realpath(temp_cwd2),
400          vim.uv.fs_realpath(test_cwd_after) == vim.uv.fs_realpath(temp_cwd),
401        }
402      ]]
403      eq({ true, true, true, true }, out)
404    end)
405
406    it('does not modify global CWD', function()
407      local out = exec_lua [[
408        local other_buf, _ = setup_buffers()
409        local cwd = fn.getcwd()
410        -- Activate a window-local dir, so that the global dir must be remembered.
411        vim.cmd.lcd(vim.fs.joinpath(cwd, 'test'))
412        local lcd_cwd = fn.getcwd() -- Not necessarily `cwd .. '/test'`: symlinks are resolved.
413        vim._with({ buf = other_buf, cwd = vim.fs.joinpath(cwd, 'src') }, function() end)
414        return { fn.getcwd() == lcd_cwd, fn.getcwd(-1, -1) == cwd }
415      ]]
416      eq({ true, true }, out)
417    end)
418  end)
419
420  describe('`keepcwd` context', function()
421    it('undoes chdir at every scope', function()
422      local out = exec_lua [[
423        local cwd = fn.getcwd()
424        local dir = vim.fs.joinpath(cwd, 'test')
425        vim._with({ keepcwd = true }, function()
426          vim.cmd.cd(dir)
427          vim.cmd.tcd(dir)
428          vim.cmd.bcd(dir)
429          vim.cmd.lcd(dir)
430        end)
431        return {
432          fn.haslocaldir(),          -- window
433          fn.haslocaldir(-1, 0),     -- tabpage
434          fn.haslocaldir(-1, -1, 0), -- buffer
435          fn.getcwd() == cwd,
436          fn.getcwd(-1, -1) == cwd,  -- global
437        }
438      ]]
439      eq({ 0, 0, 0, true, true }, out)
440    end)
441
442    it('discards ":bcd"/":lcd" that a `buf`/`win` context would keep', function()
443      local out = exec_lua [[
444        local other_buf, _ = setup_buffers()
445        local other_win, _ = setup_windows()
446        local cwd = fn.getcwd()
447        local dir = vim.fs.joinpath(cwd, 'test')
448        vim._with({ buf = other_buf, keepcwd = true }, function() vim.cmd.bcd(dir) end)
449        vim._with({ win = other_win, keepcwd = true }, function() vim.cmd.lcd(dir) end)
450        return {
451          fn.haslocaldir(-1, -1, other_buf),
452          fn.haslocaldir(fn.win_id2win(other_win)),
453          fn.getcwd() == cwd,
454        }
455      ]]
456      eq({ 0, 0, true }, out)
457    end)
458
459    it('restores nothing else: the callback may switch window', function()
460      local out = exec_lua [[
461        local other_win, _ = setup_windows()
462        vim._with({ keepcwd = true }, function() api.nvim_set_current_win(other_win) end)
463        return api.nvim_get_current_win() == other_win
464      ]]
465      eq(true, out)
466    end)
467  end)
468
469  describe('`emsg_silent` context', function()
470    pending('works', function()
471      local ok = pcall(
472        exec_lua,
473        [[
474          _G.f = function()
475            error('This error should not interfere with execution', 0)
476          end
477          -- Should not produce error same as `vim.cmd('silent! lua _G.f()')`
478          vim._with({ emsg_silent = true }, f)
479        ]]
480      )
481      eq(true, ok)
482
483      -- Should properly report errors afterwards
484      ok = pcall(exec_lua, 'lua _G.f()')
485      eq(false, ok)
486    end)
487
488    it('can be nested', function()
489      local ok = pcall(
490        exec_lua,
491        [[
492          _G.f = function()
493            error('This error should not interfere with execution', 0)
494          end
495          -- Should produce error same as `_G.f()`
496          vim._with({ emsg_silent = true }, function()
497            vim._with( { emsg_silent = false }, f)
498          end)
499        ]]
500      )
501      eq(false, ok)
502    end)
503  end)
504
505  describe('`env` context', function()
506    before_each(function()
507      exec_lua [[
508        vim.fn.setenv('aaa', 'hello')
509        _G.get_state = function()
510          return { aaa = vim.fn.getenv('aaa'), bbb = vim.fn.getenv('bbb') }
511        end
512      ]]
513    end)
514
515    it('works', function()
516      local out = exec_lua [[
517        local context = { env = { aaa = 'inside', bbb = 'wow' } }
518        local before = get_state()
519        local inner = vim._with(context, get_state)
520        return { before = before, inner = inner, after = get_state() }
521      ]]
522
523      eq({ aaa = 'inside', bbb = 'wow' }, out.inner)
524      eq(out.before, out.after)
525    end)
526
527    it('restores only variables from context', function()
528      local out = exec_lua [[
529        local context = { env = { bbb = 'wow' } }
530        local before = get_state()
531        local inner = vim._with(context, function()
532          vim.env.aaa = 'inside'
533          return get_state()
534        end)
535        return { before = before, inner = inner, after = get_state() }
536      ]]
537
538      eq({ aaa = 'inside', bbb = 'wow' }, out.inner)
539      eq({ aaa = 'inside', bbb = vim.NIL }, out.after)
540    end)
541
542    it('can be nested', function()
543      local out = exec_lua [[
544        local before, before_inner, after_inner = get_state(), nil, nil
545        vim._with({ env = { aaa = 'inside', bbb = 'wow' } }, function()
546          before_inner = get_state()
547          inner = vim._with({ env = { aaa = 'more inside' } }, get_state)
548          after_inner = get_state()
549        end)
550        return {
551          before = before, before_inner = before_inner,
552          inner = inner,
553          after_inner = after_inner, after = get_state(),
554        }
555      ]]
556      eq('more inside', out.inner.aaa)
557      eq('wow', out.inner.bbb)
558      eq(out.before_inner, out.after_inner)
559      eq(out.before, out.after)
560    end)
561  end)
562
563  describe('`go` context', function()
564    before_each(function()
565      exec_lua [[
566        vim.bo.commentstring = '## %s'
567        vim.go.commentstring = '$$ %s'
568        vim.wo.winblend = 25
569        vim.go.winblend = 50
570        vim.go.langmap = 'xy,yx'
571        vim.go.confirm = false
572
573        _G.get_state = function()
574          return {
575            bo = { cms = vim.bo.commentstring },
576            wo = { winbl = vim.wo.winblend },
577            go = {
578              cms = vim.go.commentstring,
579              winbl = vim.go.winblend,
580              lmap = vim.go.langmap,
581              cf = vim.go.confirm,
582            },
583          }
584        end
585      ]]
586    end)
587
588    it('works', function()
589      local out = exec_lua [[
590        local context = {
591          go = { commentstring = '-- %s', winblend = 75, langmap = 'ab,ba', cf = true },
592        }
593        local before = get_state()
594        local inner = vim._with(context, get_state)
595        return { before = before, inner = inner, after = get_state() }
596      ]]
597
598      eq({
599        bo = { cms = '## %s' },
600        wo = { winbl = 25 },
601        go = { cms = '-- %s', winbl = 75, lmap = 'ab,ba', cf = true },
602      }, out.inner)
603      eq(out.before, out.after)
604    end)
605
606    it('works with `eventignore`', function()
607      -- This might be an issue if saving and restoring option context is done
608      -- to account for triggering `OptionSet`, but in not a good way
609      local out = exec_lua [[
610        vim.go.eventignore = 'ModeChanged'
611        local inner = vim._with({ go = { eventignore = 'CursorMoved' } }, function()
612          return vim.go.eventignore
613        end)
614        return { inner = inner, after = vim.go.eventignore }
615      ]]
616      eq({ inner = 'CursorMoved', after = 'ModeChanged' }, out)
617    end)
618
619    it('restores only options from context', function()
620      local out = exec_lua [[
621        local context = { go = { langmap = 'ab,ba' } }
622
623        local inner = vim._with(context, function()
624          vim.go.commentstring = '!! %s'
625          vim.go.winblend = 75
626          vim.go.langmap = 'uv,vu'
627          return get_state()
628        end)
629
630        return { inner = inner, after = get_state() }
631      ]]
632
633      eq({
634        bo = { cms = '## %s' },
635        wo = { winbl = 25 },
636        go = { cms = '!! %s', winbl = 75, lmap = 'uv,vu', cf = false },
637      }, out.inner)
638      eq({
639        bo = { cms = '## %s' },
640        wo = { winbl = 25 },
641        go = { cms = '!! %s', winbl = 75, lmap = 'xy,yx', cf = false },
642      }, out.after)
643    end)
644
645    it('does not trigger events', function()
646      exec_lua [[
647        _G.test_events = {
648          'BufEnter', 'BufLeave', 'BufWinEnter', 'BufWinLeave', 'WinEnter', 'WinLeave'
649        }
650        _G.test_context = { go = { commentstring = '-- %s', winblend = 75, langmap = 'ab,ba' } }
651        _G.test_trig_event = function() vim.cmd.new() end
652      ]]
653      assert_events_trigger()
654    end)
655
656    it('can be nested', function()
657      local out = exec_lua [[
658        local before, before_inner, after_inner = get_state(), nil, nil
659        vim._with({ go = { langmap = 'ab,ba', commentstring = '-- %s' } }, function()
660          before_inner = get_state()
661          inner = vim._with({ go = { langmap = 'uv,vu' } }, get_state)
662          after_inner = get_state()
663        end)
664        return {
665          before = before, before_inner = before_inner,
666          inner = inner,
667          after_inner = after_inner, after = get_state(),
668        }
669      ]]
670      eq('uv,vu', out.inner.go.lmap)
671      eq('-- %s', out.inner.go.cms)
672      eq(out.before_inner, out.after_inner)
673      eq(out.before, out.after)
674    end)
675  end)
676
677  describe('`hide` context', function()
678    pending('works', function()
679      local ok = pcall(
680        exec_lua,
681        [[
682          vim.o.hidden = false
683          vim.bo.modified = true
684          local init_buf = api.nvim_get_current_buf()
685          -- Should not produce error same as `vim.cmd('hide enew')`
686          vim._with({ hide = true }, function()
687            vim.cmd.enew()
688          end)
689          assert(api.nvim_get_current_buf() ~= init_buf)
690        ]]
691      )
692      eq(true, ok)
693    end)
694
695    it('can be nested', function()
696      local ok = pcall(
697        exec_lua,
698        [[
699          vim.o.hidden = false
700          vim.bo.modified = true
701          -- Should produce error same as `vim.cmd.enew()`
702          vim._with({ hide = true }, function()
703            vim._with({ hide = false }, function()
704              vim.cmd.enew()
705            end)
706          end)
707        ]]
708      )
709      eq(false, ok)
710    end)
711  end)
712
713  describe('`horizontal` context', function()
714    local is_approx_eq = function(dim, id_1, id_2)
715      local f = dim == 'height' and api.nvim_win_get_height or api.nvim_win_get_width
716      return math.abs(f(id_1) - f(id_2)) <= 1
717    end
718
719    local win_id_1, win_id_2, win_id_3
720    before_each(function()
721      win_id_1 = api.nvim_get_current_win()
722      command('wincmd v | wincmd 5>')
723      win_id_2 = api.nvim_get_current_win()
724      command('wincmd s | wincmd 5+')
725      win_id_3 = api.nvim_get_current_win()
726
727      eq(false, is_approx_eq('width', win_id_1, win_id_2))
728      eq(false, is_approx_eq('height', win_id_3, win_id_2))
729    end)
730
731    pending('works', function()
732      exec_lua [[
733        -- Should be same as `vim.cmd('horizontal wincmd =')`
734        vim._with({ horizontal = true }, function()
735          vim.cmd.wincmd('=')
736        end)
737      ]]
738      eq(true, is_approx_eq('width', win_id_1, win_id_2))
739      eq(false, is_approx_eq('height', win_id_3, win_id_2))
740    end)
741
742    pending('can be nested', function()
743      exec_lua [[
744        -- Should be same as `vim.cmd.wincmd('=')`
745        vim._with({ horizontal = true }, function()
746          vim._with({ horizontal = false }, function()
747            vim.cmd.wincmd('=')
748          end)
749        end)
750      ]]
751      eq(true, is_approx_eq('width', win_id_1, win_id_2))
752      eq(true, is_approx_eq('height', win_id_3, win_id_2))
753    end)
754  end)
755
756  describe('`keepalt` context', function()
757    pending('works', function()
758      local out = exec_lua [[
759        vim.cmd('edit alt')
760        vim.cmd('edit new')
761        assert(fn.bufname('#') == 'alt')
762
763        -- Should work as `vim.cmd('keepalt edit very-new')`
764        vim._with({ keepalt = true }, function()
765          vim.cmd.edit('very-new')
766        end)
767        return fn.bufname('#') == 'alt'
768      ]]
769      eq(true, out)
770    end)
771
772    it('can be nested', function()
773      local out = exec_lua [[
774        vim.cmd('edit alt')
775        vim.cmd('edit new')
776        assert(fn.bufname('#') == 'alt')
777
778        -- Should work as `vim.cmd.edit('very-new')`
779        vim._with({ keepalt = true }, function()
780          vim._with({ keepalt = false }, function()
781            vim.cmd.edit('very-new')
782          end)
783        end)
784        return fn.bufname('#') == 'alt'
785      ]]
786      eq(false, out)
787    end)
788  end)
789
790  describe('`keepjumps` context', function()
791    pending('works', function()
792      local out = exec_lua [[
793        api.nvim_buf_set_lines(0, 0, -1, false, { 'aaa', 'bbb', 'ccc' })
794        local jumplist_before = fn.getjumplist()
795        -- Should work as `vim.cmd('keepjumps normal! Ggg')`
796        vim._with({ keepjumps = true }, function()
797          vim.cmd('normal! Ggg')
798        end)
799        return vim.deep_equal(jumplist_before, fn.getjumplist())
800      ]]
801      eq(true, out)
802    end)
803
804    it('can be nested', function()
805      local out = exec_lua [[
806        api.nvim_buf_set_lines(0, 0, -1, false, { 'aaa', 'bbb', 'ccc' })
807        local jumplist_before = fn.getjumplist()
808        vim._with({ keepjumps = true }, function()
809          vim._with({ keepjumps = false }, function()
810            vim.cmd('normal! Ggg')
811          end)
812        end)
813        return vim.deep_equal(jumplist_before, fn.getjumplist())
814      ]]
815      eq(false, out)
816    end)
817  end)
818
819  describe('`keepmarks` context', function()
820    pending('works', function()
821      local out = exec_lua [[
822        vim.cmd('set cpoptions+=R')
823        api.nvim_buf_set_lines(0, 0, -1, false, { 'bbb', 'ccc', 'aaa' })
824        api.nvim_buf_set_mark(0, 'm', 2, 2, {})
825
826        -- Should be the same as `vim.cmd('keepmarks %!sort')`
827        vim._with({ keepmarks = true }, function()
828          vim.cmd('%!sort')
829        end)
830        return api.nvim_buf_get_mark(0, 'm')
831      ]]
832      eq({ 2, 2 }, out)
833    end)
834
835    it('can be nested', function()
836      local out = exec_lua [[
837        vim.cmd('set cpoptions+=R')
838        api.nvim_buf_set_lines(0, 0, -1, false, { 'bbb', 'ccc', 'aaa' })
839        api.nvim_buf_set_mark(0, 'm', 2, 2, {})
840
841        vim._with({ keepmarks = true }, function()
842          vim._with({ keepmarks = false }, function()
843            vim.cmd('%!sort')
844          end)
845        end)
846        return api.nvim_buf_get_mark(0, 'm')
847      ]]
848      eq({ 0, 2 }, out)
849    end)
850  end)
851
852  describe('`keepatterns` context', function()
853    pending('works', function()
854      local out = exec_lua [[
855        api.nvim_buf_set_lines(0, 0, -1, false, { 'aaa', 'bbb' })
856        vim.cmd('/aaa')
857        -- Should be the same as `vim.cmd('keeppatterns /bbb')`
858        vim._with({ keeppatterns = true }, function()
859          vim.cmd('/bbb')
860        end)
861        return fn.getreg('/')
862      ]]
863      eq('aaa', out)
864    end)
865
866    it('can be nested', function()
867      local out = exec_lua [[
868        api.nvim_buf_set_lines(0, 0, -1, false, { 'aaa', 'bbb' })
869        vim.cmd('/aaa')
870        vim._with({ keeppatterns = true }, function()
871          vim._with({ keeppatterns = false }, function()
872            vim.cmd('/bbb')
873          end)
874        end)
875        return fn.getreg('/')
876      ]]
877      eq('bbb', out)
878    end)
879  end)
880
881  describe('`lockmarks` context', function()
882    it('works', function()
883      local mark = exec_lua [[
884        api.nvim_buf_set_lines(0, 0, 0, false, { 'aaa', 'bbb', 'ccc' })
885        api.nvim_buf_set_mark(0, 'm', 2, 2, {})
886        -- Should be same as `:lockmarks lua api.nvim_buf_set_lines(...)`
887        vim._with({ lockmarks = true }, function()
888          api.nvim_buf_set_lines(0, 0, 2, false, { 'uuu', 'vvv', 'www' })
889        end)
890        return api.nvim_buf_get_mark(0, 'm')
891      ]]
892      eq({ 2, 2 }, mark)
893    end)
894
895    it('can be nested', function()
896      local mark = exec_lua [[
897        api.nvim_buf_set_lines(0, 0, 0, false, { 'aaa', 'bbb', 'ccc' })
898        api.nvim_buf_set_mark(0, 'm', 2, 2, {})
899        vim._with({ lockmarks = true }, function()
900          vim._with({ lockmarks = false }, function()
901            api.nvim_buf_set_lines(0, 0, 2, false, { 'uuu', 'vvv', 'www' })
902          end)
903        end)
904        return api.nvim_buf_get_mark(0, 'm')
905      ]]
906      eq({ 0, 2 }, mark)
907    end)
908  end)
909
910  describe('`noautocmd` context', function()
911    it('works', function()
912      local out = exec_lua [[
913        _G.n_events = 0
914        vim.cmd('au ModeChanged * lua _G.n_events = _G.n_events + 1')
915        -- Should be the same as `vim.cmd('noautocmd normal! vv')`
916        vim._with({ noautocmd = true }, function()
917          vim.cmd('normal! vv')
918        end)
919        return _G.n_events
920      ]]
921      eq(0, out)
922    end)
923
924    it('works with User events', function()
925      local out = exec_lua [[
926        _G.n_events = 0
927        vim.cmd('au User MyEvent lua _G.n_events = _G.n_events + 1')
928        -- Should be the same as `vim.cmd('noautocmd doautocmd User MyEvent')`
929        vim._with({ noautocmd = true }, function()
930          api.nvim_exec_autocmds('User', { pattern = 'MyEvent' })
931        end)
932        return _G.n_events
933      ]]
934      eq(0, out)
935    end)
936
937    pending('can be nested', function()
938      local out = exec_lua [[
939        _G.n_events = 0
940        vim.cmd('au ModeChanged * lua _G.n_events = _G.n_events + 1')
941        vim._with({ noautocmd = true }, function()
942          vim._with({ noautocmd = false }, function()
943            vim.cmd('normal! vv')
944          end)
945        end)
946        return _G.n_events
947      ]]
948      eq(2, out)
949    end)
950  end)
951
952  describe('`o` context', function()
953    before_each(function()
954      exec_lua [[
955        _G.other_win, _G.cur_win = setup_windows()
956        _G.other_buf, _G.cur_buf = setup_buffers()
957
958        vim.bo[other_buf].commentstring = '## %s'
959        vim.bo[cur_buf].commentstring = '// %s'
960        vim.go.commentstring = '$$ %s'
961
962        vim.bo[other_buf].undolevels = 100
963        vim.bo[cur_buf].undolevels = 250
964        vim.go.undolevels = 500
965
966        vim.wo[other_win].virtualedit = 'block'
967        vim.wo[cur_win].virtualedit = 'insert'
968        vim.go.virtualedit = 'none'
969
970        vim.wo[other_win].winblend = 10
971        vim.wo[cur_win].winblend = 25
972        vim.go.winblend = 50
973
974        vim.go.langmap = 'xy,yx'
975        vim.go.confirm = false
976
977        _G.get_state = function()
978          return {
979            bo = {
980              cms_cur = vim.bo[cur_buf].commentstring,
981              cms_other = vim.bo[other_buf].commentstring,
982              ul_cur = vim.bo[cur_buf].undolevels,
983              ul_other = vim.bo[other_buf].undolevels,
984            },
985            wo = {
986              ve_cur = vim.wo[cur_win].virtualedit,
987              ve_other = vim.wo[other_win].virtualedit,
988              winbl_cur = vim.wo[cur_win].winblend,
989              winbl_other = vim.wo[other_win].winblend,
990            },
991            go = {
992              cms = vim.go.commentstring,
993              ul = vim.go.undolevels,
994              ve = vim.go.virtualedit,
995              winbl = vim.go.winblend,
996              lmap = vim.go.langmap,
997              cf = vim.go.confirm,
998            },
999          }
1000        end
1001      ]]
1002    end)
1003
1004    it('works', function()
1005      local out = exec_lua [[
1006        local context = {
1007          o = {
1008            commentstring = '-- %s',
1009            undolevels = 0,
1010            virtualedit = 'all',
1011            winblend = 75,
1012            langmap = 'ab,ba',
1013            confirm = true,
1014          },
1015        }
1016
1017        local before = get_state()
1018        local inner = vim._with(context, function()
1019          assert(api.nvim_get_current_buf() == cur_buf)
1020          assert(api.nvim_get_current_win() == cur_win)
1021          return get_state()
1022        end)
1023
1024        return { before = before, inner = inner, after = get_state() }
1025      ]]
1026
1027      -- Options in context are set with `vim.o`, so usually both local
1028      -- and global values are affected. Yet all of them should be later
1029      -- restored to pre-context values.
1030      eq({
1031        bo = { cms_cur = '-- %s', cms_other = '## %s', ul_cur = -123456, ul_other = 100 },
1032        wo = { ve_cur = 'all', ve_other = 'block', winbl_cur = 75, winbl_other = 10 },
1033        go = { cms = '-- %s', ul = 0, ve = 'all', winbl = 75, lmap = 'ab,ba', cf = true },
1034      }, out.inner)
1035      eq(out.before, out.after)
1036    end)
1037
1038    it('sets options in `buf` context', function()
1039      local out = exec_lua [[
1040        local context = { buf = other_buf, o = { commentstring = '-- %s', undolevels = 0 } }
1041
1042        local before = get_state()
1043        local inner = vim._with(context, function()
1044          assert(api.nvim_get_current_buf() == other_buf)
1045          return get_state()
1046        end)
1047
1048        return { before = before, inner = inner, after = get_state() }
1049      ]]
1050
1051      eq({
1052        bo = { cms_cur = '// %s', cms_other = '-- %s', ul_cur = 250, ul_other = -123456 },
1053        wo = { ve_cur = 'insert', ve_other = 'block', winbl_cur = 25, winbl_other = 10 },
1054        -- Global `winbl` inside context ideally should be untouched and equal
1055        -- to 50. It seems to be equal to 0 because `context.buf` uses
1056        -- `ctx_switch` C approach which has no guarantees about window or
1057        -- window option values inside context.
1058        go = { cms = '-- %s', ul = 0, ve = 'none', winbl = 0, lmap = 'xy,yx', cf = false },
1059      }, out.inner)
1060      eq(out.before, out.after)
1061    end)
1062
1063    it('sets options in `win` context', function()
1064      local out = exec_lua [[
1065        local context = { win = other_win, o = { winblend = 75, virtualedit = 'all' } }
1066
1067        local before = get_state()
1068        local inner = vim._with(context, function()
1069          assert(api.nvim_get_current_win() == other_win)
1070          return get_state()
1071        end)
1072
1073        return { before = before, inner = inner, after = get_state() }
1074      ]]
1075
1076      eq({
1077        bo = { cms_cur = '// %s', cms_other = '## %s', ul_cur = 250, ul_other = 100 },
1078        wo = { winbl_cur = 25, winbl_other = 75, ve_cur = 'insert', ve_other = 'all' },
1079        go = { cms = '$$ %s', ul = 500, winbl = 75, ve = 'all', lmap = 'xy,yx', cf = false },
1080      }, out.inner)
1081      eq(out.before, out.after)
1082    end)
1083
1084    it('restores only options from context', function()
1085      local out = exec_lua [[
1086        local context = { o = { undolevels = 0, winblend = 75, langmap = 'ab,ba' } }
1087
1088        local inner = vim._with(context, function()
1089          assert(api.nvim_get_current_buf() == cur_buf)
1090          assert(api.nvim_get_current_win() == cur_win)
1091
1092          vim.o.commentstring = '!! %s'
1093          vim.o.undolevels = 750
1094          vim.o.virtualedit = 'onemore'
1095          vim.o.winblend = 99
1096          vim.o.langmap = 'uv,vu'
1097          return get_state()
1098        end)
1099
1100        return { inner = inner, after = get_state() }
1101      ]]
1102
1103      eq({
1104        bo = { cms_cur = '!! %s', cms_other = '## %s', ul_cur = -123456, ul_other = 100 },
1105        wo = { ve_cur = 'onemore', ve_other = 'block', winbl_cur = 99, winbl_other = 10 },
1106        go = { cms = '!! %s', ul = 750, ve = 'onemore', winbl = 99, lmap = 'uv,vu', cf = false },
1107      }, out.inner)
1108      eq({
1109        bo = { cms_cur = '!! %s', cms_other = '## %s', ul_cur = 250, ul_other = 100 },
1110        wo = { ve_cur = 'onemore', ve_other = 'block', winbl_cur = 25, winbl_other = 10 },
1111        go = { cms = '!! %s', ul = 500, ve = 'onemore', winbl = 50, lmap = 'xy,yx', cf = false },
1112      }, out.after)
1113    end)
1114
1115    it('does not trigger events', function()
1116      exec_lua [[
1117        _G.test_events = {
1118          'BufEnter', 'BufLeave', 'WinEnter', 'WinLeave', 'BufWinEnter', 'BufWinLeave'
1119        }
1120        _G.test_context = { o = { undolevels = 0, winblend = 75, langmap = 'ab,ba' } }
1121        _G.test_trig_event = function() vim.cmd.new() end
1122      ]]
1123      assert_events_trigger()
1124    end)
1125
1126    it('can be nested', function()
1127      local out = exec_lua [[
1128        local before, before_inner, after_inner = get_state(), nil, nil
1129        local cxt_o = { commentstring = '-- %s', winblend = 75, langmap = 'ab,ba', undolevels = 0 }
1130        vim._with({ o = cxt_o }, function()
1131          before_inner = get_state()
1132          local inner_cxt_o = { commentstring = '!! %s', winblend = 99, langmap = 'uv,vu' }
1133          inner = vim._with({ o = inner_cxt_o }, get_state)
1134          after_inner = get_state()
1135        end)
1136        return {
1137          before = before, before_inner = before_inner,
1138          inner = inner,
1139          after_inner = after_inner, after = get_state(),
1140        }
1141      ]]
1142      eq('!! %s', out.inner.bo.cms_cur)
1143      eq(99, out.inner.wo.winbl_cur)
1144      eq('uv,vu', out.inner.go.lmap)
1145      eq(0, out.inner.go.ul)
1146      eq(out.before_inner, out.after_inner)
1147      eq(out.before, out.after)
1148    end)
1149  end)
1150
1151  describe('`sandbox` context', function()
1152    it('works', function()
1153      local ok, err = pcall(
1154        exec_lua,
1155        [[
1156          -- Should work as `vim.cmd('sandbox call append(0, "aaa")')`
1157          vim._with({ sandbox = true }, function()
1158            fn.append(0, 'aaa')
1159          end)
1160        ]]
1161      )
1162      eq(false, ok)
1163      matches('Not allowed in sandbox', err)
1164    end)
1165
1166    it('can NOT be nested', function()
1167      -- This behavior is intentionally different from other flags as allowing
1168      -- disabling `sandbox` from nested function seems to be against the point
1169      -- of using `sandbox` context in the first place
1170      local ok, err = pcall(
1171        exec_lua,
1172        [[
1173          vim._with({ sandbox = true }, function()
1174            vim._with({ sandbox = false }, function()
1175              fn.append(0, 'aaa')
1176            end)
1177          end)
1178        ]]
1179      )
1180      eq(false, ok)
1181      matches('Not allowed in sandbox', err)
1182    end)
1183  end)
1184
1185  describe('`silent` context', function()
1186    it('works', function()
1187      exec_lua [[
1188        -- Should be same as `vim.cmd('silent lua print("aaa")')`
1189        vim._with({ silent = true }, function() print('aaa') end)
1190      ]]
1191      eq('', exec_capture('messages'))
1192
1193      exec_lua [[ vim._with({ silent = true }, function() vim.cmd.echomsg('"bbb"') end) ]]
1194      eq('', exec_capture('messages'))
1195
1196      local screen = Screen.new(20, 5)
1197      exec_lua [[ vim._with({ silent = true }, function() vim.cmd.echo('"ccc"') end) ]]
1198      screen:expect [[
1199        ^                    |
1200        {1:~                   }|*3
1201                            |
1202      ]]
1203    end)
1204
1205    pending('can be nested', function()
1206      exec_lua [[ vim._with({ silent = true }, function()
1207        vim._with({ silent = false }, function()
1208          print('aaa')
1209        end)
1210      end)]]
1211      eq('aaa', exec_capture('messages'))
1212    end)
1213  end)
1214
1215  describe('`unsilent` context', function()
1216    it('works', function()
1217      exec_lua [[
1218        _G.f = function()
1219          -- Should be same as `vim.cmd('unsilent lua print("aaa")')`
1220          vim._with({ unsilent = true }, function() print('aaa') end)
1221        end
1222      ]]
1223      command('silent lua f()')
1224      eq('aaa', exec_capture('messages'))
1225    end)
1226
1227    pending('can be nested', function()
1228      exec_lua [[
1229        _G.f = function()
1230          vim._with({ unsilent = true }, function()
1231            vim._with({ unsilent = false }, function() print('aaa') end)
1232          end)
1233        end
1234      ]]
1235      command('silent lua f()')
1236      eq('', exec_capture('messages'))
1237    end)
1238  end)
1239
1240  describe('`win` context', function()
1241    it('works', function()
1242      local out = exec_lua [[
1243        local other_win, cur_win = setup_windows()
1244        local inner = vim._with({ win = other_win }, function()
1245          return api.nvim_get_current_win()
1246        end)
1247        return { inner == other_win, api.nvim_get_current_win() == cur_win }
1248      ]]
1249      eq({ true, true }, out)
1250    end)
1251
1252    it('does not trigger events', function()
1253      exec_lua [[
1254        _G.test_events = { 'WinEnter', 'WinLeave', 'BufWinEnter', 'BufWinLeave' }
1255        _G.test_context = { win = other_win }
1256        _G.test_trig_event = function() vim.cmd.new() end
1257      ]]
1258      assert_events_trigger()
1259    end)
1260
1261    it('can access window options', function()
1262      local out = exec_lua [[
1263        local other_win, cur_win = setup_windows()
1264        vim.wo[other_win].winblend = 10
1265        vim.wo[cur_win].winblend = 25
1266
1267        vim._with({ win = other_win }, function()
1268          vim.cmd.setlocal('winblend=0')
1269        end)
1270
1271        return vim.wo[other_win].winblend == 0 and vim.wo[cur_win].winblend == 25
1272      ]]
1273      eq(true, out)
1274    end)
1275
1276    it('works with different kinds of windows', function()
1277      exec_lua [[
1278        local assert_win = function(win)
1279          vim._with({ win = win }, function()
1280            assert(api.nvim_get_current_win() == win)
1281          end)
1282        end
1283
1284        -- Current
1285        assert_win(api.nvim_get_current_win())
1286
1287        local win = api.nvim_get_current_win()
1288        vim._with({ win = 0 }, function()
1289          assert(api.nvim_get_current_win() == win)
1290          -- Should restore context window if that changed
1291          vim.cmd.tabnew()
1292        end)
1293        assert(api.nvim_get_current_win() == win)
1294
1295        -- Not visible
1296        local other_win, cur_win = setup_windows()
1297        vim.cmd.tabnew()
1298        assert_win(other_win)
1299
1300        -- Floating
1301        local float_win = api.nvim_open_win(
1302          api.nvim_create_buf(false, true),
1303          false,
1304          { relative = 'editor', row = 1, col = 1, height = 5, width = 5}
1305        )
1306        assert_win(float_win)
1307      ]]
1308    end)
1309
1310    it('does not cause ml_get errors with invalid visual selection', function()
1311      exec_lua [[
1312        local feedkeys = function(keys) api.nvim_feedkeys(vim.keycode(keys), 'txn', false) end
1313
1314        -- Add lines to the current buffer and make another window looking into an empty buffer.
1315        local win_empty, win_lines = setup_windows()
1316        api.nvim_buf_set_lines(0, 0, -1, true, { 'a', 'b', 'c' })
1317
1318        -- Start Visual in current window, redraw in other window with fewer lines.
1319        -- Should be fixed by vim-patch:8.2.4018.
1320        feedkeys('G<C-V>')
1321        vim._with({ win = win_empty }, function() vim.cmd.redraw() end)
1322
1323        -- Start Visual in current window, extend it in other window with more lines.
1324        -- Fixed for win_execute by vim-patch:8.2.4026, but nvim_win_call should also not be affected.
1325        feedkeys('<Esc>gg')
1326        api.nvim_set_current_win(win_empty)
1327        feedkeys('gg<C-V>')
1328        vim._with({ win = win_lines }, function() feedkeys('G<C-V>') end)
1329        vim.cmd.redraw()
1330      ]]
1331    end)
1332
1333    it('can be nested', function()
1334      exec_lua [[
1335        local other_win, cur_win = setup_windows()
1336        vim._with({ win = other_win }, function()
1337          assert(api.nvim_get_current_win() == other_win)
1338          inner = vim._with({ win = cur_win }, function()
1339            assert(api.nvim_get_current_win() == cur_win)
1340          end)
1341          assert(api.nvim_get_current_win() == other_win)
1342        end)
1343        assert(api.nvim_get_current_win() == cur_win)
1344      ]]
1345    end)
1346
1347    it('updates ruler if cursor moved', function()
1348      local screen = Screen.new(30, 5)
1349      exec_lua [[
1350        vim.opt.ruler = true
1351        local lines = {}
1352        for i = 0, 499 do lines[#lines + 1] = tostring(i) end
1353        api.nvim_buf_set_lines(0, 0, -1, true, lines)
1354        api.nvim_win_set_cursor(0, { 20, 0 })
1355        vim.cmd 'split'
1356        _G.win = api.nvim_get_current_win()
1357        vim.cmd "wincmd w | redraw"
1358      ]]
1359      screen:expect [[
1360        19                            |
1361        {2:< Name] [+] 20,1            3%}|
1362        ^19                            |
1363        {3:< Name] [+] 20,1            3%}|
1364                                      |
1365      ]]
1366      exec_lua [[
1367        vim._with({ win = win }, function() api.nvim_win_set_cursor(0, { 100, 0 }) end)
1368        vim.cmd "redraw"
1369      ]]
1370      screen:expect [[
1371        99                            |
1372        {2:< Name] [+] 100,1          19%}|
1373        ^19                            |
1374        {3:< Name] [+] 20,1            3%}|
1375                                      |
1376      ]]
1377    end)
1378
1379    it('layout in current tabpage does not affect windows in others', function()
1380      command('tab split')
1381      local t2_move_win = api.nvim_get_current_win()
1382      command('vsplit')
1383      local t2_other_win = api.nvim_get_current_win()
1384      command('tabprevious')
1385      matches('E36: Not enough room$', pcall_err(command, 'execute "split|"->repeat(&lines)'))
1386      command('vsplit')
1387
1388      exec_lua('vim._with({ win = ... }, function() vim.cmd.wincmd "J" end)', t2_move_win)
1389      eq({ 'col', { { 'leaf', t2_other_win }, { 'leaf', t2_move_win } } }, fn.winlayout(2))
1390    end)
1391
1392    it('keeps ":lcd" on the target window, but restores the CWD', function()
1393      local out = exec_lua [[
1394        local other_win, cur_win = setup_windows()
1395        local cwd = fn.getcwd()
1396        vim._with({ win = other_win }, function()
1397          vim.cmd.lcd(vim.fs.joinpath(cwd, 'test'))
1398        end)
1399        return { fn.haslocaldir(fn.win_id2win(other_win)), fn.getcwd() == cwd }
1400      ]]
1401      eq({ 1, true }, out)
1402    end)
1403  end)
1404
1405  describe('`wo` context', function()
1406    before_each(function()
1407      exec_lua [[
1408        _G.other_win, _G.cur_win = setup_windows()
1409
1410        -- 'virtualedit' is global or local to window (global-local) and string
1411        vim.wo[other_win].virtualedit = 'block'
1412        vim.wo[cur_win].virtualedit = 'insert'
1413        vim.go.virtualedit = 'none'
1414
1415        -- 'winblend' is local to window and number
1416        vim.wo[other_win].winblend = 10
1417        vim.wo[cur_win].winblend = 25
1418        vim.go.winblend = 50
1419
1420        -- 'number' is local to window and boolean
1421        vim.wo[other_win].number = false
1422        vim.wo[cur_win].number = false
1423        vim.go.number = true
1424
1425        _G.get_state = function()
1426          return {
1427            wo = {
1428              ve_cur = vim.wo[cur_win].virtualedit,
1429              ve_other = vim.wo[other_win].virtualedit,
1430              winbl_cur = vim.wo[cur_win].winblend,
1431              winbl_other = vim.wo[other_win].winblend,
1432              nu_cur = vim.wo[cur_win].number,
1433              nu_other = vim.wo[other_win].number,
1434            },
1435            go = {
1436              ve = vim.go.virtualedit,
1437              winbl = vim.go.winblend,
1438              nu = vim.go.number,
1439            },
1440          }
1441        end
1442      ]]
1443    end)
1444
1445    it('works', function()
1446      local out = exec_lua [[
1447        local context = { wo = { virtualedit = 'all', winblend = 75, number = true } }
1448
1449        local before = get_state()
1450        local inner = vim._with(context, function()
1451          assert(api.nvim_get_current_win() == cur_win)
1452          return get_state()
1453        end)
1454
1455        return { before = before, inner = inner, after = get_state() }
1456      ]]
1457
1458      eq({
1459        wo = {
1460          ve_cur = 'all',
1461          ve_other = 'block',
1462          winbl_cur = 75,
1463          winbl_other = 10,
1464          nu_cur = true,
1465          nu_other = false,
1466        },
1467        go = { ve = 'none', winbl = 75, nu = true },
1468      }, out.inner)
1469      eq(out.before, out.after)
1470    end)
1471
1472    it('sets options in `win` context', function()
1473      local out = exec_lua [[
1474        local context = { win = other_win, wo = { virtualedit = 'all', winblend = 75, number = true } }
1475
1476        local before = get_state()
1477        local inner = vim._with(context, function()
1478          assert(api.nvim_get_current_win() == other_win)
1479          return get_state()
1480        end)
1481
1482        return { before = before, inner = inner, after = get_state() }
1483      ]]
1484
1485      eq({
1486        wo = {
1487          ve_cur = 'insert',
1488          ve_other = 'all',
1489          winbl_cur = 25,
1490          winbl_other = 75,
1491          nu_cur = false,
1492          nu_other = true,
1493        },
1494        go = { ve = 'none', winbl = 75, nu = true },
1495      }, out.inner)
1496      eq(out.before, out.after)
1497    end)
1498
1499    it('restores only options from context', function()
1500      local out = exec_lua [[
1501        local context = { wo = { winblend = 75 } }
1502
1503        local inner = vim._with(context, function()
1504          assert(api.nvim_get_current_win() == cur_win)
1505          vim.wo[cur_win].virtualedit = 'onemore'
1506          vim.wo[cur_win].winblend = 99
1507          return get_state()
1508        end)
1509
1510        return { inner = inner, after = get_state() }
1511      ]]
1512
1513      eq({
1514        wo = {
1515          ve_cur = 'onemore',
1516          ve_other = 'block',
1517          winbl_cur = 99,
1518          winbl_other = 10,
1519          nu_cur = false,
1520          nu_other = false,
1521        },
1522        go = { ve = 'none', winbl = 99, nu = true },
1523      }, out.inner)
1524      eq({
1525        wo = {
1526          ve_cur = 'onemore',
1527          ve_other = 'block',
1528          winbl_cur = 25,
1529          winbl_other = 10,
1530          nu_cur = false,
1531          nu_other = false,
1532        },
1533        go = { ve = 'none', winbl = 50, nu = true },
1534      }, out.after)
1535    end)
1536
1537    it('does not trigger events', function()
1538      exec_lua [[
1539        _G.test_events = { 'WinEnter', 'WinLeave', 'BufWinEnter', 'BufWinLeave' }
1540        _G.test_context = { wo = { winblend = 75 } }
1541        _G.test_trig_event = function() vim.cmd.new() end
1542      ]]
1543      assert_events_trigger()
1544    end)
1545
1546    it('can be nested', function()
1547      local out = exec_lua [[
1548        local before, before_inner, after_inner = get_state(), nil, nil
1549        vim._with({ wo = { winblend = 75, virtualedit = 'all', number = true } }, function()
1550          before_inner = get_state()
1551          inner = vim._with({ wo = { winblend = 99, number = false } }, get_state)
1552          after_inner = get_state()
1553        end)
1554        return {
1555          before = before, before_inner = before_inner,
1556          inner = inner,
1557          after_inner = after_inner, after = get_state(),
1558        }
1559      ]]
1560      eq(99, out.inner.wo.winbl_cur)
1561      eq('all', out.inner.wo.ve_cur)
1562      eq(false, out.inner.wo.nu_cur)
1563      eq(out.before_inner, out.after_inner)
1564      eq(out.before, out.after)
1565    end)
1566  end)
1567
1568  it('returns what callback returns', function()
1569    local out_verify = exec_lua [[
1570      out = { vim._with({}, function()
1571        return 'a', 2, nil, { 4 }, function() end
1572      end) }
1573      return {
1574        out[1] == 'a', out[2] == 2, out[3] == nil,
1575        vim.deep_equal(out[4], { 4 }),
1576        type(out[5]) == 'function',
1577        vim.tbl_count(out),
1578      }
1579    ]]
1580    eq({ true, true, true, true, true, 4 }, out_verify)
1581  end)
1582
1583  it('can return values by reference', function()
1584    local out = exec_lua [[
1585      local val = { 4, 10 }
1586      local ref = vim._with({}, function() return val end)
1587      ref[1] = 7
1588      return val
1589    ]]
1590    eq({ 7, 10 }, out)
1591  end)
1592
1593  it('can not work with conflicting `buf` and `win`', function()
1594    local out = exec_lua [[
1595      local other_buf, cur_buf = setup_buffers()
1596      local other_win, cur_win = setup_windows()
1597      assert(api.nvim_win_get_buf(other_win) ~= other_buf)
1598      local _, err = pcall(vim._with, { buf = other_buf, win = other_win }, function() end)
1599      return err
1600    ]]
1601    matches('Can not set both `buf` and `win`', out)
1602  end)
1603
1604  it('works with several contexts at once', function()
1605    local out = exec_lua [[
1606      local other_buf, cur_buf = setup_buffers()
1607      vim.bo[other_buf].commentstring = '## %s'
1608      api.nvim_buf_set_lines(other_buf, 0, -1, false, { 'aaa', 'bbb', 'ccc' })
1609      api.nvim_buf_set_mark(other_buf, 'm', 2, 2, {})
1610
1611      vim.go.commentstring = '// %s'
1612      vim.go.langmap = 'xy,yx'
1613
1614      local context = {
1615        buf = other_buf,
1616        bo = { commentstring = '-- %s' },
1617        go = { langmap = 'ab,ba' },
1618        lockmarks = true,
1619      }
1620
1621      local inner = vim._with(context, function()
1622        api.nvim_buf_set_lines(0, 0, -1, false, { 'uuu', 'vvv', 'www' })
1623        return {
1624          buf = api.nvim_get_current_buf(),
1625          bo = { cms = vim.bo.commentstring },
1626          go = { cms = vim.go.commentstring, lmap = vim.go.langmap },
1627          mark = api.nvim_buf_get_mark(0, 'm')
1628        }
1629      end)
1630
1631      local after = {
1632        buf = api.nvim_get_current_buf(),
1633        bo = { cms = vim.bo[other_buf].commentstring },
1634        go = { cms = vim.go.commentstring, lmap = vim.go.langmap },
1635        mark = api.nvim_buf_get_mark(other_buf, 'm')
1636      }
1637
1638      return {
1639        context_buf = other_buf, cur_buf = cur_buf,
1640        inner = inner, after = after
1641      }
1642    ]]
1643
1644    eq({
1645      buf = out.context_buf,
1646      bo = { cms = '-- %s' },
1647      go = { cms = '// %s', lmap = 'ab,ba' },
1648      mark = { 2, 2 },
1649    }, out.inner)
1650    eq({
1651      buf = out.cur_buf,
1652      bo = { cms = '## %s' },
1653      go = { cms = '// %s', lmap = 'xy,yx' },
1654      mark = { 2, 2 },
1655    }, out.after)
1656  end)
1657
1658  it('works with same option set in different contexts', function()
1659    local out = exec_lua [[
1660      local get_state = function()
1661        return {
1662          bo = { cms = vim.bo.commentstring },
1663          wo = { ve = vim.wo.virtualedit },
1664          go = { cms = vim.go.commentstring, ve = vim.go.virtualedit },
1665        }
1666      end
1667
1668      vim.bo.commentstring = '// %s'
1669      vim.go.commentstring = '$$ %s'
1670      vim.wo.virtualedit = 'insert'
1671      vim.go.virtualedit = 'none'
1672
1673      local before = get_state()
1674      local context_no_go = {
1675        o = { commentstring = '-- %s', virtualedit = 'all' },
1676        bo = { commentstring = '!! %s' },
1677        wo = { virtualedit = 'onemore' },
1678      }
1679      local inner_no_go = vim._with(context_no_go, get_state)
1680      local middle = get_state()
1681      local context_with_go = {
1682        o = { commentstring = '-- %s', virtualedit = 'all' },
1683        bo = { commentstring = '!! %s' },
1684        wo = { virtualedit = 'onemore' },
1685        go = { commentstring = '@@ %s', virtualedit = 'block' },
1686      }
1687      local inner_with_go = vim._with(context_with_go, get_state)
1688      return {
1689        before = before,
1690        inner_no_go = inner_no_go,
1691        middle = middle,
1692        inner_with_go = inner_with_go,
1693        after = get_state(),
1694      }
1695    ]]
1696
1697    -- Should prefer explicit local scopes instead of `o`
1698    eq({
1699      bo = { cms = '!! %s' },
1700      wo = { ve = 'onemore' },
1701      go = { cms = '-- %s', ve = 'all' },
1702    }, out.inner_no_go)
1703    eq(out.before, out.middle)
1704
1705    -- Should prefer explicit global scopes instead of `o`
1706    eq({
1707      bo = { cms = '!! %s' },
1708      wo = { ve = 'onemore' },
1709      go = { cms = '@@ %s', ve = 'block' },
1710    }, out.inner_with_go)
1711    eq(out.middle, out.after)
1712  end)
1713
1714  pending('can forward command modifiers to user command', function()
1715    local out = exec_lua [[
1716      local test_flags = {
1717        'emsg_silent',
1718        'hide',
1719        'keepalt',
1720        'keepjumps',
1721        'keepmarks',
1722        'keeppatterns',
1723        'lockmarks',
1724        'noautocmd',
1725        'silent',
1726        'unsilent',
1727      }
1728
1729      local used_smods
1730      local command = function(data)
1731        used_smods = data.smods
1732      end
1733      api.nvim_create_user_command('DummyLog', command, {})
1734
1735      local res = {}
1736      for _, flag in ipairs(test_flags) do
1737        used_smods = nil
1738        vim._with({ [flag] = true }, function() vim.cmd('DummyLog') end)
1739        res[flag] = used_smods[flag]
1740      end
1741      return res
1742    ]]
1743    for k, v in pairs(out) do
1744      eq({ k, true }, { k, v })
1745    end
1746  end)
1747
1748  it('handles error in callback', function()
1749    -- Should still restore initial context
1750    local out_buf = exec_lua [[
1751      local other_buf, cur_buf = setup_buffers()
1752      vim.bo[other_buf].commentstring = '## %s'
1753
1754      local context = { buf = other_buf, bo = { commentstring = '-- %s' } }
1755      local ok, err = pcall(vim._with, context, function() error('Oops buf', 0) end)
1756
1757      return {
1758        ok,
1759        err,
1760        api.nvim_get_current_buf() == cur_buf,
1761        vim.bo[other_buf].commentstring,
1762      }
1763    ]]
1764    eq({ false, 'Oops buf', true, '## %s' }, out_buf)
1765
1766    local out_win = exec_lua [[
1767      local other_win, cur_win = setup_windows()
1768      vim.wo[other_win].winblend = 25
1769
1770      local context = { win = other_win, wo = { winblend = 50 } }
1771      local ok, err = pcall(vim._with, context, function() error('Oops win', 0) end)
1772
1773      return {
1774        ok,
1775        err,
1776        api.nvim_get_current_win() == cur_win,
1777        vim.wo[other_win].winblend,
1778      }
1779    ]]
1780    eq({ false, 'Oops win', true, 25 }, out_win)
1781  end)
1782
1783  it('handles not supported option', function()
1784    local out = exec_lua [[
1785      -- Should still restore initial state
1786      vim.bo.commentstring = '## %s'
1787
1788      local context = { o = { commentstring = '-- %s' }, bo = { winblend = 10 } }
1789      local ok, err = pcall(vim._with, context, function() end)
1790
1791      return { ok = ok, err = err, cms = vim.bo.commentstring }
1792    ]]
1793    eq(false, out.ok)
1794    matches('window.*option.*winblend', out.err)
1795    eq('## %s', out.cms)
1796  end)
1797
1798  it('validates arguments', function()
1799    exec_lua [[
1800      _G.get_error = function(...)
1801        local _, err = pcall(vim._with, ...)
1802        return err or ''
1803      end
1804    ]]
1805    local get_error = function(string_args)
1806      return exec_lua('return get_error(' .. string_args .. ')')
1807    end
1808
1809    matches('context.*table', get_error("'a', function() end"))
1810    matches('f.*function', get_error('{}, 1'))
1811
1812    local assert_context = function(bad_context, expected_type)
1813      local bad_field = vim.tbl_keys(bad_context)[1]
1814      matches(
1815        'context%.' .. bad_field .. '.*' .. expected_type,
1816        get_error(vim.inspect(bad_context) .. ', function() end')
1817      )
1818    end
1819
1820    assert_context({ bo = 1 }, 'table')
1821    assert_context({ buf = 'a' }, 'number')
1822    assert_context({ emsg_silent = 1 }, 'boolean')
1823    assert_context({ env = 1 }, 'table')
1824    assert_context({ go = 1 }, 'table')
1825    assert_context({ hide = 1 }, 'boolean')
1826    assert_context({ keepalt = 1 }, 'boolean')
1827    assert_context({ keepjumps = 1 }, 'boolean')
1828    assert_context({ keepmarks = 1 }, 'boolean')
1829    assert_context({ keeppatterns = 1 }, 'boolean')
1830    assert_context({ lockmarks = 1 }, 'boolean')
1831    assert_context({ noautocmd = 1 }, 'boolean')
1832    assert_context({ o = 1 }, 'table')
1833    assert_context({ sandbox = 1 }, 'boolean')
1834    assert_context({ silent = 1 }, 'boolean')
1835    assert_context({ unsilent = 1 }, 'boolean')
1836    assert_context({ win = 'a' }, 'number')
1837    assert_context({ wo = 1 }, 'table')
1838
1839    matches('Invalid buffer', get_error('{ buf = -1 }, function() end'))
1840    matches('Invalid window', get_error('{ win = -1 }, function() end'))
1841  end)
1842
1843  it('no double-free when called from :filter browse oldfiles #31501', function()
1844    exec_lua([=[
1845      vim.api.nvim_create_autocmd('BufEnter', {
1846        callback = function()
1847          vim._with({ lockmarks = true }, function() end)
1848        end,
1849      })
1850      vim.cmd([[
1851        let v:oldfiles = ['Xoldfile']
1852        call nvim_input('1<CR>')
1853        noswapfile filter /Xoldfile/ browse oldfiles
1854      ]])
1855    ]=])
1856    n.assert_alive()
1857    eq('Xoldfile', fn.bufname('%'))
1858  end)
1859end)