robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// Functions for creating a session file, i.e. implementing: 2// :mkexrc 3// :mkvimrc 4// :mkview 5// :mksession 6 7#include <inttypes.h> 8#include <stdbool.h> 9#include <stdio.h> 10#include <string.h> 11 12#include "klib/kvec.h" 13#include "nvim/arglist.h" 14#include "nvim/arglist_defs.h" 15#include "nvim/ascii_defs.h" 16#include "nvim/autocmd.h" 17#include "nvim/autocmd_defs.h" 18#include "nvim/buffer.h" 19#include "nvim/buffer_defs.h" 20#include "nvim/errors.h" 21#include "nvim/eval.h" 22#include "nvim/eval/typval.h" 23#include "nvim/eval/typval_defs.h" 24#include "nvim/eval/vars.h" 25#include "nvim/ex_cmds_defs.h" 26#include "nvim/ex_docmd.h" 27#include "nvim/ex_getln.h" 28#include "nvim/ex_session.h" 29#include "nvim/file_search.h" 30#include "nvim/fileio.h" 31#include "nvim/fold.h" 32#include "nvim/garray_defs.h" 33#include "nvim/gettext_defs.h" 34#include "nvim/globals.h" 35#include "nvim/macros_defs.h" 36#include "nvim/mapping.h" 37#include "nvim/mbyte.h" 38#include "nvim/memory.h" 39#include "nvim/message.h" 40#include "nvim/option.h" 41#include "nvim/option_vars.h" 42#include "nvim/os/fs.h" 43#include "nvim/os/os.h" 44#include "nvim/os/os_defs.h" 45#include "nvim/path.h" 46#include "nvim/pos_defs.h" 47#include "nvim/runtime.h" 48#include "nvim/strings.h" 49#include "nvim/types_defs.h" 50#include "nvim/vim_defs.h" 51#include "nvim/window.h" 52 53#include "ex_session.c.generated.h" 54 55/// Whether ":lcd" or ":tcd" was produced for a session. 56static int did_lcd ; 57 58#define PUTLINE_FAIL (s ) \ 59 do { if (FAIL == put_line(fd, (s))) { return FAIL; } } while (0) 60 61static int put_view_curpos (FILE * fd ,const win_T * wp ,char * spaces ) 62{ 63int r ; 64 65if (wp -> w_curswant == MAXCOL ) { 66r = fprintf (fd ,"%snormal! $\n" ,spaces ); 67 }else { 68r = fprintf (fd ,"%snormal! 0%d|\n" ,spaces ,wp -> w_virtcol + 1 ); 69 } 70return r >=0 ; 71} 72 73static int ses_winsizes (FILE * fd ,bool restore_size ,win_T * tab_firstwin ) 74{ 75if (restore_size && (ssop_flags & kOptSsopFlagWinsize )) { 76int n = 0 ; 77for (win_T * wp = tab_firstwin ;wp != NULL ;wp = wp -> w_next ) { 78if (!ses_do_win (wp )) { 79continue ; 80 } 81n ++ ; 82 83// restore height when not full height 84if (wp -> w_height + wp -> w_hsep_height + wp -> w_status_height < topframe -> fr_height 85&& (fprintf (fd , 86"exe '%dresize ' . ((&lines * %" PRId64 87" + %" PRId64 ") / %" PRId64 ")\n" , 88n , (int64_t )wp -> w_height , 89 (int64_t )Rows /2 , (int64_t )Rows )< 0 )) { 90return FAIL ; 91 } 92 93// restore width when not full width 94if (wp -> w_width < Columns 95&& (fprintf (fd , 96"exe 'vert %dresize ' . ((&columns * %" PRId64 97" + %" PRId64 ") / %" PRId64 ")\n" , 98n , (int64_t )wp -> w_width , (int64_t )Columns /2 , 99 (int64_t )Columns )< 0 )) { 100return FAIL ; 101 } 102 } 103 }else { 104// Just equalize window sizes. 105PUTLINE_FAIL ("wincmd =" ); 106 } 107return OK ; 108} 109 110/// Write commands to "fd" to recursively create windows for frame "fr", 111/// horizontally and vertically split. 112/// After the commands the last window in the frame is the current window. 113/// 114/// @return FAIL when writing the commands to "fd" fails. 115static int ses_win_rec (FILE * fd ,frame_T * fr ) 116{ 117int count = 0 ; 118 119if (fr -> fr_layout == FR_LEAF ) { 120return OK ; 121 } 122 123// Find first frame that's not skipped and then create a window for 124// each following one (first frame is already there). 125frame_T * frc = ses_skipframe (fr -> fr_child ); 126if (frc != NULL ) { 127while ((frc = ses_skipframe (frc -> fr_next ))!= NULL ) { 128// Make window as big as possible so that we have lots of room 129// to split. 130if (fprintf (fd ,"%s%s" , 131"wincmd _ | wincmd |\n" , 132 (fr -> fr_layout == FR_COL ?"split\n" :"vsplit\n" ))< 0 ) { 133return FAIL ; 134 } 135count ++ ; 136 } 137 } 138 139// Go back to the first window. 140if (count > 0 && (fprintf (fd ,fr -> fr_layout == FR_COL 141 ?"%dwincmd k\n" :"%dwincmd h\n" ,count )< 0 )) { 142return FAIL ; 143 } 144 145// Recursively create frames/windows in each window of this column or row. 146frc = ses_skipframe (fr -> fr_child ); 147while (frc != NULL ) { 148ses_win_rec (fd ,frc ); 149frc = ses_skipframe (frc -> fr_next ); 150// Go to next window. 151if (frc != NULL && put_line (fd ,"wincmd w" )== FAIL ) { 152return FAIL ; 153 } 154 } 155 156return OK ; 157} 158 159/// Skip frames that don't contain windows we want to save in the Session. 160/// 161/// @return NULL when there none. 162static frame_T * ses_skipframe (frame_T * fr ) 163{ 164frame_T * frc ; 165 166FOR_ALL_FRAMES (frc ,fr ) { 167if (ses_do_frame (frc )) { 168break ; 169 } 170 } 171return frc ; 172} 173 174/// @return true if frame "fr" has a window somewhere that we want to save in 175/// the Session. 176static bool ses_do_frame (const frame_T * fr ) 177FUNC_ATTR_NONNULL_ARG (1 ) 178{ 179const frame_T * frc ; 180 181if (fr -> fr_layout == FR_LEAF ) { 182return ses_do_win (fr -> fr_win ); 183 } 184FOR_ALL_FRAMES (frc ,fr -> fr_child ) { 185if (ses_do_frame (frc )) { 186return true; 187 } 188 } 189return false; 190} 191 192/// @return non-zero if window "wp" is to be stored in the Session. 193static int ses_do_win (win_T * wp ) 194{ 195// Skip floating windows to avoid issues when restoring the Session. #18432 196if (wp -> w_floating ) { 197return false; 198 } 199if (wp -> w_buffer -> b_fname == NULL 200// When 'buftype' is "nofile" can't restore the window contents. 201|| (!wp -> w_buffer -> terminal && bt_nofilename (wp -> w_buffer ))) { 202return ssop_flags & kOptSsopFlagBlank ; 203 } 204if (bt_help (wp -> w_buffer )) { 205return ssop_flags & kOptSsopFlagHelp ; 206 } 207if (bt_terminal (wp -> w_buffer )) { 208return ssop_flags & kOptSsopFlagTerminal ; 209 } 210return true; 211} 212 213/// Writes an :argument list to the session file. 214/// 215/// @param fd 216/// @param cmd 217/// @param gap 218/// @param fullname true: use full path name 219/// @param flagp 220/// 221/// @returns FAIL if writing fails. 222static int ses_arglist (FILE * fd ,char * cmd ,garray_T * gap ,bool fullname ,unsigned * flagp ) 223{ 224char * buf = NULL ; 225 226if (fprintf (fd ,"%s\n%s\n" ,cmd ,"%argdel" )< 0 ) { 227return FAIL ; 228 } 229for (int i = 0 ;i < gap -> ga_len ;i ++ ) { 230// NULL file names are skipped (only happens when out of memory). 231char * s = alist_name (& ((aentry_T * )gap -> ga_data )[i ]); 232if (s != NULL ) { 233if (fullname ) { 234buf = xmalloc (MAXPATHL ); 235vim_FullName (s ,buf ,MAXPATHL , false); 236s = buf ; 237 } 238char * fname_esc = ses_escape_fname (s ,flagp ); 239if (fprintf (fd ,"$argadd %s\n" ,fname_esc )< 0 ) { 240xfree (fname_esc ); 241xfree (buf ); 242return FAIL ; 243 } 244xfree (fname_esc ); 245xfree (buf ); 246 } 247 } 248return OK ; 249} 250 251/// @return the buffer name for `buf`. 252static char * ses_get_fname (buf_T * buf ,const unsigned * flagp ) 253{ 254// Use the short file name if the current directory is known at the time 255// the session file will be sourced. 256// Don't do this for ":mkview", we don't know the current directory. 257// Don't do this after ":lcd", we don't keep track of what the current 258// directory is. 259if (buf -> b_sfname != NULL 260&& flagp == & ssop_flags 261&& (ssop_flags & (kOptSsopFlagCurdir |kOptSsopFlagSesdir )) 262&& !p_acd 263&& !did_lcd ) { 264return buf -> b_sfname ; 265 } 266return buf -> b_ffname ; 267} 268 269/// Write a buffer name to the session file. 270/// Also ends the line, if "add_eol" is true. 271/// 272/// @return FAIL if writing fails. 273static int ses_fname (FILE * fd ,buf_T * buf ,unsigned * flagp ,bool add_eol ) 274{ 275char * name = ses_get_fname (buf ,flagp ); 276if (ses_put_fname (fd ,name ,flagp )== FAIL 277|| (add_eol && fprintf (fd ,"\n" )< 0 )) { 278return FAIL ; 279 } 280return OK ; 281} 282 283/// Escapes a filename for session writing. 284/// Takes care of "slash" flag in 'sessionoptions' and escapes special 285/// characters. 286/// 287/// @return allocated string or NULL. 288static char * ses_escape_fname (char * name ,unsigned * flagp ) 289{ 290char * p ; 291char * sname = home_replace_save (NULL ,name ); 292 293// Always kOptSsopFlagSlash: change all backslashes to forward slashes. 294for (p = sname ;* p != NUL ;MB_PTR_ADV (p )) { 295if (* p == '\\' ) { 296* p = '/' ; 297 } 298 } 299 300// Escape special characters. 301p = vim_strsave_fnameescape (sname ,VSE_NONE ); 302xfree (sname ); 303return p ; 304} 305 306/// Write a file name to the session file. 307/// Takes care of the "slash" option in 'sessionoptions' and escapes special 308/// characters. 309/// 310/// @return FAIL if writing fails. 311static int ses_put_fname (FILE * fd ,char * name ,unsigned * flagp ) 312{ 313char * p = ses_escape_fname (name ,flagp ); 314bool retval = fputs (p ,fd )< 0 ?FAIL :OK ; 315xfree (p ); 316return retval ; 317} 318 319/// Write commands to "fd" to restore the view of a window. 320/// Caller must make sure 'scrolloff' is zero. 321/// 322/// @param add_edit add ":edit" command to view 323/// @param flagp vop_flags or ssop_flags 324/// @param current_arg_idx current argument index of the window, use -1 if unknown 325static int put_view (FILE * fd ,win_T * wp ,tabpage_T * tp ,bool add_edit ,unsigned * flagp , 326int current_arg_idx ) 327{ 328int f ; 329bool did_next = false; 330 331// Always restore cursor position for ":mksession". For ":mkview" only 332// when 'viewoptions' contains "cursor". 333bool do_cursor = (flagp == & ssop_flags || * flagp & kOptSsopFlagCursor ); 334 335// Local argument list. 336if (wp -> w_alist == & global_alist ) { 337PUTLINE_FAIL ("argglobal" ); 338 }else { 339if (ses_arglist (fd ,"arglocal" ,& wp -> w_alist -> al_ga , 340flagp == & vop_flags 341|| !(* flagp & kOptSsopFlagCurdir ) 342|| tp -> tp_localdir != NULL 343|| wp -> w_localdir != NULL ,flagp )== FAIL ) { 344return FAIL ; 345 } 346 } 347 348// Only when part of a session: restore the argument index. Some 349// arguments may have been deleted, check if the index is valid. 350if (wp -> w_arg_idx != current_arg_idx && wp -> w_arg_idx < WARGCOUNT (wp ) 351&& flagp == & ssop_flags ) { 352if (fprintf (fd ,"%" PRId64 "argu\n" , (int64_t )wp -> w_arg_idx + 1 )< 0 ) { 353return FAIL ; 354 } 355did_next = true; 356 } 357 358// Edit the file. Skip this when ":next" already did it. 359if (add_edit && (!did_next || wp -> w_arg_idx_invalid )) { 360char * fname_esc = ses_escape_fname (ses_get_fname (wp -> w_buffer ,flagp ),flagp ); 361if (bt_help (wp -> w_buffer )) { 362char * curtag = "" ; 363 364// A help buffer needs some options to be set. 365// First, create a new empty buffer with "buftype=help". 366// Then ":help" will re-use both the buffer and the window and set 367// the options, even when "options" is not in 'sessionoptions'. 368if (0 < wp -> w_tagstackidx && wp -> w_tagstackidx <=wp -> w_tagstacklen ) { 369curtag = wp -> w_tagstack [wp -> w_tagstackidx - 1 ].tagname ; 370 } 371 372if (put_line (fd ,"enew | setl bt=help" )== FAIL 373|| fprintf (fd ,"help %s" ,curtag )< 0 || put_eol (fd )== FAIL ) { 374xfree (fname_esc ); 375return FAIL ; 376 } 377 }else if (wp -> w_buffer -> b_ffname != NULL 378&& (!bt_nofilename (wp -> w_buffer )|| wp -> w_buffer -> terminal )) { 379// Load the file. 380 381// Editing a file in this buffer: use ":edit file". 382// This may have side effects! (e.g., compressed or network file). 383// 384// Note, if a buffer for that file already exists, use :badd to 385// edit that buffer, to not lose folding information (:edit resets 386// folds in other buffers) 387if (fprintf (fd , 388"if bufexists(fnamemodify(\"%s\", \":p\")) | buffer %s | else | edit %s | endif\n" 389// Fixup :terminal buffer name. #7836 390"if &buftype ==# 'terminal'\n" 391" silent file %s\n" 392"endif\n" , 393fname_esc , 394fname_esc , 395fname_esc , 396fname_esc )< 0 ) { 397xfree (fname_esc ); 398return FAIL ; 399 } 400 }else { 401// No file in this buffer, just make it empty. 402PUTLINE_FAIL ("enew" ); 403if (wp -> w_buffer -> b_ffname != NULL ) { 404// The buffer does have a name, but it's not a file name. 405if (fprintf (fd ,"file %s\n" ,fname_esc )< 0 ) { 406xfree (fname_esc ); 407return FAIL ; 408 } 409 } 410do_cursor = false; 411 } 412xfree (fname_esc ); 413 } 414 415if (wp -> w_alt_fnum ) { 416buf_T * const alt = buflist_findnr (wp -> w_alt_fnum ); 417 418// Set the alternate file if the buffer is listed. 419if ((flagp == & ssop_flags )&& alt != NULL && alt -> b_fname != NULL 420&& * alt -> b_fname != NUL 421&& alt -> b_p_bl 422// do not set balt if buffer is terminal and "terminal" is not set in options 423&& !(bt_terminal (alt )&& !(ssop_flags & kOptSsopFlagTerminal )) 424&& (fputs ("balt " ,fd )< 0 425|| ses_fname (fd ,alt ,flagp , true)== FAIL )) { 426return FAIL ; 427 } 428 } 429 430// Local mappings and abbreviations. 431if ((* flagp & (kOptSsopFlagOptions |kOptSsopFlagLocaloptions )) 432&& makemap (fd ,wp -> w_buffer )== FAIL ) { 433return FAIL ; 434 } 435 436// Local options. Need to go to the window temporarily. 437// Store only local values when using ":mkview" and when ":mksession" is 438// used and 'sessionoptions' doesn't include "nvim/options". 439// Some folding options are always stored when "folds" is included, 440// otherwise the folds would not be restored correctly. 441win_T * save_curwin = curwin ; 442curwin = wp ; 443curbuf = curwin -> w_buffer ; 444if (* flagp & (kOptSsopFlagOptions |kOptSsopFlagLocaloptions )) { 445f = makeset (fd ,OPT_LOCAL , 446flagp == & vop_flags || !(* flagp & kOptSsopFlagOptions )); 447 }else if (* flagp & kOptSsopFlagFolds ) { 448f = makefoldset (fd ); 449 }else { 450f = OK ; 451 } 452curwin = save_curwin ; 453curbuf = curwin -> w_buffer ; 454if (f == FAIL ) { 455return FAIL ; 456 } 457 458// Save Folds when 'buftype' is empty and for help files. 459if ((* flagp & kOptSsopFlagFolds ) 460&& wp -> w_buffer -> b_ffname != NULL 461&& (bt_normal (wp -> w_buffer ) 462|| bt_help (wp -> w_buffer ))) { 463if (put_folds (fd ,wp )== FAIL ) { 464return FAIL ; 465 } 466 } 467 468// Set the cursor after creating folds, since that moves the cursor. 469if (do_cursor ) { 470// Restore the cursor line in the file and relatively in the 471// window. Don't use "G", it changes the jumplist. 472if (wp -> w_view_height <=0 ) { 473if (fprintf (fd ,"let s:l = %" PRIdLINENR "\n" ,wp -> w_cursor .lnum )< 0 ) { 474return FAIL ; 475 } 476 }else if (fprintf (fd , 477"let s:l = %" PRIdLINENR " - ((%" PRIdLINENR 478" * winheight(0) + %d) / %d)\n" , 479wp -> w_cursor .lnum , 480wp -> w_cursor .lnum - wp -> w_topline , 481 (wp -> w_view_height /2 ), 482wp -> w_view_height )< 0 ) { 483return FAIL ; 484 } 485if (fprintf (fd , 486"if s:l < 1 | let s:l = 1 | endif\n" 487"keepjumps exe s:l\n" 488"normal! zt\n" 489"keepjumps %" PRIdLINENR "\n" , 490wp -> w_cursor .lnum )< 0 ) { 491return FAIL ; 492 } 493// Restore the cursor column and left offset when not wrapping. 494if (wp -> w_cursor .col == 0 ) { 495PUTLINE_FAIL ("normal! 0" ); 496 }else { 497if (!wp -> w_p_wrap && wp -> w_leftcol > 0 && wp -> w_width > 0 ) { 498if (fprintf (fd , 499"let s:c = %" PRId64 " - ((%" PRId64 500" * winwidth(0) + %" PRId64 ") / %" PRId64 ")\n" 501"if s:c > 0\n" 502" exe 'normal! ' . s:c . '|zs' . %" PRId64 " . '|'\n" 503"else\n" , 504 (int64_t )wp -> w_virtcol + 1 , 505 (int64_t )(wp -> w_virtcol - wp -> w_leftcol ), 506 (int64_t )(wp -> w_width /2 ), 507 (int64_t )wp -> w_width , 508 (int64_t )wp -> w_virtcol + 1 )< 0 509|| put_view_curpos (fd ,wp ," " )== FAIL 510|| put_line (fd ,"endif" )== FAIL ) { 511return FAIL ; 512 } 513 }else if (put_view_curpos (fd ,wp ,"" )== FAIL ) { 514return FAIL ; 515 } 516 } 517 } 518 519// Local directory, if the current flag is not view options or the "curdir" 520// option is included. 521if (wp -> w_localdir != NULL 522&& (flagp != & vop_flags || (* flagp & kOptSsopFlagCurdir ))) { 523if (fputs ("lcd " ,fd )< 0 524|| ses_put_fname (fd ,wp -> w_localdir ,flagp )== FAIL 525|| fprintf (fd ,"\n" )< 0 ) { 526return FAIL ; 527 } 528did_lcd = true; 529 } 530 531return OK ; 532} 533 534static int store_session_globals (FILE * fd ) 535{ 536TV_DICT_ITER (get_globvar_dict (),this_var , { 537if ((this_var -> di_tv .v_type == VAR_NUMBER 538|| this_var -> di_tv .v_type == VAR_STRING ) 539&& var_flavour (this_var -> di_key )== VAR_FLAVOUR_SESSION ) { 540// Escape special characters with a backslash. Turn a LF and 541// CR into \n and \r. 542char * const p = vim_strsave_escaped (tv_get_string (& this_var -> di_tv ),"\\\"\n\r" ); 543for (char * t = p ;* t != NUL ;t ++ ) { 544if (* t == '\n' ) { 545* t = 'n' ; 546 }else if (* t == '\r' ) { 547* t = 'r' ; 548 } 549 } 550if ((fprintf (fd ,"let %s = %c%s%c" , 551this_var -> di_key , 552 ((this_var -> di_tv .v_type == VAR_STRING ) ?'"' :' ' ), 553p , 554 ((this_var -> di_tv .v_type == VAR_STRING ) ?'"' :' ' ))< 0 ) 555|| put_eol (fd )== FAIL ) { 556xfree (p ); 557return FAIL ; 558 } 559xfree (p ); 560 }else if (this_var -> di_tv .v_type == VAR_FLOAT 561&& var_flavour (this_var -> di_key )== VAR_FLAVOUR_SESSION ) { 562float_T f = this_var -> di_tv .vval .v_float ; 563int sign = ' ' ; 564 565if (f < 0 ) { 566f = - f ; 567sign = '-' ; 568 } 569if ((fprintf (fd ,"let %s = %c%f" ,this_var -> di_key ,sign ,f )< 0 ) 570|| put_eol (fd )== FAIL ) { 571return FAIL ; 572 } 573 } 574 }); 575return OK ; 576} 577 578/// Writes commands for restoring the current buffers, for :mksession. 579/// 580/// Legacy 'sessionoptions'/'viewoptions' flags kOptSsopFlagUnix, kOptSsopFlagSlash are 581/// always enabled. 582/// 583/// @param dirnow Current directory name 584/// @param fd File descriptor to write to 585/// 586/// @return FAIL on error, OK otherwise. 587static int makeopens (FILE * fd ,char * dirnow ) 588{ 589bool only_save_windows = true; 590win_T * edited_win = NULL ; 591win_T * tab_firstwin ; 592frame_T * tab_topframe ; 593int cur_arg_idx = 0 ; 594int next_arg_idx = 0 ; 595 596if (ssop_flags & kOptSsopFlagBuffers ) { 597only_save_windows = false;// Save ALL buffers 598 } 599 600// Begin by setting v:this_session, and then other sessionable variables. 601PUTLINE_FAIL ("let v:this_session=expand(\"<sfile>:p\")" ); 602 603PUTLINE_FAIL ("doautoall SessionLoadPre" ); 604 605if (ssop_flags & kOptSsopFlagGlobals ) { 606if (store_session_globals (fd )== FAIL ) { 607return FAIL ; 608 } 609 } 610 611// Close all windows and tabs but one. 612PUTLINE_FAIL ("silent only" ); 613if ((ssop_flags & kOptSsopFlagTabpages ) 614&& put_line (fd ,"silent tabonly" )== FAIL ) { 615return FAIL ; 616 } 617 618// Now a :cd command to the session directory or the current directory 619if (ssop_flags & kOptSsopFlagSesdir ) { 620PUTLINE_FAIL ("exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')" ); 621 }else if (ssop_flags & kOptSsopFlagCurdir ) { 622char * sname = home_replace_save (NULL ,globaldir != NULL ?globaldir :dirnow ); 623char * fname_esc = ses_escape_fname (sname ,& ssop_flags ); 624if (fprintf (fd ,"cd %s\n" ,fname_esc )< 0 ) { 625xfree (fname_esc ); 626xfree (sname ); 627return FAIL ; 628 } 629xfree (fname_esc ); 630xfree (sname ); 631 } 632 633if (fprintf (fd , 634"%s" , 635// If there is an empty, unnamed buffer we will wipe it out later. 636// Remember the buffer number. 637"if expand('%') == '' && !&modified && line('$') <= 1" 638" && getline(1) == ''\n" 639" let s:wipebuf = bufnr('%')\n" 640"endif\n" )< 0 ) { 641return FAIL ; 642 } 643 644// Save 'shortmess' if not storing options. 645if ((ssop_flags & kOptSsopFlagOptions )== 0 ) { 646PUTLINE_FAIL ("let s:shortmess_save = &shortmess" ); 647 } 648 649// Set 'shortmess' for the following. 650PUTLINE_FAIL ("set shortmess+=aoO" ); 651 652// Now save the current files, current buffer first. 653// Put all buffers into the buffer list. 654// Do it very early to preserve buffer order after loading session (which 655// can be disrupted by prior `edit` or `tabedit` calls). 656FOR_ALL_BUFFERS (buf ) { 657if (!(only_save_windows && buf -> b_nwindows == 0 ) 658&& !(buf -> b_help && !(ssop_flags & kOptSsopFlagHelp )) 659&& !(bt_terminal (buf )&& !(ssop_flags & kOptSsopFlagTerminal )) 660&& buf -> b_fname != NULL 661&& buf -> b_p_bl ) { 662if (fprintf (fd ,"badd +%" PRId64 " " , 663kv_size (buf -> b_wininfo )== 0 664 ?1 : (int64_t )kv_A (buf -> b_wininfo ,0 )-> wi_mark .mark .lnum )< 0 665|| ses_fname (fd ,buf ,& ssop_flags , true)== FAIL ) { 666return FAIL ; 667 } 668 } 669 } 670 671// the global argument list 672if (ses_arglist (fd ,"argglobal" ,& global_alist .al_ga , 673 !(ssop_flags & kOptSsopFlagCurdir ),& ssop_flags )== FAIL ) { 674return FAIL ; 675 } 676 677// Restore buffer-local CWD (:bcd) via one-shot BufEnter handlers: there is no reliable point 678// during session-load where all buffers are entered. Each buffer's directory is applied when the 679// buffer is first entered, which may happen after session-load for buffers that stay hidden. 680if (ssop_flags & kOptSsopFlagCurdir ) { 681FOR_ALL_BUFFERS (buf ) { 682if (buf -> b_localdir == NULL || buf -> b_fname == NULL || !buf -> b_p_bl 683|| (only_save_windows && buf -> b_nwindows == 0 ) 684|| (buf -> b_help && !(ssop_flags & kOptSsopFlagHelp )) 685|| (bt_terminal (buf )&& !(ssop_flags & kOptSsopFlagTerminal ))) { 686continue ; 687 } 688// `bufadd()` finds the buffer by exact (literal) name. 689if (fputs ("lua vim.api.nvim_create_autocmd('BufEnter', { once = true, " 690"buffer = vim.fn.bufadd([==[" ,fd )< 0 691|| fputs (ses_get_fname (buf ,& ssop_flags ),fd )< 0 692|| fputs ("]==]), callback = function() vim.cmd.bcd({ [==[" ,fd )< 0 693|| fputs (buf -> b_localdir ,fd )< 0 694|| fputs ("]==], magic = { file = false, bar = false } }) end })\n" ,fd )< 0 ) { 695return FAIL ; 696 } 697// Cwd may change when a handler fires: filenames must be written absolute from here on. 698did_lcd = true; 699 } 700 } 701 702if (ssop_flags & kOptSsopFlagResize ) { 703// Note: after the restore we still check it worked! 704if (fprintf (fd ,"set lines=%" PRId64 " columns=%" PRId64 "\n" , 705 (int64_t )Rows , (int64_t )Columns )< 0 ) { 706return FAIL ; 707 } 708 } 709 710bool restore_stal = false; 711// When there are two or more tabpages and 'showtabline' is 1 the tabline 712// will be displayed when creating the next tab. That resizes the windows 713// in the first tab, which may cause problems. Set 'showtabline' to 2 714// temporarily to avoid that. 715if (p_stal == 1 && first_tabpage -> tp_next != NULL ) { 716PUTLINE_FAIL ("set stal=2" ); 717restore_stal = true; 718 } 719 720if ((ssop_flags & kOptSsopFlagTabpages )) { 721// "tabpages" is in 'sessionoptions': Similar to ses_win_rec() below, 722// populate the tab pages first so later local options won't be copied 723// to the new tabs. 724FOR_ALL_TABS (tp ) { 725// Use `bufhidden=wipe` to remove empty "placeholder" buffers once 726// they are not needed. This prevents creating extra buffers (see 727// cause of Vim patch 8.1.0829) 728if (tp -> tp_next != NULL && put_line (fd ,"tabnew +setlocal\\ bufhidden=wipe" )== FAIL ) { 729return FAIL ; 730 } 731 } 732 733if (first_tabpage -> tp_next != NULL && put_line (fd ,"tabrewind" )== FAIL ) { 734return FAIL ; 735 } 736 } 737 738// Assume "tabpages" is in 'sessionoptions'. If not then we only do 739// "curtab" and bail out of the loop. 740bool restore_height_width = false; 741FOR_ALL_TABS (tp ) { 742bool need_tabnext = false; 743int cnr = 1 ; 744 745// May repeat putting Windows for each tab, when "tabpages" is in 746// 'sessionoptions'. 747// Don't use goto_tabpage(), it may change directory and trigger 748// autocommands. 749if ((ssop_flags & kOptSsopFlagTabpages )) { 750if (tp == curtab ) { 751tab_firstwin = firstwin ; 752tab_topframe = topframe ; 753 }else { 754tab_firstwin = tp -> tp_firstwin ; 755tab_topframe = tp -> tp_topframe ; 756 } 757if (tp != first_tabpage ) { 758need_tabnext = true; 759 } 760 }else { 761tp = curtab ; 762tab_firstwin = firstwin ; 763tab_topframe = topframe ; 764 } 765 766// Restore the tab-local working directory before the windows and buffers, so that the 767// win-local / buf-local dir can override the tab-local dir. 768if ((ssop_flags & kOptSsopFlagCurdir )&& tp -> tp_localdir != NULL ) { 769if (need_tabnext && put_line (fd ,"tabnext" )== FAIL ) { 770return FAIL ; 771 } 772need_tabnext = false; 773if (fputs ("tcd " ,fd )< 0 774|| ses_put_fname (fd ,tp -> tp_localdir ,& ssop_flags )== FAIL 775|| put_eol (fd )== FAIL ) { 776return FAIL ; 777 } 778did_lcd = true; 779 } 780 781// Before creating the window layout, try loading one file. If this 782// is aborted we don't end up with a number of useless windows. 783// This may have side effects! (e.g., compressed or network file). 784for (win_T * wp = tab_firstwin ;wp != NULL ;wp = wp -> w_next ) { 785if (ses_do_win (wp ) 786&& wp -> w_buffer -> b_ffname != NULL 787&& !bt_help (wp -> w_buffer ) 788&& !bt_nofilename (wp -> w_buffer )) { 789if (need_tabnext && put_line (fd ,"tabnext" )== FAIL ) { 790return FAIL ; 791 } 792need_tabnext = false; 793 794if (fputs ("edit " ,fd )< 0 795|| ses_fname (fd ,wp -> w_buffer ,& ssop_flags , true)== FAIL ) { 796return FAIL ; 797 } 798if (!wp -> w_arg_idx_invalid ) { 799edited_win = wp ; 800 } 801break ; 802 } 803 } 804 805// If no file got edited create an empty tab page. 806if (need_tabnext && put_line (fd ,"tabnext" )== FAIL ) { 807return FAIL ; 808 } 809 810if (tab_topframe -> fr_layout != FR_LEAF ) { 811// Save current window layout. 812PUTLINE_FAIL ("let s:save_splitbelow = &splitbelow" ); 813PUTLINE_FAIL ("let s:save_splitright = &splitright" ); 814PUTLINE_FAIL ("set splitbelow splitright" ); 815if (ses_win_rec (fd ,tab_topframe )== FAIL ) { 816return FAIL ; 817 } 818PUTLINE_FAIL ("let &splitbelow = s:save_splitbelow" ); 819PUTLINE_FAIL ("let &splitright = s:save_splitright" ); 820 } 821 822// Check if window sizes can be restored (no windows omitted). 823// Remember the window number of the current window after restoring. 824int nr = 0 ; 825bool restore_size = true; 826for (win_T * wp = tab_firstwin ;wp != NULL ;wp = wp -> w_next ) { 827if (ses_do_win (wp )) { 828nr ++ ; 829 }else if (!wp -> w_floating ) { 830restore_size = false; 831 } 832if (curwin == wp ) { 833cnr = nr ; 834 } 835 } 836 837if (tab_firstwin != NULL && tab_firstwin -> w_next != NULL ) { 838// Go to the first window. 839PUTLINE_FAIL ("wincmd t" ); 840 841// If more than one window, see if sizes can be restored. 842// First set 'winheight' and 'winwidth' to 1 to avoid the windows 843// being resized when moving between windows. 844// Do this before restoring the view, so that the topline and the 845// cursor can be set. This is done again below. 846// winminheight and winminwidth need to be set to avoid an error if 847// the user has set winheight or winwidth. 848if (!restore_height_width ) { 849PUTLINE_FAIL ("let s:save_winminheight = &winminheight" ); 850PUTLINE_FAIL ("let s:save_winminwidth = &winminwidth" ); 851 } 852if (fprintf (fd , 853"set winminheight=0\n" 854"set winheight=1\n" 855"set winminwidth=0\n" 856"set winwidth=1\n" )< 0 ) { 857return FAIL ; 858 } 859restore_height_width = true; 860 } 861if (nr > 1 && ses_winsizes (fd ,restore_size ,tab_firstwin )== FAIL ) { 862return FAIL ; 863 } 864 865// Restore the view of the window (options, file, cursor, etc.). 866for (win_T * wp = tab_firstwin ;wp != NULL ;wp = wp -> w_next ) { 867if (!ses_do_win (wp )) { 868continue ; 869 } 870if (put_view (fd ,wp ,tp ,wp != edited_win ,& ssop_flags ,cur_arg_idx ) 871== FAIL ) { 872return FAIL ; 873 } 874if (nr > 1 && put_line (fd ,"wincmd w" )== FAIL ) { 875return FAIL ; 876 } 877next_arg_idx = wp -> w_arg_idx ; 878 } 879 880// The argument index in the first tab page is zero, need to set it in 881// each window. For further tab pages it's the window where we do 882// "tabedit". 883cur_arg_idx = next_arg_idx ; 884 885// Restore cursor to the current window if it's not the first one. 886if (cnr > 1 && (fprintf (fd ,"%dwincmd w\n" ,cnr )< 0 )) { 887return FAIL ; 888 } 889 890// Restore window sizes again after jumping around in windows, because 891// the current window has a minimum size while others may not. 892if (nr > 1 && ses_winsizes (fd ,restore_size ,tab_firstwin )== FAIL ) { 893return FAIL ; 894 } 895 896// Don't continue in another tab page when doing only the current one 897// or when at the last tab page. 898if (!(ssop_flags & kOptSsopFlagTabpages )) { 899break ; 900 } 901 } 902 903if (ssop_flags & kOptSsopFlagTabpages ) { 904if (fprintf (fd ,"tabnext %d\n" ,tabpage_index (curtab ))< 0 ) { 905return FAIL ; 906 } 907 } 908if (restore_stal && put_line (fd ,"set stal=1" )== FAIL ) { 909return FAIL ; 910 } 911 912// Wipe out an empty unnamed buffer we started in. 913if (fprintf (fd ,"%s" , 914"if exists('s:wipebuf') " 915"&& len(win_findbuf(s:wipebuf)) == 0 " 916"&& getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'\n" 917" silent exe 'bwipe ' . s:wipebuf\n" 918"endif\n" 919"unlet! s:wipebuf\n" )< 0 ) { 920return FAIL ; 921 } 922 923// Re-apply 'winheight' and 'winwidth'. 924if (fprintf (fd ,"set winheight=%" PRId64 " winwidth=%" PRId64 "\n" , 925 (int64_t )p_wh , (int64_t )p_wiw )< 0 ) { 926return FAIL ; 927 } 928 929// Restore 'shortmess'. 930if (ssop_flags & kOptSsopFlagOptions ) { 931if (fprintf (fd ,"set shortmess=%s\n" ,p_shm )< 0 ) { 932return FAIL ; 933 } 934 }else { 935PUTLINE_FAIL ("let &shortmess = s:shortmess_save" ); 936 } 937 938if (restore_height_width ) { 939// Restore 'winminheight' and 'winminwidth'. 940PUTLINE_FAIL ("let &winminheight = s:save_winminheight" ); 941PUTLINE_FAIL ("let &winminwidth = s:save_winminwidth" ); 942 } 943 944// Lastly, execute the x.vim file if it exists. 945if (fprintf (fd ,"%s" , 946"let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"\n" 947"if filereadable(s:sx)\n" 948" exe \"source \" . fnameescape(s:sx)\n" 949"endif\n" )< 0 ) { 950return FAIL ; 951 } 952 953return OK ; 954} 955 956/// ":loadview [nr]" 957void ex_loadview (exarg_T * eap ) 958{ 959char * fname = get_view_file (* eap -> arg ); 960if (fname == NULL ) { 961return ; 962 } 963 964if (do_source (fname , false,DOSO_NONE ,NULL )== FAIL ) { 965semsg (_ (e_notopen ),fname ); 966 } 967xfree (fname ); 968} 969 970/// ":mkexrc", ":mkvimrc", ":mkview", ":mksession". 971/// 972/// Legacy 'sessionoptions'/'viewoptions' flags are always enabled: 973/// - kOptSsopFlagUnix: line-endings are LF 974/// - kOptSsopFlagSlash: filenames are written with "/" slash 975void ex_mkrc (exarg_T * eap ) 976{ 977bool view_session = false;// :mkview, :mksession 978int using_vdir = false;// using 'viewdir'? 979char * viewFile = NULL ; 980 981if (eap -> cmdidx == CMD_mksession || eap -> cmdidx == CMD_mkview ) { 982view_session = true; 983 } 984 985// Use the short file name until ":lcd" is used. We also don't use the 986// short file name when 'acd' is set, that is checked later. 987did_lcd = false; 988 989char * fname ; 990// ":mkview" or ":mkview 9": generate file name with 'viewdir' 991if (eap -> cmdidx == CMD_mkview 992&& (* eap -> arg == NUL 993|| (ascii_isdigit (* eap -> arg )&& eap -> arg [1 ]== NUL ))) { 994eap -> forceit = true; 995fname = get_view_file (* eap -> arg ); 996if (fname == NULL ) { 997return ; 998 } 999viewFile = fname ; 1000using_vdir = true; 1001 }else if (* eap -> arg != NUL ) { 1002fname = eap -> arg ; 1003 }else if (eap -> cmdidx == CMD_mkvimrc ) { 1004fname = VIMRC_FILE ; 1005 }else if (eap -> cmdidx == CMD_mksession ) { 1006fname = SESSION_FILE ; 1007 }else { 1008fname = EXRC_FILE ; 1009 } 1010 1011// When using 'viewdir' may have to create the directory. 1012if (using_vdir && !os_isdir (p_vdir )) { 1013vim_mkdir_emsg (p_vdir ,0755 ); 1014 } 1015 1016FILE * fd = open_exfile (fname ,eap -> forceit ,WRITEBIN ); 1017if (fd != NULL ) { 1018bool failed = false; 1019unsigned * flagp ; 1020if (eap -> cmdidx == CMD_mkview ) { 1021flagp = & vop_flags ; 1022 }else { 1023flagp = & ssop_flags ; 1024 } 1025 1026if (eap -> cmdidx == CMD_mksession ) { 1027apply_autocmds (EVENT_SESSIONWRITEPRE ,NULL ,NULL , false,curbuf ); 1028 } 1029 1030// Write the version command for :mkvimrc 1031if (eap -> cmdidx == CMD_mkvimrc ) { 1032put_line (fd ,"version 6.0" ); 1033 } 1034 1035if (eap -> cmdidx == CMD_mksession ) { 1036if (put_line (fd ,"let SessionLoad = 1" )== FAIL ) { 1037failed = true; 1038 } 1039 } 1040 1041if (!view_session || (eap -> cmdidx == CMD_mksession 1042&& (* flagp & kOptSsopFlagOptions ))) { 1043int flags = OPT_GLOBAL ; 1044 1045if (eap -> cmdidx == CMD_mksession && (* flagp & kOptSsopFlagSkiprtp )) { 1046flags |=OPT_SKIPRTP ; 1047 } 1048failed |= (makemap (fd ,NULL )== FAIL 1049|| makeset (fd ,flags , false)== FAIL ); 1050 } 1051 1052if (!failed && view_session ) { 1053if (put_line (fd , 1054"let s:so_save = &g:so | let s:siso_save = &g:siso" 1055" | setg so=0 siso=0 | setl so=-1 siso=-1" )== FAIL ) { 1056failed = true; 1057 } 1058if (eap -> cmdidx == CMD_mksession ) { 1059char * dirnow ;// current directory 1060 1061dirnow = xmalloc (MAXPATHL ); 1062 1063// Change to session file's dir. 1064if (os_dirname (dirnow ,MAXPATHL )== FAIL 1065|| os_chdir (dirnow )!= 0 ) { 1066* dirnow = NUL ; 1067 } 1068if (* dirnow != NUL && (ssop_flags & kOptSsopFlagSesdir )) { 1069if (vim_chdirfile (fname ,kCdCauseOther )== OK ) { 1070shorten_fnames (true); 1071 } 1072 }else if (* dirnow != NUL 1073&& (ssop_flags & kOptSsopFlagCurdir )&& globaldir != NULL ) { 1074if (os_chdir (globaldir )== 0 ) { 1075shorten_fnames (true); 1076 } 1077 } 1078 1079failed |= (makeopens (fd ,dirnow )== FAIL ); 1080 1081// restore original dir 1082if (* dirnow != NUL && ((ssop_flags & kOptSsopFlagSesdir ) 1083|| ((ssop_flags & kOptSsopFlagCurdir )&& globaldir != 1084NULL ))) { 1085if (os_chdir (dirnow )!= 0 ) { 1086emsg (_ (e_prev_dir )); 1087 } 1088shorten_fnames (true); 1089 } 1090xfree (dirnow ); 1091 }else { 1092failed |= (put_view (fd ,curwin ,curtab , !using_vdir ,flagp ,-1 )== FAIL ); 1093 } 1094if (fprintf (fd , 1095"%s" , 1096"let &g:so = s:so_save | let &g:siso = s:siso_save\n" ) 1097< 0 ) { 1098failed = true; 1099 } 1100if (p_hls && fprintf (fd ,"%s" ,"set hlsearch\n" )< 0 ) { 1101failed = true; 1102 } 1103if (Search .no_hlsearch && fprintf (fd ,"%s" ,"nohlsearch\n" )< 0 ) { 1104failed = true; 1105 } 1106if (eap -> cmdidx == CMD_mksession 1107&& fprintf (fd ,"doautoall SessionLoadPost\nunlet SessionLoad\n" )< 0 ) { 1108failed = true; 1109 } 1110 } 1111if (put_line (fd ,"\" vim: set ft=vim :" )== FAIL ) { 1112failed = true; 1113 } 1114 1115failed |=fclose (fd ); 1116 1117if (failed ) { 1118emsg (_ (e_write )); 1119 }else if (eap -> cmdidx == CMD_mksession ) { 1120// successful session write - set v:this_session 1121char * const tbuf = xmalloc (MAXPATHL ); 1122if (vim_FullName (fname ,tbuf ,MAXPATHL , false)== OK ) { 1123set_vim_var_string (VV_THIS_SESSION ,tbuf ,-1 ); 1124 } 1125xfree (tbuf ); 1126 } 1127 } 1128 1129xfree (viewFile ); 1130 1131if (eap -> cmdidx == CMD_mksession ) { 1132apply_autocmds (EVENT_SESSIONWRITEPOST ,NULL ,NULL , false,curbuf ); 1133 } 1134} 1135 1136/// @return the name of the view file for the current buffer. 1137static char * get_view_file (char c ) 1138{ 1139if (curbuf -> b_ffname == NULL ) { 1140emsg (_ (e_noname )); 1141return NULL ; 1142 } 1143char * sname = home_replace_save (NULL ,curbuf -> b_ffname ); 1144 1145// We want a file name without separators, because we're not going to make 1146// a directory. 1147// "normal" path separator -> "=+" 1148// "=" -> "==" 1149// ":" path separator -> "=-" 1150size_t len = 0 ; 1151for (char * p = sname ;* p ;p ++ ) { 1152if (* p == '=' || vim_ispathsep (* p )) { 1153len ++ ; 1154 } 1155 } 1156char * retval = xmalloc (strlen (sname )+ len + strlen (p_vdir )+ 9 ); 1157STRCPY (retval ,p_vdir ); 1158add_pathsep (retval ); 1159char * s = retval + strlen (retval ); 1160for (char * p = sname ;* p ;p ++ ) { 1161if (* p == '=' ) { 1162* s ++ = '=' ; 1163* s ++ = '=' ; 1164 }else if (vim_ispathsep (* p )) { 1165* s ++ = '=' ; 1166#ifdef BACKSLASH_IN_FILENAME 1167* s ++ = (* p == ':' ) ?'-' :'+' ; 1168#else 1169* s ++ = '+' ; 1170#endif 1171 }else { 1172* s ++ = * p ; 1173 } 1174 } 1175* s ++ = '=' ; 1176* s ++ = c ; 1177xmemcpyz (s ,S_LEN (".vim" )); 1178 1179xfree (sname ); 1180return retval ; 1181} 1182 1183/// TODO(justinmk): remove this, not needed after 5ba3cecb68cd. 1184int put_eol (FILE * fd ) 1185{ 1186if (putc ('\n' ,fd )< 0 ) { 1187return FAIL ; 1188 } 1189return OK ; 1190} 1191 1192/// TODO(justinmk): remove this, not needed after 5ba3cecb68cd. 1193int put_line (FILE * fd ,char * s ) 1194{ 1195if (fprintf (fd ,"%s\n" ,s )< 0 ) { 1196return FAIL ; 1197 } 1198return OK ; 1199}