robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
36.3 KiB1148 linesraw
1--
2-- Tests for default options and environment decisions.
3--
4-- See editor/defaults_spec.lua for default autocmds, mappings, commands, and menus.
5--
6
7local t = require('test.testutil')
8local n = require('test.functional.testnvim')()
9local Screen = require('test.functional.ui.screen')
10
11local describe, it, before_each, after_each, finally =
12  t.describe, t.it, t.before_each, t.after_each, t.finally
13local assert_alive = n.assert_alive
14local assert_log = t.assert_log
15local pcall_err = t.pcall_err
16local api = n.api
17local command = n.command
18local clear = n.clear
19local eval = n.eval
20local eq = t.eq
21local ok = t.ok
22local fn = n.fn
23local insert = n.insert
24local neq = t.neq
25local mkdir = t.mkdir
26local rmdir = n.rmdir
27local tbl_contains = vim.tbl_contains
28local expect_exit = n.expect_exit
29local check_close = n.check_close
30local is_os = t.is_os
31
32local testlog = 'Xtest-defaults-log'
33
34describe('startup defaults', function()
35  it("NVIM_NOTTYFAST=1 unsets 'ttyfast'", function()
36    clear { env = { NVIM_NOTTYFAST = '1' } }
37    eq(0, n.eval('&ttyfast'))
38  end)
39
40  describe(':filetype', function()
41    local function expect_filetype(expected)
42      local screen = Screen.new(50, 4)
43      command('filetype')
44      screen:expect([[
45        ^                                                  |
46        {1:~                                                 }|*2
47        ]] .. expected)
48    end
49
50    it('all ON after `-u NORC`', function()
51      clear('-u', 'NORC')
52      expect_filetype('filetype detection:ON  plugin:ON  indent:ON       |')
53    end)
54
55    it('all ON after `:syntax …` #7765', function()
56      clear('-u', 'NORC', '--cmd', 'syntax on')
57      expect_filetype('filetype detection:ON  plugin:ON  indent:ON       |')
58      clear('-u', 'NORC', '--cmd', 'syntax off')
59      expect_filetype('filetype detection:ON  plugin:ON  indent:ON       |')
60    end)
61
62    it('all OFF after `-u NONE`', function()
63      clear('-u', 'NONE')
64      expect_filetype('filetype detection:OFF  plugin:OFF  indent:OFF    |')
65    end)
66
67    it('explicit OFF stays OFF', function()
68      clear('-u', 'NORC', '--cmd', 'syntax off | filetype off | filetype plugin indent off')
69      expect_filetype('filetype detection:OFF  plugin:OFF  indent:OFF    |')
70      clear('-u', 'NORC', '--cmd', 'syntax off | filetype plugin indent off')
71      expect_filetype('filetype detection:ON  plugin:OFF  indent:OFF     |')
72      clear('-u', 'NORC', '--cmd', 'filetype indent off')
73      expect_filetype('filetype detection:ON  plugin:ON  indent:OFF      |')
74      clear('-u', 'NORC', '--cmd', 'syntax off | filetype off')
75      expect_filetype('filetype detection:OFF  plugin:(on)  indent:(on)  |')
76      -- Swap the order.
77      clear('-u', 'NORC', '--cmd', 'filetype off | syntax off')
78      expect_filetype('filetype detection:OFF  plugin:(on)  indent:(on)  |')
79    end)
80
81    it('all ON after early `:filetype … on`', function()
82      -- `:filetype … on` should not change the defaults. #7765
83      -- Only an explicit `:filetype … off` sets OFF.
84
85      clear('-u', 'NORC', '--cmd', 'filetype on')
86      expect_filetype('filetype detection:ON  plugin:ON  indent:ON       |')
87      clear('-u', 'NORC', '--cmd', 'filetype plugin on')
88      expect_filetype('filetype detection:ON  plugin:ON  indent:ON       |')
89      clear('-u', 'NORC', '--cmd', 'filetype indent on')
90      expect_filetype('filetype detection:ON  plugin:ON  indent:ON       |')
91    end)
92
93    it('late `:filetype … off` stays OFF', function()
94      clear('-u', 'NORC', '-c', 'filetype off')
95      expect_filetype('filetype detection:OFF  plugin:(on)  indent:(on)  |')
96      clear('-u', 'NORC', '-c', 'filetype plugin off')
97      expect_filetype('filetype detection:ON  plugin:OFF  indent:ON      |')
98      clear('-u', 'NORC', '-c', 'filetype indent off')
99      expect_filetype('filetype detection:ON  plugin:ON  indent:OFF      |')
100    end)
101  end)
102
103  describe('syntax', function()
104    it('enabled by `-u NORC`', function()
105      clear('-u', 'NORC')
106      eq(1, eval('g:syntax_on'))
107    end)
108
109    it('disabled by `-u NONE`', function()
110      clear('-u', 'NONE')
111      eq(0, eval('exists("g:syntax_on")'))
112    end)
113
114    it('`:syntax off` stays off', function()
115      -- early
116      clear('-u', 'NORC', '--cmd', 'syntax off')
117      eq(0, eval('exists("g:syntax_on")'))
118      -- late
119      clear('-u', 'NORC', '-c', 'syntax off')
120      eq(0, eval('exists("g:syntax_on")'))
121    end)
122
123    it('":if 0|syntax on|endif" does not affect default #8728', function()
124      clear('-u', 'NORC', '--cmd', ':if 0|syntax on|endif')
125      eq(1, eval('exists("g:syntax_on")'))
126      clear('-u', 'NORC', '--cmd', ':if 0|syntax off|endif')
127      eq(1, eval('exists("g:syntax_on")'))
128    end)
129  end)
130
131  describe("'fillchars'", function()
132    it('vert/fold flags', function()
133      clear()
134      local screen = Screen.new(50, 5)
135      command('set laststatus=0')
136      insert([[
137        1
138        2
139        3
140        4]])
141      command('normal! ggjzfj')
142      command('vsp')
143      screen:expect([[
144        1                        │1                       |
145        {13:^+--  2 lines: 2··········}│{13:+--  2 lines: 2·········}|
146        4                        │4                       |
147        {1:~                        }│{1:~                       }|
148                                                          |
149      ]])
150
151      -- ambiwidth=double defaults to single-byte fillchars.
152      command('set ambiwidth=double')
153      screen:expect([[
154        1                        |1                       |
155        {13:^+--  2 lines: 2----------}|{13:+--  2 lines: 2---------}|
156        4                        |4                       |
157        {1:~                        }|{1:~                       }|
158                                                          |
159      ]])
160
161      -- change "vert" character to single-cell
162      fn.setcellwidths({ { 0x2502, 0x2502, 1 } })
163      screen:expect([[
164        1                        │1                       |
165        {13:^+--  2 lines: 2----------}│{13:+--  2 lines: 2---------}|
166        4                        │4                       |
167        {1:~                        }│{1:~                       }|
168                                                          |
169      ]])
170
171      -- change "vert" character to double-cell
172      fn.setcellwidths({ { 0x2502, 0x2502, 2 } })
173      screen:expect([[
174        1                        |1                       |
175        {13:^+--  2 lines: 2----------}|{13:+--  2 lines: 2---------}|
176        4                        |4                       |
177        {1:~                        }|{1:~                       }|
178                                                          |
179      ]])
180
181      -- "vert" character should still default to single-byte fillchars because of setcellwidths().
182      command('set ambiwidth=single')
183      screen:expect([[
184        1                        |1                       |
185        {13:^+--  2 lines: 2··········}|{13:+--  2 lines: 2·········}|
186        4                        |4                       |
187        {1:~                        }|{1:~                       }|
188                                                          |
189      ]])
190    end)
191  end)
192
193  it("'shadafile' ('viminfofile')", function()
194    local env = {
195      XDG_DATA_HOME = 'Xtest-userdata',
196      XDG_STATE_HOME = 'Xtest-userstate',
197      XDG_CONFIG_HOME = 'Xtest-userconfig',
198    }
199    finally(function()
200      command('set shadafile=NONE') -- Avoid writing shada file on exit
201      rmdir('Xtest-userstate')
202      os.remove('Xtest-foo')
203    end)
204
205    clear { args = {}, args_rm = { '-i', '--cmd' }, env = env }
206    -- Default 'shadafile' is empty.
207    -- This means use the default location. :help shada-file-name
208    eq('', api.nvim_get_option_value('shadafile', {}))
209    eq('', api.nvim_get_option_value('viminfofile', {}))
210    -- Handles viminfo/viminfofile as alias for shada/shadafile.
211    eq('\n  shadafile=', eval('execute("set shadafile?")'))
212    eq('\n  shadafile=', eval('execute("set viminfofile?")'))
213    eq("\n  shada=!,'100,<50,s10,h,r/tmp/,r/private/", eval('execute("set shada?")'))
214    eq("\n  shada=!,'100,<50,s10,h,r/tmp/,r/private/", eval('execute("set viminfo?")'))
215
216    -- Remove /tmp/ exclusion so test works when run in temp directories.
217    command("set shada=!,'100,<50,s10,h")
218    -- Check that shada data (such as v:oldfiles) is saved/restored.
219    command('edit Xtest-foo')
220    command('write')
221    local f = eval('fnamemodify(@%,":p")')
222    assert(string.len(f) > 3)
223    expect_exit(command, 'qall')
224    clear { args = {}, args_rm = { '-i', '--cmd' }, env = env }
225    eq({ f }, eval('v:oldfiles'))
226  end)
227
228  it("'packpath'", function()
229    clear {
230      args_rm = { 'runtimepath' },
231    }
232    -- Defaults to &runtimepath.
233    eq(api.nvim_get_option_value('runtimepath', {}), api.nvim_get_option_value('packpath', {}))
234
235    -- Does not follow modifications to runtimepath.
236    command('set runtimepath+=foo')
237    neq(api.nvim_get_option_value('runtimepath', {}), api.nvim_get_option_value('packpath', {}))
238    command('set packpath+=foo')
239    eq(api.nvim_get_option_value('runtimepath', {}), api.nvim_get_option_value('packpath', {}))
240  end)
241
242  it('v:progpath is set to the absolute path', function()
243    clear()
244    eq(eval("fnamemodify(v:progpath, ':p')"), eval('v:progpath'))
245  end)
246
247  describe('$NVIM_LOG_FILE', function()
248    local xdgdir = 'Xtest-startup-xdg-logpath'
249    local xdgstatedir = is_os('win') and xdgdir .. '/nvim-data' or xdgdir .. '/nvim'
250    after_each(function()
251      os.remove('Xtest-logpath')
252      rmdir(xdgdir)
253    end)
254
255    it('is used if expansion succeeds', function()
256      clear({ env = {
257        NVIM_LOG_FILE = 'Xtest-logpath',
258      } })
259      eq('Xtest-logpath', eval('$NVIM_LOG_FILE'))
260    end)
261
262    it('defaults to stdpath("log")/nvim.log if empty', function()
263      eq(true, mkdir(xdgdir) and mkdir(xdgstatedir))
264      clear({
265        env = {
266          XDG_STATE_HOME = xdgdir,
267          NVIM_LOG_FILE = '', -- Empty is invalid.
268        },
269      })
270      eq(('%s/logs/nvim.log'):format(xdgstatedir), eval('$NVIM_LOG_FILE'))
271    end)
272
273    it('defaults to stdpath("log")/nvim.log if invalid', function()
274      eq(true, mkdir(xdgdir) and mkdir(xdgstatedir))
275      clear({
276        env = {
277          XDG_STATE_HOME = xdgdir,
278          NVIM_LOG_FILE = '.', -- Any directory is invalid.
279        },
280      })
281      eq(('%s/logs/nvim.log'):format(xdgstatedir), eval('$NVIM_LOG_FILE'))
282      -- Avoid "failed to open $NVIM_LOG_FILE" noise in test output.
283      expect_exit(command, 'qall!')
284    end)
285  end)
286end)
287
288describe('XDG defaults', function()
289  -- Need separate describe() blocks to not run clear() twice.
290  -- Do not put before_each() here for the same reasons.
291
292  after_each(function()
293    check_close()
294    os.remove(testlog)
295  end)
296
297  it("&runtimepath data-dir matches stdpath('data') #9910", function()
298    clear()
299    local rtp = eval('split(&runtimepath, ",")')
300    local rv = {}
301    local data_dir = is_os('win') and '/nvim-data' or '/nvim'
302    local expected = { data_dir .. '/site', data_dir .. '/site/after' }
303
304    for _, v in ipairs(rtp) do
305      local m = string.match(v, [=[[/\]nvim[^/\]*[/\]site.*$]=])
306      if m and not tbl_contains(rv, m) then
307        table.insert(rv, m)
308      end
309    end
310    eq(expected, rv)
311  end)
312
313  describe('with empty/broken environment', function()
314    it('sets correct defaults', function()
315      clear({
316        env = {
317          XDG_CONFIG_HOME = nil,
318          XDG_DATA_HOME = nil,
319          XDG_CACHE_HOME = nil,
320          XDG_STATE_HOME = nil,
321          XDG_RUNTIME_DIR = nil,
322          XDG_CONFIG_DIRS = nil,
323          XDG_DATA_DIRS = nil,
324          LOCALAPPDATA = nil,
325          HOMEPATH = nil,
326          HOMEDRIVE = nil,
327          HOME = nil,
328          TEMP = nil,
329          VIMRUNTIME = nil,
330          USER = nil,
331        },
332      })
333
334      eq('.', api.nvim_get_option_value('backupdir', {}))
335      eq('.', api.nvim_get_option_value('viewdir', {}))
336      eq('.', api.nvim_get_option_value('directory', {}))
337      eq('.', api.nvim_get_option_value('undodir', {}))
338      ok((fn.tempname()):len() > 4)
339    end)
340  end)
341
342  local function vimruntime_and_libdir()
343    local vimruntime = eval('$VIMRUNTIME')
344    -- libdir is hard to calculate reliably across various ci platforms
345    -- local libdir = string.gsub(vimruntime, "share/nvim/runtime$", "lib/nvim")
346    local libdir = api.nvim__get_lib_dir()
347    return vimruntime, libdir
348  end
349
350  local env_sep = is_os('win') and ';' or ':'
351  local data_dir = is_os('win') and 'nvim-data' or 'nvim'
352  local state_dir = is_os('win') and 'nvim-data' or 'nvim'
353  local root_path = is_os('win') and 'C:' or ''
354
355  describe('with too long XDG vars', function()
356    before_each(function()
357      clear({
358        -- Ensure valid --listen address despite broken XDG vars (else Nvim won't start).
359        args = { '--listen', is_os('win') and '' or t.tmpname(false) },
360        args_rm = { 'runtimepath' },
361        env = {
362          NVIM_LOG_FILE = testlog,
363          XDG_CONFIG_HOME = (root_path .. ('/x'):rep(4096)),
364          XDG_CONFIG_DIRS = (root_path .. ('/a'):rep(2048) .. env_sep .. root_path .. ('/b'):rep(
365            2048
366          ) .. (env_sep .. root_path .. '/c'):rep(512)),
367          XDG_DATA_HOME = (root_path .. ('/X'):rep(4096)),
368          XDG_RUNTIME_DIR = (root_path .. ('/X'):rep(4096)),
369          XDG_STATE_HOME = (root_path .. ('/X'):rep(4096)),
370          XDG_DATA_DIRS = (root_path .. ('/A'):rep(2048) .. env_sep .. root_path .. ('/B'):rep(
371            2048
372          ) .. (env_sep .. root_path .. '/C'):rep(512)),
373        },
374      })
375    end)
376
377    it('are correctly set', function()
378      if not is_os('win') then
379        -- Broken XDG vars cause serverstart() to fail (except on Windows, where servernames are not
380        -- informed by $XDG_STATE_HOME).
381        t.matches('Failed to start server: invalid argument', t.pcall_err(fn.serverstart))
382        assert_log('Failed to start server: invalid argument: /X/X/X', testlog, 10)
383      end
384
385      local vimruntime, libdir = vimruntime_and_libdir()
386
387      local expected_paths = table.concat({
388        ('%s%s/nvim'):format(root_path, ('/x'):rep(4096)),
389        ('%s%s/nvim'):format(root_path, ('/a'):rep(2048)),
390        ('%s%s/nvim'):format(root_path, ('/b'):rep(2048)),
391        ('%s/c/nvim'):format(root_path),
392        ('%s%s/%s/site'):format(root_path, ('/X'):rep(4096), data_dir),
393        ('%s%s/nvim/site'):format(root_path, ('/A'):rep(2048)),
394        ('%s%s/nvim/site'):format(root_path, ('/B'):rep(2048)),
395        ('%s/C/nvim/site'):format(root_path),
396        vimruntime,
397        libdir,
398        ('%s/C/nvim/site/after'):format(root_path),
399        ('%s%s/nvim/site/after'):format(root_path, ('/B'):rep(2048)),
400        ('%s%s/nvim/site/after'):format(root_path, ('/A'):rep(2048)),
401        ('%s%s/%s/site/after'):format(root_path, ('/X'):rep(4096), data_dir),
402        ('%s/c/nvim/after'):format(root_path),
403        ('%s%s/nvim/after'):format(root_path, ('/b'):rep(2048)),
404        ('%s%s/nvim/after'):format(root_path, ('/a'):rep(2048)),
405        ('%s%s/nvim/after'):format(root_path, ('/x'):rep(4096)),
406      }, ',')
407      eq(expected_paths, api.nvim_get_option_value('runtimepath', {}))
408      command('set runtimepath&')
409      command('set backupdir&')
410      command('set directory&')
411      command('set undodir&')
412      command('set viewdir&')
413      eq(expected_paths, api.nvim_get_option_value('runtimepath', {}))
414      eq(
415        ('.,%s%s/%s/backup//'):format(root_path, ('/X'):rep(4096), state_dir),
416        api.nvim_get_option_value('backupdir', {})
417      )
418      eq(
419        ('%s%s/%s/swap//'):format(root_path, ('/X'):rep(4096), state_dir),
420        api.nvim_get_option_value('directory', {})
421      )
422      eq(
423        ('%s%s/%s/undo//'):format(root_path, ('/X'):rep(4096), state_dir),
424        api.nvim_get_option_value('undodir', {})
425      )
426      eq(
427        ('%s%s/%s/view//'):format(root_path, ('/X'):rep(4096), state_dir),
428        api.nvim_get_option_value('viewdir', {})
429      )
430    end)
431  end)
432
433  describe('with expandable XDG vars', function()
434    before_each(function()
435      clear({
436        -- Ensure valid --listen address despite broken XDG vars (else Nvim won't start).
437        args = { '--listen', is_os('win') and '' or t.tmpname(false) },
438        args_rm = { 'runtimepath' },
439        env = {
440          NVIM_LOG_FILE = testlog,
441          XDG_CONFIG_HOME = '$XDG_DATA_HOME',
442          XDG_CONFIG_DIRS = '$XDG_DATA_DIRS',
443          XDG_DATA_HOME = '$XDG_CONFIG_HOME',
444          XDG_RUNTIME_DIR = '$XDG_RUNTIME_DIR',
445          XDG_STATE_HOME = '$XDG_CONFIG_HOME',
446          XDG_DATA_DIRS = '$XDG_CONFIG_DIRS',
447        },
448      })
449    end)
450
451    after_each(function()
452      command('set shadafile=NONE') -- Avoid writing shada file on exit
453    end)
454
455    it('are not expanded', function()
456      if not is_os('win') then
457        -- Broken XDG vars cause serverstart() to fail (except on Windows, where servernames are not
458        -- informed by $XDG_STATE_HOME).
459        t.matches('Failed to start server: no such file or directory', t.pcall_err(fn.serverstart))
460        assert_log(
461          'Failed to start server: no such file or directory: %$XDG_RUNTIME_DIR%/',
462          testlog,
463          10
464        )
465      end
466
467      local vimruntime, libdir = vimruntime_and_libdir()
468      local expected_paths = table.concat({
469        '$XDG_DATA_HOME/nvim',
470        '$XDG_DATA_DIRS/nvim',
471        ('$XDG_CONFIG_HOME/%s/site'):format(data_dir),
472        '$XDG_CONFIG_DIRS/nvim/site',
473        vimruntime,
474        libdir,
475        '$XDG_CONFIG_DIRS/nvim/site/after',
476        ('$XDG_CONFIG_HOME/%s/site/after'):format(data_dir),
477        '$XDG_DATA_DIRS/nvim/after',
478        '$XDG_DATA_HOME/nvim/after',
479      }, ',')
480      eq(expected_paths, api.nvim_get_option_value('runtimepath', {}))
481      command('set runtimepath&')
482      command('set backupdir&')
483      command('set directory&')
484      command('set undodir&')
485      command('set viewdir&')
486      eq(expected_paths, api.nvim_get_option_value('runtimepath', {}))
487      eq(
488        ('.,$XDG_CONFIG_HOME/%s/backup//'):format(state_dir),
489        api.nvim_get_option_value('backupdir', {})
490      )
491      eq(
492        ('$XDG_CONFIG_HOME/%s/swap//'):format(state_dir),
493        api.nvim_get_option_value('directory', {})
494      )
495      eq(('$XDG_CONFIG_HOME/%s/undo//'):format(state_dir), api.nvim_get_option_value('undodir', {}))
496      eq(('$XDG_CONFIG_HOME/%s/view//'):format(state_dir), api.nvim_get_option_value('viewdir', {}))
497      command('set all&')
498      eq(expected_paths, api.nvim_get_option_value('runtimepath', {}))
499      eq(
500        ('.,$XDG_CONFIG_HOME/%s/backup//'):format(state_dir),
501        api.nvim_get_option_value('backupdir', {})
502      )
503      eq(
504        ('$XDG_CONFIG_HOME/%s/swap//'):format(state_dir),
505        api.nvim_get_option_value('directory', {})
506      )
507      eq(('$XDG_CONFIG_HOME/%s/undo//'):format(state_dir), api.nvim_get_option_value('undodir', {}))
508      eq(('$XDG_CONFIG_HOME/%s/view//'):format(state_dir), api.nvim_get_option_value('viewdir', {}))
509      eq(nil, (fn.tempname()):match('XDG_RUNTIME_DIR'))
510    end)
511  end)
512
513  describe('with commas', function()
514    before_each(function()
515      clear({
516        args_rm = { 'runtimepath' },
517        env = {
518          XDG_CONFIG_HOME = ', , ,',
519          XDG_CONFIG_DIRS = ',-,-,' .. env_sep .. '-,-,-',
520          XDG_DATA_HOME = ',=,=,',
521          XDG_STATE_HOME = ',=,=,',
522          XDG_DATA_DIRS = ',≡,≡,' .. env_sep .. '≡,≡,≡',
523        },
524      })
525    end)
526
527    it('are escaped properly', function()
528      local vimruntime, libdir = vimruntime_and_libdir()
529      local path_sep = '/'
530      eq(
531        (
532          '\\, \\, \\,'
533          .. path_sep
534          .. 'nvim'
535          .. ',\\,-\\,-\\,'
536          .. path_sep
537          .. 'nvim'
538          .. ',-\\,-\\,-'
539          .. path_sep
540          .. 'nvim'
541          .. ',\\,=\\,=\\,'
542          .. path_sep
543          .. data_dir
544          .. path_sep
545          .. 'site'
546          .. ',\\,≡\\,≡\\,'
547          .. path_sep
548          .. 'nvim'
549          .. path_sep
550          .. 'site'
551          .. ',≡\\,≡\\,≡'
552          .. path_sep
553          .. 'nvim'
554          .. path_sep
555          .. 'site'
556          .. ','
557          .. vimruntime
558          .. ','
559          .. libdir
560          .. ',≡\\,≡\\,≡'
561          .. path_sep
562          .. 'nvim'
563          .. path_sep
564          .. 'site'
565          .. path_sep
566          .. 'after'
567          .. ',\\,≡\\,≡\\,'
568          .. path_sep
569          .. 'nvim'
570          .. path_sep
571          .. 'site'
572          .. path_sep
573          .. 'after'
574          .. ',\\,=\\,=\\,'
575          .. path_sep
576          .. data_dir
577          .. path_sep
578          .. 'site'
579          .. path_sep
580          .. 'after'
581          .. ',-\\,-\\,-'
582          .. path_sep
583          .. 'nvim'
584          .. path_sep
585          .. 'after'
586          .. ',\\,-\\,-\\,'
587          .. path_sep
588          .. 'nvim'
589          .. path_sep
590          .. 'after'
591          .. ',\\, \\, \\,'
592          .. path_sep
593          .. 'nvim'
594          .. path_sep
595          .. 'after'
596        ),
597        api.nvim_get_option_value('runtimepath', {})
598      )
599      command('set runtimepath&')
600      command('set backupdir&')
601      command('set directory&')
602      command('set undodir&')
603      command('set viewdir&')
604      eq(
605        (
606          '\\, \\, \\,'
607          .. path_sep
608          .. 'nvim'
609          .. ',\\,-\\,-\\,'
610          .. path_sep
611          .. 'nvim'
612          .. ',-\\,-\\,-'
613          .. path_sep
614          .. 'nvim'
615          .. ',\\,=\\,=\\,'
616          .. path_sep
617          .. ''
618          .. data_dir
619          .. ''
620          .. path_sep
621          .. 'site'
622          .. ',\\,≡\\,≡\\,'
623          .. path_sep
624          .. 'nvim'
625          .. path_sep
626          .. 'site'
627          .. ',≡\\,≡\\,≡'
628          .. path_sep
629          .. 'nvim'
630          .. path_sep
631          .. 'site'
632          .. ','
633          .. vimruntime
634          .. ','
635          .. libdir
636          .. ',≡\\,≡\\,≡'
637          .. path_sep
638          .. 'nvim'
639          .. path_sep
640          .. 'site'
641          .. path_sep
642          .. 'after'
643          .. ',\\,≡\\,≡\\,'
644          .. path_sep
645          .. 'nvim'
646          .. path_sep
647          .. 'site'
648          .. path_sep
649          .. 'after'
650          .. ',\\,=\\,=\\,'
651          .. path_sep
652          .. ''
653          .. data_dir
654          .. ''
655          .. path_sep
656          .. 'site'
657          .. path_sep
658          .. 'after'
659          .. ',-\\,-\\,-'
660          .. path_sep
661          .. 'nvim'
662          .. path_sep
663          .. 'after'
664          .. ',\\,-\\,-\\,'
665          .. path_sep
666          .. 'nvim'
667          .. path_sep
668          .. 'after'
669          .. ',\\, \\, \\,'
670          .. path_sep
671          .. 'nvim'
672          .. path_sep
673          .. 'after'
674        ),
675        api.nvim_get_option_value('runtimepath', {})
676      )
677      eq(
678        '.,\\,=\\,=\\,' .. path_sep .. state_dir .. '' .. path_sep .. 'backup' .. (path_sep):rep(2),
679        api.nvim_get_option_value('backupdir', {})
680      )
681      eq(
682        '\\,=\\,=\\,'
683          .. path_sep
684          .. ''
685          .. state_dir
686          .. ''
687          .. path_sep
688          .. 'swap'
689          .. (path_sep):rep(2),
690        api.nvim_get_option_value('directory', {})
691      )
692      eq(
693        '\\,=\\,=\\,'
694          .. path_sep
695          .. ''
696          .. state_dir
697          .. ''
698          .. path_sep
699          .. 'undo'
700          .. (path_sep):rep(2),
701        api.nvim_get_option_value('undodir', {})
702      )
703      eq(',=,=,/' .. state_dir .. '/view//', api.nvim_get_option_value('viewdir', {}))
704    end)
705  end)
706end)
707
708describe('stdpath()', function()
709  after_each(function()
710    check_close()
711    os.remove(testlog)
712  end)
713
714  --- Windows appends 'nvim-data' instead of just 'nvim' to prevent collisions
715  --- due to XDG_CONFIG_HOME, XDG_DATA_HOME and XDG_STATE_HOME being the same.
716  --- @param name string
717  local function maybe_data(name)
718    return is_os('win') and name .. '-data' or name
719  end
720
721  local datadir = maybe_data('nvim')
722  local statedir = maybe_data('nvim')
723  local env_sep = is_os('win') and ';' or ':'
724
725  it('works', function()
726    clear() -- Do not explicitly set any env vars.
727
728    eq('nvim', fn.fnamemodify(fn.stdpath('cache'), ':t'))
729    eq('nvim', fn.fnamemodify(fn.stdpath('config'), ':t'))
730    eq(datadir, fn.fnamemodify(fn.stdpath('data'), ':t'))
731    eq(statedir, fn.fnamemodify(fn.stdpath('state'), ':t'))
732    eq('table', type(fn.stdpath('config_dirs')))
733    eq('table', type(fn.stdpath('data_dirs')))
734    eq('string', type(fn.stdpath('run')))
735    assert_alive() -- Check for crash. #8393
736  end)
737
738  it('failure modes', function()
739    clear()
740    eq(
741      'Vim(call):E6100: "capybara" is not a valid stdpath',
742      pcall_err(command, 'call stdpath("capybara")')
743    )
744    eq('Vim(call):E6100: "" is not a valid stdpath', pcall_err(command, 'call stdpath("")'))
745    eq('Vim(call):E6100: "23" is not a valid stdpath', pcall_err(command, 'call stdpath(23)'))
746    eq(
747      'Vim(call):E731: Using a Dictionary as a String',
748      pcall_err(command, 'call stdpath({"eris": 23})')
749    )
750    eq('Vim(call):E730: Using a List as a String', pcall_err(command, 'call stdpath([23])'))
751  end)
752
753  it('$NVIM_APPNAME', function()
754    local appname = 'NVIM_APPNAME_TEST' .. ('_'):rep(106)
755    clear({ env = { NVIM_APPNAME = appname, NVIM_LOG_FILE = testlog } })
756    eq(appname, fn.fnamemodify(fn.stdpath('config'), ':t'))
757    eq(appname, fn.fnamemodify(fn.stdpath('cache'), ':t'))
758    eq(maybe_data(appname), fn.fnamemodify(fn.stdpath('log'), ':h:t'))
759    eq(maybe_data(appname), fn.fnamemodify(fn.stdpath('data'), ':t'))
760    eq(maybe_data(appname), fn.fnamemodify(fn.stdpath('state'), ':t'))
761    -- config_dirs and data_dirs are empty on windows, so don't check them on
762    -- that platform
763    if not is_os('win') then
764      eq(appname, fn.fnamemodify(fn.stdpath('config_dirs')[1], ':t'))
765      eq(appname, fn.fnamemodify(fn.stdpath('data_dirs')[1], ':t'))
766    end
767    assert_alive() -- Check for crash. #8393
768
769    -- Check that Nvim rejects invalid APPNAMEs
770    local function test_appname(testAppname, expected_exitcode)
771      local p = n.spawn_wait({
772        args = { '--listen', 'x', '+qall!' },
773        env = { NVIM_APPNAME = testAppname },
774      })
775      eq(expected_exitcode, p.status)
776    end
777    -- Invalid appnames:
778    test_appname('a/../b', 1)
779    test_appname('../a', 1)
780    test_appname('a/..', 1)
781    test_appname('..', 1)
782    test_appname('.', 1)
783    test_appname('/', 1)
784    test_appname('\\', 1)
785    if is_os('win') then
786      test_appname('..\\a', 1)
787      test_appname('a\\..', 1)
788    end
789    test_appname(is_os('win') and 'C:/a/b' or '/a/b', 1)
790    -- Valid appnames:
791    test_appname('a/b', 0)
792    test_appname('a/b\\c', 0)
793  end)
794
795  it('$NVIM_APPNAME relative path', function()
796    local tmpdir = t.tmpname(false)
797    t.mkdir(tmpdir)
798    -- Short runtime dir so the autogenerated server socket fits in sun_path even
799    -- when $TMPDIR is deep (otherwise the server fails to bind, see #38623).
800    local xdg_run = 'Xtest-appname-run'
801    mkdir(xdg_run)
802    finally(function()
803      rmdir(xdg_run)
804    end)
805
806    clear({
807      args_rm = { '--listen' },
808      env = {
809        NVIM_APPNAME = 'relative/appname',
810        NVIM_LOG_FILE = testlog,
811        TMPDIR = tmpdir,
812        XDG_RUNTIME_DIR = xdg_run,
813      },
814    })
815
816    t.matches(vim.pesc(tmpdir), fn.tempname())
817    t.assert_nolog('tempdir', testlog, 100)
818    t.assert_nolog('TMPDIR', testlog, 100)
819    t.matches([[/relative%-appname.%d+]], api.nvim_get_vvar('servername'))
820  end)
821
822  describe('returns a String', function()
823    describe('with "config"', function()
824      it('knows XDG_CONFIG_HOME', function()
825        clear({
826          env = {
827            XDG_CONFIG_HOME = '/home/docwhat/.config',
828          },
829        })
830        eq('/home/docwhat/.config/nvim', fn.stdpath('config'))
831      end)
832
833      it('handles changes during runtime', function()
834        clear({ env = {
835          XDG_CONFIG_HOME = '/home/original',
836        } })
837        eq('/home/original/nvim', fn.stdpath('config'))
838        command("let $XDG_CONFIG_HOME='/home/new'")
839        eq('/home/new/nvim', fn.stdpath('config'))
840      end)
841
842      it("doesn't expand $VARIABLES", function()
843        clear({
844          env = {
845            XDG_CONFIG_HOME = '$VARIABLES',
846            VARIABLES = 'this-should-not-happen',
847          },
848        })
849        eq('$VARIABLES/nvim', fn.stdpath('config'))
850      end)
851
852      it("doesn't expand ~/", function()
853        clear({ env = {
854          XDG_CONFIG_HOME = '~/frobnitz',
855        } })
856        eq('~/frobnitz/nvim', fn.stdpath('config'))
857      end)
858    end)
859
860    describe('with "data"', function()
861      it('knows XDG_DATA_HOME', function()
862        clear({ env = {
863          XDG_DATA_HOME = '/home/docwhat/.local',
864        } })
865        eq(('/home/docwhat/.local/%s'):format(datadir), fn.stdpath('data'))
866      end)
867
868      it('handles changes during runtime', function()
869        clear({ env = {
870          XDG_DATA_HOME = '/home/original',
871        } })
872        eq(('/home/original/%s'):format(datadir), fn.stdpath('data'))
873        command("let $XDG_DATA_HOME='/home/new'")
874        eq(('/home/new/%s'):format(datadir), fn.stdpath('data'))
875      end)
876
877      it("doesn't expand $VARIABLES", function()
878        clear({
879          env = {
880            XDG_DATA_HOME = '$VARIABLES',
881            VARIABLES = 'this-should-not-happen',
882          },
883        })
884        eq(('$VARIABLES/%s'):format(datadir), fn.stdpath('data'))
885      end)
886
887      it("doesn't expand ~/", function()
888        clear({ env = {
889          XDG_DATA_HOME = '~/frobnitz',
890        } })
891        eq(('~/frobnitz/%s'):format(datadir), fn.stdpath('data'))
892      end)
893    end)
894
895    describe('with "state"', function()
896      it('knows XDG_STATE_HOME', function()
897        clear({
898          env = {
899            XDG_STATE_HOME = '/home/docwhat/.local',
900          },
901        })
902        eq(('/home/docwhat/.local/%s'):format(statedir), fn.stdpath('state'))
903      end)
904
905      it('handles changes during runtime', function()
906        clear({ env = {
907          XDG_STATE_HOME = '/home/original',
908        } })
909        eq(('/home/original/%s'):format(statedir), fn.stdpath('state'))
910        command("let $XDG_STATE_HOME='" .. '/home/new' .. "'")
911        eq(('/home/new/%s'):format(statedir), fn.stdpath('state'))
912      end)
913
914      it("doesn't expand $VARIABLES", function()
915        clear({
916          env = {
917            XDG_STATE_HOME = '$VARIABLES',
918            VARIABLES = 'this-should-not-happen',
919          },
920        })
921        eq(('$VARIABLES/%s'):format(statedir), fn.stdpath('state'))
922      end)
923
924      it("doesn't expand ~/", function()
925        clear({ env = {
926          XDG_STATE_HOME = '~/frobnitz',
927        } })
928        eq(('~/frobnitz/%s'):format(statedir), fn.stdpath('state'))
929      end)
930    end)
931
932    describe('with "cache"', function()
933      it('knows XDG_CACHE_HOME', function()
934        clear({
935          env = {
936            XDG_CACHE_HOME = '/home/docwhat/.cache',
937          },
938        })
939        eq('/home/docwhat/.cache/nvim', fn.stdpath('cache'))
940      end)
941
942      it('handles changes during runtime', function()
943        clear({ env = {
944          XDG_CACHE_HOME = '/home/original',
945        } })
946        eq('/home/original/nvim', fn.stdpath('cache'))
947        command("let $XDG_CACHE_HOME='" .. '/home/new' .. "'")
948        eq('/home/new/nvim', fn.stdpath('cache'))
949      end)
950
951      it("doesn't expand $VARIABLES", function()
952        clear({
953          env = {
954            XDG_CACHE_HOME = '$VARIABLES',
955            VARIABLES = 'this-should-not-happen',
956          },
957        })
958        eq('$VARIABLES/nvim', fn.stdpath('cache'))
959      end)
960
961      it("doesn't expand ~/", function()
962        clear({ env = {
963          XDG_CACHE_HOME = '~/frobnitz',
964        } })
965        eq('~/frobnitz/nvim', fn.stdpath('cache'))
966      end)
967    end)
968  end)
969
970  describe('returns a List', function()
971    -- Some OS specific variables the system would have set.
972    local function base_env()
973      if is_os('win') then
974        return {
975          HOME = 'C:\\Users\\docwhat', -- technically, is not a usual PATH
976          HOMEDRIVE = 'C:',
977          HOMEPATH = '\\Users\\docwhat',
978          LOCALAPPDATA = 'C:\\Users\\docwhat\\AppData\\Local',
979          NVIM_LOG_FILE = testlog,
980          TEMP = 'C:\\Users\\docwhat\\AppData\\Local\\Temp',
981          TMPDIR = 'C:\\Users\\docwhat\\AppData\\Local\\Temp',
982          TMP = 'C:\\Users\\docwhat\\AppData\\Local\\Temp',
983        }
984      else
985        return {
986          HOME = '/home/docwhat',
987          HOMEDRIVE = 'HOMEDRIVE-should-be-ignored',
988          HOMEPATH = 'HOMEPATH-should-be-ignored',
989          LOCALAPPDATA = 'LOCALAPPDATA-should-be-ignored',
990          NVIM_LOG_FILE = testlog,
991          TEMP = 'TEMP-should-be-ignored',
992          TMPDIR = 'TMPDIR-should-be-ignored',
993          TMP = 'TMP-should-be-ignored',
994        }
995      end
996    end
997
998    local function set_paths_via_system(var_name, paths)
999      local env = base_env()
1000      env[var_name] = table.concat(paths, env_sep)
1001      clear({ env = env })
1002    end
1003
1004    local function set_paths_at_runtime(var_name, paths)
1005      clear({ env = base_env() })
1006      api.nvim_set_var('env_val', table.concat(paths, env_sep))
1007      command(('let $%s=g:env_val'):format(var_name))
1008    end
1009
1010    local function behaves_like_dir_list_env(msg, stdpath_arg, env_var_name, paths, expected_paths)
1011      describe(msg, function()
1012        it('set via system', function()
1013          set_paths_via_system(env_var_name, paths)
1014          eq(expected_paths, fn.stdpath(stdpath_arg))
1015          if not is_os('win') then
1016            assert_log(
1017              '$TMPDIR tempdir not a directory[^\n]*TMPDIR%-should%-be%-ignored',
1018              testlog,
1019              100
1020            )
1021          end
1022        end)
1023
1024        it('set at runtime', function()
1025          set_paths_at_runtime(env_var_name, paths)
1026          eq(expected_paths, fn.stdpath(stdpath_arg))
1027          if not is_os('win') then
1028            assert_log(
1029              '$TMPDIR tempdir not a directory[^\n]*TMPDIR%-should%-be%-ignored',
1030              testlog,
1031              100
1032            )
1033          end
1034        end)
1035      end)
1036    end
1037
1038    describe('with "config_dirs"', function()
1039      behaves_like_dir_list_env(
1040        'handles XDG_CONFIG_DIRS with one path',
1041        'config_dirs',
1042        'XDG_CONFIG_DIRS',
1043        {
1044          '/home/docwhat/.config',
1045        },
1046        {
1047          '/home/docwhat/.config/nvim',
1048        }
1049      )
1050
1051      behaves_like_dir_list_env(
1052        'handles XDG_CONFIG_DIRS with two paths',
1053        'config_dirs',
1054        'XDG_CONFIG_DIRS',
1055        {
1056          '/home/docwhat/.config',
1057          '/etc/config',
1058        },
1059        {
1060          '/home/docwhat/.config/nvim',
1061          '/etc/config/nvim',
1062        }
1063      )
1064
1065      behaves_like_dir_list_env(
1066        "doesn't expand $VAR and $IBLES",
1067        'config_dirs',
1068        'XDG_CONFIG_DIRS',
1069        { '$HOME', '$TMP' },
1070        {
1071          '$HOME/nvim',
1072          '$TMP/nvim',
1073        }
1074      )
1075
1076      behaves_like_dir_list_env("doesn't expand ~/", 'config_dirs', 'XDG_CONFIG_DIRS', {
1077        '~/.oldconfig',
1078        '~/.olderconfig',
1079      }, {
1080        '~/.oldconfig/nvim',
1081        '~/.olderconfig/nvim',
1082      })
1083    end)
1084
1085    describe('with "data_dirs"', function()
1086      behaves_like_dir_list_env('knows XDG_DATA_DIRS with one path', 'data_dirs', 'XDG_DATA_DIRS', {
1087        '/home/docwhat/.data',
1088      }, {
1089        '/home/docwhat/.data/nvim',
1090      })
1091
1092      behaves_like_dir_list_env(
1093        'knows XDG_DATA_DIRS with two paths',
1094        'data_dirs',
1095        'XDG_DATA_DIRS',
1096        {
1097          '/home/docwhat/.data',
1098          '/etc/local',
1099        },
1100        {
1101          '/home/docwhat/.data/nvim',
1102          '/etc/local/nvim',
1103        }
1104      )
1105
1106      behaves_like_dir_list_env(
1107        "doesn't expand $VAR and $IBLES",
1108        'data_dirs',
1109        'XDG_DATA_DIRS',
1110        { '$HOME', '$TMP' },
1111        {
1112          '$HOME/nvim',
1113          '$TMP/nvim',
1114        }
1115      )
1116
1117      behaves_like_dir_list_env("doesn't expand ~/", 'data_dirs', 'XDG_DATA_DIRS', {
1118        '~/.oldconfig',
1119        '~/.olderconfig',
1120      }, {
1121        '~/.oldconfig/nvim',
1122        '~/.olderconfig/nvim',
1123      })
1124    end)
1125  end)
1126
1127  it('avoids DOS 8.3 filenames for "cache" and "run" #25019', function()
1128    t.skip(not is_os('win'), 'N/A: 8.3 filenames are only available on Windows')
1129    vim.fn.system(('fsutil 8dot3name set %s 0'):format(n.nvim_dir:sub(1, 2)))
1130    local dir = 'Xtest_temp_path'
1131    mkdir(dir)
1132    finally(function()
1133      rmdir(dir)
1134    end)
1135    local short_path =
1136      vim.fn.system(('for %%I in ("%s") do @echo %%~sI'):format(dir), ''):gsub('\n', '')
1137    t.matches('^XTEST_~[12]$', vim.fs.basename(short_path))
1138    clear({
1139      env = {
1140        TMP = short_path,
1141        TEMP = short_path,
1142        TMPDIR = short_path,
1143      },
1144    })
1145    t.matches(dir, fn.stdpath('cache'))
1146    t.matches(dir, fn.stdpath('run'))
1147  end)
1148end)