robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
40.6 KiB1632 linesraw
1" Test for :mksession, :mkview and :loadview in latin1 encoding
2
3scriptencoding latin1
4
5source check.vim
6CheckFeature mksession
7
8source shared.vim
9source term_util.vim
10
11" Test for storing global and local argument list in a session file
12" This one must be done first.
13func Test__mksession_arglocal()
14  enew | only
15  n a b c
16  new
17  arglocal
18  mksession! Xtest_mks.out
19
20  %bwipe!
21  %argdelete
22  argglobal
23  source Xtest_mks.out
24  call assert_equal(2, winnr('$'))
25  call assert_equal(2, arglistid(1))
26  call assert_equal(0, arglistid(2))
27
28  %bwipe!
29  %argdelete
30  argglobal
31  call delete('Xtest_mks.out')
32endfunc
33
34func Test_mksession_arglocal_localdir()
35  argglobal
36  %argdelete
37
38  call mkdir('Xa', 'R')
39  call writefile(['This is Xb'], 'Xa/Xb.txt', 'D')
40  let olddir = getcwd()
41  let oldargs = argv()
42
43  for tabpage in [v:false, v:true]
44    let msg = tabpage ? 'tabpage-local' : 'window-local'
45
46    exe tabpage ? 'tabnew' : 'botright new'
47    exe tabpage ? 'tcd Xa' : 'lcd Xa'
48    let localdir = getcwd()
49    arglocal
50    $argadd Xb.txt
51    let localargs = argv()
52    exe tabpage ? 'tabprev' : 'wincmd p'
53    call assert_equal(olddir, getcwd(), msg)
54    call assert_equal(oldargs, argv(), msg)
55    mksession! Xtest_mks_localdir.out
56    exe tabpage ? '+tabclose' : '$close'
57    bwipe! Xa/Xb.txt
58
59    source Xtest_mks_localdir.out
60    exe tabpage ? 'tabnext' : 'wincmd b'
61    call assert_equal(localdir, getcwd(), msg)
62    call assert_equal(localargs, argv(), msg)
63    $argument
64    call assert_equal('This is Xb', getline(1), msg)
65
66    bwipe!
67    call assert_equal(olddir, getcwd(), msg)
68    call assert_equal(oldargs, argv(), msg)
69    call delete('Xtest_mks_localdir.out')
70  endfor
71endfunc
72
73func Test_mksession()
74  tabnew
75  let wrap_save = &wrap
76  set sessionoptions=buffers splitbelow fileencoding=latin1
77  defer execute('set sessionoptions& splitbelow&')
78  call setline(1, [
79    \   'start:',
80    \   'no multibyte chAracter',
81    \   '	one leaDing tab',
82    \   '    four leadinG spaces',
83    \   'two		consecutive tabs',
84    \   'two	tabs	in one line',
85    \   'one � multibyteCharacter',
86    \   'a� �  two multiByte characters',
87    \   'A���  three mulTibyte characters',
88    \   'short line',
89    \ ])
90  let tmpfile = 'Xtemp'
91  exec 'w! ' . tmpfile
92  /^start:
93  set wrap
94  vsplit
95  norm! j16|
96  split
97  norm! j16|
98  split
99  norm! j16|
100  split
101  norm! j8|
102  split
103  norm! j8|
104  split
105  norm! j16|
106  split
107  norm! j16|
108  split
109  norm! j16|
110  split
111  norm! j$
112  wincmd l
113
114  set nowrap
115  /^start:
116  norm! j16|3zl
117  split
118  norm! j016|3zl
119  split
120  norm! j016|3zl
121  split
122  norm! j08|3zl
123  split
124  norm! j08|3zl
125  split
126  norm! j016|3zl
127  split
128  norm! j016|3zl
129  split
130  norm! j016|3zl
131  split
132  call wincol()
133  mksession! Xtest_mks.out
134  let li = filter(readfile('Xtest_mks.out'), 'v:val =~# "\\(^ *normal! [0$]\\|^ *exe ''normal!\\)"')
135  let expected = [
136    \   'normal! 016|',
137    \   'normal! 016|',
138    \   'normal! 016|',
139    \   'normal! 08|',
140    \   'normal! 08|',
141    \   'normal! 016|',
142    \   'normal! 016|',
143    \   'normal! 016|',
144    \   'normal! $',
145    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
146    \   "  normal! 016|",
147    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
148    \   "  normal! 016|",
149    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
150    \   "  normal! 016|",
151    \   "  exe 'normal! ' . s:c . '|zs' . 8 . '|'",
152    \   "  normal! 08|",
153    \   "  exe 'normal! ' . s:c . '|zs' . 8 . '|'",
154    \   "  normal! 08|",
155    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
156    \   "  normal! 016|",
157    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
158    \   "  normal! 016|",
159    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
160    \   "  normal! 016|",
161    \   "  exe 'normal! ' . s:c . '|zs' . 16 . '|'",
162    \   "  normal! 016|"
163    \ ]
164  call assert_equal(expected, li)
165  tabclose!
166
167  call delete('Xtest_mks.out')
168  call delete(tmpfile)
169  let &wrap = wrap_save
170endfunc
171
172func Test_mksession_winheight()
173  new
174  set winheight=10
175  defer execute('set winheight&')
176  set winminheight=2
177  defer execute('set winminheight&')
178  mksession! Xtest_mks.out
179  source Xtest_mks.out
180
181  call delete('Xtest_mks.out')
182endfunc
183
184func Test_mksession_large_winheight()
185  set winheight=999
186  defer execute('set winheight&')
187  mksession! Xtest_mks_winheight.out
188  set winheight&
189  source Xtest_mks_winheight.out
190  call delete('Xtest_mks_winheight.out')
191endfunc
192
193func Test_mksession_zero_winheight()
194  set winminheight=0
195  defer execute('set winminheight&')
196  edit SomeFile
197  split
198  wincmd _
199  mksession! Xtest_mks_zero
200  set winminheight&
201  let text = readfile('Xtest_mks_zero')->join()
202  call delete('Xtest_mks_zero')
203  close
204  " check there is no divide by zero
205  call assert_notmatch('/ 0[^0-9]', text)
206endfunc
207
208func Test_mksession_rtp()
209  if has('win32')
210    " TODO: fix problem with backslashes
211    return
212  endif
213  new
214  let _rtp=&rtp
215  " Make a real long (invalid) runtimepath value,
216  " that should exceed PATH_MAX (hopefully)
217  let newrtp=&rtp.',~'.repeat('/foobar', 1000)
218  let newrtp.=",".expand("$HOME")."/.vim"
219  let &rtp=newrtp
220
221  " determine expected value
222  let expected=split(&rtp, ',')
223  let expected = map(expected, '"set runtimepath+=".v:val')
224  let expected = ['set runtimepath='] + expected
225  let expected = map(expected, {v,w -> substitute(w, $HOME, "~", "g")})
226
227  mksession! Xtest_mks.out
228  let &rtp=_rtp
229  let li = filter(readfile('Xtest_mks.out'), 'v:val =~# "runtimepath"')
230  call assert_equal(expected, li)
231
232  call delete('Xtest_mks.out')
233endfunc
234
235func Test_mksession_arglist()
236  %argdel
237  next file1 file2 file3 file4
238  new
239  next | next
240  mksession! Xtest_mks.out
241  source Xtest_mks.out
242  call assert_equal(['file1', 'file2', 'file3', 'file4'], argv())
243  call assert_equal(2, argidx())
244  wincmd w
245  call assert_equal(0, argidx())
246
247  call delete('Xtest_mks.out')
248  enew | only
249  argdel *
250endfunc
251
252func Test_mksession_one_buffer_two_windows()
253  set splitbelow
254  defer execute('set splitbelow&')
255
256  edit Xtest1
257  new Xtest2
258  split
259  mksession! Xtest_mks.out
260  let lines = readfile('Xtest_mks.out')
261  let count1 = 0
262  let count2 = 0
263  let count2buf = 0
264  let bufexists = 0
265  for line in lines
266    if line =~ 'edit \f*Xtest1$'
267      let count1 += 1
268    endif
269    if line =~ 'edit \f\{-}Xtest2'
270      let count2 += 1
271    endif
272    if line =~ 'buffer \f\{-}Xtest2'
273      let count2buf += 1
274    endif
275    if line =~ 'bufexists(fnamemodify(.*, ":p")'
276      let bufexists += 1
277    endif
278  endfor
279  call assert_equal(1, count1, 'Xtest1 count')
280  call assert_equal(2, count2, 'Xtest2 count')
281  call assert_equal(2, count2buf, 'Xtest2 buffer count')
282  call assert_equal(2, bufexists)
283
284  close
285  bwipe!
286  call delete('Xtest_mks.out')
287endfunc
288
289func Test_mksession_lcd_multiple_tabs()
290  tabnew
291  tabnew
292  lcd .
293  tabfirst
294  lcd .
295  mksession! Xtest_mks.out
296  tabonly
297  source Xtest_mks.out
298  call assert_true(haslocaldir(), 'Tab 1 localdir')
299  tabnext 2
300  call assert_true(!haslocaldir(), 'Tab 2 localdir')
301  tabnext 3
302  call assert_true(haslocaldir(), 'Tab 3 localdir')
303  call delete('Xtest_mks.out')
304endfunc
305
306" Test for tabpage-local directory
307func Test_mksession_tcd_multiple_tabs()
308  let save_cwd = getcwd()
309  call mkdir('Xtopdir')
310  cd Xtopdir
311  call mkdir('Xtabdir1')
312  call mkdir('Xtabdir2')
313  call mkdir('Xtabdir3')
314  call mkdir('Xwindir1')
315  call mkdir('Xwindir2')
316  call mkdir('Xwindir3')
317  tcd Xtabdir1
318  botright new
319  wincmd t
320  lcd ../Xwindir1
321  tabnew
322  tcd ../Xtabdir2
323  botright new
324  lcd ../Xwindir2
325  tabnew
326  tcd ../Xtabdir3
327  botright new
328  lcd ../Xwindir3
329  tabfirst
330  1wincmd w
331  mksession! Xtest_mks.out
332  only | tabonly
333  source Xtest_mks.out
334  call assert_equal('Xtabdir1', fnamemodify(getcwd(-1, 1), ':t'))
335  call assert_equal('Xwindir1', fnamemodify(getcwd(1, 1), ':t'))
336  call assert_equal('Xtabdir1', fnamemodify(getcwd(2, 1), ':t'))
337  call assert_equal('Xtabdir2', fnamemodify(getcwd(-1, 2), ':t'))
338  call assert_equal('Xtabdir2', fnamemodify(getcwd(1, 2), ':t'))
339  call assert_equal('Xwindir2', fnamemodify(getcwd(2, 2), ':t'))
340  call assert_equal('Xtabdir3', fnamemodify(getcwd(-1, 3), ':t'))
341  call assert_equal('Xtabdir3', fnamemodify(getcwd(1, 3), ':t'))
342  call assert_equal('Xwindir3', fnamemodify(getcwd(2, 3), ':t'))
343  %bwipe
344  call chdir(save_cwd)
345  call delete("Xtopdir", "rf")
346endfunc
347
348func Test_mksession_blank_tabs()
349  tabnew
350  tabnew
351  tabnew
352  tabnext 3
353  mksession! Xtest_mks.out
354  tabnew
355  tabnew
356  tabnext 2
357  source Xtest_mks.out
358  call assert_equal(4, tabpagenr('$'), 'session restore should restore number of tabs')
359  call assert_equal(3, tabpagenr(), 'session restore should restore the active tab')
360  call delete('Xtest_mks.out')
361endfunc
362
363func Test_mksession_buffer_count()
364  argglobal
365  %argdelete
366
367  set hidden
368
369  " Edit exactly three files in the current session.
370  %bwipe!
371  e Xfoo | tabe Xbar | tabe Xbaz
372  tabdo write
373  mksession! Xtest_mks.out
374
375  " Verify that loading the session does not create additional buffers.
376  %bwipe!
377  source Xtest_mks.out
378  call assert_equal(3, len(getbufinfo()))
379
380  " Clean up.
381  call delete('Xfoo')
382  call delete('Xbar')
383  call delete('Xbaz')
384  call delete('Xtest_mks.out')
385  %bwipe!
386  set hidden&
387endfunc
388
389func Test_mksession_buffer_order()
390  %bwipe!
391  e Xfoo | e Xbar | e Xbaz | e Xqux
392  bufdo write
393  mksession! Xtest_mks.out
394
395  " Verify that loading the session preserves order of buffers
396  %bwipe!
397  source Xtest_mks.out
398
399  let s:buf_info = getbufinfo()
400  call assert_true(s:buf_info[0]['name'] =~# 'Xfoo$')
401  call assert_true(s:buf_info[1]['name'] =~# 'Xbar$')
402  call assert_true(s:buf_info[2]['name'] =~# 'Xbaz$')
403  call assert_true(s:buf_info[3]['name'] =~# 'Xqux$')
404
405  " Clean up.
406  call delete('Xfoo')
407  call delete('Xbar')
408  call delete('Xbaz')
409  call delete('Xqux')
410  call delete('Xtest_mks.out')
411  %bwipe!
412endfunc
413
414if has('extra_search')
415
416func Test_mksession_hlsearch()
417  set hlsearch
418  mksession! Xtest_mks.out
419  nohlsearch
420  source Xtest_mks.out
421  call assert_equal(1, v:hlsearch, 'session should restore search highlighting state')
422  nohlsearch
423  mksession! Xtest_mks.out
424  source Xtest_mks.out
425  call assert_equal(0, v:hlsearch, 'session should restore search highlighting state')
426  call delete('Xtest_mks.out')
427endfunc
428
429endif
430
431
432func Test_mksession_blank_windows()
433  split
434  split
435  split
436  3 wincmd w
437  mksession! Xtest_mks.out
438  split
439  split
440  2 wincmd w
441  source Xtest_mks.out
442  call assert_equal(4, winnr('$'), 'session restore should restore number of windows')
443  call assert_equal(3, winnr(), 'session restore should restore the active window')
444  call delete('Xtest_mks.out')
445endfunc
446
447if has('terminal')
448
449func Test_mksession_terminal_shell()
450  CheckFeature quickfix
451
452  terminal
453  mksession! Xtest_mks.out
454  let lines = readfile('Xtest_mks.out')
455  let term_cmd = ''
456  for line in lines
457    if line =~ '^terminal'
458      let term_cmd = line
459    elseif line =~ 'badd.*' . &shell
460      call assert_report('unexpected shell line: ' . line)
461    endif
462  endfor
463  call assert_match('terminal ++curwin ++cols=\d\+ ++rows=\d\+\s*.*$', term_cmd)
464
465  call StopShellInTerminal(bufnr('%'))
466  call delete('Xtest_mks.out')
467endfunc
468
469func Test_mksession_terminal_no_restore_cmdarg()
470  terminal ++norestore
471  mksession! Xtest_mks.out
472  let lines = readfile('Xtest_mks.out')
473  let term_cmd = ''
474  for line in lines
475    if line =~ '^terminal'
476      call assert_report('session must not restore terminal')
477    endif
478  endfor
479
480  call StopShellInTerminal(bufnr('%'))
481  call delete('Xtest_mks.out')
482endfunc
483
484func Test_mksession_terminal_no_restore_funcarg()
485  call term_start(&shell, {'norestore': 1})
486  mksession! Xtest_mks.out
487  let lines = readfile('Xtest_mks.out')
488  let term_cmd = ''
489  for line in lines
490    if line =~ '^terminal'
491      call assert_report('session must not restore terminal')
492    endif
493  endfor
494
495  call StopShellInTerminal(bufnr('%'))
496  call delete('Xtest_mks.out')
497endfunc
498
499func Test_mksession_terminal_no_restore_func()
500  terminal
501  call term_setrestore(bufnr('%'), 'NONE')
502  mksession! Xtest_mks.out
503  let lines = readfile('Xtest_mks.out')
504  let term_cmd = ''
505  for line in lines
506    if line =~ '^terminal'
507      call assert_report('session must not restore terminal')
508    endif
509  endfor
510
511  call StopShellInTerminal(bufnr('%'))
512  call delete('Xtest_mks.out')
513endfunc
514
515func Test_mksession_terminal_no_ssop()
516  terminal
517  set sessionoptions-=terminal
518  mksession! Xtest_mks.out
519  let lines = readfile('Xtest_mks.out')
520  let term_cmd = ''
521  for line in lines
522    if line =~ '^terminal'
523      call assert_report('session must not restore terminal')
524    endif
525  endfor
526
527  call StopShellInTerminal(bufnr('%'))
528  call delete('Xtest_mks.out')
529  set sessionoptions&
530endfunc
531
532func Test_mksession_terminal_restore_other()
533  CheckFeature quickfix
534
535  terminal
536  eval bufnr('%')->term_setrestore('other')
537  mksession! Xtest_mks.out
538  let lines = readfile('Xtest_mks.out')
539  let term_cmd = ''
540  for line in lines
541    if line =~ '^terminal'
542      let term_cmd = line
543    endif
544  endfor
545  call assert_match('terminal ++curwin ++cols=\d\+ ++rows=\d\+.*other', term_cmd)
546
547  call StopShellInTerminal(bufnr('%'))
548  call delete('Xtest_mks.out')
549endfunc
550
551endif " has('terminal')
552
553func Test_mkview_open_folds()
554  enew!
555
556  call append(0, ['a', 'b', 'c'])
557  1,3fold
558  write! Xtestfile
559
560  call assert_notequal(-1, foldclosed(1))
561  call assert_notequal(-1, foldclosed(2))
562  call assert_notequal(-1, foldclosed(3))
563
564  " Save the view with folds closed
565  mkview! Xtestview
566
567  " zR affects 'foldlevel', make sure the option is applied after the folds
568  " have been recreated.
569  " Open folds to ensure they get closed when restoring the view
570  normal zR
571
572  call assert_equal(-1, foldclosed(1))
573  call assert_equal(-1, foldclosed(2))
574  call assert_equal(-1, foldclosed(3))
575
576  source Xtestview
577
578  call assert_notequal(-1, foldclosed(1))
579  call assert_notequal(-1, foldclosed(2))
580  call assert_notequal(-1, foldclosed(3))
581
582  call delete('Xtestview')
583  call delete('Xtestfile')
584  %bwipe
585endfunc
586
587func Test_mkview_no_balt()
588  edit Xtestfile1
589  edit Xtestfile2
590
591  mkview! Xtestview
592  bdelete Xtestfile1
593
594  source Xtestview
595  call assert_equal(0, buflisted('Xtestfile1'))
596
597  call delete('Xtestview')
598  %bwipe
599endfunc
600
601func Test_mksession_no_balt()
602  edit Xtestfile1
603  edit Xtestfile2
604
605  bdelete Xtestfile1
606  mksession! Xtestview
607
608  source Xtestview
609  call assert_equal(0, buflisted('Xtestfile1'))
610
611  call delete('Xtestview')
612  %bwipe
613endfunc
614
615" Test :mkview with a file argument.
616func Test_mkview_file()
617  " Create a view with line number and a fold.
618  help :mkview
619  set number
620  norm! V}zf0
621  let pos = getpos('.')
622  let linefoldclosed1 = foldclosed('.')
623  mkview! Xview
624  set nonumber
625  norm! zrj
626  " We can close the help window, as mkview with a file name should
627  " generate a command to edit the file.
628  helpclose
629
630  source Xview
631  call assert_equal(1, &number)
632  call assert_match('\*:mkview\*$', getline('.'))
633  call assert_equal(pos, getpos('.'))
634  call assert_equal(linefoldclosed1, foldclosed('.'))
635
636  " Creating a view again with the same file name should fail (file
637  " already exists). But with a !, the previous view should be
638  " overwritten without error.
639  help :loadview
640  call assert_fails('mkview Xview', 'E189:')
641  call assert_match('\*:loadview\*$', getline('.'))
642  mkview! Xview
643  call assert_match('\*:loadview\*$', getline('.'))
644
645  call delete('Xview')
646  bwipe
647endfunc
648
649" Test :mkview and :loadview with a custom 'viewdir'.
650func Test_mkview_loadview_with_viewdir()
651  set viewdir=Xviewdir
652
653  help :mkview
654  set number
655  norm! V}zf
656  let pos = getpos('.')
657  let linefoldclosed1 = foldclosed('.')
658  mkview 1
659  set nonumber
660  norm! zrj
661
662  loadview 1
663
664  " The directory Xviewdir/ should have been created and the view
665  " should be stored in that directory.
666  call assert_equal('Xviewdir/' .
667        \           substitute(
668        \             substitute(
669        \               expand('%:p'), '/', '=+', 'g'), ':', '=-', 'g') . '=1.vim',
670        \           glob('Xviewdir/*'))
671  call assert_equal(1, &number)
672  call assert_match('\*:mkview\*$', getline('.'))
673  call assert_equal(pos, getpos('.'))
674  call assert_equal(linefoldclosed1, foldclosed('.'))
675
676  call delete('Xviewdir', 'rf')
677  set viewdir&
678  helpclose
679endfunc
680
681func Test_mkview_no_file_name()
682  new
683  " :mkview or :mkview {nr} should fail in an unnamed buffer.
684  call assert_fails('mkview', 'E32:')
685  call assert_fails('mkview 1', 'E32:')
686
687  " :mkview {file} should succeed in an unnamed buffer.
688  mkview Xview
689  help
690  source Xview
691  call assert_equal('', bufname('%'))
692
693  call delete('Xview')
694  %bwipe
695endfunc
696
697func Test_mkview_loadview_jumplist()
698  set viewdir=Xviewdir
699  au BufWinLeave * silent mkview
700  " au BufWinEnter * silent loadview
701
702  edit Xfile1
703  call setline(1, ['a', 'bbbbbbb', 'c'])
704  normal j3l
705  call assert_equal([2, 4], getcurpos()[1:2])
706  write
707
708  edit Xfile2
709  call setline(1, ['d', 'eeeeeee', 'f'])
710  normal j5l
711  call assert_equal([2, 6], getcurpos()[1:2])
712  write
713
714  edit Xfile3
715  call setline(1, ['g', 'h', 'iiiii'])
716  normal jj3l
717  call assert_equal([3, 4], getcurpos()[1:2])
718  write
719
720  " The commented :au above was moved here so that :mkview (on BufWinLeave) can
721  " run before :loadview. This is needed because Nvim's :loadview raises E484 if
722  " the view can't be opened, while Vim's silently fails instead.
723  au BufWinEnter * silent loadview
724
725  edit Xfile1
726  call assert_equal([2, 4], getcurpos()[1:2])
727  edit Xfile2
728  call assert_equal([2, 6], getcurpos()[1:2])
729  edit Xfile3
730  call assert_equal([3, 4], getcurpos()[1:2])
731
732  exe "normal \<C-O>"
733  call assert_equal('Xfile2', expand('%'))
734  call assert_equal([2, 6], getcurpos()[1:2])
735  exe "normal \<C-O>"
736  call assert_equal('Xfile1', expand('%'))
737  call assert_equal([2, 4], getcurpos()[1:2])
738
739  au! BufWinLeave
740  au! BufWinEnter
741  bwipe!
742  call delete('Xviewdir', 'rf')
743  call delete('Xfile1')
744  call delete('Xfile2')
745  call delete('Xfile3')
746  set viewdir&
747endfunc
748
749" A clean session (one empty buffer, one window, and one tab) should not
750" set any error messages when sourced because no commands should fail.
751func Test_mksession_no_errmsg()
752  let v:errmsg = ''
753  %bwipe!
754  mksession! Xtest_mks.out
755  source Xtest_mks.out
756  call assert_equal('', v:errmsg)
757  call delete('Xtest_mks.out')
758endfunc
759
760func Test_mksession_quote_in_filename()
761  if !has('unix')
762    " only Unix can handle this weird filename
763    return
764  endif
765  let v:errmsg = ''
766  let filename = has('win32') ? 'x''y' : 'x''y"z'
767  %bwipe!
768  split another
769  execute 'split' escape(filename, '"')
770  mksession! Xtest_mks_quoted.out
771  %bwipe!
772  source Xtest_mks_quoted.out
773  call assert_true(bufexists(filename))
774
775  %bwipe!
776  call delete('Xtest_mks_quoted.out')
777endfunc
778
779" Test for storing global variables in a session file
780func Test_mksession_globals()
781  set sessionoptions+=globals
782
783  " create different global variables
784  let g:Global_string = "Sun is shining\r\n"
785  let g:Global_count = 100
786  let g:Global_pi = 3.14
787  let g:Global_neg_float = -2.68
788
789  mksession! Xtest_mks.out
790
791  unlet g:Global_string
792  unlet g:Global_count
793  unlet g:Global_pi
794  unlet g:Global_neg_float
795
796  source Xtest_mks.out
797  call assert_equal("Sun is shining\r\n", g:Global_string)
798  call assert_equal(100, g:Global_count)
799  call assert_equal(3.14, g:Global_pi)
800  call assert_equal(-2.68, g:Global_neg_float)
801
802  unlet g:Global_string
803  unlet g:Global_count
804  unlet g:Global_pi
805  unlet g:Global_neg_float
806  call delete('Xtest_mks.out')
807  set sessionoptions&
808endfunc
809
810" Test for changing backslash to forward slash in filenames
811func Test_mksession_slash()
812  if exists('+shellslash')
813    throw 'Skipped: cannot use backslash in file name'
814  endif
815  enew
816  %bwipe!
817  e a\\b\\c
818  mksession! Xtest_mks1.out
819  set sessionoptions+=slash
820  mksession! Xtest_mks2.out
821
822  %bwipe!
823  source Xtest_mks1.out
824  call assert_equal('a/b/c', bufname(''))
825  %bwipe!
826  source Xtest_mks2.out
827  call assert_equal('a/b/c', bufname(''))
828
829  %bwipe!
830  call delete('Xtest_mks1.out')
831  call delete('Xtest_mks2.out')
832  set sessionoptions&
833endfunc
834
835" Test for changing directory to the session file directory
836func Test_mksession_sesdir()
837  let save_cwd = getcwd()
838  call mkdir('Xproj')
839  mksession! Xproj/Xtest_mks1.out
840  set sessionoptions-=curdir
841  set sessionoptions+=sesdir
842  mksession! Xproj/Xtest_mks2.out
843
844  source Xproj/Xtest_mks1.out
845  call assert_equal('testdir', fnamemodify(getcwd(), ':t'))
846  source Xproj/Xtest_mks2.out
847  call assert_equal('Xproj', fnamemodify(getcwd(), ':t'))
848  call chdir(save_cwd)
849  %bwipe
850
851  set sessionoptions&
852  call delete('Xproj', 'rf')
853endfunc
854
855" Test for saving and restoring the tab-local working directory when there is
856" only a single tab and 'tabpages' is not in 'sessionoptions'.
857func Test_mksession_tcd_single_tabs()
858  only | tabonly
859
860  let save_cwd = getcwd()
861  set sessionoptions-=tabpages
862  set sessionoptions+=curdir
863  call mkdir('Xtopdir1')
864  call mkdir('Xtopdir2')
865
866  " There are two tab pages, the current one has local cwd set to 'Xtopdir2'.
867  exec 'tcd ' .. save_cwd .. '/Xtopdir1'
868  tabnew
869  exec 'tcd ' .. save_cwd .. '/Xtopdir2'
870  mksession! Xtest_tcd_single
871
872  source Xtest_tcd_single
873  " call assert_equal(2, haslocaldir())
874  call assert_equal(1, haslocaldir(-1))
875  call assert_equal('Xtopdir2', fnamemodify(getcwd(-1, 0), ':t'))
876  %bwipe
877
878  set sessionoptions&
879  call chdir(save_cwd)
880  call delete('Xtopdir1', 'rf')
881  call delete('Xtopdir2', 'rf')
882endfunc
883
884" Test for storing the 'lines' and 'columns' settings
885func Test_mksession_resize()
886  mksession! Xtest_mks1.out
887  set sessionoptions+=resize
888  mksession! Xtest_mks2.out
889
890  let lines = readfile('Xtest_mks1.out')
891  let found_resize = v:false
892  for line in lines
893    if line =~ '^set lines='
894      let found_resize = v:true
895      break
896    endif
897  endfor
898  call assert_false(found_resize)
899  let lines = readfile('Xtest_mks2.out')
900  let found_resize = v:false
901  for line in lines
902    if line =~ '^set lines='
903      let found_resize = v:true
904      break
905    endif
906  endfor
907  call assert_true(found_resize)
908
909  call delete('Xtest_mks1.out')
910  call delete('Xtest_mks2.out')
911  set sessionoptions&
912endfunc
913
914" Test for mksession with a named scratch buffer
915func Test_mksession_scratch()
916  enew | only
917  file Xscratch
918  set buftype=nofile
919  mksession! Xtest_mks.out
920  %bwipe
921  source Xtest_mks.out
922  call assert_equal('Xscratch', bufname(''))
923  call assert_equal('nofile', &buftype)
924  %bwipe
925  call delete('Xtest_mks.out')
926endfunc
927
928" Test for mksession with fold options
929func Test_mksession_foldopt()
930  set sessionoptions-=options
931  set sessionoptions+=folds
932  new
933  setlocal foldenable
934  setlocal foldmethod=expr
935  setlocal foldmarker=<<<,>>>
936  setlocal foldignore=%
937  setlocal foldlevel=2
938  setlocal foldminlines=10
939  setlocal foldnestmax=15
940  mksession! Xtest_mks.out
941  close
942  %bwipe
943
944  source Xtest_mks.out
945  call assert_true(&foldenable)
946  call assert_equal('expr', &foldmethod)
947  call assert_equal('<<<,>>>', &foldmarker)
948  call assert_equal('%', &foldignore)
949  call assert_equal(2, &foldlevel)
950  call assert_equal(10, &foldminlines)
951  call assert_equal(15, &foldnestmax)
952
953  close
954  %bwipe
955  set sessionoptions&
956  call delete('Xtest_mks.out')
957endfunc
958
959" Test for mksession with "help" but not "options" in 'sessionoptions'
960func Test_mksession_help_noopt()
961  set sessionoptions-=options
962  set sessionoptions+=help
963  help
964  let fname = expand('%')
965  mksession! Xtest_mks.out
966  bwipe
967
968  source Xtest_mks.out
969  call assert_equal('help', &buftype)
970  call assert_equal('help', &filetype)
971  call assert_equal(fname, expand('%'))
972  call assert_false(&modifiable)
973  call assert_true(&readonly)
974
975  helpclose
976  help index
977  let fname = expand('%')
978  mksession! Xtest_mks.out
979  bwipe
980
981  source Xtest_mks.out
982  call assert_equal('help', &buftype)
983  call assert_equal(fname, expand('%'))
984
985  call delete('Xtest_mks.out')
986  set sessionoptions&
987endfunc
988
989" Test for mksession with window position
990func Test_mksession_winpos()
991  if !has('gui_running')
992    " Only applicable in GUI Vim
993    return
994  endif
995  set sessionoptions+=winpos
996  mksession! Xtest_mks.out
997  let found_winpos = v:false
998  let lines = readfile('Xtest_mks.out')
999  for line in lines
1000    if line =~ '^winpos '
1001      let found_winpos = v:true
1002      break
1003    endif
1004  endfor
1005  call assert_true(found_winpos)
1006  call delete('Xtest_mks.out')
1007  set sessionoptions&
1008endfunc
1009
1010" Test for mksession without options restores winminheight
1011func Test_mksession_winminheight()
1012  set winheight=10 winwidth=10 winminheight& winminwidth&
1013  defer execute('set winheight& winwidth&')
1014  set sessionoptions-=options
1015  defer execute('set sessionoptions&')
1016  split
1017  mksession! Xtest_mks.out
1018  defer delete('Xtest_mks.out')
1019  let found_restore = 0
1020  let lines = readfile('Xtest_mks.out')
1021  for line in lines
1022    if line =~ '= s:save_winmin\(width\|height\)'
1023      let found_restore += 1
1024    endif
1025  endfor
1026  call assert_equal(2, found_restore)
1027  " Test with multiple tabpages
1028  tab split | split | tab split | split
1029  call assert_equal(3, tabpagenr('$'))
1030  mksession! Xtest_mks.out
1031  tabclose | tabclose | close
1032  call assert_equal(1, tabpagenr('$'))
1033  set winminheight=2 winminwidth=2
1034  defer execute('set winminheight& winminwidth&')
1035  source Xtest_mks.out
1036  call assert_equal(3, tabpagenr('$'))
1037  call assert_equal([2, 2], [&winminheight, &winminwidth])
1038  tabclose | tabclose | close
1039endfunc
1040
1041" Test for mksession with and without options restores shortmess
1042func Test_mksession_shortmess()
1043  " Without options
1044  set sessionoptions-=options
1045  split
1046  mksession! Xtest_mks.out
1047  let found_save = 0
1048  let found_restore = 0
1049  let lines = readfile('Xtest_mks.out')
1050  for line in lines
1051    let line = trim(line)
1052
1053    if line ==# 'let s:shortmess_save = &shortmess'
1054      let found_save += 1
1055    endif
1056
1057    if found_save !=# 0 && line ==# 'let &shortmess = s:shortmess_save'
1058      let found_restore += 1
1059    endif
1060  endfor
1061  call assert_equal(1, found_save)
1062  call assert_equal(1, found_restore)
1063  call delete('Xtest_mks.out')
1064  close
1065  set sessionoptions&
1066
1067  " With options
1068  set sessionoptions+=options
1069  split
1070  mksession! Xtest_mks.out
1071  let found_restore = 0
1072  let lines = readfile('Xtest_mks.out')
1073  for line in lines
1074    if line =~# 's:shortmess_save'
1075      let found_restore += 1
1076    endif
1077  endfor
1078  call assert_equal(0, found_restore)
1079  call delete('Xtest_mks.out')
1080  close
1081  set sessionoptions&
1082endfunc
1083
1084" Test that when Vim loading session has 'A' in 'shortmess' it does not
1085" complain about an existing swapfile.
1086func Test_mksession_shortmess_with_A()
1087  edit Xtestfile
1088  write
1089  let fname = swapname('%')
1090  let cont = readblob(fname)
1091  set sessionoptions-=options
1092  mksession Xtestsession
1093  bwipe!
1094
1095  " Recreate the swap file to pretend the file is being edited
1096  call writefile(cont, fname, 'D')
1097  set shortmess+=A
1098  source Xtestsession
1099
1100  set shortmess&
1101  set sessionoptions&
1102  call delete('Xtestsession')
1103  call delete('Xtestfile')
1104endfunc
1105
1106" Test for mksession with 'compatible' option
1107func Test_mksession_compatible()
1108  throw 'skipped: Nvim does not support "compatible" option'
1109  mksession! Xtest_mks1.out
1110  set compatible
1111  mksession! Xtest_mks2.out
1112  set nocp
1113
1114  let test_success = v:false
1115  let lines = readfile('Xtest_mks1.out')
1116  for line in lines
1117    if line =~ '^if &cp | set nocp | endif'
1118      let test_success = v:true
1119      break
1120    endif
1121  endfor
1122  call assert_true(test_success)
1123
1124  let test_success = v:false
1125  let lines = readfile('Xtest_mks2.out')
1126  for line in lines
1127    if line =~ '^if !&cp | set cp | endif'
1128      let test_success = v:true
1129      break
1130    endif
1131  endfor
1132  call assert_true(test_success)
1133
1134  call delete('Xtest_mks1.out')
1135  call delete('Xtest_mks2.out')
1136  set compatible&
1137  set sessionoptions&
1138endfunc
1139
1140func s:ClearMappings()
1141  mapclear
1142  omapclear
1143  mapclear!
1144  lmapclear
1145  tmapclear
1146endfunc
1147
1148func Test_mkvimrc()
1149  let entries = [
1150        \ ['', 'nothing', '<Nop>'],
1151        \ ['n', 'normal', 'NORMAL<Up>'],
1152        \ ['v', 'visual', 'VISUAL<S-Down>'],
1153        \ ['s', 'select', 'SELECT<C-Left>'],
1154        \ ['x', 'visualonly', 'VISUALONLY<M-Right>'],
1155        \ ['o', 'operator', 'OPERATOR'],
1156        \ ['i', 'insert', 'INSERT'],
1157        \ ['l', 'lang', 'LANG'],
1158        \ ['c', 'command', 'COMMAND'],
1159        \ ['t', 'terminal', 'TERMINAL'],
1160        \ ]
1161  for entry in entries
1162    exe entry[0] .. 'map ' .. entry[1] .. ' ' .. entry[2]
1163  endfor
1164
1165  mkvimrc Xtestvimrc
1166
1167  call s:ClearMappings()
1168  for entry in entries
1169    call assert_equal('', maparg(entry[1], entry[0]))
1170  endfor
1171
1172  source Xtestvimrc
1173
1174  for entry in entries
1175    call assert_equal(entry[2], maparg(entry[1], entry[0]))
1176  endfor
1177
1178  call s:ClearMappings()
1179
1180  " the 'pastetoggle', 'wildchar' and 'wildcharm' option values should be
1181  " stored as key names in the vimrc file
1182  " set pastetoggle=<F5>
1183  set wildchar=<F6>
1184  set wildcharm=<F7>
1185  call assert_fails('mkvimrc Xtestvimrc', 'E189: "Xtestvimrc" exists')
1186  mkvimrc! Xtestvimrc
1187  " call assert_notequal(-1, index(readfile('Xtestvimrc'), 'set pastetoggle=<F5>'))
1188  call assert_notequal(-1, index(readfile('Xtestvimrc'), 'set wildchar=<F6>'))
1189  call assert_notequal(-1, index(readfile('Xtestvimrc'), 'set wildcharm=<F7>'))
1190  " set pastetoggle& wildchar& wildcharm&
1191  set wildchar& wildcharm&
1192
1193  call delete('Xtestvimrc')
1194endfunc
1195
1196func Test_scrolloff()
1197  set sessionoptions+=localoptions
1198  setlocal so=1 siso=1
1199  mksession! Xtest_mks.out
1200  setlocal so=-1 siso=-1
1201  source Xtest_mks.out
1202  call assert_equal(1, &l:so)
1203  call assert_equal(1, &l:siso)
1204  call delete('Xtest_mks.out')
1205  setlocal so& siso&
1206  set sessionoptions&
1207endfunc
1208
1209func Test_altfile()
1210  edit Xone
1211  split Xtwo
1212  edit Xtwoalt
1213  edit #
1214  wincmd w
1215  edit Xonealt
1216  edit #
1217  mksession! Xtest_altfile
1218  only
1219  bwipe Xonealt
1220  bwipe Xtwoalt
1221  bwipe!
1222  source Xtest_altfile
1223  call assert_equal('Xone', bufname())
1224  call assert_equal('Xonealt', bufname('#'))
1225  wincmd w
1226  call assert_equal('Xtwo', bufname())
1227  call assert_equal('Xtwoalt', bufname('#'))
1228  only
1229  bwipe!
1230  call delete('Xtest_altfile')
1231endfunc
1232
1233" Test for creating views with manual folds
1234func Test_mkview_manual_fold()
1235  call writefile(range(1,10), 'Xmkvfile', 'D')
1236  new Xmkvfile
1237  " create recursive folds
1238  5,6fold
1239  4,7fold
1240  mkview Xview
1241  normal zE
1242  source Xview
1243  call assert_equal([-1, 4, 4, 4, 4, -1], [foldclosed(3), foldclosed(4),
1244        \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)])
1245  " open one level of fold
1246  4foldopen
1247  mkview! Xview
1248  normal zE
1249  source Xview
1250  call assert_equal([-1, -1, 5, 5, -1, -1], [foldclosed(3), foldclosed(4),
1251        \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)])
1252  " open all the folds
1253  %foldopen!
1254  mkview! Xview
1255  normal zE
1256  source Xview
1257  call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4),
1258        \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)])
1259  call delete('Xview')
1260  bw!
1261endfunc
1262
1263" Test for handling invalid folds within views
1264func Test_mkview_ignore_invalid_folds()
1265  call writefile(range(1,10), 'Xmkvfile', 'D')
1266  new Xmkvfile
1267  " create some folds
1268  5,6fold
1269  4,7fold
1270  mkview Xview
1271  normal zE
1272  " delete lines to make folds invalid
1273  call deletebufline('', 6, '$')
1274  source Xview
1275  call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4),
1276        \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)])
1277  call delete('Xview')
1278  bw!
1279endfunc
1280
1281" Test default 'viewdir' value
1282func Test_mkview_default_home()
1283  throw 'Skipped: N/A'
1284  if has('win32')
1285    " use escape() to handle backslash path separators
1286    call assert_match('^' .. escape($ORIGHOME, '\') .. '/vimfiles', &viewdir)
1287  elseif has('unix')
1288    call assert_match(
1289          \ '^' .. $ORIGHOME .. '/.vim\|' ..
1290          \ '^' .. $XDG_CONFIG_HOME .. '/vim'
1291          \ , &viewdir)
1292  elseif has('amiga')
1293    call assert_match('^home:vimfiles', &viewdir)
1294  elseif has('mac')
1295    call assert_match('^' .. $VIM .. '/vimfiles', &viewdir)
1296  endif
1297endfunc
1298
1299" Test vim9 expression mappings
1300func Test_mksession_vim9_expr_mappings()
1301  throw 'Skipped: Vim9 script is N/A'
1302  CheckFeature packages
1303
1304  " Create a dummy vim9 plugin
1305  const base = getcwd() . '/rtdir'
1306  const root = base . '/pack/test/opt/dummy9'
1307  call mkdir(root . '/plugin', 'p')
1308  let plugin_sources =<< trim END
1309    vim9script
1310    import autoload 'dummy9.vim'
1311    nnoremap <expr> dummy-test dummy9.Test() .. "<CR>"
1312  END
1313  call writefile(plugin_sources, root . '/plugin/dummy9.vim')
1314
1315  call mkdir(root . '/autoload', 'p')
1316  let auto_sources =<< trim END
1317    vim9script
1318    const ref_txt = 'Hello from vim9 dummy plugin!'
1319    export def Test(): string
1320      writefile([ref_txt], 'XDummyOutput')
1321      return has("gui_running") ? '' : $':echomsg "{ref_txt}"'
1322    enddef
1323  END
1324  call writefile(auto_sources, root . '/autoload/dummy9.vim')
1325
1326  " clean up later
1327  defer delete(base, 'rf')
1328
1329  " Load and check the plugin
1330  const ref_txt = 'Hello from vim9 dummy plugin!'
1331  let orig_packpath = &packpath
1332  let &packpath .= ',' . base
1333  let orig_runtimepath = &runtimepath
1334  packadd dummy9
1335  defer execute('let &packpath = orig_runtimepath')
1336  defer execute('let &runtimepath = orig_runtimepath')
1337  messages clear
1338  normal dummy-test
1339
1340  if !has('gui_running')
1341    call assert_match(ref_txt, execute('messages'), 'No vim9 plugin dummy.Test() execution')
1342  endif
1343  call assert_true(filereadable('XDummyOutput'), 'Output file was not created by Vim9 plugin')
1344  call assert_equal([ref_txt], readfile('XDummyOutput'))
1345  call delete('XDummyOutput')
1346
1347  " Create a session file
1348  mksession! XDummySession.vim
1349  defer delete('XDummySession.vim')
1350  call assert_true(filereadable('XDummySession.vim'), 'Session file was not created')
1351
1352  " Check the session file mappings are operational
1353  let test_sources =<< trim END
1354    " load session
1355    source XDummySession.vim
1356    " execute vim9 expression mapping
1357    normal dummy-test
1358    " on my way
1359    cq
1360  END
1361  call writefile(test_sources, 'XTest.vim', 'D')
1362  " spawn a new Vim instance to load the session and execute the mapping
1363  call system(GetVimCommand('XTest.vim'))
1364  defer delete('XDummyOutput')
1365  call assert_true(filereadable('XDummyOutput'),
1366        \ 'Expected output file was not created by Vim9 plugin')
1367  call assert_equal([ref_txt], readfile('XDummyOutput'))
1368
1369endfunc
1370
1371" Test legacy vimscript expression mappings
1372func Test_mksession_legacy_expr_mappings()
1373
1374  CheckFeature packages
1375
1376  " Create a dummy vim9 plugin
1377  const base = getcwd() . '/rtdir'
1378  const root = base . '/pack/test/opt/dummy'
1379  call mkdir(root . '/plugin', 'p')
1380
1381  " clean up later
1382  defer delete(base, 'rf')
1383
1384  let plugin_sources =<< trim END
1385    nnoremap <expr> dummy-test dummy#Test() . "<CR>"
1386  END
1387  call writefile(plugin_sources, root . '/plugin/dummy.vim')
1388
1389  call mkdir(root . '/autoload', 'p')
1390  let auto_sources =<< trim END
1391    const s:ref_txt = 'Hello from good old dummy plugin!'
1392    func dummy#Test()
1393      call writefile([s:ref_txt], 'XDummyOutput')
1394      return has("gui_running") ? '' : $':echomsg "{s:ref_txt}"'
1395    endfunc
1396  END
1397  call writefile(auto_sources, root . '/autoload/dummy.vim')
1398
1399  " Load and check the plugin
1400  const ref_txt = 'Hello from good old dummy plugin!'
1401  let orig_packpath = &packpath
1402  let &packpath .= ',' . base
1403  let orig_runtimepath = &runtimepath
1404  packadd dummy
1405  defer execute('let &packpath = orig_runtimepath')
1406  defer execute('let &runtimepath = orig_runtimepath')
1407  messages clear
1408  normal dummy-test
1409
1410  if !has("gui_running")
1411    call assert_match(ref_txt, execute('messages'), 'No vim9 plugin dummy.Test() execution')
1412  endif
1413  call assert_true(filereadable('XDummyOutput'), 'Output file was not created by legacy plugin')
1414  call assert_equal([ref_txt], readfile('XDummyOutput'))
1415  call delete('XDummyOutput')
1416
1417  " Create a session file
1418  mksession! XDummySession.vim
1419  defer delete('XDummySession.vim')
1420  call assert_true(filereadable('XDummySession.vim'), 'Session file was not created')
1421
1422  " Check the session file mappings are operational
1423  let test_sources =<< trim END
1424    " load session
1425    source XDummySession.vim
1426    " execute legacy vimscript expression mapping
1427    normal dummy-test
1428    " on my way
1429    cq
1430  END
1431  call writefile(test_sources, 'XTest.vim', 'D')
1432  " spawn a new Vim instance to load the session and execute the mapping
1433  call system(GetVimCommand('XTest.vim'))
1434  defer delete('XDummyOutput')
1435  call assert_true(filereadable('XDummyOutput'),
1436        \ 'Expected output file was not created by legacy vim plugin')
1437  call assert_equal([ref_txt], readfile('XDummyOutput'))
1438
1439endfunc
1440
1441" Test sessions cursor position management
1442func Test_mksession_cursor_position()
1443
1444  " Set windows test scenario
1445  let files = []
1446  for i in range(10)
1447      let file = $'Xfile{i}'
1448      exe $"{i ? 'split' : 'edit'} {file}"
1449      call append(0, $"Session file cursor position testing {i}")
1450      " Force cursor position restoring commands
1451      setlocal nowrap
1452      normal dd29zl
1453      " Check expected position
1454      call assert_equal([0, 1, 30, 0], getpos('.'), $"Fail to set cursor position for {file}")
1455      write!
1456      let files += [file]
1457  endfor
1458
1459  " Save session
1460  mksession! Xtest_curpos
1461
1462  " Test restoring session
1463  %bwipe!
1464  try
1465      source Xtest_curpos
1466  catch
1467      call assert_report("Failure sourcing session file")
1468  endtry
1469
1470  " Check cursor position
1471  for file in files
1472      exe $"drop {file}"
1473      call assert_equal([0, 1, 30, 0], getpos('.'), $"Cursor position not restored correctly for {file}")
1474  endfor
1475
1476  " Clean up
1477  call delete('Xtest_curpos')
1478  for file in files
1479      call delete(file)
1480  endfor
1481
1482  %bwipe
1483endfunc
1484
1485func Test_mksession_with_Ctrl_I_map()
1486  set sessionoptions=options
1487
1488  " <Tab> and g<Tab> not mapped explicitly
1489  imapclear
1490  inoremap <C-I> foo
1491  inoremap g<C-I> bar
1492  imap <F2> <C-I>
1493  imap g<F2> g<C-I>
1494  mksession! Xtest_mks.out
1495
1496  " Check that the session doesn't create spurious simplified mappings
1497  imapclear
1498  source Xtest_mks.out
1499  call assert_equal('i  <C-I>       * foo', execute('imap <C-I>')->trim())
1500  call assert_equal('No mapping found', execute('imap <Tab>')->trim())
1501  call assert_equal('i  g<C-I>      * bar', execute('imap g<C-I>')->trim())
1502  call assert_equal('No mapping found', execute('imap g<Tab>')->trim())
1503
1504  " Check that the restored mappings are working properly
1505  new
1506  call feedkeys("i\<*C-I>\<F2>g\<*C-I>g\<F2>\<Esc>", 'tx')
1507  call assert_equal('foofoobarbar', getline('.'))
1508  bwipe!
1509
1510  " <Tab> and g<Tab> mapped explicitly
1511  imapclear
1512  inoremap <C-I> foo
1513  inoremap <Tab> FOO
1514  inoremap g<C-I> bar
1515  inoremap g<Tab> BAR
1516  mksession! Xtest_mks.out
1517
1518  " Check that the session restores mappings properly
1519  imapclear
1520  source Xtest_mks.out
1521  call assert_equal('i  <C-I>       * foo', execute('imap <C-I>')->trim())
1522  call assert_equal('i  <Tab>       * FOO', execute('imap <Tab>')->trim())
1523  call assert_equal('i  g<C-I>      * bar', execute('imap g<C-I>')->trim())
1524  call assert_equal('i  g<Tab>      * BAR', execute('imap g<Tab>')->trim())
1525
1526  " Check that the restored mappings are working properly
1527  new
1528  call feedkeys("i\<*C-I>\<Tab>g\<*C-I>g\<Tab>\<Esc>", 'tx')
1529  call assert_equal('fooFOObarBAR', getline('.'))
1530  bwipe!
1531
1532  call delete('Xtest_mks.out')
1533  imapclear
1534  set sessionoptions&
1535endfunc
1536
1537" Test sessions global and local mappings
1538func Test_mksession_localmappings()
1539
1540  " Create sessions. Mapping execution is tested running a file
1541  let valid_sessions = [] " keep map info
1542  let invalid_sessions = [] " do not keep map info
1543  " localoptions requires a buffer
1544  setlocal noswapfile
1545  silent write XDummy
1546  defer delete('XDummy')
1547
1548  " Nvim: default 'sessionoptions' doesn't include "options"
1549  "for option in ["&", "=options", "=localoptions"]
1550  for option in ["=options", "=localoptions"]
1551    for global in [0, 1]
1552
1553      try
1554        " select options
1555        exe "set sessionoptions" .. option
1556
1557        " mapping
1558        exe "nnoremap" . (global ? " " : " <buffer> ")
1559              \ . "dummy-test <Cmd>silent write XDummyOutput<CR>"
1560        let case = $"mapping_{global ? "global" : "local"}_{option}"
1561
1562        " test mapping
1563        normal dummy-test
1564        call assert_true(filereadable("XDummyOutput"), $"Output file was not created by {case}")
1565
1566        " session
1567        let sessionfile = "XSession_" . case
1568        exe $"mksession {sessionfile}"
1569
1570        if global && option =~ "localoptions"
1571          let invalid_sessions += [sessionfile]
1572        else
1573          let valid_sessions += [sessionfile]
1574        endif
1575
1576      finally
1577        call delete("XDummyOutput")
1578
1579        " clear mappings
1580        nmapclear
1581        nmapclear <buffer>
1582        set sessionoptions&
1583      endtry
1584
1585    endfor
1586  endfor
1587
1588  " Check the session files are operational
1589  for session in valid_sessions
1590
1591    let test_sources =<< trim eval END
1592      " load session
1593      silent source {session}
1594      " execute legacy vimscript expression mapping
1595      normal dummy-test
1596      " on my way
1597      cq
1598    END
1599
1600    call writefile(test_sources, 'XTest.vim')
1601    call system(GetVimCommand('XTest.vim'))
1602    call assert_true(filereadable('XDummyOutput'),
1603          \ $"Expected map not defined in session file {session}")
1604    call delete('XDummyOutput')
1605    call delete(session)
1606
1607  endfor
1608
1609  for session in invalid_sessions
1610
1611    let test_sources =<< trim eval END
1612      " load session
1613      silent source {session}
1614      " execute legacy vimscript expression mapping
1615      normal dummy-test
1616      " on my way
1617      cq
1618    END
1619
1620    call writefile(test_sources, 'XTest.vim')
1621    call system(GetVimCommand('XTest.vim'))
1622    call assert_false(filereadable('XDummyOutput'),
1623          \ $"Unexpected map defined in session file {session}")
1624    if filereadable('XDummyOutput')
1625      call delete('XDummyOutput')
1626    endif
1627    call delete(session)
1628  endfor
1629
1630endfunc
1631
1632" vim: shiftwidth=2 sts=2 expandtab