robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
104.3 KiB3264 linesraw
1" Test for options
2
3source shared.vim
4source check.vim
5source view_util.vim
6
7scriptencoding utf-8
8
9func Test_whichwrap()
10  set whichwrap=b,s
11  call assert_equal('b,s', &whichwrap)
12
13  set whichwrap+=h,l
14  call assert_equal('b,s,h,l', &whichwrap)
15
16  set whichwrap+=h,l
17  call assert_equal('b,s,h,l', &whichwrap)
18
19  set whichwrap+=h,l
20  call assert_equal('b,s,h,l', &whichwrap)
21
22  set whichwrap=h,h
23  call assert_equal('h', &whichwrap)
24
25  set whichwrap=h,h,h
26  call assert_equal('h', &whichwrap)
27
28  " " For compatibility with Vim 3.0 and before, number values are also
29  " " supported for 'whichwrap'
30  " set whichwrap=1
31  " call assert_equal('b', &whichwrap)
32  " set whichwrap=2
33  " call assert_equal('s', &whichwrap)
34  " set whichwrap=4
35  " call assert_equal('h,l', &whichwrap)
36  " set whichwrap=8
37  " call assert_equal('<,>', &whichwrap)
38  " set whichwrap=16
39  " call assert_equal('[,]', &whichwrap)
40  " set whichwrap=31
41  " call assert_equal('b,s,h,l,<,>,[,]', &whichwrap)
42
43  set whichwrap&
44endfunc
45
46func Test_isfname()
47  " This used to cause Vim to access uninitialized memory.
48  set isfname=
49  call assert_equal("~X", expand("~X"))
50  set isfname&
51  " Test for setting 'isfname' to an unsupported character
52  let save_isfname = &isfname
53  call assert_fails('exe $"set isfname+={"\u1234"}"', 'E474:')
54  call assert_equal(save_isfname, &isfname)
55endfunc
56
57" Test for getting the value of 'pastetoggle'
58func Test_pastetoggle()
59  throw "Skipped: 'pastetoggle' is removed from Nvim"
60  " character with K_SPECIAL byte
61  let &pastetoggle = '…'
62  call assert_equal('…', &pastetoggle)
63  call assert_equal("\n  pastetoggle=…", execute('set pastetoggle?'))
64
65  " modified character with K_SPECIAL byte
66  let &pastetoggle = '<M-…>'
67  call assert_equal('<M-…>', &pastetoggle)
68  call assert_equal("\n  pastetoggle=<M-…>", execute('set pastetoggle?'))
69
70  " illegal bytes
71  let str = ":\x7f:\x80:\x90:\xd0:"
72  let &pastetoggle = str
73  call assert_equal(str, &pastetoggle)
74  call assert_equal("\n  pastetoggle=" .. strtrans(str), execute('set pastetoggle?'))
75
76  unlet str
77  set pastetoggle&
78endfunc
79
80func Test_wildchar()
81  " Empty 'wildchar' used to access invalid memory.
82  call assert_fails('set wildchar=', 'E521:')
83  call assert_fails('set wildchar=abc', 'E521:')
84  set wildchar=<Esc>
85  let a=execute('set wildchar?')
86  call assert_equal("\n  wildchar=<Esc>", a)
87  set wildchar=27
88  let a=execute('set wildchar?')
89  call assert_equal("\n  wildchar=<Esc>", a)
90  set wildchar&
91endfunc
92
93func Test_wildoptions()
94  set wildoptions=
95  set wildoptions+=tagfile
96  set wildoptions+=tagfile
97  call assert_equal('tagfile', &wildoptions)
98endfunc
99
100func Test_options_command()
101  let caught = 'ok'
102  try
103    options
104  catch
105    let caught = v:throwpoint . "\n" . v:exception
106  endtry
107  call assert_equal('ok', caught)
108
109  " Check if the option-window is opened horizontally.
110  wincmd j
111  call assert_notequal('nvim-optwin://optwin', bufname(''))
112  wincmd k
113  call assert_equal('nvim-optwin://optwin', bufname(''))
114  " close option-window
115  close
116
117  " Open the option-window vertically.
118  vert options
119  " Check if the option-window is opened vertically.
120  wincmd l
121  call assert_notequal('nvim-optwin://optwin', bufname(''))
122  wincmd h
123  call assert_equal('nvim-optwin://optwin', bufname(''))
124  " close option-window
125  close
126
127  " Open the option-window at the top.
128  set splitbelow
129  topleft options
130  call assert_equal(1, winnr())
131  close
132
133  " Open the option-window at the bottom.
134  set nosplitbelow
135  botright options
136  call assert_equal(winnr('$'), winnr())
137  close
138  set splitbelow&
139
140  " Open the option-window in a new tab.
141  tab options
142  " Check if the option-window is opened in a tab.
143  normal gT
144  call assert_notequal('nvim-optwin://optwin', bufname(''))
145  normal gt
146  call assert_equal('nvim-optwin://optwin', bufname(''))
147  " close option-window
148  close
149
150  " Open the options window browse
151  if has('browse')
152    browse set
153    call assert_equal('nvim-optwin://optwin', bufname(''))
154    close
155  endif
156endfunc
157
158func Test_path_keep_commas()
159  " Test that changing 'path' keeps two commas.
160  set path=foo,,bar
161  set path-=bar
162  set path+=bar
163  call assert_equal('foo,,bar', &path)
164
165  set path&
166endfunc
167
168func Test_path_too_long()
169  exe 'set path=' .. repeat('x', 10000)
170  call assert_fails('find x', 'E854:')
171  set path&
172endfunc
173
174func Test_signcolumn()
175  CheckFeature signs
176  call assert_equal("auto", &signcolumn)
177  set signcolumn=yes
178  set signcolumn=no
179  call assert_fails('set signcolumn=nope', 'E474: Invalid argument: signcolumn=nope')
180endfunc
181
182func Test_filetype_valid()
183  set ft=valid_name
184  call assert_equal("valid_name", &filetype)
185  set ft=valid-name
186  call assert_equal("valid-name", &filetype)
187
188  call assert_fails(":set ft=wrong;name", "E474:")
189  call assert_fails(":set ft=wrong\\\\name", "E474:")
190  call assert_fails(":set ft=wrong\\|name", "E474:")
191  call assert_fails(":set ft=wrong/name", "E474:")
192  call assert_fails(":set ft=wrong\\\nname", "E474:")
193  call assert_equal("valid-name", &filetype)
194
195  exe "set ft=trunc\x00name"
196  call assert_equal("trunc", &filetype)
197endfunc
198
199func Test_syntax_valid()
200  if !has('syntax')
201    return
202  endif
203  set syn=valid_name
204  call assert_equal("valid_name", &syntax)
205  set syn=valid-name
206  call assert_equal("valid-name", &syntax)
207
208  call assert_fails(":set syn=wrong;name", "E474:")
209  call assert_fails(":set syn=wrong\\\\name", "E474:")
210  call assert_fails(":set syn=wrong\\|name", "E474:")
211  call assert_fails(":set syn=wrong/name", "E474:")
212  call assert_fails(":set syn=wrong\\\nname", "E474:")
213  call assert_equal("valid-name", &syntax)
214
215  exe "set syn=trunc\x00name"
216  call assert_equal("trunc", &syntax)
217endfunc
218
219func Test_keymap_valid()
220  if !has('keymap')
221    return
222  endif
223  call assert_fails(":set kmp=valid_name", "E544:")
224  call assert_fails(":set kmp=valid_name", "valid_name")
225  call assert_fails(":set kmp=valid-name", "E544:")
226  call assert_fails(":set kmp=valid-name", "valid-name")
227
228  call assert_fails(":set kmp=wrong;name", "E474:")
229  call assert_fails(":set kmp=wrong\\\\name", "E474:")
230  call assert_fails(":set kmp=wrong\\|name", "E474:")
231  call assert_fails(":set kmp=wrong/name", "E474:")
232  call assert_fails(":set kmp=wrong\\\nname", "E474:")
233
234  call assert_fails(":set kmp=trunc\x00name", "E544:")
235  call assert_fails(":set kmp=trunc\x00name", "trunc")
236endfunc
237
238func Test_wildchar_valid()
239  call assert_fails("set wildchar=<CR>", "E474:")
240  call assert_fails("set wildcharm=<C-C>", "E474:")
241endfunc
242
243func Check_dir_option(name)
244  " Check that it's possible to set the option.
245  exe 'set ' . a:name . '=/usr/share/dict/words'
246  call assert_equal('/usr/share/dict/words', eval('&' . a:name))
247  exe 'set ' . a:name . '=/usr/share/dict/words,/and/there'
248  call assert_equal('/usr/share/dict/words,/and/there', eval('&' . a:name))
249  exe 'set ' . a:name . '=/usr/share/dict\ words'
250  call assert_equal('/usr/share/dict words', eval('&' . a:name))
251
252  " Check rejecting weird characters.
253  call assert_fails("set " . a:name . "=/not&there", "E474:")
254  call assert_fails("set " . a:name . "=/not>there", "E474:")
255  call assert_fails("set " . a:name . "=/not.*there", "E474:")
256endfunc
257
258func Test_cinkeys()
259  " This used to cause invalid memory access
260  set cindent cinkeys=0
261  norm a
262  set cindent& cinkeys&
263endfunc
264
265func Test_dictionary()
266  call Check_dir_option('dictionary')
267endfunc
268
269func Test_thesaurus()
270  call Check_dir_option('thesaurus')
271endfun
272
273func Test_complete()
274  " Trailing single backslash used to cause invalid memory access.
275  set complete=s\
276  new
277  call feedkeys("i\<C-N>\<Esc>", 'xt')
278  bwipe!
279  call assert_fails('set complete=ix', 'E535: Illegal character after <i>')
280  call assert_fails('set complete=x', 'E539: Illegal character <x>')
281  call assert_fails('set complete=..', 'E535: Illegal character after <.>')
282  set complete=.,w,b,u,k,\ s,i,d,],t,U,F,o
283  call assert_fails('set complete=i^-10', 'E535: Illegal character after <^>')
284  call assert_fails('set complete=i^x', 'E535: Illegal character after <^>')
285  call assert_fails('set complete=k^2,t^-1,s^', 'E535: Illegal character after <^>')
286  call assert_fails('set complete=t^-1', 'E535: Illegal character after <^>')
287  call assert_fails('set complete=kfoo^foo2', 'E535: Illegal character after <^>')
288  call assert_fails('set complete=kfoo^', 'E535: Illegal character after <^>')
289  call assert_fails('set complete=.^', 'E535: Illegal character after <^>')
290  set complete=.,w,b,u,k,s,i,d,],t,U,F,o
291  set complete=.
292  set complete=.^10,t^0
293
294  func Foo(a, b)
295    return ''
296  endfunc
297
298  set complete+=Ffuncref('Foo'\\,\ [10])
299  set complete=Ffuncref('Foo'\\,\ [10])^10
300  set complete&
301  set complete+=Ffunction('g:Foo'\\,\ [10\\,\ 20])
302  set complete&
303  delfunc Foo
304endfun
305
306func Test_set_completion()
307  call feedkeys(":set di\<C-A>\<C-B>\"\<CR>", 'tx')
308  call assert_equal('"set dictionary diff diffanchors diffexpr diffopt digraph directory display', @:)
309
310  call feedkeys(":setlocal di\<C-A>\<C-B>\"\<CR>", 'tx')
311  call assert_equal('"setlocal dictionary diff diffanchors diffexpr diffopt digraph directory display', @:)
312
313  call feedkeys(":setglobal di\<C-A>\<C-B>\"\<CR>", 'tx')
314  call assert_equal('"setglobal dictionary diff diffanchors diffexpr diffopt digraph directory display', @:)
315
316  " Expand boolean options. When doing :set no<Tab> Vim prefixes the option
317  " names with "no".
318  call feedkeys(":set nodi\<C-A>\<C-B>\"\<CR>", 'tx')
319  call assert_equal('"set nodiff nodigraph', @:)
320
321  call feedkeys(":set invdi\<C-A>\<C-B>\"\<CR>", 'tx')
322  call assert_equal('"set invdiff invdigraph', @:)
323
324  " Expanding "set noinv" does nothing.
325  call feedkeys(":set noinv\<C-A>\<C-B>\"\<CR>", 'tx')
326  call assert_equal('"set noinv', @:)
327
328  " Expand abbreviation of options.
329  call feedkeys(":set ts\<C-A>\<C-B>\"\<CR>", 'tx')
330  call assert_equal('"set tabstop thesaurus thesaurusfunc', @:)
331
332  " Expand current value
333  call feedkeys(":set suffixes=\<C-A>\<C-B>\"\<CR>", 'tx')
334  call assert_equal('"set suffixes=.bak,~,.o,.h,.info,.swp,.obj', @:)
335
336  call feedkeys(":set suffixes:\<C-A>\<C-B>\"\<CR>", 'tx')
337  call assert_equal('"set suffixes:.bak,~,.o,.h,.info,.swp,.obj', @:)
338
339  " " Expand key codes.
340  " call feedkeys(":set <H\<C-A>\<C-B>\"\<CR>", 'tx')
341  " call assert_equal('"set <Help> <Home>', @:)
342  " " <BackSpace> (alt name) and <BS> should both show up in auto-complete
343  " call feedkeys(":set <B\<C-A>\<C-B>\"\<CR>", 'tx')
344  " call assert_equal('"set <BackSpace> <Bar> <BS> <Bslash>', @:)
345  " " <ScrollWheelDown> has alt name <MouseUp> but it should not show up here
346  " " nor show up as duplicates
347  " call feedkeys(":set <ScrollWheel\<C-A>\<C-B>\"\<CR>", 'tx')
348  " call assert_equal('"set <ScrollWheelDown> <ScrollWheelLeft> <ScrollWheelRight> <ScrollWheelUp>', @:)
349  "
350  " " Expand terminal options.
351  " call feedkeys(":set t_A\<C-A>\<C-B>\"\<CR>", 'tx')
352  " call assert_equal('"set t_AB t_AF t_AU t_AL', @:)
353  " call assert_fails('call feedkeys(":set <t_afoo>=\<C-A>\<CR>", "xt")', 'E474:')
354
355  " Expand directories.
356  call feedkeys(":set cdpath=./\<C-A>\<C-B>\"\<CR>", 'tx')
357  call assert_match(' ./samples/ ', @:)
358  call assert_notmatch(' ./summarize.vim ', @:)
359  set cdpath&
360
361  " Expand files and directories.
362  call feedkeys(":set tags=./\<C-A>\<C-B>\"\<CR>", 'tx')
363  call assert_match(' ./samples/.* ./summarize.vim', @:)
364
365  call feedkeys(":set tags=./\\\\ dif\<C-A>\<C-B>\"\<CR>", 'tx')
366  call assert_equal('"set tags=./\\ diff diffanchors diffexpr diffopt', @:)
367
368  " Expand files with spaces/commas in them. Make sure we delimit correctly.
369  "
370  " 'tags' allow for for spaces/commas to both act as delimiters, with actual
371  " spaces requiring double escape, and commas need a single escape.
372  " 'dictionary' is a normal comma-separated option where only commas act as
373  " delimiters, and both space/comma need one single escape.
374  " 'makeprg' is a non-comma-separated option. Commas don't need escape.
375  defer delete('Xfoo Xspace.txt')
376  defer delete('Xsp_dummy')
377  defer delete('Xbar,Xcomma.txt')
378  defer delete('Xcom_dummy')
379  call writefile([], 'Xfoo Xspace.txt')
380  call writefile([], 'Xsp_dummy')
381  call writefile([], 'Xbar,Xcomma.txt')
382  call writefile([], 'Xcom_dummy')
383
384  call feedkeys(':set tags=./Xfoo\ Xsp' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
385  call assert_equal('"set tags=./Xfoo\ Xsp_dummy', @:)
386  call feedkeys(':set tags=./Xfoo\\\ Xsp' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
387  call assert_equal('"set tags=./Xfoo\\\ Xspace.txt', @:)
388  call feedkeys(':set dictionary=./Xfoo\ Xsp' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
389  call assert_equal('"set dictionary=./Xfoo\ Xspace.txt', @:)
390
391  call feedkeys(':set dictionary=./Xbar,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
392  call assert_equal('"set dictionary=./Xbar,Xcom_dummy', @:)
393  if has('win32')
394    " In Windows, '\,' is literal, see `:help filename-backslash`, so this
395    " means we treat it as one file name.
396    call feedkeys(':set dictionary=Xbar\,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
397    call assert_equal('"set dictionary=Xbar\,Xcomma.txt', @:)
398  else
399    " In other platforms, '\,' simply escape to ',', and indicate a delimiter
400    " to split into a separate file name. You need '\\,' to escape the comma
401    " as part of the file name.
402    call feedkeys(':set dictionary=Xbar\,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
403    call assert_equal('"set dictionary=Xbar\,Xcom_dummy', @:)
404
405    call feedkeys(':set dictionary=Xbar\\,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx')
406    call assert_equal('"set dictionary=Xbar\\,Xcomma.txt', @:)
407  endif
408  call feedkeys(":set makeprg=./Xbar,Xcom\<C-A>\<C-B>\"\<CR>", 'tx')
409  call assert_equal('"set makeprg=./Xbar,Xcomma.txt', @:)
410  set tags& dictionary& makeprg&
411
412  " Expanding the option names
413  call feedkeys(":set \<Tab>\<C-B>\"\<CR>", 'xt')
414  call assert_equal('"set all', @:)
415
416  " Expanding a second set of option names
417  call feedkeys(":set wrapscan \<Tab>\<C-B>\"\<CR>", 'xt')
418  call assert_equal('"set wrapscan all', @:)
419
420  " Expanding a special keycode
421  " call feedkeys(":set <Home>\<Tab>\<C-B>\"\<CR>", 'xt')
422  " call assert_equal('"set <Home>', @:)
423
424  " Expanding an invalid special keycode
425  call feedkeys(":set <abcd>\<Tab>\<C-B>\"\<CR>", 'xt')
426  call assert_equal("\"set <abcd>\<Tab>", @:)
427
428  " Expanding a terminal keycode
429  " call feedkeys(":set t_AB\<Tab>\<C-B>\"\<CR>", 'xt')
430  " call assert_equal("\"set t_AB", @:)
431
432  " Expanding an invalid option name
433  call feedkeys(":set abcde=\<Tab>\<C-B>\"\<CR>", 'xt')
434  call assert_equal("\"set abcde=\<Tab>", @:)
435
436  " Expanding after a = for a boolean option
437  call feedkeys(":set wrapscan=\<Tab>\<C-B>\"\<CR>", 'xt')
438  call assert_equal("\"set wrapscan=\<Tab>", @:)
439
440  " Expanding a numeric option
441  call feedkeys(":set tabstop+=\<Tab>\<C-B>\"\<CR>", 'xt')
442  call assert_equal("\"set tabstop+=" .. &tabstop, @:)
443
444  " Expanding a non-boolean option
445  call feedkeys(":set invtabstop=\<Tab>\<C-B>\"\<CR>", 'xt')
446  call assert_equal("\"set invtabstop=", @:)
447
448  " Expand options for 'spellsuggest'
449  call feedkeys(":set spellsuggest=file:test_options.v\<Tab>\<C-B>\"\<CR>", 'xt')
450  call assert_equal("\"set spellsuggest=file:test_options.vim", @:)
451  call feedkeys(":set spellsuggest=best,file:test_options.v\<Tab>\<C-B>\"\<CR>", 'xt')
452  call assert_equal("\"set spellsuggest=best,file:test_options.vim", @:)
453
454  " Expanding value for 'key' is disallowed
455  if exists('+key')
456    set key=abcd
457    call feedkeys(":set key=\<Tab>\<C-B>\"\<CR>", 'xt')
458    call assert_equal('"set key=', @:)
459    call feedkeys(":set key-=\<Tab>\<C-B>\"\<CR>", 'xt')
460    call assert_equal('"set key-=', @:)
461    set key=
462  endif
463
464  " Expand values for 'filetype'
465  call feedkeys(":set filetype=sshdconfi\<Tab>\<C-B>\"\<CR>", 'xt')
466  call assert_equal('"set filetype=sshdconfig', @:)
467  call feedkeys(":set filetype=a\<C-A>\<C-B>\"\<CR>", 'xt')
468  call assert_equal('"set filetype=' .. getcompletion('a*', 'filetype')->join(), @:)
469
470  " Expand values for 'syntax'
471  call feedkeys(":set syntax=sshdconfi\<Tab>\<C-B>\"\<CR>", 'xt')
472  call assert_equal('"set syntax=sshdconfig', @:)
473  call feedkeys(":set syntax=a\<C-A>\<C-B>\"\<CR>", 'xt')
474  call assert_equal('"set syntax=' .. getcompletion('a*', 'syntax')->join(), @:)
475
476  if has('keymap')
477    " Expand values for 'keymap'
478    call feedkeys(":set keymap=acc\<Tab>\<C-B>\"\<CR>", 'xt')
479    call assert_equal('"set keymap=accents', @:)
480    call feedkeys(":set keymap=a\<C-A>\<C-B>\"\<CR>", 'xt')
481    call assert_equal('"set keymap=' .. getcompletion('a*', 'keymap')->join(), @:)
482  endif
483endfunc
484
485" Test handling of expanding individual string option values
486func Test_set_completion_string_values()
487  "
488  " Test basic enum string options that have well-defined enum names
489  "
490
491  " call assert_equal(['lastline', 'truncate', 'uhex'], getcompletion('set display=', 'cmdline'))
492  call assert_equal(['lastline', 'truncate', 'uhex', 'msgsep'], getcompletion('set display=', 'cmdline'))
493  call assert_equal(['truncate'], getcompletion('set display=t', 'cmdline'))
494  call assert_equal(['uhex'], getcompletion('set display=*ex*', 'cmdline'))
495
496  " Test that if a value is set, it will populate the results, but only if
497  " typed value is empty.
498  set display=uhex,lastline
499  " call assert_equal(['uhex,lastline', 'lastline', 'truncate', 'uhex'], getcompletion('set display=', 'cmdline'))
500  call assert_equal(['uhex,lastline', 'lastline', 'truncate', 'uhex', 'msgsep'], getcompletion('set display=', 'cmdline'))
501  call assert_equal(['uhex'], getcompletion('set display=u', 'cmdline'))
502  " If the set value is part of the enum list, it will show as the first
503  " result with no duplicate.
504  set display=uhex
505  " call assert_equal(['uhex', 'lastline', 'truncate'], getcompletion('set display=', 'cmdline'))
506  call assert_equal(['uhex', 'lastline', 'truncate', 'msgsep'], getcompletion('set display=', 'cmdline'))
507  " If empty value, will just show the normal list without an empty item
508  set display=
509  " call assert_equal(['lastline', 'truncate', 'uhex'], getcompletion('set display=', 'cmdline'))
510  call assert_equal(['lastline', 'truncate', 'uhex', 'msgsep'], getcompletion('set display=', 'cmdline'))
511  " Test escaping of the values
512  " call assert_equal('vert:\|,fold:-,eob:~,lastline:@', getcompletion('set fillchars=', 'cmdline')[0])
513  call assert_equal('vert:\|,foldsep:\|,fold:-', getcompletion('set fillchars=', 'cmdline')[0])
514
515  " Test comma-separated lists will expand after a comma.
516  call assert_equal(['uhex'], getcompletion('set display=truncate,*ex*', 'cmdline'))
517  " Also test the positioning of the expansion is correct
518  call feedkeys(":set display=truncate,l\<Tab>\<C-B>\"\<CR>", 'xt')
519  call assert_equal('"set display=truncate,lastline', @:)
520  set display&
521
522  " Test single-value options will not expand after a comma
523  call assert_equal([], getcompletion('set ambw=single,', 'cmdline'))
524
525  " Test the other simple options to make sure they have basic auto-complete,
526  " but don't exhaustively validate their results.
527  call assert_equal('single', getcompletion('set ambw=', 'cmdline')[0])
528  call assert_match('light\|dark', getcompletion('set bg=', 'cmdline')[1])
529  call assert_equal('indent,eol,start', getcompletion('set backspace=', 'cmdline')[0])
530  call assert_equal('yes', getcompletion('set backupcopy=', 'cmdline')[1])
531  call assert_equal('backspace', getcompletion('set belloff=', 'cmdline')[1])
532  call assert_equal('min:', getcompletion('set briopt=', 'cmdline')[1])
533  if exists('+browsedir')
534    call assert_equal('current', getcompletion('set browsedir=', 'cmdline')[1])
535  endif
536  call assert_equal('unload', getcompletion('set bufhidden=', 'cmdline')[1])
537  "call assert_equal('nowrite', getcompletion('set buftype=', 'cmdline')[1])
538  call assert_equal('help', getcompletion('set buftype=', 'cmdline')[1])
539  call assert_equal('internal', getcompletion('set casemap=', 'cmdline')[1])
540  if exists('+clipboard')
541    " call assert_match('unnamed', getcompletion('set clipboard=', 'cmdline')[1])
542    call assert_match('unnamed', getcompletion('set clipboard=', 'cmdline')[0])
543  endif
544  call assert_equal('.', getcompletion('set complete=', 'cmdline')[1])
545  call assert_equal('fuzzy', getcompletion('set completeopt=', 'cmdline')[1])
546  " call assert_equal('keyword', getcompletion('set completefuzzycollect=', 'cmdline')[0])
547  if exists('+completeslash')
548    call assert_equal('backslash', getcompletion('set completeslash=', 'cmdline')[1])
549  endif
550  if exists('+cryptmethod')
551    call assert_equal('zip', getcompletion('set cryptmethod=', 'cmdline')[1])
552  endif
553  if exists('+cursorlineopt')
554    call assert_equal('line', getcompletion('set cursorlineopt=', 'cmdline')[1])
555  endif
556  call assert_equal('throw', getcompletion('set debug=', 'cmdline')[1])
557  call assert_equal('ver', getcompletion('set eadirection=', 'cmdline')[1])
558  call assert_equal('mac', getcompletion('set fileformat=', 'cmdline')[2])
559  if exists('+foldclose')
560    call assert_equal('all', getcompletion('set foldclose=', 'cmdline')[0])
561  endif
562  if exists('+foldmethod')
563    call assert_equal('expr', getcompletion('set foldmethod=', 'cmdline')[1])
564  endif
565  if exists('+foldopen')
566    call assert_equal('all', getcompletion('set foldopen=', 'cmdline')[1])
567  endif
568  call assert_equal('stack', getcompletion('set jumpoptions=', 'cmdline')[0])
569  call assert_equal('stopsel', getcompletion('set keymodel=', 'cmdline')[1])
570  call assert_equal('expr:1', getcompletion('set lispoptions=', 'cmdline')[1])
571  call assert_match('popup', getcompletion('set mousemodel=', 'cmdline')[2])
572  call assert_equal('bin', getcompletion('set nrformats=', 'cmdline')[1])
573  if exists('+rightleftcmd')
574    call assert_equal('search', getcompletion('set rightleftcmd=', 'cmdline')[0])
575  endif
576  call assert_equal('ver', getcompletion('set scrollopt=', 'cmdline')[1])
577  call assert_equal('exclusive', getcompletion('set selection=', 'cmdline')[1])
578  call assert_equal('key', getcompletion('set selectmode=', 'cmdline')[1])
579  if exists('+ssop')
580    call assert_equal('buffers', getcompletion('set ssop=', 'cmdline')[1])
581  endif
582  call assert_equal('statusline', getcompletion('set showcmdloc=', 'cmdline')[1])
583  if exists('+signcolumn')
584    call assert_equal('yes', getcompletion('set signcolumn=', 'cmdline')[1])
585  endif
586  if exists('+spelloptions')
587    call assert_equal('camel', getcompletion('set spelloptions=', 'cmdline')[0])
588  endif
589  if exists('+spellsuggest')
590    call assert_equal('best', getcompletion('set spellsuggest+=', 'cmdline')[0])
591  endif
592  call assert_equal('screen', getcompletion('set splitkeep=', 'cmdline')[1])
593  " call assert_equal('sync', getcompletion('set swapsync=', 'cmdline')[1])
594  call assert_equal('usetab', getcompletion('set switchbuf=', 'cmdline')[1])
595  call assert_equal('ignore', getcompletion('set tagcase=', 'cmdline')[1])
596  if exists('+tabclose')
597    call assert_equal('left uselast', join(sort(getcompletion('set tabclose=', 'cmdline'))), ' ')
598  endif
599  if exists('+termwintype')
600    call assert_equal('conpty', getcompletion('set termwintype=', 'cmdline')[1])
601  endif
602  if exists('+toolbar')
603    call assert_equal('text', getcompletion('set toolbar=', 'cmdline')[1])
604  endif
605  if exists('+tbis')
606    call assert_equal('medium', getcompletion('set tbis=', 'cmdline')[2])
607  endif
608  if exists('+ttymouse')
609    set ttymouse=
610    call assert_equal('xterm2', getcompletion('set ttymouse=', 'cmdline')[1])
611    set ttymouse&
612  endif
613  call assert_equal('insert', getcompletion('set virtualedit=', 'cmdline')[1])
614  call assert_equal('longest', getcompletion('set wildmode=', 'cmdline')[1])
615  call assert_equal('full', getcompletion('set wildmode=list,longest:', 'cmdline')[0])
616  call assert_equal('tagfile', getcompletion('set wildoptions=', 'cmdline')[1])
617  if exists('+winaltkeys')
618    call assert_equal('yes', getcompletion('set winaltkeys=', 'cmdline')[1])
619  endif
620
621  " Other string options that queries the system rather than fixed enum names
622  call assert_equal(['all', 'BufAdd'], getcompletion('set eventignore=', 'cmdline')[0:1])
623  call assert_equal(['-BufAdd', '-BufCreate'], getcompletion('set eventignore=all,-', 'cmdline')[0:1])
624  call assert_equal(['WinLeave', 'WinResized', 'WinScrolled'], getcompletion('set eiw=', 'cmdline')[-3:-1])
625  call assert_equal('latin1', getcompletion('set fileencodings=', 'cmdline')[1])
626  " call assert_equal('top', getcompletion('set printoptions=', 'cmdline')[0])
627  " call assert_equal('SpecialKey', getcompletion('set wincolor=', 'cmdline')[0])
628
629  call assert_equal('eol', getcompletion('set listchars+=', 'cmdline')[0])
630  call assert_equal(['multispace', 'leadmultispace'], getcompletion('set listchars+=', 'cmdline')[-2:])
631  call assert_equal(['tab', 'leadtab'], getcompletion('set listchars+=', 'cmdline')[5:6])
632  call assert_equal('eol', getcompletion('setl listchars+=', 'cmdline')[0])
633  call assert_equal(['tab', 'leadtab'], getcompletion('setl listchars+=', 'cmdline')[5:6])
634  call assert_equal(['multispace', 'leadmultispace'], getcompletion('setl listchars+=', 'cmdline')[-2:])
635  call assert_equal('stl', getcompletion('set fillchars+=', 'cmdline')[0])
636  call assert_equal('stl', getcompletion('setl fillchars+=', 'cmdline')[0])
637
638  "
639  " Unique string options below
640  "
641
642  " keyprotocol: only auto-complete when after ':' with known protocol types
643  " call assert_equal([&keyprotocol], getcompletion('set keyprotocol=', 'cmdline'))
644  " call feedkeys(":set keyprotocol+=someterm:m\<Tab>\<C-B>\"\<CR>", 'xt')
645  " call assert_equal('"set keyprotocol+=someterm:mok2', @:)
646  " set keyprotocol&
647
648  " previewpopup / completepopup
649  " call assert_equal('height:', getcompletion('set previewpopup=', 'cmdline')[0])
650  " call assert_equal('EndOfBuffer', getcompletion('set previewpopup=highlight:End*Buffer', 'cmdline')[0])
651  " call feedkeys(":set previewpopup+=border:\<Tab>\<C-B>\"\<CR>", 'xt')
652  " call assert_equal('"set previewpopup+=border:on', @:)
653  " call feedkeys(":set completepopup=height:10,align:\<Tab>\<C-B>\"\<CR>", 'xt')
654  " call assert_equal('"set completepopup=height:10,align:item', @:)
655  " call assert_equal([], getcompletion('set completepopup=bogusname:', 'cmdline'))
656  " set previewpopup& completepopup&
657
658  " diffopt: special handling of algorithm:<alg_list> and inline:<inline_type>
659  call assert_equal('filler', getcompletion('set diffopt+=', 'cmdline')[0])
660  call assert_equal([], getcompletion('set diffopt+=iblank,foldcolumn:', 'cmdline'))
661  call assert_equal('patience', getcompletion('set diffopt+=iblank,algorithm:pat*', 'cmdline')[0])
662  call assert_equal('char', getcompletion('set diffopt+=iwhite,inline:ch*', 'cmdline')[0])
663
664  " highlight: special parsing, including auto-completing highlight groups
665  " after ':'
666  " call assert_equal([&hl, '8'], getcompletion('set hl=', 'cmdline')[0:1])
667  " call assert_equal('8', getcompletion('set hl+=', 'cmdline')[0])
668  " call assert_equal(['8:', '8b', '8i'], getcompletion('set hl+=8', 'cmdline')[0:2])
669  " call assert_equal('8bi', getcompletion('set hl+=8b', 'cmdline')[0])
670  " call assert_equal('NonText', getcompletion('set hl+=8:No*ext', 'cmdline')[0])
671  " If all the display modes are used up we should be suggesting nothing. Make
672  " a hl typed option with all the modes which will look like '8bi-nrsuc2d=t',
673  " and make sure nothing is suggested from that.
674  " let hl_display_modes = join(
675  "       \ filter(map(getcompletion('set hl+=8', 'cmdline'),
676  "       \            {idx, val -> val[1]}),
677  "       \        {idx, val -> val != ':'}),
678  "       \ '')
679  " call assert_equal([], getcompletion('set hl+=8'..hl_display_modes, 'cmdline'))
680  " Test completion in middle of the line
681  " call feedkeys(":set hl=8b i\<Left>\<Left>\<Tab>\<C-B>\"\<CR>", 'xt')
682  " call assert_equal("\"set hl=8bi i", @:)
683
684  " messagesopt
685  call assert_equal(['history:', 'hit-enter', 'maxheight:', 'pager:', 'progress:', 'timeout:', 'wait:'],
686        \ getcompletion('set messagesopt+=', 'cmdline')->sort())
687
688  "
689  " Test flag lists
690  "
691
692  " Test set=. Show the original value if nothing is typed after '='.
693  " Otherwise, the list should avoid showing what's already typed.
694  set mouse=v
695  call assert_equal(['v','a','n','i','c','h','r'], getcompletion('set mouse=', 'cmdline'))
696  set mouse=nvi
697  call assert_equal(['nvi','a','n','v','i','c','h','r'], getcompletion('set mouse=', 'cmdline'))
698  call assert_equal(['a','v','i','c','r'], getcompletion('set mouse=hn', 'cmdline'))
699
700  " Test set+=. Never show original value, and it also tries to avoid listing
701  " flags that's already in the option value.
702  call assert_equal(['a','c','h','r'], getcompletion('set mouse+=', 'cmdline'))
703  call assert_equal(['a','c','r'], getcompletion('set mouse+=hn', 'cmdline'))
704  call assert_equal([], getcompletion('set mouse+=acrhn', 'cmdline'))
705
706  " Test that the position of the expansion is correct (even if there are
707  " additional values after the current cursor)
708  call feedkeys(":set mouse=hn\<Left>\<Tab>\<C-B>\"\<CR>", 'xt')
709  call assert_equal('"set mouse=han', @:)
710  set mouse&
711
712  " Test that other flag list options have auto-complete, but don't
713  " exhaustively validate their results.
714  if exists('+concealcursor')
715    call assert_equal('n', getcompletion('set cocu=', 'cmdline')[0])
716  endif
717  call assert_equal('a', getcompletion('set cpo=', 'cmdline')[1])
718  call assert_equal('t', getcompletion('set fo=', 'cmdline')[1])
719  if exists('+guioptions')
720    call assert_equal('!', getcompletion('set go=', 'cmdline')[1])
721  endif
722  call assert_equal('r', getcompletion('set shortmess=', 'cmdline')[1])
723  call assert_equal('b', getcompletion('set whichwrap=', 'cmdline')[1])
724
725  "
726  "Test set-=
727  "
728
729  " Normal single-value option just shows the existing value
730  set ambiwidth=double
731  call assert_equal(['double'], getcompletion('set ambw-=', 'cmdline'))
732  set ambiwidth&
733
734  " Works on numbers and term options as well
735  call assert_equal([string(&laststatus)], getcompletion('set laststatus-=', 'cmdline'))
736  set t_Ce=testCe
737  " call assert_equal(['testCe'], getcompletion('set t_Ce-=', 'cmdline'))
738  set t_Ce&
739
740  " Comma-separated lists should present each option
741  set diffopt=context:123,,,,,iblank,iwhiteall
742  call assert_equal(['context:123', 'iblank', 'iwhiteall'], getcompletion('set diffopt-=', 'cmdline'))
743  call assert_equal(['context:123', 'iblank'], getcompletion('set diffopt-=*n*', 'cmdline'))
744  call assert_equal(['iblank', 'iwhiteall'], getcompletion('set diffopt-=i', 'cmdline'))
745  " Don't present more than one option as it doesn't make sense in set-=
746  call assert_equal([], getcompletion('set diffopt-=iblank,', 'cmdline'))
747  " Test empty option
748  set diffopt=
749  call assert_equal([], getcompletion('set diffopt-=', 'cmdline'))
750  " Test all possible values
751  call assert_equal(['filler', 'anchor', 'context:', 'iblank', 'icase', 'iwhite', 'iwhiteall', 'iwhiteeol', 'horizontal',
752        \ 'vertical', 'closeoff', 'hiddenoff', 'foldcolumn:', 'followwrap', 'internal', 'indent-heuristic', 'algorithm:', 'inline:', 'linematch:'],
753        \ getcompletion('set diffopt=', 'cmdline'))
754  set diffopt&
755
756  " Test escaping output
757  call assert_equal('vert:\|', getcompletion('set fillchars-=', 'cmdline')[0])
758
759  " Test files with commas in name are being parsed and escaped properly
760  set path=has\\\ space,file\\,with\\,comma,normal_file
761  if exists('+completeslash')
762    call assert_equal(['has\\\ space', 'file\,with\,comma', 'normal_file'], getcompletion('set path-=', 'cmdline'))
763  else
764    call assert_equal(['has\\\ space', 'file\\,with\\,comma', 'normal_file'], getcompletion('set path-=', 'cmdline'))
765  endif
766  set path&
767
768  " Flag list should present orig value, then individual flags
769  set mouse=v
770  call assert_equal(['v'], getcompletion('set mouse-=', 'cmdline'))
771  set mouse=avn
772  call assert_equal(['avn','a','v','n'], getcompletion('set mouse-=', 'cmdline'))
773  " Don't auto-complete when we have at least one flags already
774  call assert_equal([], getcompletion('set mouse-=n', 'cmdline'))
775  " Test empty option
776  set mouse=
777  call assert_equal([], getcompletion('set mouse-=', 'cmdline'))
778  set mouse&
779
780  " 'whichwrap' is an odd case where it's both flag list and comma-separated
781  set ww=b,h
782  call assert_equal(['b','h'], getcompletion('set ww-=', 'cmdline'))
783  set ww&
784endfunc
785
786func Test_set_option_errors()
787  call assert_fails('set scroll=-1', 'E49:')
788  call assert_fails('set backupcopy=', 'E474:')
789  call assert_fails('set regexpengine=3', 'E474:')
790  call assert_fails('set history=10001', 'E474:')
791  call assert_fails('set numberwidth=21', 'E474:')
792  call assert_fails('set colorcolumn=-a', 'E474:')
793  call assert_fails('set colorcolumn=a', 'E474:')
794  call assert_fails('set colorcolumn=1,', 'E474:')
795  call assert_fails('set colorcolumn=1;', 'E474:')
796  call assert_fails('set cmdheight=-1', 'E487:')
797  call assert_fails('set cmdwinheight=-1', 'E487:')
798  if has('conceal')
799    call assert_fails('set conceallevel=-1', 'E487:')
800    call assert_fails('set conceallevel=4', 'E474:')
801  endif
802  call assert_fails('set helpheight=-1', 'E487:')
803  call assert_fails('set history=-1', 'E487:')
804  call assert_fails('set report=-1', 'E487:')
805  call assert_fails('set shiftwidth=-1', 'E487:')
806  call assert_fails('set sidescroll=-1', 'E487:')
807  call assert_fails('set tabstop=-1', 'E487:')
808  call assert_fails('set tabstop=10000', 'E474:')
809  call assert_fails('let &tabstop = 10000', 'E474:')
810  call assert_fails('set tabstop=5500000000', 'E474:')
811  call assert_fails('set textwidth=-1', 'E487:')
812  call assert_fails('set timeoutlen=-1', 'E487:')
813  call assert_fails('set updatecount=-1', 'E487:')
814  call assert_fails('set updatetime=-1', 'E487:')
815  call assert_fails('set winheight=-1', 'E487:')
816  call assert_fails('set tabstop!', 'E488:')
817
818  " Test for setting unknown option errors
819  call assert_fails('set xxx', 'E518:')
820  call assert_fails('setlocal xxx', 'E518:')
821  call assert_fails('setglobal xxx', 'E518:')
822  call assert_fails('set xxx=', 'E518:')
823  call assert_fails('setlocal xxx=', 'E518:')
824  call assert_fails('setglobal xxx=', 'E518:')
825  call assert_fails('set xxx:', 'E518:')
826  call assert_fails('setlocal xxx:', 'E518:')
827  call assert_fails('setglobal xxx:', 'E518:')
828  call assert_fails('set xxx!', 'E518:')
829  call assert_fails('setlocal xxx!', 'E518:')
830  call assert_fails('setglobal xxx!', 'E518:')
831  call assert_fails('set xxx?', 'E518:')
832  call assert_fails('setlocal xxx?', 'E518:')
833  call assert_fails('setglobal xxx?', 'E518:')
834  call assert_fails('set xxx&', 'E518:')
835  call assert_fails('setlocal xxx&', 'E518:')
836  call assert_fails('setglobal xxx&', 'E518:')
837  call assert_fails('set xxx<', 'E518:')
838  call assert_fails('setlocal xxx<', 'E518:')
839  call assert_fails('setglobal xxx<', 'E518:')
840
841  " Test for missing-options errors.
842  " call assert_fails('set autoprint?', 'E519:')
843  " call assert_fails('set beautify?', 'E519:')
844  " call assert_fails('set flash?', 'E519:')
845  " call assert_fails('set graphic?', 'E519:')
846  " call assert_fails('set hardtabs?', 'E519:')
847  " call assert_fails('set mesg?', 'E519:')
848  " call assert_fails('set novice?', 'E519:')
849  " call assert_fails('set open?', 'E519:')
850  " call assert_fails('set optimize?', 'E519:')
851  " call assert_fails('set redraw?', 'E519:')
852  " call assert_fails('set slowopen?', 'E519:')
853  " call assert_fails('set sourceany?', 'E519:')
854  " call assert_fails('set w300?', 'E519:')
855  " call assert_fails('set w1200?', 'E519:')
856  " call assert_fails('set w9600?', 'E519:')
857
858  call assert_fails('set undolevels=x', 'E521:')
859  call assert_fails('set tabstop=', 'E521:')
860  call assert_fails('set comments=-', 'E524:')
861  call assert_fails('set comments=a', 'E525:')
862  call assert_fails('set foldmarker=x', 'E536:')
863  call assert_fails('set commentstring=x', 'E537:')
864  call assert_fails('let &commentstring = "x"', 'E537:')
865  call assert_fails('set complete=x', 'E539:')
866
867  " Test for 'statusline' errors
868  call assert_fails('set statusline=%^', 'E539:')  " Nvim: supports %$
869  call assert_fails('set statusline=%{', 'E540:')
870  call assert_fails('set statusline=%{%', 'E540:')
871  call assert_fails('set statusline=%{%}', 'E539:')
872  call assert_fails('set statusline=%(', 'E542:')
873  call assert_fails('set statusline=%)', 'E542:')
874
875  " Test for 'tabline' errors
876  call assert_fails('set tabline=%^', 'E539:')  " Nvim: supports %$
877  call assert_fails('set tabline=%{', 'E540:')
878  call assert_fails('set tabline=%{%', 'E540:')
879  call assert_fails('set tabline=%{%}', 'E539:')
880  call assert_fails('set tabline=%(', 'E542:')
881  call assert_fails('set tabline=%)', 'E542:')
882
883  " Test for 'rulerformat' errors
884  call assert_fails('set rulerformat=%-', 'E539:')
885  call assert_fails('set rulerformat=%(', 'E542:')
886  call assert_fails('set rulerformat=%15(%%', 'E542:')
887
888  if has('cursorshape')
889    " This invalid value for 'guicursor' used to cause Vim to crash.
890    call assert_fails('set guicursor=i-ci,r-cr:h', 'E545:')
891    call assert_fails('set guicursor=i-ci', 'E545:')
892    call assert_fails('set guicursor=x', 'E545:')
893    call assert_fails('set guicursor=x:', 'E546:')
894    call assert_fails('set guicursor=r-cr:horx', 'E548:')
895    call assert_fails('set guicursor=r-cr:hor0', 'E549:')
896  endif
897
898  if has('mouseshape')
899    call assert_fails('se mouseshape=i-r:x', 'E547:')
900  endif
901
902  " Test for 'backupext' and 'patchmode' set to the same value
903  set backupext=.bak
904  set patchmode=.patch
905  call assert_fails('set patchmode=.bak', 'E589:')
906  call assert_equal('.patch', &patchmode)
907  call assert_fails('set backupext=.patch', 'E589:')
908  call assert_equal('.bak', &backupext)
909  set backupext& patchmode&
910
911  " 'winheight' cannot be smaller than 'winminheight'
912  call assert_fails('set winminheight=10 winheight=9', 'E591:')
913  set winminheight& winheight&
914  set winheight=10 winminheight=10
915  call assert_fails('set winheight=9', 'E591:')
916  set winminheight& winheight&
917
918  " 'winwidth' cannot be smaller than 'winminwidth'
919  call assert_fails('set winminwidth=10 winwidth=9', 'E592:')
920  set winminwidth& winwidth&
921  call assert_fails('set winwidth=9 winminwidth=10', 'E592:')
922  set winwidth& winminwidth&
923
924  call assert_fails("set showbreak=\x01", 'E595:')
925  " call assert_fails('set t_foo=', 'E846:')
926  call assert_fails('set tabstop??', 'E488:')
927  call assert_fails('set wrapscan!!', 'E488:')
928  call assert_fails('set tabstop&&', 'E488:')
929  call assert_fails('set wrapscan<<', 'E488:')
930  call assert_fails('set wrapscan=1', 'E474:')
931  call assert_fails('set autoindent@', 'E488:')
932  call assert_fails('set wildchar=<abc>', 'E474:')
933  call assert_fails('set cmdheight=1a', 'E521:')
934  call assert_fails('set invcmdheight', 'E474:')
935  if has('python') || has('python3')
936    call assert_fails('set pyxversion=6', 'E474:')
937  endif
938  call assert_fails("let &tabstop='ab'", ['E521:', 'E521:'])
939  call assert_fails('set spellcapcheck=%\\(', 'E54:')
940  call assert_fails('set sessionoptions=curdir,sesdir', 'E474:')
941  call assert_fails('set foldmarker={{{,', 'E474:')
942  call assert_fails('set sessionoptions=sesdir,curdir', 'E474:')
943
944  " 'ambiwidth' conflict 'listchars'
945  setlocal listchars=trail:·
946  call assert_fails('set ambiwidth=double', 'E834:')
947  setlocal listchars=trail:-
948  setglobal listchars=trail:·
949  call assert_fails('set ambiwidth=double', 'E834:')
950  set listchars&
951
952  " 'ambiwidth' conflict 'fillchars'
953  setlocal fillchars=stl:·
954  call assert_fails('set ambiwidth=double', 'E835:')
955  setlocal fillchars=stl:-
956  setglobal fillchars=stl:·
957  call assert_fails('set ambiwidth=double', 'E835:')
958  set fillchars&
959
960  call assert_fails('set fileencoding=latin1,utf-8', 'E474:')
961  set nomodifiable
962  call assert_fails('set fileencoding=latin1', 'E21:')
963  set modifiable&
964  " call assert_fails('set t_#-&', 'E522:')
965  call assert_fails('let &formatoptions = "?"', 'E539:')
966  call assert_fails('call setbufvar("", "&formatoptions", "?")', 'E539:')
967
968  " Should raises only one error if passing a wrong variable type.
969  call assert_fails('call setwinvar(0, "&scrolloff", [])', ['E745:', 'E745:'])
970  call assert_fails('call setwinvar(0, "&list", [])', ['E745:', 'E745:'])
971  call assert_fails('call setwinvar(0, "&listchars", [])', ['E730:', 'E730:'])
972  call assert_fails('call setwinvar(0, "&nosuchoption", 0)', ['E355:', 'E355:'])
973  call assert_fails('call setwinvar(0, "&nosuchoption", "")', ['E355:', 'E355:'])
974  call assert_fails('call setwinvar(0, "&nosuchoption", [])', ['E355:', 'E355:'])
975endfunc
976
977func Test_set_encoding()
978  throw 'skipped: Nvim supports ''utf8'' encoding only'
979  let save_encoding = &encoding
980
981  set enc=iso8859-1
982  call assert_equal('latin1', &enc)
983  set enc=iso8859_1
984  call assert_equal('latin1', &enc)
985  set enc=iso-8859-1
986  call assert_equal('latin1', &enc)
987  set enc=iso_8859_1
988  call assert_equal('latin1', &enc)
989  set enc=iso88591
990  call assert_equal('latin1', &enc)
991  set enc=iso8859
992  call assert_equal('latin1', &enc)
993  set enc=iso-8859
994  call assert_equal('latin1', &enc)
995  set enc=iso_8859
996  call assert_equal('latin1', &enc)
997  call assert_fails('set enc=iso8858', 'E474:')
998  call assert_equal('latin1', &enc)
999
1000  let &encoding = save_encoding
1001endfunc
1002
1003func CheckWasSet(name)
1004  let verb_cm = execute('verbose set ' .. a:name .. '?')
1005  call assert_match('Last set from.*test_options.vim', verb_cm)
1006endfunc
1007func CheckWasNotSet(name)
1008  let verb_cm = execute('verbose set ' .. a:name .. '?')
1009  call assert_notmatch('Last set from', verb_cm)
1010endfunc
1011
1012" Must be executed before other tests that set 'term'.
1013func Test_000_term_option_verbose()
1014  throw "Skipped: Nvim does not support setting 'term'"
1015  CheckNotGui
1016
1017  call CheckWasNotSet('t_cm')
1018
1019  let term_save = &term
1020  set term=ansi
1021  call CheckWasSet('t_cm')
1022  let &term = term_save
1023endfunc
1024
1025func Test_copy_context()
1026  setlocal list
1027  call CheckWasSet('list')
1028  split
1029  call CheckWasSet('list')
1030  quit
1031  setlocal nolist
1032
1033  set ai
1034  call CheckWasSet('ai')
1035  set filetype=perl
1036  call CheckWasSet('filetype')
1037  set fo=tcroq
1038  call CheckWasSet('fo')
1039
1040  split Xsomebuf
1041  call CheckWasSet('ai')
1042  call CheckWasNotSet('filetype')
1043  call CheckWasSet('fo')
1044endfunc
1045
1046func Test_set_ttytype()
1047  throw "Skipped: Nvim does not support 'ttytype'"
1048  CheckUnix
1049  CheckNotGui
1050
1051  " Setting 'ttytype' used to cause a double-free when exiting vim and
1052  " when vim is compiled with -DEXITFREE.
1053  set ttytype=ansi
1054  call assert_equal('ansi', &ttytype)
1055  call assert_equal(&ttytype, &term)
1056  set ttytype=xterm
1057  call assert_equal('xterm', &ttytype)
1058  call assert_equal(&ttytype, &term)
1059  try
1060    set ttytype=
1061    call assert_report('set ttytype= did not fail')
1062  catch /E529/
1063  endtry
1064
1065  " Some systems accept any terminal name and return dumb settings,
1066  " check for failure of finding the entry and for missing 'cm' entry.
1067  try
1068    set ttytype=xxx
1069    call assert_report('set ttytype=xxx did not fail')
1070  catch /E522\|E437/
1071  endtry
1072
1073  set ttytype&
1074  call assert_equal(&ttytype, &term)
1075
1076  if has('gui') && !has('gui_running')
1077    call assert_fails('set term=gui', 'E531:')
1078  endif
1079endfunc
1080
1081" Test for :set all
1082func Test_set_all()
1083  set tw=75
1084  set iskeyword=a-z,A-Z
1085  set nosplitbelow
1086  let out = execute('set all')
1087  call assert_match('textwidth=75', out)
1088  call assert_match('iskeyword=a-z,A-Z', out)
1089  call assert_match('nosplitbelow', out)
1090  set tw& iskeyword& splitbelow&
1091endfunc
1092
1093" Test for :set! all
1094func Test_set_all_one_column()
1095  let out_mult = execute('set all')->split("\n")
1096  let out_one = execute('set! all')->split("\n")
1097  call assert_true(len(out_mult) < len(out_one))
1098  call assert_equal(out_one[0], '--- Options ---')
1099  let options = out_one[1:]->mapnew({_, line -> line[2:]})
1100  call assert_equal(sort(copy(options)), options)
1101endfunc
1102
1103func Test_renderoptions()
1104  throw 'skipped: Nvim does not support renderoptions'
1105  " Only do this for Windows Vista and later, fails on Windows XP and earlier.
1106  " Doesn't hurt to do this on a non-Windows system.
1107  if windowsversion() !~ '^[345]\.'
1108    set renderoptions=type:directx
1109    set rop=type:directx
1110  endif
1111endfunc
1112
1113func ResetIndentexpr()
1114  set indentexpr=
1115endfunc
1116
1117func Test_set_indentexpr()
1118  " this was causing usage of freed memory
1119  set indentexpr=ResetIndentexpr()
1120  new
1121  call feedkeys("i\<c-f>", 'x')
1122  call assert_equal('', &indentexpr)
1123  bwipe!
1124endfunc
1125
1126func Test_backupskip()
1127  " Option 'backupskip' may contain several comma-separated path
1128  " specifications if one or more of the environment variables TMPDIR, TMP,
1129  " or TEMP is defined.  To simplify testing, convert the string value into a
1130  " list.
1131  let bsklist = split(&bsk, ',')
1132
1133  if has("mac")
1134    let found = (index(bsklist, '/private/tmp/*') >= 0)
1135    call assert_true(found, '/private/tmp not in option bsk: ' . &bsk)
1136  elseif has("unix")
1137    let found = (index(bsklist, '/tmp/*') >= 0)
1138    call assert_true(found, '/tmp not in option bsk: ' . &bsk)
1139  endif
1140
1141  " If our test platform is Windows, the path(s) in option bsk will use
1142  " backslash for the path separator and the components could be in short
1143  " (8.3) format.  As such, we need to replace the backslashes with forward
1144  " slashes and convert the path components to long format.  The expand()
1145  " function will do this but it cannot handle comma-separated paths.  This is
1146  " why bsk was converted from a string into a list of strings above.
1147  "
1148  " One final complication is that the wildcard "/*" is at the end of each
1149  " path and so expand() might return a list of matching files.  To prevent
1150  " this, we need to remove the wildcard before calling expand() and then
1151  " append it afterwards.
1152  if has('win32')
1153    let item_nbr = 0
1154    while item_nbr < len(bsklist)
1155      let path_spec = bsklist[item_nbr]
1156      let path_spec = strcharpart(path_spec, 0, strlen(path_spec)-2)
1157      let path_spec = substitute(expand(path_spec), '\\', '/', 'g')
1158      let bsklist[item_nbr] = path_spec . '/*'
1159      let item_nbr += 1
1160    endwhile
1161  endif
1162
1163  " Option bsk will also include these environment variables if defined.
1164  " If they're defined, verify they appear in the option value.
1165  for var in  ['$TMPDIR', '$TMP', '$TEMP']
1166    if exists(var)
1167      let varvalue = substitute(expand(var), '\\', '/', 'g')
1168      let varvalue = substitute(varvalue, '/$', '', '')
1169      let varvalue .= '/*'
1170      let found = (index(bsklist, varvalue) >= 0)
1171      call assert_true(found, var . ' (' . varvalue . ') not in option bsk: ' . &bsk)
1172    endif
1173  endfor
1174
1175  " Duplicates from environment variables should be filtered out (option has
1176  " P_NODUP).  Run this in a separate instance and write v:errors in a file,
1177  " so that we see what happens on startup.
1178  let after =<< trim [CODE]
1179      let bsklist = split(&backupskip, ',')
1180      call assert_equal(uniq(copy(bsklist)), bsklist)
1181      call writefile(['errors:'] + v:errors, 'Xtestout')
1182      qall
1183  [CODE]
1184  call writefile(after, 'Xafter', 'D')
1185  " let cmd = GetVimProg() . ' --clean --not-a-term -S Xafter --cmd "set enc=utf8"'
1186  let cmd = GetVimProg() . ' --clean -S Xafter --cmd "set enc=utf8"'
1187
1188  let saveenv = {}
1189  for var in ['TMPDIR', 'TMP', 'TEMP']
1190    let saveenv[var] = getenv(var)
1191    call setenv(var, '/duplicate/path')
1192  endfor
1193
1194  " set $HOME='', so that Vim won't try to read init files
1195  let saveenv['HOME'] = getenv("HOME")
1196  call setenv('HOME', '')
1197  exe 'silent !' . cmd
1198  call assert_equal(['errors:'], readfile('Xtestout'))
1199
1200  " restore environment variables
1201  for var in ['TMPDIR', 'TMP', 'TEMP', 'HOME']
1202    call setenv(var, saveenv[var])
1203  endfor
1204
1205  call delete('Xtestout')
1206
1207  " Duplicates should be filtered out (option has P_NODUP)
1208  let backupskip = &backupskip
1209  set backupskip=
1210  set backupskip+=/test/dir
1211  set backupskip+=/other/dir
1212  set backupskip+=/test/dir
1213  call assert_equal('/test/dir,/other/dir', &backupskip)
1214  let &backupskip = backupskip
1215endfunc
1216
1217func Test_buf_copy_winopt()
1218  set hidden
1219
1220  " Test copy option from current buffer in window
1221  split
1222  enew
1223  setlocal numberwidth=5
1224  wincmd w
1225  call assert_equal(4,&numberwidth)
1226  bnext
1227  call assert_equal(5,&numberwidth)
1228  bw!
1229  call assert_equal(4,&numberwidth)
1230
1231  " Test copy value from window that used to be display the buffer
1232  split
1233  enew
1234  setlocal numberwidth=6
1235  bnext
1236  wincmd w
1237  call assert_equal(4,&numberwidth)
1238  bnext
1239  call assert_equal(6,&numberwidth)
1240  bw!
1241
1242  " Test that if buffer is current, don't use the stale cached value
1243  " from the last time the buffer was displayed.
1244  split
1245  enew
1246  setlocal numberwidth=7
1247  bnext
1248  bnext
1249  setlocal numberwidth=8
1250  wincmd w
1251  call assert_equal(4,&numberwidth)
1252  bnext
1253  call assert_equal(8,&numberwidth)
1254  bw!
1255
1256  " Test value is not copied if window already has seen the buffer
1257  enew
1258  split
1259  setlocal numberwidth=9
1260  bnext
1261  setlocal numberwidth=10
1262  wincmd w
1263  call assert_equal(4,&numberwidth)
1264  bnext
1265  call assert_equal(4,&numberwidth)
1266  bw!
1267
1268  set hidden&
1269endfunc
1270
1271func Test_split_copy_options()
1272  let values = [
1273    \['cursorbind', 1, 0],
1274    \['fillchars', '"vert:-"', '"' .. &fillchars .. '"'],
1275    \['list', 1, 0],
1276    \['listchars', '"space:-"', '"' .. &listchars .. '"'],
1277    \['number', 1, 0],
1278    \['relativenumber', 1, 0],
1279    \['scrollbind', 1, 0],
1280    \['smoothscroll', 1, 0],
1281    \['virtualedit', '"block"', '"' .. &virtualedit .. '"'],
1282    "\ ['wincolor', '"Search"', '"' .. &wincolor .. '"'],
1283    \['wrap', 0, 1],
1284  \]
1285  if has('linebreak')
1286    let values += [
1287      \['breakindent', 1, 0],
1288      \['breakindentopt', '"min:5"', '"' .. &breakindentopt .. '"'],
1289      \['linebreak', 1, 0],
1290      \['numberwidth', 7, 4],
1291      \['showbreak', '"++"', '"' .. &showbreak .. '"'],
1292    \]
1293  endif
1294  if has('rightleft')
1295    let values += [
1296      \['rightleft', 1, 0],
1297      \['rightleftcmd', '"search"', '"' .. &rightleftcmd .. '"'],
1298    \]
1299  endif
1300  if has('statusline')
1301    let values += [
1302      \['statusline', '"---%f---"', '"' .. &statusline .. '"'],
1303    \]
1304  endif
1305  if has('spell')
1306    let values += [
1307      \['spell', 1, 0],
1308    \]
1309  endif
1310  if has('syntax')
1311    let values += [
1312      \['cursorcolumn', 1, 0],
1313      \['cursorline', 1, 0],
1314      \['cursorlineopt', '"screenline"', '"' .. &cursorlineopt .. '"'],
1315      \['colorcolumn', '"+1"', '"' .. &colorcolumn .. '"'],
1316    \]
1317  endif
1318  if has('diff')
1319    let values += [
1320      \['diff', 1, 0],
1321    \]
1322  endif
1323  if has('conceal')
1324    let values += [
1325      \['concealcursor', '"nv"', '"' .. &concealcursor .. '"'],
1326      \['conceallevel', '3', &conceallevel],
1327    \]
1328  endif
1329  if has('terminal')
1330    let values += [
1331      \['termwinkey', '"<C-X>"', '"' .. &termwinkey .. '"'],
1332      \['termwinsize', '"10x20"', '"' .. &termwinsize .. '"'],
1333    \]
1334  endif
1335  if has('folding')
1336    let values += [
1337      \['foldcolumn', '"5"',  &foldcolumn],
1338      \['foldenable', 0, 1],
1339      \['foldexpr', '"2 + 3"', '"' .. &foldexpr .. '"'],
1340      \['foldignore', '"+="', '"' .. &foldignore .. '"'],
1341      \['foldlevel', 4,  &foldlevel],
1342      \['foldmarker', '">>,<<"', '"' .. &foldmarker .. '"'],
1343      \['foldmethod', '"marker"', '"' .. &foldmethod .. '"'],
1344      \['foldminlines', 3,  &foldminlines],
1345      \['foldnestmax', 17,  &foldnestmax],
1346      \['foldtext', '"closed"', '"' .. &foldtext .. '"'],
1347    \]
1348  endif
1349  if has('signs')
1350    let values += [
1351      \['signcolumn', '"number"', '"' .. &signcolumn .. '"'],
1352    \]
1353  endif
1354
1355  " set options to non-default value
1356  for item in values
1357    exe $"let &{item[0]} = {item[1]}"
1358  endfor
1359
1360  " check values are set in new window
1361  split
1362  for item in values
1363    exe $'call assert_equal({item[1]}, &{item[0]}, "{item[0]}")'
1364  endfor
1365
1366  " restore
1367  close
1368  for item in values
1369    exe $"let &{item[0]} = {item[1]}"
1370  endfor
1371endfunc
1372
1373func Test_shortmess_F()
1374  new
1375  call assert_match('\[No Name\]', execute('file'))
1376  set shortmess+=F
1377  call assert_match('\[No Name\]', execute('file'))
1378  call assert_match('^\s*$', execute('file foo'))
1379  call assert_match('foo', execute('file'))
1380  set shortmess-=F
1381  call assert_match('bar', execute('file bar'))
1382  call assert_match('bar', execute('file'))
1383  set shortmess&
1384  bwipe
1385endfunc
1386
1387func Test_shortmess_F2()
1388  e file1
1389  e file2
1390  call assert_match('file1', execute('bn', ''))
1391  call assert_match('file2', execute('bn', ''))
1392  set shortmess+=F
1393  call assert_true(empty(execute('bn', '')))
1394  " call assert_false(test_getvalue('need_fileinfo'))
1395  call assert_true(empty(execute('bn', '')))
1396  " call assert_false(test_getvalue('need_fileinfo'))
1397  set hidden
1398  call assert_true(empty(execute('bn', '')))
1399  " call assert_false(test_getvalue('need_fileinfo'))
1400  call assert_true(empty(execute('bn', '')))
1401  " call assert_false(test_getvalue('need_fileinfo'))
1402  set nohidden
1403  call assert_true(empty(execute('bn', '')))
1404  " call assert_false(test_getvalue('need_fileinfo'))
1405  call assert_true(empty(execute('bn', '')))
1406  " call assert_false(test_getvalue('need_fileinfo'))
1407  set shortmess-=F  " Accommodate Nvim default.
1408  call assert_match('file1', execute('bn', ''))
1409  call assert_match('file2', execute('bn', ''))
1410  bwipe
1411  bwipe
1412  " call assert_fails('call test_getvalue("abc")', 'E475:')
1413endfunc
1414
1415func Test_shortmess_F3()
1416  call writefile(['foo'], 'X_dummy', 'D')
1417
1418  set hidden
1419  set autoread
1420  e X_dummy
1421  e Xotherfile
1422  call assert_equal(['foo'], getbufline('X_dummy', 1, '$'))
1423  set shortmess+=F
1424  echo ''
1425
1426  if has('nanotime')
1427    sleep 10m
1428  else
1429    sleep 3
1430  endif
1431  call writefile(['bar'], 'X_dummy')
1432  bprev
1433  call assert_equal('', Screenline(&lines))
1434  call assert_equal(['bar'], getbufline('X_dummy', 1, '$'))
1435
1436  if has('nanotime')
1437    sleep 10m
1438  else
1439    sleep 3
1440  endif
1441  call writefile(['baz'], 'X_dummy')
1442  checktime
1443  call assert_equal('', Screenline(&lines))
1444  call assert_equal(['baz'], getbufline('X_dummy', 1, '$'))
1445
1446  set shortmess&
1447  set autoread&
1448  set hidden&
1449  bwipe X_dummy
1450  bwipe Xotherfile
1451endfunc
1452
1453func Test_local_scrolloff()
1454  set so=5
1455  set siso=7
1456  split
1457  call assert_equal(5, &so)
1458  setlocal so=3
1459  call assert_equal(3, &so)
1460  wincmd w
1461  call assert_equal(5, &so)
1462  wincmd w
1463  call assert_equal(3, &so)
1464  "setlocal so<
1465  set so<
1466  call assert_equal(5, &so)
1467  setglob so=8
1468  call assert_equal(8, &so)
1469  call assert_equal(-1, &l:so)
1470  setlocal so=0
1471  call assert_equal(0, &so)
1472  setlocal so=-1
1473  call assert_equal(8, &so)
1474
1475  call assert_equal(7, &siso)
1476  setlocal siso=3
1477  call assert_equal(3, &siso)
1478  wincmd w
1479  call assert_equal(7, &siso)
1480  wincmd w
1481  call assert_equal(3, &siso)
1482  "setlocal siso<
1483  set siso<
1484  call assert_equal(7, &siso)
1485  setglob siso=4
1486  call assert_equal(4, &siso)
1487  call assert_equal(-1, &l:siso)
1488  setlocal siso=0
1489  call assert_equal(0, &siso)
1490  setlocal siso=-1
1491  call assert_equal(4, &siso)
1492
1493  close
1494  set so&
1495  set siso&
1496endfunc
1497
1498func Test_local_scrolloffpad()
1499  let save_g_sop = &g:sop
1500  let save_l_sop = &l:sop
1501  set sop=0
1502  call assert_equal(0, &g:sop)
1503  call assert_equal(-1, &l:sop)
1504  call assert_equal(0, &sop)
1505  setglobal sop=1
1506  call assert_equal(1, &g:sop)
1507  call assert_equal(1, &sop)
1508  split
1509  call assert_equal(1, &g:sop)
1510  call assert_equal(-1, &l:sop)
1511  call assert_equal(1, &sop)
1512  setlocal sop=0
1513  call assert_equal(0, &l:sop)
1514  call assert_equal(0, &sop)
1515  call assert_equal(1, &g:sop)
1516  wincmd p
1517  call assert_equal(1, &sop)
1518  wincmd p
1519  "setlocal sop<
1520  set sop<
1521  call assert_equal(-1, &l:sop)
1522  call assert_equal(1, &sop)
1523  setlocal sop=2
1524  call assert_equal(2, &l:sop)
1525  call assert_equal(2, &sop)
1526  setlocal sop=-1
1527  call assert_equal(-1, &l:sop)
1528  call assert_equal(1, &sop)  " Uses global value because local is -1
1529  call assert_fails("setlocal sop=-2", 'E474:')
1530  call assert_equal(-1, &l:sop)
1531  call assert_equal(1, &sop)
1532  call assert_fails("setlocal sop=foo", 'E521:')
1533  close
1534  let &g:sop = save_g_sop
1535  let &l:sop = save_l_sop
1536endfunc
1537
1538func Test_writedelay()
1539  CheckFunction reltimefloat
1540
1541  new
1542  call setline(1, 'empty')
1543  " Nvim: 'writedelay' is applied per screen line.
1544  " Create 7 vertical splits first.
1545  vs | vs | vs | vs | vs | vs
1546  redraw
1547  set writedelay=10
1548  let start = reltime()
1549  " call setline(1, repeat('x', 70))
1550  " Nvim: enable 'writedelay' per screen line.
1551  " In each of the 7 vertical splits, 10 screen lines need to be drawn.
1552  set redrawdebug+=line
1553  call setline(1, repeat(['x'], 10))
1554  redraw
1555  let elapsed = reltimefloat(reltime(start))
1556  set writedelay=0
1557  " With 'writedelay' set should take at least 30 * 10 msec
1558  call assert_inrange(30 * 0.01, 999.0, elapsed)
1559
1560  bwipe!
1561endfunc
1562
1563func Test_visualbell()
1564  set belloff=
1565  set visualbell
1566  call assert_beeps('normal 0h')
1567  set novisualbell
1568  set belloff=all
1569endfunc
1570
1571" Test for the 'write' option
1572func Test_write()
1573  new
1574  call setline(1, ['L1'])
1575  set nowrite
1576  call assert_fails('write Xwrfile', 'E142:')
1577  set write
1578  " close swapfile
1579  bw!
1580endfunc
1581
1582" Test for 'buftype' option
1583func Test_buftype()
1584  new
1585  call setline(1, ['L1'])
1586  set buftype=nowrite
1587  call assert_fails('write', 'E382:')
1588
1589  " for val in ['', 'nofile', 'nowrite', 'acwrite', 'quickfix', 'help', 'terminal', 'prompt', 'popup']
1590  for val in ['', 'nofile', 'nowrite', 'acwrite', 'quickfix', 'help', 'prompt']
1591    exe 'set buftype=' .. val
1592    call writefile(['something'], 'XBuftype')
1593    call assert_fails('write XBuftype', 'E13:', 'with buftype=' .. val)
1594  endfor
1595
1596  call delete('XBuftype')
1597  bwipe!
1598endfunc
1599
1600" Test for the 'rightleftcmd' option
1601func Test_rightleftcmd()
1602  CheckFeature rightleft
1603  set rightleft
1604
1605  let g:l = []
1606  func AddPos()
1607    call add(g:l, screencol())
1608    return ''
1609  endfunc
1610  cmap <expr> <F2> AddPos()
1611
1612  set rightleftcmd=
1613  call feedkeys("/\<F2>abc\<Right>\<F2>\<Left>\<Left>\<F2>" ..
1614        \ "\<Right>\<F2>\<Esc>", 'xt')
1615  call assert_equal([2, 5, 3, 4], g:l)
1616
1617  let g:l = []
1618  set rightleftcmd=search
1619  call feedkeys("/\<F2>abc\<Left>\<F2>\<Right>\<Right>\<F2>" ..
1620        \ "\<Left>\<F2>\<Esc>", 'xt')
1621  call assert_equal([&co - 1, &co - 4, &co - 2, &co - 3], g:l)
1622
1623  cunmap <F2>
1624  unlet g:l
1625  set rightleftcmd&
1626  set rightleft&
1627endfunc
1628
1629" Test for the 'debug' option
1630func Test_debug_option()
1631  " redraw to avoid matching previous messages
1632  redraw
1633  set debug=beep
1634  exe "normal \<C-c>"
1635  call assert_equal('Beep!', Screenline(&lines))
1636  call assert_equal('line    4:', Screenline(&lines - 1))
1637  " also check a line above, with a certain window width the colon is there
1638  call assert_match('Test_debug_option:$',
1639        \ Screenline(&lines - 3) .. Screenline(&lines - 2))
1640  set debug&
1641endfunc
1642
1643" Test for the default CDPATH option
1644func Test_opt_default_cdpath()
1645  let after =<< trim [CODE]
1646    call assert_equal(',/path/to/dir1,/path/to/dir2', &cdpath)
1647    call writefile(v:errors, 'Xtestout')
1648    qall
1649  [CODE]
1650  if has('unix')
1651    let $CDPATH='/path/to/dir1:/path/to/dir2'
1652  else
1653    let $CDPATH='/path/to/dir1;/path/to/dir2'
1654  endif
1655  if RunVim([], after, '')
1656    call assert_equal([], readfile('Xtestout'))
1657    call delete('Xtestout')
1658  endif
1659endfunc
1660
1661" Test for setting keycodes using set
1662func Test_opt_set_keycode()
1663  " call assert_fails('set <t_k1=l', 'E474:')
1664  " call assert_fails('set <Home=l', 'E474:')
1665  call assert_fails('set <t_k1=l', 'E518:')
1666  call assert_fails('set <Home=l', 'E518:')
1667  set <t_k9>=abcd
1668  " call assert_equal('abcd', &t_k9)
1669  set <t_k9>&
1670  set <F9>=xyz
1671  " call assert_equal('xyz', &t_k9)
1672  set <t_k9>&
1673endfunc
1674
1675" Test for changing options in a sandbox
1676func Test_opt_sandbox()
1677  for opt in ['backupdir', 'cdpath', 'exrc', 'findfunc']
1678    call assert_fails('sandbox set ' .. opt .. '?', 'E48:')
1679    call assert_fails('sandbox let &' .. opt .. ' = 1', 'E48:')
1680  endfor
1681  call assert_fails('sandbox let &modelineexpr = 1', 'E48:')
1682endfunc
1683
1684" Test for setting string global-local option value
1685func Test_set_string_global_local_option()
1686  setglobal equalprg=gprg
1687  setlocal equalprg=lprg
1688  call assert_equal('gprg', &g:equalprg)
1689  call assert_equal('lprg', &l:equalprg)
1690  call assert_equal('lprg', &equalprg)
1691
1692  " :set {option}< removes the local value, so that the global value will be used.
1693  set equalprg<
1694  call assert_equal('', &l:equalprg)
1695  call assert_equal('gprg', &equalprg)
1696
1697  " :setlocal {option}< set the effective value of {option} to its global value.
1698  setglobal equalprg=gnewprg
1699  setlocal equalprg=lnewprg
1700  setlocal equalprg<
1701  call assert_equal('gnewprg', &l:equalprg)
1702  call assert_equal('gnewprg', &equalprg)
1703
1704  set equalprg&
1705endfunc
1706
1707" Test for setting number global-local option value
1708func Test_set_number_global_local_option()
1709  setglobal scrolloff=10
1710  setlocal scrolloff=12
1711  call assert_equal(10, &g:scrolloff)
1712  call assert_equal(12, &l:scrolloff)
1713  call assert_equal(12, &scrolloff)
1714
1715  " :setlocal {option}< set the effective value of {option} to its global value.
1716  "set scrolloff<
1717  setlocal scrolloff<
1718  call assert_equal(10, &l:scrolloff)
1719  call assert_equal(10, &scrolloff)
1720
1721  " :set {option}< removes the local value, so that the global value will be used.
1722  setglobal scrolloff=15
1723  setlocal scrolloff=18
1724  "setlocal scrolloff<
1725  set scrolloff<
1726  call assert_equal(-1, &l:scrolloff)
1727  call assert_equal(15, &scrolloff)
1728
1729  set scrolloff&
1730endfunc
1731
1732" Test for setting boolean global-local option value
1733func Test_set_boolean_global_local_option()
1734  CheckUnix
1735
1736  setglobal autoread fsync
1737  setlocal noautoread nofsync
1738  call assert_equal(1, &g:autoread)
1739  call assert_equal(0, &l:autoread)
1740  call assert_equal(0, &autoread)
1741  call assert_equal(1, &g:fsync)
1742  call assert_equal(0, &l:fsync)
1743  call assert_equal(0, &fsync)
1744
1745  " :setlocal {option}< set the effective value of {option} to its global value.
1746  "set autoread< fsync<
1747  setlocal autoread< fsync<
1748  call assert_equal(1, &l:autoread)
1749  call assert_equal(1, &autoread)
1750  call assert_equal(1, &l:fsync)
1751  call assert_equal(1, &fsync)
1752
1753  " :set {option}< removes the local value, so that the global value will be used.
1754  setglobal noautoread nofsync
1755  setlocal autoread fsync
1756  "setlocal autoread< fsync<
1757  set autoread< fsync<
1758  call assert_equal(-1, &l:autoread)
1759  call assert_equal(0, &autoread)
1760  call assert_equal(-1, &l:fsync)
1761  call assert_equal(0, &fsync)
1762
1763  set autoread& fsync&
1764endfunc
1765
1766func Test_set_in_sandbox()
1767  " Some boolean options cannot be set in sandbox, some can.
1768  call assert_fails('sandbox set modelineexpr', 'E48:')
1769  sandbox set number
1770  call assert_true(&number)
1771  set number&
1772
1773  " Some boolean options cannot be set in sandbox, some can.
1774  if has('python') || has('python3')
1775    call assert_fails('sandbox set pyxversion=3', 'E48:')
1776  endif
1777  sandbox set tabstop=4
1778  call assert_equal(4, &tabstop)
1779  set tabstop&
1780
1781  " Some string options cannot be set in sandbox, some can.
1782  call assert_fails('sandbox set backupdir=/tmp', 'E48:')
1783  sandbox set filetype=perl
1784  call assert_equal('perl', &filetype)
1785  set filetype&
1786endfunc
1787
1788" Test for setting string option value
1789func Test_set_string_option()
1790  " :set {option}=
1791  set makeprg=
1792  call assert_equal('', &mp)
1793  set makeprg=abc
1794  call assert_equal('abc', &mp)
1795
1796  " :set {option}:
1797  set makeprg:
1798  call assert_equal('', &mp)
1799  set makeprg:abc
1800  call assert_equal('abc', &mp)
1801
1802  " Let string
1803  let &makeprg = ''
1804  call assert_equal('', &mp)
1805  let &makeprg = 'abc'
1806  call assert_equal('abc', &mp)
1807
1808  " Let number converts to string
1809  let &makeprg = 42
1810  call assert_equal('42', &mp)
1811
1812  " Appending
1813  set makeprg=abc
1814  set makeprg+=def
1815  call assert_equal('abcdef', &mp)
1816  set makeprg+=def
1817  call assert_equal('abcdefdef', &mp, ':set+= appends a value even if it already contained')
1818  let &makeprg .= 'gh'
1819  call assert_equal('abcdefdefgh', &mp)
1820  let &makeprg ..= 'ij'
1821  call assert_equal('abcdefdefghij', &mp)
1822
1823  " Removing
1824  set makeprg=abcdefghi
1825  set makeprg-=def
1826  call assert_equal('abcghi', &mp)
1827  set makeprg-=def
1828  call assert_equal('abcghi', &mp, ':set-= does not remove a value if it is not contained')
1829
1830  " Prepending
1831  set makeprg=abc
1832  set makeprg^=def
1833  call assert_equal('defabc', &mp)
1834  set makeprg^=def
1835  call assert_equal('defdefabc', &mp, ':set+= prepends a value even if it already contained')
1836
1837  set makeprg&
1838endfunc
1839
1840" Test for setting string comma-separated list option value
1841func Test_set_string_comma_list_option()
1842  " :set {option}=
1843  set wildignore=
1844  call assert_equal('', &wildignore)
1845  set wildignore=*.png
1846  call assert_equal('*.png', &wildignore)
1847
1848  " :set {option}:
1849  set wildignore:
1850  call assert_equal('', &wildignore)
1851  set wildignore:*.png
1852  call assert_equal('*.png', &wildignore)
1853
1854  " Let string
1855  let &wildignore = ''
1856  call assert_equal('', &wildignore)
1857  let &wildignore = '*.png'
1858  call assert_equal('*.png', &wildignore)
1859
1860  " Let number converts to string
1861  let &wildignore = 42
1862  call assert_equal('42', &wildignore)
1863
1864  " Appending
1865  set wildignore=*.png
1866  set wildignore+=*.jpg
1867  call assert_equal('*.png,*.jpg', &wildignore, ':set+= prepends a comma to append a value')
1868  set wildignore+=*.jpg
1869  call assert_equal('*.png,*.jpg', &wildignore, ':set+= does not append a value if it already contained')
1870  set wildignore+=jpg
1871  call assert_equal('*.png,*.jpg,jpg', &wildignore, ':set+= prepends a comma to append a value if it is not exactly match to item')
1872  let &wildignore .= 'foo'
1873  call assert_equal('*.png,*.jpg,jpgfoo', &wildignore, ':let-& .= appends a value without a comma')
1874  let &wildignore ..= 'bar'
1875  call assert_equal('*.png,*.jpg,jpgfoobar', &wildignore, ':let-& ..= appends a value without a comma')
1876
1877  " Removing
1878  set wildignore=*.png,*.jpg,*.obj
1879  set wildignore-=*.jpg
1880  call assert_equal('*.png,*.obj', &wildignore)
1881  set wildignore-=*.jpg
1882  call assert_equal('*.png,*.obj', &wildignore, ':set-= does not remove a value if it is not contained')
1883  set wildignore-=jpg
1884  call assert_equal('*.png,*.obj', &wildignore, ':set-= does not remove a value if it is not exactly match to item')
1885
1886  " Prepending
1887  set wildignore=*.png
1888  set wildignore^=*.jpg
1889  call assert_equal('*.jpg,*.png', &wildignore)
1890  set wildignore^=*.jpg
1891  call assert_equal('*.jpg,*.png', &wildignore, ':set+= does not prepend a value if it already contained')
1892  set wildignore^=jpg
1893  call assert_equal('jpg,*.jpg,*.png', &wildignore, ':set+= prepend a value if it is not exactly match to item')
1894
1895  set wildignore&
1896endfunc
1897
1898" Test for setting string flags option value
1899func Test_set_string_flags_option()
1900  " :set {option}=
1901  set formatoptions=
1902  call assert_equal('', &fo)
1903  set formatoptions=abc
1904  call assert_equal('abc', &fo)
1905
1906  " :set {option}:
1907  set formatoptions:
1908  call assert_equal('', &fo)
1909  set formatoptions:abc
1910  call assert_equal('abc', &fo)
1911
1912  " Let string
1913  let &formatoptions = ''
1914  call assert_equal('', &fo)
1915  let &formatoptions = 'abc'
1916  call assert_equal('abc', &fo)
1917
1918  " Let number converts to string
1919  let &formatoptions = 12
1920  call assert_equal('12', &fo)
1921
1922  " Appending
1923  set formatoptions=abc
1924  set formatoptions+=pqr
1925  call assert_equal('abcpqr', &fo)
1926  set formatoptions+=pqr
1927  call assert_equal('abcpqr', &fo, ':set+= does not append a value if it already contained')
1928  let &formatoptions .= 'r'
1929  call assert_equal('abcpqrr', &fo, ':let-& .= appends a value even if it already contained')
1930  let &formatoptions ..= 'r'
1931  call assert_equal('abcpqrrr', &fo, ':let-& ..= appends a value even if it already contained')
1932
1933  " Removing
1934  set formatoptions=abcpqr
1935  set formatoptions-=cp
1936  call assert_equal('abqr', &fo)
1937  set formatoptions-=cp
1938  call assert_equal('abqr', &fo, ':set-= does not remove a value if it is not contained')
1939  set formatoptions-=ar
1940  call assert_equal('abqr', &fo, ':set-= does not remove a value if it is not exactly match')
1941
1942  " Prepending
1943  set formatoptions=abc
1944  set formatoptions^=pqr
1945  call assert_equal('pqrabc', &fo)
1946  set formatoptions^=qr
1947  call assert_equal('pqrabc', &fo, ':set+= does not prepend a value if it already contained')
1948
1949  set formatoptions&
1950endfunc
1951
1952" Test for setting number option value
1953func Test_set_number_option()
1954  " :set {option}=
1955  set scrolljump=5
1956  call assert_equal(5, &sj)
1957  set scrolljump=-3
1958  call assert_equal(-3, &sj)
1959
1960  " :set {option}:
1961  set scrolljump:7
1962  call assert_equal(7, &sj)
1963  set scrolljump:-5
1964  call assert_equal(-5, &sj)
1965
1966  " Set hex
1967  set scrolljump=0x10
1968  call assert_equal(16, &sj)
1969  set scrolljump=-0x10
1970  call assert_equal(-16, &sj)
1971  set scrolljump=0X12
1972  call assert_equal(18, &sj)
1973  set scrolljump=-0X12
1974  call assert_equal(-18, &sj)
1975
1976  " Set octal
1977  set scrolljump=010
1978  call assert_equal(8, &sj)
1979  set scrolljump=-010
1980  call assert_equal(-8, &sj)
1981  set scrolljump=0o12
1982  call assert_equal(10, &sj)
1983  set scrolljump=-0o12
1984  call assert_equal(-10, &sj)
1985  set scrolljump=0O15
1986  call assert_equal(13, &sj)
1987  set scrolljump=-0O15
1988  call assert_equal(-13, &sj)
1989
1990  " Let number
1991  let &scrolljump = 4
1992  call assert_equal(4, &sj)
1993  let &scrolljump = -6
1994  call assert_equal(-6, &sj)
1995
1996  " Let numeric string converts to number
1997  let &scrolljump = '7'
1998  call assert_equal(7, &sj)
1999  let &scrolljump = '-9'
2000  call assert_equal(-9, &sj)
2001
2002  " Incrementing
2003  set shiftwidth=4
2004  set sw+=2
2005  call assert_equal(6, &sw)
2006  let &shiftwidth += 2
2007  call assert_equal(8, &sw)
2008
2009  " Decrementing
2010  set shiftwidth=6
2011  set sw-=2
2012  call assert_equal(4, &sw)
2013  let &shiftwidth -= 2
2014  call assert_equal(2, &sw)
2015
2016  " Multiplying
2017  set shiftwidth=4
2018  set sw^=2
2019  call assert_equal(8, &sw)
2020  let &shiftwidth *= 2
2021  call assert_equal(16, &sw)
2022
2023  set scrolljump&
2024  set shiftwidth&
2025endfunc
2026
2027" Test for setting boolean option value
2028func Test_set_boolean_option()
2029  set number&
2030
2031  " :set {option}
2032  set number
2033  call assert_equal(1, &nu)
2034
2035  " :set no{option}
2036  set nonu
2037  call assert_equal(0, &nu)
2038
2039  " :set {option}!
2040  set number!
2041  call assert_equal(1, &nu)
2042  set number!
2043  call assert_equal(0, &nu)
2044
2045  " :set inv{option}
2046  set invnumber
2047  call assert_equal(1, &nu)
2048  set invnumber
2049  call assert_equal(0, &nu)
2050
2051  " Let number
2052  let &number = 1
2053  call assert_equal(1, &nu)
2054  let &number = 0
2055  call assert_equal(0, &nu)
2056
2057  " Let numeric string converts to number
2058  let &number = '1'
2059  call assert_equal(1, &nu)
2060  let &number = '0'
2061  call assert_equal(0, &nu)
2062
2063  " Let v:true and v:false
2064  let &nu = v:true
2065  call assert_equal(1, &nu)
2066  let &nu = v:false
2067  call assert_equal(0, &nu)
2068
2069  set number&
2070endfunc
2071
2072" Test for setting string option errors
2073func Test_set_string_option_errors()
2074  " :set no{option}
2075  call assert_fails('set nomakeprg', 'E474:')
2076  call assert_fails('setlocal nomakeprg', 'E474:')
2077  call assert_fails('setglobal nomakeprg', 'E474:')
2078
2079  " :set inv{option}
2080  call assert_fails('set invmakeprg', 'E474:')
2081  call assert_fails('setlocal invmakeprg', 'E474:')
2082  call assert_fails('setglobal invmakeprg', 'E474:')
2083
2084  " :set {option}!
2085  call assert_fails('set makeprg!', 'E488:')
2086  call assert_fails('setlocal makeprg!', 'E488:')
2087  call assert_fails('setglobal makeprg!', 'E488:')
2088
2089  " Invalid trailing chars
2090  call assert_fails('set makeprg??', 'E488:')
2091  call assert_fails('setlocal makeprg??', 'E488:')
2092  call assert_fails('setglobal makeprg??', 'E488:')
2093  call assert_fails('set makeprg&&', 'E488:')
2094  call assert_fails('setlocal makeprg&&', 'E488:')
2095  call assert_fails('setglobal makeprg&&', 'E488:')
2096  call assert_fails('set makeprg<<', 'E488:')
2097  call assert_fails('setlocal makeprg<<', 'E488:')
2098  call assert_fails('setglobal makeprg<<', 'E488:')
2099  call assert_fails('set makeprg@', 'E488:')
2100  call assert_fails('setlocal makeprg@', 'E488:')
2101  call assert_fails('setglobal makeprg@', 'E488:')
2102
2103  " Invalid type
2104  call assert_fails("let &makeprg = ['xxx']", 'E730:')
2105endfunc
2106
2107" Test for setting number option errors
2108func Test_set_number_option_errors()
2109  " :set no{option}
2110  call assert_fails('set notabstop', 'E474:')
2111  call assert_fails('setlocal notabstop', 'E474:')
2112  call assert_fails('setglobal notabstop', 'E474:')
2113
2114  " :set inv{option}
2115  call assert_fails('set invtabstop', 'E474:')
2116  call assert_fails('setlocal invtabstop', 'E474:')
2117  call assert_fails('setglobal invtabstop', 'E474:')
2118
2119  " :set {option}!
2120  call assert_fails('set tabstop!', 'E488:')
2121  call assert_fails('setlocal tabstop!', 'E488:')
2122  call assert_fails('setglobal tabstop!', 'E488:')
2123
2124  " Invalid trailing chars
2125  call assert_fails('set tabstop??', 'E488:')
2126  call assert_fails('setlocal tabstop??', 'E488:')
2127  call assert_fails('setglobal tabstop??', 'E488:')
2128  call assert_fails('set tabstop&&', 'E488:')
2129  call assert_fails('setlocal tabstop&&', 'E488:')
2130  call assert_fails('setglobal tabstop&&', 'E488:')
2131  call assert_fails('set tabstop<<', 'E488:')
2132  call assert_fails('setlocal tabstop<<', 'E488:')
2133  call assert_fails('setglobal tabstop<<', 'E488:')
2134  call assert_fails('set tabstop@', 'E488:')
2135  call assert_fails('setlocal tabstop@', 'E488:')
2136  call assert_fails('setglobal tabstop@', 'E488:')
2137
2138  " Not a number
2139  call assert_fails('set tabstop=', 'E521:')
2140  call assert_fails('setlocal tabstop=', 'E521:')
2141  call assert_fails('setglobal tabstop=', 'E521:')
2142  call assert_fails('set tabstop=x', 'E521:')
2143  call assert_fails('setlocal tabstop=x', 'E521:')
2144  call assert_fails('setglobal tabstop=x', 'E521:')
2145  call assert_fails('set tabstop=1x', 'E521:')
2146  call assert_fails('setlocal tabstop=1x', 'E521:')
2147  call assert_fails('setglobal tabstop=1x', 'E521:')
2148  call assert_fails('set tabstop=-x', 'E521:')
2149  call assert_fails('setlocal tabstop=-x', 'E521:')
2150  call assert_fails('setglobal tabstop=-x', 'E521:')
2151  call assert_fails('set tabstop=0x', 'E521:')
2152  call assert_fails('setlocal tabstop=0x', 'E521:')
2153  call assert_fails('setglobal tabstop=0x', 'E521:')
2154  call assert_fails('set tabstop=0o', 'E521:')
2155  call assert_fails('setlocal tabstop=0o', 'E521:')
2156  call assert_fails('setglobal tabstop=0o', 'E521:')
2157  call assert_fails("let &tabstop = 'x'", 'E521:')
2158  call assert_fails("let &g:tabstop = 'x'", 'E521:')
2159  call assert_fails("let &l:tabstop = 'x'", 'E521:')
2160
2161  " Invalid type
2162  call assert_fails("let &tabstop = 'xxx'", 'E521:')
2163endfunc
2164
2165" Test for setting boolean option errors
2166func Test_set_boolean_option_errors()
2167  " :set {option}=
2168  call assert_fails('set number=', 'E474:')
2169  call assert_fails('setlocal number=', 'E474:')
2170  call assert_fails('setglobal number=', 'E474:')
2171  call assert_fails('set number=1', 'E474:')
2172  call assert_fails('setlocal number=1', 'E474:')
2173  call assert_fails('setglobal number=1', 'E474:')
2174
2175  " :set {option}:
2176  call assert_fails('set number:', 'E474:')
2177  call assert_fails('setlocal number:', 'E474:')
2178  call assert_fails('setglobal number:', 'E474:')
2179  call assert_fails('set number:1', 'E474:')
2180  call assert_fails('setlocal number:1', 'E474:')
2181  call assert_fails('setglobal number:1', 'E474:')
2182
2183  " :set {option}+=
2184  call assert_fails('set number+=1', 'E474:')
2185  call assert_fails('setlocal number+=1', 'E474:')
2186  call assert_fails('setglobal number+=1', 'E474:')
2187
2188  " :set {option}^=
2189  call assert_fails('set number^=1', 'E474:')
2190  call assert_fails('setlocal number^=1', 'E474:')
2191  call assert_fails('setglobal number^=1', 'E474:')
2192
2193  " :set {option}-=
2194  call assert_fails('set number-=1', 'E474:')
2195  call assert_fails('setlocal number-=1', 'E474:')
2196  call assert_fails('setglobal number-=1', 'E474:')
2197
2198  " Invalid trailing chars
2199  call assert_fails('set number!!', 'E488:')
2200  call assert_fails('setlocal number!!', 'E488:')
2201  call assert_fails('setglobal number!!', 'E488:')
2202  call assert_fails('set number??', 'E488:')
2203  call assert_fails('setlocal number??', 'E488:')
2204  call assert_fails('setglobal number??', 'E488:')
2205  call assert_fails('set number&&', 'E488:')
2206  call assert_fails('setlocal number&&', 'E488:')
2207  call assert_fails('setglobal number&&', 'E488:')
2208  call assert_fails('set number<<', 'E488:')
2209  call assert_fails('setlocal number<<', 'E488:')
2210  call assert_fails('setglobal number<<', 'E488:')
2211  call assert_fails('set number@', 'E488:')
2212  call assert_fails('setlocal number@', 'E488:')
2213  call assert_fails('setglobal number@', 'E488:')
2214
2215  " Invalid type
2216  call assert_fails("let &number = 'xxx'", 'E521:')
2217endfunc
2218
2219" Test for the 'window' option
2220func Test_window_opt()
2221  " Needs only one open widow
2222  %bw!
2223  call setline(1, range(1, 8))
2224  set window=5
2225  exe "normal \<C-F>"
2226  call assert_equal(4, line('w0'))
2227  exe "normal \<C-F>"
2228  call assert_equal(7, line('w0'))
2229  exe "normal \<C-F>"
2230  call assert_equal(8, line('w0'))
2231  exe "normal \<C-B>"
2232  call assert_equal(5, line('w0'))
2233  exe "normal \<C-B>"
2234  call assert_equal(2, line('w0'))
2235  exe "normal \<C-B>"
2236  call assert_equal(1, line('w0'))
2237  set window=1
2238  exe "normal gg\<C-F>"
2239  call assert_equal(2, line('w0'))
2240  exe "normal \<C-F>"
2241  call assert_equal(3, line('w0'))
2242  exe "normal \<C-B>"
2243  call assert_equal(2, line('w0'))
2244  exe "normal \<C-B>"
2245  call assert_equal(1, line('w0'))
2246  enew!
2247  set window&
2248endfunc
2249
2250" Test for the 'winminheight' option
2251func Test_opt_winminheight()
2252  only!
2253  let &winheight = &lines + 4
2254  call assert_fails('let &winminheight = &lines + 2', 'E36:')
2255  call assert_true(&winminheight <= &lines)
2256  set winminheight&
2257  set winheight&
2258endfunc
2259
2260func Test_opt_winminheight_term()
2261  " See test/functional/options/options_spec.lua
2262  CheckRunVimInTerminal
2263
2264  " The tabline should be taken into account.
2265  let lines =<< trim END
2266    set wmh=0 stal=2
2267    below sp | wincmd _
2268    below sp | wincmd _
2269    below sp | wincmd _
2270    below sp
2271  END
2272  call writefile(lines, 'Xwinminheight')
2273  let buf = RunVimInTerminal('-S Xwinminheight', #{rows: 11})
2274  call term_sendkeys(buf, ":set wmh=1\n")
2275  call WaitForAssert({-> assert_match('E36: Not enough room', term_getline(buf, 11))})
2276
2277  call StopVimInTerminal(buf)
2278  call delete('Xwinminheight')
2279endfunc
2280
2281func Test_opt_winminheight_term_tabs()
2282  " See test/functional/options/options_spec.lua
2283  CheckRunVimInTerminal
2284
2285  " The tabline should be taken into account.
2286  let lines =<< trim END
2287    set wmh=0 stal=2
2288    split
2289    split
2290    split
2291    split
2292    tabnew
2293  END
2294  call writefile(lines, 'Xwinminheight')
2295  let buf = RunVimInTerminal('-S Xwinminheight', #{rows: 11})
2296  call term_sendkeys(buf, ":set wmh=1\n")
2297  call WaitForAssert({-> assert_match('E36: Not enough room', term_getline(buf, 11))})
2298
2299  call StopVimInTerminal(buf)
2300  call delete('Xwinminheight')
2301endfunc
2302
2303" Test for the 'winminwidth' option
2304func Test_opt_winminwidth()
2305  only!
2306  let &winwidth = &columns + 4
2307  call assert_fails('let &winminwidth = &columns + 2', 'E36:')
2308  call assert_true(&winminwidth <= &columns)
2309  set winminwidth&
2310  set winwidth&
2311endfunc
2312
2313" Test for setting option value containing spaces with isfname+=32
2314func Test_isfname_with_options()
2315  set isfname+=32
2316  setlocal keywordprg=:term\ help.exe
2317  call assert_equal(':term help.exe', &keywordprg)
2318  set isfname&
2319  setlocal keywordprg&
2320endfunc
2321
2322" Test that resetting laststatus does change scroll option
2323func Test_opt_reset_scroll()
2324  " See test/functional/options/options_spec.lua
2325  CheckRunVimInTerminal
2326  let vimrc =<< trim [CODE]
2327    set scroll=2
2328    set laststatus=2
2329  [CODE]
2330  call writefile(vimrc, 'Xscroll')
2331  let buf = RunVimInTerminal('-S Xscroll', {'rows': 16, 'cols': 45})
2332  call term_sendkeys(buf, ":verbose set scroll?\n")
2333  call WaitForAssert({-> assert_match('Last set.*window size', term_getline(buf, 15))})
2334  call assert_match('^\s*scroll=7$', term_getline(buf, 14))
2335  call StopVimInTerminal(buf)
2336
2337  " clean up
2338  call delete('Xscroll')
2339endfunc
2340
2341" Check that VIM_POSIX env variable influences default value of 'cpo' and 'shm'
2342func Test_VIM_POSIX()
2343  throw 'Skipped: Nvim does not support $VIM_POSIX'
2344  let saved_VIM_POSIX = getenv("VIM_POSIX")
2345
2346  call setenv('VIM_POSIX', "1")
2347  let after =<< trim [CODE]
2348    call writefile([&cpo, &shm], 'X_VIM_POSIX')
2349    qall
2350  [CODE]
2351  if RunVim([], after, '')
2352    call assert_equal(['aAbBcCdDeEfFgHiIjJkKlLmMnoOpPqrRsStuvwWxXyZ$!%*-+<>#{|&/\.;~',
2353          \            'AS'], readfile('X_VIM_POSIX'))
2354  endif
2355
2356  call setenv('VIM_POSIX', v:null)
2357  let after =<< trim [CODE]
2358    call writefile([&cpo, &shm], 'X_VIM_POSIX')
2359    qall
2360  [CODE]
2361  if RunVim([], after, '')
2362    call assert_equal(['aAbBcCdDeEfFgHiIjJkKlLmMnoOpPqrRsStuvwWxXyZ$!%*-+<>;',
2363          \            'S'], readfile('X_VIM_POSIX'))
2364  endif
2365
2366  call delete('X_VIM_POSIX')
2367  call setenv('VIM_POSIX', saved_VIM_POSIX)
2368endfunc
2369
2370" Test for setting an option to a Vi or Vim default
2371func Test_opt_default()
2372  throw 'Skipped: Nvim has different defaults'
2373  set formatoptions&vi
2374  call assert_equal('vt', &formatoptions)
2375  set formatoptions&vim
2376  call assert_equal('tcq', &formatoptions)
2377
2378  call assert_equal('ucs-bom,utf-8,default,latin1', &fencs)
2379  set fencs=latin1
2380  set fencs&
2381  call assert_equal('ucs-bom,utf-8,default,latin1', &fencs)
2382  set fencs=latin1
2383  set all&
2384  call assert_equal('ucs-bom,utf-8,default,latin1', &fencs)
2385endfunc
2386
2387" Test for the 'cmdheight' option
2388func Test_opt_cmdheight()
2389  %bw!
2390  let ht = &lines
2391  set cmdheight=9999
2392  call assert_equal(1, winheight(0))
2393  call assert_equal(ht - 1, &cmdheight)
2394  set cmdheight&
2395
2396  " The status line should be taken into account.
2397  set laststatus=2
2398  set cmdheight=9999
2399  call assert_equal(ht - 2, &cmdheight)
2400  set cmdheight& laststatus=1  " Accommodate Nvim default
2401
2402  " The tabline should be taken into account only non-GUI.
2403  set showtabline=2
2404  set cmdheight=9999
2405  if has('gui_running')
2406    call assert_equal(ht - 1, &cmdheight)
2407  else
2408    call assert_equal(ht - 2, &cmdheight)
2409  endif
2410  set cmdheight& showtabline&
2411
2412  " The 'winminheight' should be taken into account.
2413  set winheight=3 winminheight=3
2414  split
2415  set cmdheight=9999
2416  call assert_equal(ht - 8, &cmdheight)
2417  %bw!
2418  set cmdheight& winminheight& winheight&
2419
2420  " Only the windows in the current tabpage are taken into account.
2421  set winheight=3 winminheight=3 showtabline=0
2422  split
2423  tabnew
2424  set cmdheight=9999
2425  call assert_equal(ht - 3, &cmdheight)
2426  %bw!
2427  set cmdheight& winminheight& winheight& showtabline&
2428endfunc
2429
2430" To specify a control character as an option value, '^' can be used
2431func Test_opt_control_char()
2432  set wildchar=^v
2433  call assert_equal("\<C-V>", nr2char(&wildchar))
2434  set wildcharm=^r
2435  call assert_equal("\<C-R>", nr2char(&wildcharm))
2436  " Bug: This doesn't work for the 'cedit' and 'termwinkey' options
2437  set wildchar& wildcharm&
2438endfunc
2439
2440" Test for the 'errorbells' option
2441func Test_opt_errorbells()
2442  set errorbells
2443  call assert_beeps('s/a1b2/x1y2/')
2444  set noerrorbells
2445endfunc
2446
2447func Test_opt_scrolljump()
2448  help
2449  resize 10
2450
2451  " Test with positive 'scrolljump'.
2452  set scrolljump=2
2453  norm! Lj
2454  call assert_equal({'lnum':11, 'leftcol':0, 'col':0, 'topfill':0,
2455        \            'topline':3, 'coladd':0, 'skipcol':0, 'curswant':0},
2456        \           winsaveview())
2457
2458  " Test with negative 'scrolljump' (percentage of window height).
2459  set scrolljump=-40
2460  norm! ggLj
2461  call assert_equal({'lnum':11, 'leftcol':0, 'col':0, 'topfill':0,
2462         \            'topline':5, 'coladd':0, 'skipcol':0, 'curswant':0},
2463         \           winsaveview())
2464
2465  norm! 100Gzt
2466  set scrolljump=-100
2467  norm! 20k
2468  call assert_equal({'lnum':80, 'leftcol':0, 'col':0, 'topfill':0,
2469        \            'topline':71, 'coladd':0, 'skipcol':0, 'curswant':0},
2470        \           winsaveview())
2471
2472  set scrolljump&
2473  bw
2474endfunc
2475
2476" Test for the 'cdhome' option
2477func Test_opt_cdhome()
2478  if has('unix') || has('vms')
2479    throw 'Skipped: only works on non-Unix'
2480  endif
2481
2482  set cdhome&
2483  call assert_equal(0, &cdhome)
2484  set cdhome
2485
2486  " This paragraph is copied from Test_cd_no_arg().
2487  let path = getcwd()
2488  cd
2489  call assert_equal($HOME, getcwd())
2490  call assert_notequal(path, getcwd())
2491  exe 'cd ' .. fnameescape(path)
2492  call assert_equal(path, getcwd())
2493
2494  set cdhome&
2495endfunc
2496
2497func Test_set_completion_fuzzy()
2498  CheckOption termguicolors
2499
2500  " Test default option completion
2501  set wildoptions=
2502  call feedkeys(":set termg\<C-A>\<C-B>\"\<CR>", 'tx')
2503  call assert_equal('"set termguicolors', @:)
2504
2505  call feedkeys(":set notermg\<C-A>\<C-B>\"\<CR>", 'tx')
2506  call assert_equal('"set notermguicolors', @:)
2507
2508  " Test fuzzy option completion
2509  set wildoptions=fuzzy
2510  call feedkeys(":set termg\<C-A>\<C-B>\"\<CR>", 'tx')
2511  " Nvim doesn't have 'termencoding'
2512  " call assert_equal('"set termguicolors termencoding', @:)
2513  call assert_equal('"set termguicolors', @:)
2514
2515  call feedkeys(":set notermg\<C-A>\<C-B>\"\<CR>", 'tx')
2516  call assert_equal('"set notermguicolors', @:)
2517
2518  set wildoptions=
2519endfunc
2520
2521func Test_switchbuf_reset()
2522  set switchbuf=useopen
2523  sblast
2524  call assert_equal(1, winnr('$'))
2525  set all&
2526  " Nvim has a different default for 'switchbuf'
2527  " call assert_equal('', &switchbuf)
2528  call assert_equal('uselast', &switchbuf)
2529  sblast
2530  call assert_equal(2, winnr('$'))
2531  only!
2532endfunc
2533
2534" :set empty string for global 'keywordprg' falls back to ":help"
2535func Test_keywordprg_empty()
2536  let k = &keywordprg
2537  set keywordprg=man
2538  call assert_equal('man', &keywordprg)
2539  set keywordprg=
2540  call assert_equal(':help', &keywordprg)
2541  set keywordprg=man
2542  call assert_equal('man', &keywordprg)
2543  call assert_equal("\n  keywordprg=:help", execute('set kp= kp?'))
2544  let &keywordprg = k
2545endfunc
2546
2547" check that the very first buffer created does not have 'endoffile' set
2548func Test_endoffile_default()
2549  let after =<< trim [CODE]
2550    call writefile([execute('set eof?')], 'Xtestout')
2551    qall!
2552  [CODE]
2553  if RunVim([], after, '')
2554    call assert_equal(["\nnoendoffile"], readfile('Xtestout'))
2555  endif
2556  call delete('Xtestout')
2557endfunc
2558
2559" Test for setting the 'lines' and 'columns' options to a minimum value
2560func Test_set_min_lines_columns()
2561  let save_lines = &lines
2562  let save_columns = &columns
2563
2564  let after =<< trim END
2565    set laststatus=1
2566    set nomore
2567    let msg = []
2568    let v:errmsg = ''
2569    silent! let &columns=0
2570    call add(msg, v:errmsg)
2571    silent! set columns=0
2572    call add(msg, v:errmsg)
2573    silent! call setbufvar('', '&columns', 0)
2574    call add(msg, v:errmsg)
2575    "call writefile(msg, 'XResultsetminlines')
2576    silent! let &lines=0
2577    call add(msg, v:errmsg)
2578    silent! set lines=0
2579    call add(msg, v:errmsg)
2580    silent! call setbufvar('', '&lines', 0)
2581    call add(msg, v:errmsg)
2582    call writefile(msg, 'XResultsetminlines')
2583    qall!
2584  END
2585  if RunVim([], after, '')
2586    call assert_equal(['E594: Need at least 12 columns',
2587          \ 'E594: Need at least 12 columns: columns=0',
2588          \ 'E594: Need at least 12 columns',
2589          \ 'E593: Need at least 2 lines',
2590          \ 'E593: Need at least 2 lines: lines=0',
2591          \ 'E593: Need at least 2 lines',], readfile('XResultsetminlines'))
2592  endif
2593
2594  call delete('XResultsetminlines')
2595  let &lines = save_lines
2596  let &columns = save_columns
2597endfunc
2598
2599" Test for reverting a string option value if the new value is invalid.
2600func Test_string_option_revert_on_failure()
2601  new
2602  let optlist = [
2603        \ ['ambiwidth', 'double', 'a123'],
2604        \ ['background', 'dark', 'a123'],
2605        \ ['backspace', 'eol', 'a123'],
2606        \ ['backupcopy', 'no', 'a123'],
2607        \ ['belloff', 'showmatch', 'a123'],
2608        \ ['breakindentopt', 'min:10', 'list'],
2609        \ ['bufhidden', 'wipe', 'a123'],
2610        \ ['buftype', 'nowrite', 'a123'],
2611        \ ['casemap', 'keepascii', 'a123'],
2612        \ ['cedit', "\<C-Y>", 'z'],
2613        \ ['colorcolumn', '10', 'z'],
2614        \ ['commentstring', '#%s', 'a123'],
2615        \ ['complete', '.,t', 'a'],
2616        \ ['completefunc', 'MyCmplFunc', '1a-'],
2617        "\ ['completeopt', 'popup', 'a123'],
2618        \ ['completeopt', 'preview', 'a123'],
2619        "\ ['completepopup', 'width:20', 'border'],
2620        \ ['concealcursor', 'v', 'xyz'],
2621        "\ ['cpoptions', 'HJ', 'Q'],
2622        \ ['cpoptions', 'J', 'Q'],
2623        "\ ['cryptmethod', 'zip', 'a123'],
2624        \ ['cursorlineopt', 'screenline', 'a123'],
2625        \ ['debug', 'throw', 'a123'],
2626        \ ['diffopt', 'iwhite', 'a123'],
2627        \ ['display', 'uhex', 'a123'],
2628        \ ['eadirection', 'hor', 'a123'],
2629        \ ['encoding', 'utf-8', 'a123'],
2630        \ ['eventignore', 'TextYankPost', 'a123'],
2631        \ ['eventignorewin', 'WinScrolled', 'a123'],
2632        \ ['fileencoding', 'utf-8', 'a123,'],
2633        \ ['fileformat', 'mac', 'a123'],
2634        \ ['fileformats', 'mac', 'a123'],
2635        \ ['filetype', 'abc', 'a^b'],
2636        \ ['fillchars', 'diff:~', 'a123'],
2637        \ ['foldclose', 'all', 'a123'],
2638        \ ['foldmarker', '[[[,]]]', '[[['],
2639        \ ['foldmethod', 'marker', 'a123'],
2640        \ ['foldopen', 'percent', 'a123'],
2641        \ ['formatoptions', 'an', '*'],
2642        \ ['guicursor', 'n-v-c:block-Cursor/lCursor', 'n-v-c'],
2643        \ ['helplang', 'en', 'a'],
2644        "\ ['highlight', '!:CursorColumn', '8:'],
2645        \ ['keymodel', 'stopsel', 'a123'],
2646        "\ ['keyprotocol', 'kitty:kitty', 'kitty:'],
2647        \ ['lispoptions', 'expr:1', 'a123'],
2648        \ ['listchars', 'tab:->', 'tab:'],
2649        \ ['matchpairs', '<:>', '<:'],
2650        \ ['messagesopt', 'hit-enter,history:100', 'a123'],
2651        \ ['mkspellmem', '100000,1000,100', '100000'],
2652        \ ['mouse', 'nvi', 'z'],
2653        \ ['mousemodel', 'extend', 'a123'],
2654        \ ['nrformats', 'alpha', 'a123'],
2655        \ ['omnifunc', 'MyOmniFunc', '1a-'],
2656        \ ['operatorfunc', 'MyOpFunc', '1a-'],
2657        \ ['previewpopup', 'width:20', 'a123'],
2658        "\ ['printoptions', 'paper:A4', 'a123:'],
2659        \ ['quickfixtextfunc', 'MyQfFunc', '1a-'],
2660        \ ['rulerformat', '%l', '%['],
2661        \ ['scrollopt', 'hor,jump', 'a123'],
2662        \ ['selection', 'exclusive', 'a123'],
2663        \ ['selectmode', 'cmd', 'a123'],
2664        \ ['sessionoptions', 'options', 'a123'],
2665        \ ['shellpipe', '>%s', "%s%s%s"],
2666        \ ['shellredir', '>%s', "%s%s%s"],
2667        \ ['shortmess', 'w', '2'],
2668        \ ['showbreak', '>>', "\x01"],
2669        \ ['showcmdloc', 'statusline', 'a123'],
2670        \ ['signcolumn', 'no', 'a123'],
2671        \ ['spellcapcheck', '[.?!]\+', '%\{'],
2672        \ ['spellfile', 'MySpell.en.add', "\x01"],
2673        \ ['spelllang', 'en', "#"],
2674        \ ['spelloptions', 'camel', 'a123'],
2675        \ ['spellsuggest', 'double', 'a123'],
2676        \ ['splitkeep', 'topline', 'a123'],
2677        \ ['statusline', '%f', '%['],
2678        "\ ['swapsync', 'sync', 'a123'],
2679        \ ['switchbuf', 'usetab', 'a123'],
2680        \ ['syntax', 'abc', 'a^b'],
2681        \ ['tabline', '%f', '%['],
2682        \ ['tagcase', 'ignore', 'a123'],
2683        \ ['tagfunc', 'MyTagFunc', '1a-'],
2684        \ ['thesaurusfunc', 'MyThesaurusFunc', '1a-'],
2685        \ ['viewoptions', 'options', 'a123'],
2686        \ ['virtualedit', 'onemore', 'a123'],
2687        \ ['whichwrap', '<,>', '{,}'],
2688        \ ['wildmode', 'list', 'a123'],
2689        \ ['wildoptions', 'pum', 'a123']
2690        \ ]
2691  if has('gui')
2692    call add(optlist, ['browsedir', 'buffer', 'a123'])
2693  endif
2694  if has('clipboard_working')
2695    call add(optlist, ['clipboard', 'unnamed', 'a123'])
2696  endif
2697  if has('win32')
2698    call add(optlist, ['completeslash', 'slash', 'a123'])
2699  endif
2700  if has('cscope')
2701    call add(optlist, ['cscopequickfix', 't-', 'z-'])
2702  endif
2703  if !has('win32') && !has('nvim')
2704    call add(optlist, ['imactivatefunc', 'MyActFunc', '1a-'])
2705    call add(optlist, ['imstatusfunc', 'MyStatusFunc', '1a-'])
2706  endif
2707  if has('keymap')
2708    call add(optlist, ['keymap', 'greek', '[]'])
2709  endif
2710  if has('mouseshape')
2711    call add(optlist, ['mouseshape', 'm:no', 'a123:'])
2712  endif
2713  if has('win32') && has('gui')
2714    call add(optlist, ['renderoptions', 'type:directx', 'type:directx,a123'])
2715  endif
2716  if has('rightleft')
2717    call add(optlist, ['rightleftcmd', 'search', 'a123'])
2718  endif
2719  if has('terminal')
2720    call add(optlist, ['termwinkey', '<C-L>', '<C'])
2721    call add(optlist, ['termwinsize', '24x80', '100'])
2722  endif
2723  if has('win32') && has('terminal')
2724    call add(optlist, ['termwintype', 'winpty', 'a123'])
2725  endif
2726  if exists('+toolbar')
2727    call add(optlist, ['toolbar', 'text', 'a123'])
2728  endif
2729  if exists('+toolbariconsize')
2730    call add(optlist, ['toolbariconsize', 'medium', 'a123'])
2731  endif
2732  if exists('+ttymouse') && !has('gui')
2733    call add(optlist, ['ttymouse', 'xterm', 'a123'])
2734  endif
2735  if exists('+vartabs')
2736    call add(optlist, ['varsofttabstop', '12', 'a123'])
2737    call add(optlist, ['vartabstop', '4,20', '4,'])
2738  endif
2739  if exists('+winaltkeys')
2740    call add(optlist, ['winaltkeys', 'no', 'a123'])
2741  endif
2742  for opt in optlist
2743    exe $"let save_opt = &{opt[0]}"
2744    try
2745      exe $"let &{opt[0]} = '{opt[1]}'"
2746    catch
2747      call assert_report($"Caught {v:exception} with {opt->string()}")
2748    endtry
2749    call assert_fails($"let &{opt[0]} = '{opt[2]}'", '', opt[0])
2750    call assert_equal(opt[1], eval($"&{opt[0]}"), opt[0])
2751    exe $"let &{opt[0]} = save_opt"
2752  endfor
2753  bw!
2754endfunc
2755
2756func Test_set_option_window_global_local()
2757  new Xbuffer1
2758  let [ _gso, _lso ] = [ &g:scrolloff, &l:scrolloff ]
2759  setlocal scrolloff=2
2760  setglobal scrolloff=3
2761  setl modified
2762  " A new buffer has its own window-local options
2763  hide enew
2764  call assert_equal(-1, &l:scrolloff)
2765  call assert_equal(3, &g:scrolloff)
2766  " A new window opened with its own buffer-local options
2767  new
2768  call assert_equal(-1, &l:scrolloff)
2769  call assert_equal(3, &g:scrolloff)
2770  " Re-open Xbuffer1 and it should use
2771  " the previous set window-local options
2772  b Xbuffer1
2773  call assert_equal(2, &l:scrolloff)
2774  call assert_equal(3, &g:scrolloff)
2775  bw!
2776  bw!
2777  let &g:scrolloff =  _gso
2778endfunc
2779
2780func GetGlobalLocalWindowOptions()
2781  new
2782  sil! r $VIMRUNTIME/doc/options.txt
2783  " Filter for global or local to window
2784  v/^'.*'.*\n.*global or local to window |global-local/d
2785  " get option value and type
2786  sil %s/^'\([^']*\)'.*'\s\+\(\w\+\)\s\+(default \%(\(".*"\|\d\+\|empty\|is very long\)\).*/\1 \2 \3/g
2787  " sil %s/empty/""/g
2788  " split the result
2789  " let result=getline(1,'$')->map({_, val -> split(val, ' ')})
2790  let result = getline(1, '$')->map({_, val -> matchlist(val, '\([^ ]\+\) \+\([^ ]\+\) \+\(.*\)')[1:3]})
2791  bw!
2792  return result
2793endfunc
2794
2795func Test_set_option_window_global_local_all()
2796  new Xbuffer2
2797
2798  let optionlist = GetGlobalLocalWindowOptions()
2799  for [opt, type, default] in optionlist
2800    let _old = eval('&g:' .. opt)
2801    if opt == 'statusline'
2802      " parsed default value is "is very long" as it is a doc string, not actual value
2803      let default = "\"" . _old . "\""
2804    endif
2805    if type == 'string'
2806      if opt == 'fillchars'
2807        exe 'setl ' .. opt .. '=vert:+'
2808        exe 'setg ' .. opt .. '=vert:+,fold:+'
2809      elseif opt == 'listchars'
2810        exe 'setl ' .. opt .. '=tab:>>'
2811        exe 'setg ' .. opt .. '=tab:++'
2812      elseif opt == 'virtualedit'
2813        exe 'setl ' .. opt .. '=all'
2814        exe 'setg ' .. opt .. '=block'
2815      else
2816        exe 'setl ' .. opt .. '=Local'
2817        exe 'setg ' .. opt .. '=Global'
2818      endif
2819    elseif type == 'number'
2820      exe 'setl ' .. opt .. '=5'
2821      exe 'setg ' .. opt .. '=10'
2822    endif
2823    setl modified
2824    hide enew
2825    if type == 'string'
2826      call assert_equal('', eval('&l:' .. opt))
2827      if opt == 'fillchars'
2828        call assert_equal('vert:+,fold:+', eval('&g:' .. opt), 'option:' .. opt)
2829      elseif opt == 'listchars'
2830        call assert_equal('tab:++', eval('&g:' .. opt), 'option:' .. opt)
2831      elseif opt == 'virtualedit'
2832        call assert_equal('block', eval('&g:' .. opt), 'option:' .. opt)
2833      else
2834        call assert_equal('Global', eval('&g:' .. opt), 'option:' .. opt)
2835      endif
2836    elseif type == 'number'
2837      call assert_equal(-1, eval('&l:' .. opt), 'option:' .. opt)
2838      call assert_equal(10, eval('&g:' .. opt), 'option:' .. opt)
2839    endif
2840    bw!
2841    exe 'let &g:' .. opt .. '=' .. default
2842  endfor
2843  bw!
2844endfunc
2845
2846func Test_paste_depending_options()
2847  " setting the paste option, resets all dependent options
2848  " and will be reported correctly using :verbose set <option>?
2849  let lines =<< trim [CODE]
2850    " set paste test
2851    set autoindent
2852    set expandtab
2853    " disabled, because depends on compiled feature set
2854    " set hkmap
2855    " set revins
2856    " set varsofttabstop=8,32,8
2857    set ruler
2858    set showmatch
2859    set smarttab
2860    set softtabstop=4
2861    set textwidth=80
2862    set wrapmargin=10
2863
2864    source Xvimrc_paste2
2865
2866    redir > Xoutput_paste
2867    verbose set expandtab?
2868    verbose setg expandtab?
2869    verbose setl expandtab?
2870    redir END
2871
2872    qall!
2873  [CODE]
2874
2875  call writefile(lines, 'Xvimrc_paste', 'D')
2876  call writefile(['set paste'], 'Xvimrc_paste2', 'D')
2877  if !RunVim([], lines, '--clean')
2878    return
2879  endif
2880
2881  let result = readfile('Xoutput_paste')->filter('!empty(v:val)')
2882  call assert_equal('noexpandtab', result[0])
2883  call assert_match("^\tLast set from .*Xvimrc_paste2 line 1$", result[1])
2884  call assert_equal('noexpandtab', result[2])
2885  call assert_match("^\tLast set from .*Xvimrc_paste2 line 1$", result[3])
2886  call assert_equal('noexpandtab', result[4])
2887  call assert_match("^\tLast set from .*Xvimrc_paste2 line 1$", result[5])
2888
2889  call delete('Xoutput_paste')
2890endfunc
2891
2892func Test_binary_depending_options()
2893  " setting the paste option, resets all dependent options
2894  " and will be reported correctly using :verbose set <option>?
2895  let lines =<< trim [CODE]
2896    " set binary test
2897    set expandtab
2898
2899    source Xvimrc_bin2
2900
2901    redir > Xoutput_bin
2902    verbose set expandtab?
2903    verbose setg expandtab?
2904    verbose setl expandtab?
2905    redir END
2906
2907    qall!
2908  [CODE]
2909
2910  call writefile(lines, 'Xvimrc_bin', 'D')
2911  call writefile(['set binary'], 'Xvimrc_bin2', 'D')
2912  if !RunVim([], lines, '--clean')
2913    return
2914  endif
2915
2916  let result = readfile('Xoutput_bin')->filter('!empty(v:val)')
2917  call assert_equal('noexpandtab', result[0])
2918  call assert_match("^\tLast set from .*Xvimrc_bin2 line 1$", result[1])
2919  call assert_equal('noexpandtab', result[2])
2920  call assert_match("^\tLast set from .*Xvimrc_bin2 line 1$", result[3])
2921  call assert_equal('noexpandtab', result[4])
2922  call assert_match("^\tLast set from .*Xvimrc_bin2 line 1$", result[5])
2923
2924  call delete('Xoutput_bin')
2925endfunc
2926
2927func Test_set_wrap()
2928  " Unsetting 'wrap' when 'smoothscroll' is set does not result in incorrect
2929  " cursor position.
2930  set wrap smoothscroll scrolloff=5
2931
2932  call setline(1, ['', 'aaaa'->repeat(500)])
2933  20 split
2934  20 vsplit
2935  norm 2G$
2936  redraw
2937  set nowrap
2938  call assert_equal(2, winline())
2939
2940  set wrap& smoothscroll& scrolloff&
2941endfunc
2942
2943func Test_delcombine()
2944  new
2945  set backspace=indent,eol,start
2946
2947  set delcombine
2948  call setline(1, 'β̳̈:β̳̈')
2949  normal! 0x
2950  call assert_equal('β̈:β̳̈', getline(1))
2951  exe "normal! A\<BS>"
2952  call assert_equal('β̈:β̈', getline(1))
2953  normal! 0x
2954  call assert_equal('β:β̈', getline(1))
2955  exe "normal! A\<BS>"
2956  call assert_equal('β:β', getline(1))
2957  normal! 0x
2958  call assert_equal(':β', getline(1))
2959  exe "normal! A\<BS>"
2960  call assert_equal(':', getline(1))
2961
2962  set nodelcombine
2963  call setline(1, 'β̳̈:β̳̈')
2964  normal! 0x
2965  call assert_equal(':β̳̈', getline(1))
2966  exe "normal! A\<BS>"
2967  call assert_equal(':', getline(1))
2968
2969  set backspace& delcombine&
2970  bwipe!
2971endfunc
2972
2973" Should not raise errors when set missing-options.
2974func Test_set_missing_options()
2975  throw 'Skipped: N/A'
2976  set autoprint
2977  set beautify
2978  set flash
2979  set graphic
2980  set hardtabs=8
2981  set mesg
2982  set novice
2983  set open
2984  set optimize
2985  set redraw
2986  set slowopen
2987  set sourceany
2988  set w300=23
2989  set w1200=23
2990  set w9600=23
2991endfunc
2992
2993func Test_showcmd()
2994  throw 'Skipped: Nvim does not support support Vi-compatible mode'
2995  " in no-cp mode, 'showcmd' is enabled
2996  let _cp=&cp
2997  call assert_equal(1, &showcmd)
2998  set cp
2999  call assert_equal(0, &showcmd)
3000  set nocp
3001  call assert_equal(1, &showcmd)
3002  let &cp = _cp
3003endfunc
3004
3005" Test that :set+= and :set-= handle "key:value" items in comma-separated
3006" options by matching on the key part.
3007func Test_comma_option_key_value()
3008  " += replaces existing item with same key
3009  set diffopt=internal,filler,algorithm:patience
3010  set diffopt+=algorithm:histogram
3011  call assert_equal('internal,filler,algorithm:histogram', &diffopt)
3012
3013  " += with exact duplicate does nothing
3014  set diffopt=internal,filler,algorithm:patience
3015  set diffopt+=algorithm:patience
3016  call assert_equal('internal,filler,algorithm:patience', &diffopt)
3017
3018  " += with multiple items, each processed individually
3019  set diffopt=algorithm:patience,filler
3020  set diffopt+=algorithm:histogram,filler
3021  call assert_equal('filler,algorithm:histogram', &diffopt)
3022
3023  " += with non-colon item appends normally
3024  set diffopt=internal,filler
3025  set diffopt+=iwhite
3026  call assert_equal('internal,filler,iwhite', &diffopt)
3027
3028  " += repeated updates
3029  set diffopt=internal,filler,algorithm:patience
3030  set diffopt+=algorithm:histogram
3031  set diffopt+=algorithm:minimal
3032  set diffopt+=algorithm:myers
3033  call assert_equal('internal,filler,algorithm:myers', &diffopt)
3034
3035  " += all exact duplicates does nothing
3036  set diffopt=internal,filler,algorithm:patience
3037  set diffopt+=algorithm:patience,filler
3038  call assert_equal('internal,filler,algorithm:patience', &diffopt)
3039
3040  " -= with "key:" removes item regardless of value
3041  set diffopt=internal,filler,algorithm:patience
3042  set diffopt-=algorithm:
3043  call assert_equal('internal,filler', &diffopt)
3044
3045  " -= with "key:value" also matches by key
3046  set diffopt=internal,filler,algorithm:patience
3047  set diffopt-=algorithm:histogram
3048  call assert_equal('internal,filler', &diffopt)
3049
3050  " -= without colon does not match "key:value" items
3051  set diffopt=internal,filler,algorithm:patience
3052  set diffopt-=algorithm
3053  call assert_equal('internal,filler,algorithm:patience', &diffopt)
3054
3055  " -= with multiple non-colon items (order independent)
3056  set diffopt=internal,filler,closeoff
3057  set diffopt-=filler,internal
3058  call assert_equal('closeoff', &diffopt)
3059
3060  " -= with multiple non-colon items (same order as in option)
3061  set diffopt=internal,filler,closeoff
3062  set diffopt-=internal,filler
3063  call assert_equal('closeoff', &diffopt)
3064
3065  " -= with multiple items: non-colon and colon mixed
3066  set diffopt& diffopt=internal,filler,closeoff,indent-heuristic,inline:char
3067  set diffopt-=indent-heuristic,inline:char
3068  call assert_equal('internal,filler,closeoff', &diffopt)
3069
3070  " -= with multiple items: colon and non-colon mixed (reverse order)
3071  set diffopt& diffopt=internal,filler,closeoff,indent-heuristic,inline:char
3072  set diffopt-=inline:char,indent-heuristic
3073  call assert_equal('internal,filler,closeoff', &diffopt)
3074
3075  " += with multiple non-colon items
3076  set diffopt=internal,filler
3077  set diffopt+=closeoff,iwhite
3078  call assert_equal('internal,filler,closeoff,iwhite', &diffopt)
3079
3080  " += with multiple non-colon items, some already exist
3081  set diffopt=internal,filler,closeoff
3082  set diffopt+=filler,iwhite
3083  call assert_equal('internal,filler,closeoff,iwhite', &diffopt)
3084
3085  " -= with multiple items including key match
3086  set diffopt=internal,filler,algorithm:patience
3087  set diffopt-=algorithm:,filler
3088  call assert_equal('internal', &diffopt)
3089
3090  " -= key match when item is at the beginning
3091  set diffopt=algorithm:patience,internal,filler
3092  set diffopt-=algorithm:
3093  call assert_equal('internal,filler', &diffopt)
3094
3095  " -= key match when item is at the end
3096  set diffopt=internal,filler,algorithm:patience
3097  set diffopt-=algorithm:
3098  call assert_equal('internal,filler', &diffopt)
3099
3100  " -= key match when item is the only item
3101  set diffopt=algorithm:patience
3102  set diffopt-=algorithm:
3103  call assert_equal('', &diffopt)
3104
3105  " ^= prepends new item
3106  set diffopt=internal,filler
3107  set diffopt^=algorithm:histogram
3108  call assert_equal('algorithm:histogram,internal,filler', &diffopt)
3109
3110  " ^= replaces item and prepends
3111  set diffopt=internal,filler,algorithm:patience
3112  set diffopt^=algorithm:histogram
3113  call assert_equal('algorithm:histogram,internal,filler', &diffopt)
3114
3115  " ^= with exact duplicate does nothing
3116  set diffopt=internal,filler,algorithm:patience
3117  set diffopt^=algorithm:patience
3118  call assert_equal('internal,filler,algorithm:patience', &diffopt)
3119
3120  set diffopt&
3121
3122  " Multiple items with the same key (set via :let)
3123  " += with different value removes all items with the same key
3124  let &lcs = 'eol:$,multispace:yY,space:x,multispace:XY'
3125  set lcs+=multispace:AB
3126  call assert_equal('eol:$,space:x,multispace:AB', &lcs)
3127
3128  " += with exact duplicate keeps it and removes others with the same key
3129  let &lcs = 'eol:$,multispace:XY,space:x,multispace:XY'
3130  set lcs+=multispace:XY
3131  call assert_equal('eol:$,multispace:XY,space:x', &lcs)
3132
3133  " -= removes all items with the same key
3134  let &lcs = 'eol:$,multispace:yY,space:x,multispace:XY'
3135  set lcs-=multispace:
3136  call assert_equal('eol:$,space:x', &lcs)
3137
3138  " ^= with different value removes all items and prepends
3139  let &lcs = 'eol:$,multispace:yY,space:x,multispace:XY'
3140  set lcs^=multispace:AB
3141  call assert_equal('multispace:AB,eol:$,space:x', &lcs)
3142
3143  set lcs&
3144endfunc
3145
3146func Test_insecure_flag_copied_to_new_buffer_indentexpr()
3147  let modeline = &modeline
3148  let modelineexpr = &modelineexpr
3149  "let modelinestrict = &modelinestrict
3150
3151  func! Xindentexprpwn(findstart, base)
3152    if a:findstart
3153      sandbox setglobal indentexpr=writefile(['leak'],\ 'Xindentexpr_proof')
3154      return 0
3155    endif
3156    return []
3157  endfunc
3158
3159  try
3160    set modeline modelineexpr "nomodelinestrict
3161
3162    call writefile([
3163          \ 'vim: set complete=FXindentexprpwn :',
3164          \ 'body',
3165          \ ], 'Xindentexpr_attack', 'D')
3166    call delete('Xindentexpr_proof')
3167    edit Xindentexpr_attack
3168    call cursor(2, 1)
3169    call feedkeys("i\<C-N>\<Esc>", 'xt')
3170    bwipe!
3171
3172    " A brand new buffer now inherits the poisoned 'indentexpr' via
3173    " buf_copy_options().  It must still be evaluated in the sandbox.
3174    enew!
3175    call setline(1, ['{', 'x', '}'])
3176    normal! 2G==
3177    call assert_false(filereadable('Xindentexpr_proof'))
3178    bwipe!
3179  finally
3180    let &modeline = modeline
3181    let &modelineexpr = modelineexpr
3182    "let &modelinestrict = modelinestrict
3183    set indentexpr&
3184    call delete('Xindentexpr_proof')
3185    delfunc Xindentexprpwn
3186  endtry
3187endfunc
3188
3189func Test_insecure_flag_not_cleared_by_other_buffer_complete()
3190  let modeline = &modeline
3191  let modelineexpr = &modelineexpr
3192  "let modelinestrict = &modelinestrict
3193
3194  func! Xcompletepwn(findstart, base)
3195    if a:findstart
3196      call writefile(['leak'], 'Xcomplete_cross_proof')
3197      return 0
3198    endif
3199    return ['match']
3200  endfunc
3201
3202  try
3203    set modeline modelineexpr "nomodelinestrict
3204
3205    call writefile([
3206          \ 'vim: set complete=FXcompletepwn :',
3207          \ 'body',
3208          \ ], 'Xcomplete_cross_attack', 'D')
3209    call delete('Xcomplete_cross_proof')
3210    edit Xcomplete_cross_attack
3211    let bufA = bufnr('%')
3212
3213    " An unrelated buffer does a completely ordinary, trusted reset.
3214    new
3215    setlocal complete=.,w,b,u,t
3216    bwipe!
3217
3218    " Back in the modeline-tainted buffer: must still be sandboxed.
3219    exe 'buffer ' .. bufA
3220    call cursor(2, 1)
3221    call assert_fails('call feedkeys("i\<C-N>\<Esc>", "xt")', 'E48:')
3222    call assert_false(filereadable('Xcomplete_cross_proof'))
3223    bwipe!
3224  finally
3225    let &modeline = modeline
3226    let &modelineexpr = modelineexpr
3227    "let &modelinestrict = modelinestrict
3228    call delete('Xcomplete_cross_proof')
3229    delfunc Xcompletepwn
3230  endtry
3231endfunc
3232
3233func Test_formatexpr_insecure_copied_to_new_buffer()
3234  new
3235  sandbox setglobal formatexpr=writefile(['leak'],\ 'Xleak_fex')
3236  enew!
3237  call setline(1, ['some text to format'])
3238  set textwidth=10
3239  silent! normal! gqq
3240  call assert_false(filereadable('Xleak_fex'))
3241  call delete('Xleak_fex')
3242  set formatexpr& textwidth&
3243  bwipe!
3244endfunc
3245
3246" includeexpr: triggered via gf / find_pattern_in_path (used by [i, gf, etc.)
3247func Test_includeexpr_insecure_copied_to_new_buffer()
3248  func Xleakinclude(fname)
3249    call writefile(['leak'], 'Xleak_inex')
3250    return a:fname
3251  endfunc
3252  new
3253  sandbox setglobal includeexpr=Xleakinclude(v:fname)
3254  enew!
3255  call setline(1, ['#include "foo.h"'])
3256  silent! normal! [i
3257  call assert_false(filereadable('Xleak_inex'))
3258  call delete('Xleak_inex')
3259  set includeexpr&
3260  delfunc Xleakinclude
3261  bwipe!
3262endfunc
3263
3264" vim: shiftwidth=2 sts=2 expandtab