robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
12.2 KiB374 linesraw
1-- See also: test/old/testdir/test_options.vim
2local t = require('test.testutil')
3local n = require('test.functional.testnvim')()
4local Screen = require('test.functional.ui.screen')
5
6local describe, it, before_each, setup = t.describe, t.it, t.before_each, t.setup
7local command, clear = n.command, n.clear
8local poke_eventloop = n.poke_eventloop
9local source, expect = n.source, n.expect
10local eval = n.eval
11local exec_lua = n.exec_lua
12local matches = t.matches
13local pcall_err = t.pcall_err
14local eq = t.eq
15
16describe('options', function()
17  setup(clear)
18
19  it('should not throw any exception', function()
20    command('options')
21  end)
22end)
23
24describe('options :set', function()
25  before_each(clear)
26
27  it("should keep two comma when 'path' is changed", function()
28    source([[
29      set path=foo,,bar
30      set path-=bar
31      set path+=bar
32      $put =&path]])
33
34    expect([[
35
36      foo,,bar]])
37  end)
38
39  it("'winminheight'", function()
40    local _ = Screen.new(20, 11)
41    source([[
42      set wmh=0 stal=2
43      below sp | wincmd _
44      below sp | wincmd _
45      below sp | wincmd _
46      below sp
47    ]])
48    matches('E36: Not enough room', pcall_err(command, 'set wmh=1'))
49  end)
50
51  it("'winminheight' with tabline", function()
52    local _ = Screen.new(20, 11)
53    source([[
54      set wmh=0 stal=2
55      split
56      split
57      split
58      split
59      tabnew
60    ]])
61    matches('E36: Not enough room', pcall_err(command, 'set wmh=1'))
62  end)
63
64  it("'scroll'", function()
65    local screen = Screen.new(42, 16)
66    source([[
67      set scroll=2
68      set laststatus=2
69    ]])
70    command('verbose set scroll?')
71    screen:expect([[
72                                                |
73      {1:~                                         }|*11
74      {3:                                          }|
75        scroll=7                                |
76              Last set from changed window size |
77      {6:Press ENTER or type command to continue}^   |
78    ]])
79  end)
80
81  it('foldcolumn and signcolumn to empty string is disallowed', function()
82    matches("E474: Invalid value ''.*fdc=", pcall_err(command, 'set fdc='))
83    matches('E474: Invalid argument: scl=', pcall_err(command, 'set scl='))
84  end)
85end)
86
87describe('options validation', function()
88  before_each(clear)
89
90  it('rejects a restricted callback assignment before evaluating its expression', function()
91    local filename = t.tmpname()
92    t.finally(function()
93      os.remove(filename)
94    end)
95    t.write_file(filename, 'vim: set syntax=optiontest :\n')
96    source([[
97      set modeline
98      let g:arg_calls = 0
99      function! MakeArg()
100        let g:arg_calls += 1
101        return 0
102      endfunction
103      function! Handler(...)
104        return 0
105      endfunction
106      set operatorfunc=Handler
107      autocmd Syntax optiontest set operatorfunc=function('Handler',\ [MakeArg()])
108    ]])
109
110    -- Syntax handlers triggered by a modeline run in secure mode. Setting operatorfunc
111    -- must be rejected before MakeArg() runs, even though it only constructs a callback.
112    matches('E523:', pcall_err(command, 'edit ' .. n.fn.fnameescape(filename)))
113    eq(0, eval('g:arg_calls'))
114    eq('Handler', eval('&operatorfunc'))
115
116    -- The same assignment is allowed afterwards, outside the modeline's restrictions.
117    command([[set operatorfunc=function('Handler',\ [MakeArg()])]])
118    eq(1, eval('g:arg_calls > 0'))
119  end)
120
121  -- Improved error messages for structured "key:value" options ("schema" in options.lua).
122  it('reports specific errors for structured (schema) options', function()
123    eq("Vim(set):E474: Unknown item 'foo': diffopt=foo", pcall_err(command, 'set diffopt=foo'))
124    eq(
125      "Vim(set):E474: 'context' requires a number: diffopt=context:x",
126      pcall_err(command, 'set diffopt=context:x')
127    )
128    eq(
129      'Vim(set):E474: '
130        .. "'algorithm' must be one of: myers, minimal, patience, histogram: diffopt=algorithm:bad",
131      pcall_err(command, 'set diffopt=algorithm:bad')
132    )
133    eq(
134      "Vim(set):E474: 'filler' does not take a value: diffopt=filler:1",
135      pcall_err(command, 'set diffopt=filler:1')
136    )
137    eq(
138      "Vim(set):E474: 'ver' number is out of range: mousescroll=ver:99999999999",
139      pcall_err(command, 'set mousescroll=ver:99999999999')
140    )
141  end)
142
143  -- Enum / flag-list options name the offending value and list the valid ones.
144  it('reports specific errors for enum and flag-list options', function()
145    eq(
146      "Vim(set):E474: Invalid value 'x', expected one of: single, double: ambiwidth=x",
147      pcall_err(command, 'set ambiwidth=x')
148    )
149    eq(
150      'Vim(set):E474: '
151        .. "Invalid value 'x', expected one of: yes, auto, no, breaksymlink, breakhardlink: backupcopy=x",
152      pcall_err(command, 'set backupcopy=x')
153    )
154  end)
155end)
156
157describe('callback (func/expr) options', function()
158  before_each(clear)
159
160  it('accept a Lua function, preserving identity and captured upvalues', function()
161    -- 'operatorfunc' is global; 'tagfunc' is buffer-local: exercise both storage paths.
162    eq(
163      { identity = true, captured = 'CAP', kind = 'function', optset_old = '', optset_new = true },
164      exec_lua(function()
165        vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'abcdef' })
166        local captured = 'CAP'
167        _G.seen = nil
168        local fn = function(_)
169          _G.seen = captured
170        end
171        -- OptionSet emits with Lua function as "<Lua …>".
172        local optset
173        vim.api.nvim_create_autocmd('OptionSet', {
174          pattern = 'operatorfunc',
175          callback = function()
176            optset = { old = vim.v.option_old, new = vim.v.option_new }
177          end,
178        })
179        vim.o.operatorfunc = fn
180        vim.cmd('normal! g@l')
181        return {
182          identity = vim.o.operatorfunc == fn,
183          captured = _G.seen,
184          kind = type(vim.o.operatorfunc),
185          optset_old = optset.old,
186          optset_new = tostring(optset.new):match('^<Lua ') ~= nil,
187        }
188      end)
189    )
190    eq(
191      true,
192      exec_lua(function()
193        local tfn = function(_, _, _)
194          return {}
195        end
196        vim.bo.tagfunc = tfn
197        return vim.bo.tagfunc == tfn
198      end)
199    )
200    -- Vimscript GC traverses buffer-local callback options; a Lua-function callback must survive it
201    -- garbagecollect() defers to main loop, so spin it with a motion to actually run collection.
202    command('call garbagecollect(1)')
203    n.feed('ll')
204    poke_eventloop()
205    eq('function', exec_lua('return type(vim.bo.tagfunc)'))
206  end)
207
208  it('accept a string funcref, read back as a string', function()
209    eq(
210      { type = 'string', value = 'SomeFunc' },
211      exec_lua(function()
212        vim.o.operatorfunc = 'SomeFunc'
213        return { type = type(vim.o.operatorfunc), value = vim.o.operatorfunc }
214      end)
215    )
216  end)
217
218  it('reject a non-function, non-string value', function()
219    matches(
220      "Invalid 'operatorfunc': expected a valid type, got Integer",
221      pcall_err(exec_lua, 'vim.o.operatorfunc = 42')
222    )
223    -- Only callback (func/expr) options accept a function; others reject it.
224    matches(
225      "Invalid 'statusline': expected a valid type, got Function",
226      pcall_err(exec_lua, 'vim.o.statusline = function() end')
227    )
228    matches(
229      "Invalid 'shiftwidth': expected a valid type, got Function",
230      pcall_err(exec_lua, 'vim.bo.shiftwidth = function() end')
231    )
232  end)
233
234  it("preserve a partial's bound args when the value is copied to the global default", function()
235    -- 'tagfunc' is buffer-local; setting it also copies the value to the global default (which
236    -- new buffers inherit). A partial must keep its bound args across that copy.
237    command([[
238      func! Foo(bound, pat, flags, info)
239        return []
240      endfunc
241      set tagfunc=function('Foo',\ [10])
242    ]])
243    eq("function('Foo', [10])", eval('&g:tagfunc'))
244  end)
245
246  it('keep the previous callback when set to an invalid function', function()
247    command('set operatorfunc=GoodFunc')
248    matches('E700:', pcall_err(command, "set operatorfunc=function('NoSuchFuncXYZ')"))
249    eq('GoodFunc', eval('&operatorfunc'))
250  end)
251
252  it(':set', function()
253    command('set operatorfunc=SomeFunc')
254    command('set quickfixtextfunc={\\ d\\ ->\\ []\\ }')
255    exec_lua(function()
256      vim.o.omnifunc = function() end
257      vim.wo.foldexpr = function() end
258    end)
259    command('set all')
260    n.assert_alive()
261
262    -- ":set opt?" shows funcref/lambda name, or "<Lua …>".
263    local function set_q(opt)
264      return n.api.nvim_exec2(('set %s?'):format(opt), { output = true }).output
265    end
266    eq('  operatorfunc=SomeFunc', set_q('operatorfunc'))
267    matches("^  quickfixtextfunc=function%('<lambda>%d+'%)$", set_q('quickfixtextfunc'))
268    matches('^  omnifunc=<Lua .+:%d+>$', set_q('omnifunc'))
269    matches('^  foldexpr=<Lua .+:%d+>$', set_q('foldexpr'))
270    eq(set_q('omnifunc'), set_q('omnifunc')) -- Stable: no per-read ref id.
271
272    -- ":set opt=<Tab>" completes a funcref value, but not a Lua function.
273    eq({ 'SomeFunc' }, n.fn.getcompletion('set operatorfunc=', 'cmdline'))
274    eq({}, n.fn.getcompletion('set omnifunc=', 'cmdline'))
275  end)
276
277  it("expr option ('foldexpr') accepts string, reads back string", function()
278    eq(
279      { kind = 'string', value = 'v:lnum - 1', l1 = 0, l3 = 2 },
280      exec_lua(function()
281        vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'a', 'b', 'c', 'd' })
282        vim.wo.foldmethod = 'expr'
283        vim.wo.foldexpr = 'v:lnum - 1'
284        return {
285          kind = type(vim.wo.foldexpr),
286          value = vim.wo.foldexpr,
287          l1 = vim.fn.foldlevel(1),
288          l3 = vim.fn.foldlevel(3),
289        }
290      end)
291    )
292  end)
293
294  it("expr option ('foldexpr') accepts Lua function, preserving identity", function()
295    -- Lua-function 'foldexpr' is invoked per line.
296    eq(
297      { identity = true, kind = 'function', l2 = 0, l3 = 1 },
298      exec_lua(function()
299        vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'a', 'b', 'c', 'd' })
300        local fn = function()
301          return vim.v.lnum >= 3 and 1 or 0
302        end
303        vim.wo.foldmethod = 'expr'
304        vim.wo.foldexpr = fn
305        return {
306          identity = vim.wo.foldexpr == fn,
307          kind = type(vim.wo.foldexpr),
308          l2 = vim.fn.foldlevel(2),
309          l3 = vim.fn.foldlevel(3),
310        }
311      end)
312    )
313  end)
314
315  it("buffer-local expr option ('indentexpr') accepts Lua function", function()
316    -- Exercises the buffer-local Callback path (copy/free) and get_expr_indent via `==`.
317    eq(
318      { identity = true, indent = 8 },
319      exec_lua(function()
320        local myfn = function()
321          return 8
322        end
323        vim.bo.indentexpr = myfn
324        vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'line1', 'line2' })
325        vim.cmd('normal! 2G==')
326        return {
327          identity = vim.bo.indentexpr == myfn,
328          indent = vim.fn.indent(2),
329        }
330      end)
331    )
332  end)
333
334  it("Lua function 'formatexpr' on another buffer (vim.bo[bufnr])", function()
335    -- Sets via the non-curbuf API path (context switch), the way LSP configures 'formatexpr'.
336    eq(
337      { identity = true, cur_unchanged = true, invoked = true },
338      exec_lua(function()
339        local buf = vim.api.nvim_create_buf(true, false)
340        local invoked = false
341        local fexpr = function()
342          invoked = true
343          return 0
344        end
345        vim.bo[buf].formatexpr = fexpr
346        vim.api.nvim_buf_set_lines(buf, 0, -1, false, { 'some text to format' })
347        local identity = vim.bo[buf].formatexpr == fexpr
348        vim.api.nvim_buf_call(buf, function()
349          vim.cmd('normal! gqq')
350        end)
351        return {
352          identity = identity,
353          cur_unchanged = vim.bo.formatexpr == '',
354          invoked = invoked,
355        }
356      end)
357    )
358  end)
359
360  it("omits a Lua-function value from :mksession/:mkvimrc (no ':set' form)", function()
361    -- A Lua function has no ":set" representation, so it must be skipped, not crash the writer.
362    local session = exec_lua(function()
363      vim.opt.sessionoptions:append('options')
364      vim.o.operatorfunc = 'StrOpFunc' -- string funcref: written
365      vim.o.quickfixtextfunc = function() end -- Lua function: omitted
366      local f = vim.fn.tempname()
367      vim.cmd('mksession! ' .. f)
368      vim.cmd('mkvimrc! ' .. vim.fn.tempname()) -- also exercises the makeset()/put_set() path
369      return table.concat(vim.fn.readfile(f), '\n')
370    end)
371    matches('operatorfunc=StrOpFunc', session)
372    eq(nil, session:find('quickfixtextfunc'))
373  end)
374end)