robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// Context = "full app state" abstraction. So named to disambiguate state.c, which is about the 2// event-loop state-machine, not "total program state". 3// 4// Unified interface of: 5// + shada 6// + CtxSwitch/ctx_switch (FKA: aucmd_prepbuf, switch_win, win_execute_T) 7// + TODO: save_state_T/save_current_state 8// + TODO: sessions 9// + TODO: undo save/restore (for cmdpreview, multicursor) 10// + TODO: TRY_WRAP ? 11// + TODO: viewstate_T ? 12// 13// Related: 14// - vim.with() 15// - switch_option_context(), restore_option_context() 16// - McSandbox/mc_sandbox_enter: input-replay guard. Sibling axis to ctx_switch() and ctx_save(). 17 18#include <assert.h> 19#include <stdbool.h> 20#include <stdint.h> 21#include <stdio.h> 22#include <string.h> 23 24#include "nvim/api/extmark.h" 25#include "nvim/api/keysets_defs.h" 26#include "nvim/api/private/converter.h" 27#include "nvim/api/private/defs.h" 28#include "nvim/api/private/helpers.h" 29#include "nvim/api/vim.h" 30#include "nvim/api/vimscript.h" 31#include "nvim/autocmd.h" 32#include "nvim/buffer.h" 33#include "nvim/context.h" 34#include "nvim/cursor.h" 35#include "nvim/decoration.h" 36#include "nvim/eval/encode.h" 37#include "nvim/eval/typval.h" 38#include "nvim/eval/typval_defs.h" 39#include "nvim/eval/userfunc.h" 40#include "nvim/eval/vars.h" 41#include "nvim/ex_docmd.h" 42#include "nvim/extmark.h" 43#include "nvim/fileio.h" 44#include "nvim/globals.h" 45#include "nvim/hashtab.h" 46#include "nvim/keycodes.h" 47#include "nvim/mark.h" 48#include "nvim/marktree.h" 49#include "nvim/memory.h" 50#include "nvim/memory_defs.h" 51#include "nvim/option.h" 52#include "nvim/option_defs.h" 53#include "nvim/option_vars.h" 54#include "nvim/os/fs.h" 55#include "nvim/register.h" 56#include "nvim/shada.h" 57#include "nvim/state_defs.h" 58#include "nvim/vim_defs.h" 59#include "nvim/window.h" 60#include "nvim/winfloat.h" 61 62#include "context.c.generated.h" 63 64/// Nesting depth of ctx_switch() calls that changed curwin. 65static int _ctx_switch_depth = 0 ; 66 67/// curwin saved by the outermost curwin-changing ctx_switch() (0: none). 68static handle_T _ctx_saved_curwin = 0 ; 69 70/// Whether an explicit :cd/:tcd/:lcd/:bcd/chdir() happened since the innermost ctx_switch(). 71static bool _ctx_did_chdir = false; 72 73/// Namespace for the extmarks tracking a Context's kCtxVisual/kCtxMarks positions. 74static uint32_t ctx_marks_ns (void ) 75{ 76static uint32_t ns = 0 ; 77if (ns == 0 ) { 78ns = (uint32_t )nvim_create_namespace (STATIC_CSTR_AS_STRING ("nvim.context" )); 79 } 80return ns ; 81} 82 83/// kCtxVisual/kCtxMarks positions of `ctx`, in `Context.pos_marks` order. NULL: not in `flags`. 84static void ctx_positions (Context * ctx ,CtxStateFlags flags ,pos_T * pos [6 ]) 85{ 86const bool visual = flags & kCtxVisual ; 87const bool marks = flags & kCtxMarks ; 88pos [0 ]= visual ?& ctx -> visual .vi_start :NULL ; 89pos [1 ]= visual ?& ctx -> visual .vi_end :NULL ; 90pos [2 ]= marks ?& ctx -> op_start :NULL ; 91pos [3 ]= marks ?& ctx -> op_end :NULL ; 92pos [4 ]= marks ?& ctx -> last_change .mark :NULL ; 93pos [5 ]= marks ?& ctx -> last_insert .mark :NULL ; 94} 95 96/// Frees a Context's resources and resets it via CONTEXT_INIT (thus the Context can be "reused"). 97void ctx_free (Context * ctx ) 98FUNC_ATTR_NONNULL_ALL 99{ 100buf_T * buf = handle_get_buffer (ctx -> buf ); 101if (buf != NULL ) {// Else the extmarks died with the buffer. 102for (size_t i = 0 ;i < ARRAY_SIZE (ctx -> pos_marks );i ++ ) { 103if (ctx -> pos_marks [i ]!= 0 ) { 104extmark_del_id (buf ,ctx_marks_ns (),ctx -> pos_marks [i ]); 105 } 106 } 107 } 108api_free_string (ctx -> regs ); 109api_free_string (ctx -> jumps ); 110api_free_string (ctx -> bufs ); 111api_free_string (ctx -> gvars ); 112api_free_array (ctx -> funcs ); 113* ctx = (Context )CONTEXT_INIT ; 114} 115 116/// Saves the editor state (ALL THE THINGS!!!1) to a context. 117/// 118/// @param ctx Save to this context. 119/// @param flags State types to save. 120void ctx_save (Context * ctx ,const CtxStateFlags flags ) 121FUNC_ATTR_NONNULL_ALL 122{ 123// Its extmarks live in its buffer: re-save a Context only there, else ctx_free() it first. 124assert (ctx -> buf == 0 || ctx -> buf == curbuf -> handle ); 125ctx -> buf = curbuf -> handle ; 126ctx -> pos = (pos_T ) { 127 .lnum = curwin -> w_cursor .lnum , 128 .col = curwin -> w_cursor .col , 129 .coladd = curwin -> w_cursor .coladd , 130 }; 131 132if (flags & kCtxCursor ) { 133ctx -> curswant = curwin -> w_set_curswant ?-1 :curwin -> w_curswant ; 134 } 135 136if (flags & kCtxVisual ) { 137ctx -> visual = curbuf -> b_visual ; 138ctx -> visual_mode_eval = curbuf -> b_visual_mode_eval ; 139 } 140if (flags & kCtxMarks ) { 141ctx -> op_start = curbuf -> b_op_start ; 142ctx -> op_end = curbuf -> b_op_end ; 143ctx -> last_change = curbuf -> b_last_change ; 144ctx -> last_insert = curbuf -> b_last_insert ; 145 } 146if (flags & (kCtxVisual |kCtxMarks )) { 147// Track the positions by extmarks, so buffer edits before ctx_load() shift them. 148pos_T * pos [6 ]; 149ctx_positions (ctx ,flags ,pos ); 150for (size_t i = 0 ;i < ARRAY_SIZE (pos );i ++ ) { 151if (pos [i ]== NULL ) { 152continue ; 153 } 154if (pos [i ]-> lnum == 0 ) {// Unset mark: no extmark. 155if (ctx -> pos_marks [i ]!= 0 ) { 156extmark_del_id (curbuf ,ctx_marks_ns (),ctx -> pos_marks [i ]); 157ctx -> pos_marks [i ]= 0 ; 158 } 159continue ; 160 } 161pos_T p = * pos [i ]; 162check_pos (curbuf ,& p );// Vim clamps marks at use; an extmark needs a valid position. 163extmark_set_pos (curbuf ,ctx_marks_ns (),& ctx -> pos_marks [i ],p , true, true, false); 164 } 165 } 166 167if (flags & kCtxRegs ) { 168ctx -> regs = shada_encode_regs (false,0 ); 169 } 170 171if (flags & kCtxJumps ) { 172ctx -> jumps = shada_encode_jumps (); 173 } 174 175if (flags & kCtxBufs ) { 176ctx -> bufs = shada_encode_buflist (); 177 } 178 179if (flags & kCtxGVars ) { 180ctx -> gvars = shada_encode_gvars (); 181 } 182 183if (flags & (kCtxFuncs |kCtxSFuncs )) { 184const bool scriptonly = !(flags & kCtxFuncs );// kCtxSFuncs: s: functions only 185ctx -> funcs = (Array )ARRAY_DICT_INIT ; 186Error err = ERROR_INIT ; 187 188HASHTAB_ITER (func_tbl_get (),hi , { 189const char * const name = hi -> hi_key ; 190bool islambda = (strncmp (name ,"<lambda>" ,8 )== 0 ); 191bool isscript = ((uint8_t )name [0 ]== K_SPECIAL ); 192 193if (!islambda && (!scriptonly || isscript )) { 194size_t cmd_len = sizeof ("func! " )+ strlen (name ); 195char * cmd = xmalloc (cmd_len ); 196snprintf (cmd ,cmd_len ,"func! %s" ,name ); 197Dict (exec_opts )opts = { .output = true }; 198String func_body = exec_impl (VIML_INTERNAL_CALL ,cstr_as_string (cmd ),& opts ,& err ); 199xfree (cmd ); 200if (!ERROR_SET (& err )) { 201ADD (ctx -> funcs ,STRING_OBJ (func_body )); 202 } 203api_clear_error (& err ); 204 } 205 }); 206 } 207} 208 209/// Loads (restores) the editor state from a Context snapshot. Restores registers EXACTLY, unless 210/// kCtxMergeReg is specified. 211/// 212/// @param ctx Load from this context. 213/// @param flags State types to load. 214/// @param loadflags Controls load behavior. 215void ctx_load (Context * ctx ,const CtxStateFlags flags ,const CtxLoadFlags loadflags ) 216FUNC_ATTR_NONNULL_ALL 217{ 218// TODO(jkeyes): restore window (add a `win` param?), mode? 219 220if (flags & kCtxCursor ) { 221assert (handle_get_buffer (ctx -> buf )== curbuf ); 222curwin -> w_cursor = ctx -> pos ;// The caller clamps it (check_cursor()). 223// Unset curswant: derive from the position, like a new cursor. 224if (ctx -> curswant >=0 ) { 225curwin -> w_curswant = ctx -> curswant ; 226curwin -> w_set_curswant = false; 227 }else { 228curwin -> w_set_curswant = true; 229 } 230 } 231 232buf_T * buf = handle_get_buffer (ctx -> buf ); 233if ((flags & (kCtxVisual |kCtxMarks ))&& buf != NULL ) { 234pos_T * pos [6 ]; 235ctx_positions (ctx ,flags ,pos ); 236for (size_t i = 0 ;i < ARRAY_SIZE (pos );i ++ ) { 237if (pos [i ]== NULL || ctx -> pos_marks [i ]== 0 ) { 238continue ; 239 } 240// Shifted by edits since ctx_save(); a deleted mark keeps the saved position. 241extmark_get_pos (buf ,ctx_marks_ns (),ctx -> pos_marks [i ],pos [i ]); 242 } 243if (flags & kCtxVisual ) { 244buf -> b_visual = ctx -> visual ; 245buf -> b_visual_mode_eval = ctx -> visual_mode_eval ; 246 } 247if (flags & kCtxMarks ) { 248buf -> b_op_start = ctx -> op_start ; 249buf -> b_op_end = ctx -> op_end ; 250buf -> b_last_change = ctx -> last_change ; 251buf -> b_last_insert = ctx -> last_insert ; 252 } 253 } 254 255if (flags & kCtxRegs ) { 256if (!(loadflags & kCtxMergeReg )) { 257// Avoid shada "merge" behavior for registers; restore "exact", don't merge. 258for (int i = 0 ;i < NUM_SAVED_REGISTERS ;i ++ ) { 259free_register (get_y_register (i )); 260 } 261 } 262shada_read_string (ctx -> regs ,kShaDaWantInfo |kShaDaForceit |kShaDaNanos |kShaDaNoHistory ); 263 } 264 265if (flags & kCtxJumps ) { 266shada_read_string (ctx -> jumps ,kShaDaWantInfo |kShaDaForceit |kShaDaNoHistory ); 267 } 268 269if (flags & kCtxBufs ) { 270shada_read_string (ctx -> bufs ,kShaDaWantInfo |kShaDaForceit |kShaDaNoHistory |kShaDaNoOpt ); 271 } 272 273if (flags & kCtxGVars ) { 274shada_read_string (ctx -> gvars ,kShaDaWantInfo |kShaDaForceit |kShaDaNoHistory |kShaDaNoOpt ); 275 } 276 277if (flags & kCtxFuncs ) { 278for (size_t i = 0 ;i < ctx -> funcs .size ;i ++ ) { 279do_cmdline_cmd (ctx -> funcs .items [i ].data .string .data ); 280 } 281 } 282} 283 284/// Convert readfile()-style array to String 285/// 286/// @param[in] array readfile()-style array to convert. 287/// @param[out] err Error object. 288/// 289/// @return String with conversion result. 290static inline String array_to_string (Array array ,Error * err ) 291FUNC_ATTR_NONNULL_ALL 292{ 293String sbuf = STRING_INIT ; 294 295typval_T list_tv ; 296object_to_vim (ARRAY_OBJ (array ),& list_tv ,err ); 297 298assert (list_tv .v_type == VAR_LIST ); 299if (!encode_vim_list_to_buf (list_tv .vval .v_list ,& sbuf .size ,& sbuf .data )) { 300api_set_error (err ,kErrorTypeException ,"%s" , 301"E474: Failed to convert list to msgpack string buffer" ); 302 } 303 304tv_clear (& list_tv ); 305return sbuf ; 306} 307 308/// Converts Context to Dict representation. 309/// 310/// @param[in] ctx Context to convert. 311/// 312/// @return Dict representing "ctx". 313Dict ctx_to_dict (Context * ctx ,Arena * arena ) 314FUNC_ATTR_NONNULL_ALL 315{ 316assert (ctx != NULL ); 317 318Dict rv = arena_dict (arena ,5 ); 319 320PUT_C (rv ,"regs" ,ARRAY_OBJ (string_to_array (ctx -> regs , false,arena ))); 321PUT_C (rv ,"jumps" ,ARRAY_OBJ (string_to_array (ctx -> jumps , false,arena ))); 322PUT_C (rv ,"bufs" ,ARRAY_OBJ (string_to_array (ctx -> bufs , false,arena ))); 323PUT_C (rv ,"gvars" ,ARRAY_OBJ (string_to_array (ctx -> gvars , false,arena ))); 324PUT_C (rv ,"funcs" ,ARRAY_OBJ (copy_array (ctx -> funcs ,arena ))); 325 326return rv ; 327} 328 329/// Converts Dict representation of Context back to Context object. 330/// 331/// @param[in] dict Context Dict representation. 332/// @param[out] ctx Context object to store conversion result into. 333/// @param[out] err Error object. 334/// 335/// @return types of included context items. 336CtxStateFlags ctx_from_dict (Dict dict ,Context * ctx ,Error * err ) 337FUNC_ATTR_NONNULL_ALL 338{ 339assert (ctx != NULL ); 340 341CtxStateFlags types = 0 ; 342for (size_t i = 0 ;i < dict .size && !ERROR_SET (err );i ++ ) { 343KeyValuePair item = dict .items [i ]; 344if (item .value .type != kObjectTypeArray ) { 345continue ; 346 } 347if (strequal (item .key .data ,"regs" )) { 348types |=kCtxRegs ; 349ctx -> regs = array_to_string (item .value .data .array ,err ); 350 }else if (strequal (item .key .data ,"jumps" )) { 351types |=kCtxJumps ; 352ctx -> jumps = array_to_string (item .value .data .array ,err ); 353 }else if (strequal (item .key .data ,"bufs" )) { 354types |=kCtxBufs ; 355ctx -> bufs = array_to_string (item .value .data .array ,err ); 356 }else if (strequal (item .key .data ,"gvars" )) { 357types |=kCtxGVars ; 358ctx -> gvars = array_to_string (item .value .data .array ,err ); 359 }else if (strequal (item .key .data ,"funcs" )) { 360types |=kCtxFuncs ; 361ctx -> funcs = copy_object (item .value ,NULL ).data .array ; 362 } 363 } 364 365return types ; 366} 367 368/// Moves CWD state aside, so that the temporary "autocmd window" starts clean. 369/// Undone by ctx_localdirs_restore(). 370static void ctx_win_dirs_save (CtxSwitch * cs ,win_T * cw_win ,buf_T * buf ) 371{ 372// A pooled tmp-window must not carry a stale w_localdir. 373XFREE_CLEAR (cw_win -> w_localdir ); 374cs -> cs_b_localdir = buf -> b_localdir ; 375buf -> b_localdir = NULL ; 376cs -> cs_tp_localdir = curtab -> tp_localdir ; 377curtab -> tp_localdir = NULL ; 378cs -> cs_globaldir = globaldir ; 379globaldir = NULL ; 380} 381 382/// Restores the dir scopes saved in `cs`. With `persist`, a scope explicitly changed 383/// (user :bcd/:tcd/:cd) keeps its new value instead. 384/// 385/// @param cwp The discarded temp win of a hidden buf, or NULL. If given, also fix the process CWD. 386/// @param tp Tabpage that owns cs_tp_localdir, or NULL if it no longer exists. 387static void ctx_localdirs_restore (CtxSwitch * cs ,win_T * cwp ,tabpage_T * tp ,bool persist ) 388{ 389const bool did_chdir = _ctx_did_chdir ; 390_ctx_did_chdir = persist && did_chdir ; 391 392win_T * dirs_win = win_find_by_handle (cs -> cs_new_curwin ); 393if (dirs_win != NULL ) { 394xfree (dirs_win -> w_localdir ); 395dirs_win -> w_localdir = cs -> cs_w_localdir ; 396 }else { 397xfree (cs -> cs_w_localdir ); 398 } 399 400buf_T * b = bufref_valid (& cs -> cs_new_curbuf ) ?cs -> cs_new_curbuf .br_buf :NULL ; 401if (b != NULL && !(persist && b -> b_localdir != NULL )) { 402xfree (b -> b_localdir ); 403b -> b_localdir = cs -> cs_b_localdir ; 404 }else { 405xfree (cs -> cs_b_localdir ); 406 } 407 408if (tp != NULL && !(persist && tp -> tp_localdir != NULL )) { 409xfree (tp -> tp_localdir ); 410tp -> tp_localdir = cs -> cs_tp_localdir ; 411 }else { 412xfree (cs -> cs_tp_localdir ); 413 } 414 415// Correct the directory before restoring globaldir: the first chdir during the switch saved 416// the pre-switch cwd in `globaldir` (see `post_chdir`), which update_cwd() uses as fallback. 417if (cwp != NULL && (did_chdir || cwp -> w_localdir != NULL )) { 418update_cwd (kCdCauseWindow ); 419 } 420 421// Keep-case: the globaldir set during the switch (pre-switch cwd, see `post_chdir`). 422if (!(persist && cs -> cs_globaldir == NULL && globaldir != NULL )) { 423xfree (globaldir ); 424globaldir = cs -> cs_globaldir ; 425cs -> cs_globaldir = NULL ; 426 } 427} 428 429/// Saves the dir state to be restored by ctx_dirs_restore(): 430/// - kCtxKeepCwd or kCtxKeepDirs: the CWD and `globaldir`, so any directory change caused by 431/// switching to `wp` ('autochdir', win/tab-local directories) can be undone. 432/// - kCtxKeepDirs: also copies of the target context's dir scopes (w/b/tp-local). 433static void ctx_dirs_save (CtxSwitch * cs ,win_T * wp ,tabpage_T * tp ,buf_T * buf ) 434FUNC_ATTR_NONNULL_ARG (1 ,2 ,3 ) 435{ 436if (!(cs -> cs_flags & (kCtxKeepCwd |kCtxKeepDirs ))) { 437return ; 438 } 439 440// `globaldir` is where to return when no local dir applies (NULL: the CWD is already there). 441cs -> cs_globaldir = globaldir == NULL ?NULL :xstrdup (globaldir ); 442 443// kCtxKeepDirs: also save copies of the target context's dir scopes. 444if (cs -> cs_flags & kCtxKeepDirs ) { 445buf_T * target_buf = buf != NULL ?buf :wp -> w_buffer ; 446cs -> cs_dirs_tab = tp -> handle ; 447cs -> cs_w_localdir = wp -> w_localdir == NULL ?NULL :xstrdup (wp -> w_localdir ); 448cs -> cs_b_localdir = target_buf -> b_localdir == NULL ?NULL :xstrdup (target_buf -> b_localdir ); 449cs -> cs_tp_localdir = tp -> tp_localdir == NULL ?NULL :xstrdup (tp -> tp_localdir ); 450 } 451 452char cwd [MAXPATHL ]; 453if ((cs -> cs_flags & kCtxKeepDirs )|| curwin != wp ) { 454if (os_dirname (cwd ,MAXPATHL )== OK ) { 455cs -> cs_cwd = xstrdup (cwd );// allocated on demand: keeps CtxSwitch small 456 } 457 } 458 459// If 'acd' is set, check we are using that directory. If yes, then 460// apply 'acd' afterwards, otherwise restore the current directory. 461if (cs -> cs_cwd != NULL && p_acd ) { 462do_autochdir (); 463char autocwd [MAXPATHL ]; 464if (os_dirname (autocwd ,MAXPATHL )== OK ) { 465cs -> cs_apply_acd = strcmp (cs -> cs_cwd ,autocwd )== 0 ; 466 } 467 } 468} 469 470/// Restores the dir state saved by ctx_dirs_save(), undoing any chdir made while switched. The 471/// target window/buffer/tab may have been closed meanwhile. 472static void ctx_dirs_restore (CtxSwitch * cs ) 473{ 474if (cs -> cs_ctxwin_idx >=0 ) { 475return ;// Hidden-buffer target: ctx_localdirs_restore() already restored dirs. 476 } 477 478// kCtxKeepDirs: restore the saved dir scopes. 479if (cs -> cs_flags & kCtxKeepDirs ) { 480tabpage_T * dirs_tab = NULL ; 481FOR_ALL_TABS (tp ) { 482if (tp -> handle == cs -> cs_dirs_tab ) { 483dirs_tab = tp ; 484break ; 485 } 486 } 487ctx_localdirs_restore (cs ,NULL ,dirs_tab , false); 488 }else if (cs -> cs_cwd != NULL && !_ctx_did_chdir ) { 489// Pairs with the CWD restore below. 490xfree (globaldir ); 491globaldir = cs -> cs_globaldir ; 492cs -> cs_globaldir = NULL ; 493 } 494XFREE_CLEAR (cs -> cs_globaldir ); 495 496// Restore the CWD itself. After an explicit chdir, ctx_restore() re-derives it instead. 497if (cs -> cs_apply_acd ) { 498do_autochdir (); 499 }else if (cs -> cs_cwd != NULL && ((cs -> cs_flags & kCtxKeepDirs )|| !_ctx_did_chdir )) { 500os_chdir (cs -> cs_cwd ); 501// Buffer names are relative to the CWD, so they must follow it back. #41424 502shorten_fnames (true); 503 } 504XFREE_CLEAR (cs -> cs_cwd ); 505} 506 507void ctx_did_chdir (void ) 508{ 509_ctx_did_chdir = true; 510} 511 512/// Return true if `win` is an active entry in ctx_win[] (the pool of temporary scratch windows). 513bool is_ctx_win (win_T * win ) 514{ 515for (int i = 0 ;i < CTX_WIN_COUNT ;i ++ ) { 516if (ctx_win [i ].cw_used && ctx_win [i ].cw_win == win ) { 517return true; 518 } 519 } 520return false; 521} 522 523/// Prepares a temporary "autocmd window" showing `buf`: allocated/reused from the `ctx_win[]` pool 524/// and appended to the window list of curtab. Records what ctx_restore() needs to undo in `cs`. 525/// 526/// Window lifecycle only: does not enter the window, no side effects (autocmds, chdir, redraw). 527/// 528/// @return the prepared autocmd window. 529static win_T * ctx_win_prep (CtxSwitch * cs ,buf_T * buf ) 530{ 531bool need_append = true;// Append `cw_win` to the window list. 532 533// Allocate a window when needed. 534int idx ; 535for (idx = 0 ;idx < CTX_WIN_COUNT ;idx ++ ) { 536if (!ctx_win [idx ].cw_used ) { 537break ; 538 } 539 } 540if (idx == CTX_WIN_COUNT ) { 541kv_push (ctx_win_vec , ((CtxWin ){ 542 .cw_win = NULL , 543 .cw_used = false, 544 })); 545 } 546if (ctx_win [idx ].cw_win == NULL ) { 547win_alloc_ctx_win (idx ); 548need_append = false; 549 } 550win_T * cw_win = ctx_win [idx ].cw_win ; 551ctx_win [idx ].cw_used = true; 552cs -> cs_ctxwin_idx = idx ; 553 554cw_win -> w_buffer = buf ; 555cw_win -> w_s = & buf -> b_s ; 556buf -> b_nwindows ++ ; 557win_init_empty (cw_win );// set cursor and topline to safe values 558 559ctx_win_dirs_save (cs ,cw_win ,buf ); 560 561if (need_append ) { 562win_append (lastwin ,cw_win ,NULL ); 563pmap_put (int )(& window_handles ,cw_win -> handle ,cw_win ); 564win_config_float (cw_win ,cw_win -> w_config ); 565 } 566 567return cw_win ; 568} 569 570/// Removes the temp win (FKA "autocmd win") prepared by ctx_win_prep() from the window list 571/// (entering it if needed), and releases its pool slot. Caller must restore curwin (the removed 572/// window is curwin) and the directory state saved in "cs". 573/// 574/// @return the removed autocmd window. 575static win_T * ctx_win_rest (CtxSwitch * cs ) 576{ 577win_T * cwp = ctx_win [cs -> cs_ctxwin_idx ].cw_win ; 578 579// Find `cwp`, it can't be closed, but it may be in another tab page. 580// Do not trigger autocommands here. 581block_autocmds (); 582if (curwin != cwp ) { 583FOR_ALL_TAB_WINDOWS (tp ,wp ) { 584if (wp == cwp ) { 585if (tp != curtab ) { 586goto_tabpage_tp (tp , true, true); 587 } 588win_goto (cwp ); 589 gotowin_found ; 590 } 591 } 592 } 593win_found : 594curbuf -> b_nwindows -- ; 595// Remove the window. 596win_remove (curwin ,NULL ); 597pmap_del (int )(& window_handles ,curwin -> handle ,NULL ); 598 599// Mark window as "not used", but don't free, it can be used again. 600ctx_win [cs -> cs_ctxwin_idx ].cw_used = false; 601 602if (!valid_tabpage_win (curtab )) { 603// no valid window in current tabpage 604close_tabpage (curtab ); 605 } 606 607unblock_autocmds (); 608return cwp ; 609} 610 611/// Window saved by the outermost curwin-changing ctx_switch(), or NULL. Used to restore the 612/// actual current window when redrawing. 613win_T * ctx_saved_curwin (void ) 614{ 615return _ctx_saved_curwin == 0 ?NULL :win_find_by_handle (_ctx_saved_curwin ); 616} 617 618/// Prepares a temporary execution context. ctx_restore() MUST be called afterwards, also when this 619/// returns false. 620/// 621/// - Passing `wp` makes that window the curwin (in tabpage `tp`, or NULL for current tabpage). 622/// - (Legacy: switch_win(), switch_win_noblock(), win_execute_before().) 623/// - Passing `buf`, enters a window showing `buf` in the current tabpage, or prepares a temporary 624/// "autocmd window" for it (never switches tabpage). 625/// - (Legacy: aucmd_prepbuf().) 626/// - Passing neither: only CWD state is saved; flags must include `kCtxKeepDirs`. 627/// 628/// The switch itself never triggers autocommands; whether autocommands can fire _while_ switched 629/// (until ctx_restore()) is the caller's choice via kCtxNoEvents. 630/// 631/// @param wp Target window, or NULL. 632/// @param tp Tabpage of `wp`, or NULL to not switch tabpage. 633/// @param buf Target buffer, or NULL. 634/// @param flags kCtx flags. 635/// 636/// @return false if switching failed (only possible for a window target). 637bool ctx_switch (CtxSwitch * cs ,win_T * wp ,tabpage_T * tp ,buf_T * buf ,CtxSwitchFlags flags ) 638{ 639// Exactly one target, or none with kCtxKeepDirs (which only saves the CWD state). 640assert (((wp == NULL )!= (buf == NULL ))|| (wp == NULL && (flags & kCtxKeepDirs ))); 641assert (buf == NULL || tp == NULL );// a buffer target never switches tabpage 642CLEAR_POINTER (cs ); 643cs -> cs_flags = flags ; 644cs -> cs_mode = buf != NULL ?kCtxSwitchBuf :wp != NULL ?kCtxSwitchWin :kCtxSwitchDirs ; 645cs -> cs_ctxwin_idx = -1 ; 646cs -> cs_did_chdir = _ctx_did_chdir ; 647_ctx_did_chdir = false; 648if (cs -> cs_mode == kCtxSwitchDirs ) { 649wp = curwin ;// No target: "switch" to curwin, i.e. stay put. 650 } 651 652// Resolve the target window. A buffer target prefers a window already showing it, in the current 653// tabpage (minimizes side effects); else a ctx_win is prepared below (ctx_win_prep). 654if (buf != NULL ) { 655if (buf == curbuf ) {// be quick when buf is curbuf 656wp = curwin ; 657 }else { 658FOR_ALL_WINDOWS_IN_TAB (wp2 ,curtab ) { 659if (wp2 -> w_buffer == buf ) { 660wp = wp2 ; 661break ; 662 } 663 } 664 } 665 } 666 667if ((flags & kCtxValidate )&& wp != NULL ) { 668cs -> cs_target_win = wp -> handle ; 669cs -> cs_target_old_pos = wp -> w_cursor ; 670 } 671// The CWD-state snapshot is only for a real window target; hidden-buffer target is handled by the 672// ctx_win machinery (ctx_win_prep). 673if (wp != NULL ) { 674ctx_dirs_save (cs ,wp ,tp == NULL ?curtab :tp ,buf ); 675 } 676 677// Save the current state. 678cs -> cs_curwin = curwin -> handle ; 679cs -> cs_prevwin = prevwin == NULL ?0 :prevwin -> handle ; 680cs -> cs_same_win = wp == curwin ; 681if (bt_prompt (curbuf )) { 682cs -> cs_prompt_insert = curbuf -> b_prompt_insert ; 683 } 684if (!cs -> cs_same_win ) { 685// Disable Visual selection, because redrawing may fail. 686cs -> cs_visual_active = Visual .active ; 687Visual .active = false; 688 } 689 690if (flags & kCtxNoEvents ) { 691block_autocmds (); 692 } 693if (tp != NULL ) { 694cs -> cs_curtab = curtab ; 695if (flags & kCtxNoDisplay ) { 696unuse_tabpage (curtab ); 697use_tabpage (tp ); 698 }else { 699goto_tabpage_tp (tp , false, false); 700 } 701 } 702 703if (buf != NULL ) { 704if (wp == NULL ) { 705// Hidden buffer (`buf` not visible in any window): prepare a temp window. 706// Window behavior (e.g., setting folds) may have unexpected results. 707wp = ctx_win_prep (cs ,buf ); 708// Leave the window we entered "from". 709leaving_window (curwin ); 710// We will soon enter "buf" and may have to copy buffer options. 711buf_copy_options (buf ,BCO_ENTER |BCO_NOHELP ); 712prevwin = curwin ; 713 } 714assert (win_valid (wp )); 715 }else if (!win_valid (wp )) { 716return false; 717 } 718curwin = wp ; 719curbuf = curwin -> w_buffer ; 720cs -> cs_new_curwin = curwin -> handle ; 721set_bufref (& cs -> cs_new_curbuf ,curbuf ); 722 723if (cs -> cs_mode == kCtxSwitchBuf && cs -> cs_new_curwin != cs -> cs_curwin ) { 724_ctx_saved_curwin = _ctx_switch_depth == 0 ?cs -> cs_curwin :_ctx_saved_curwin ; 725_ctx_switch_depth ++ ; 726 } 727if (flags & kCtxValidate ) { 728check_cursor (curwin ); 729 } 730return true; 731} 732 733/// Restores curwin/curbuf and prevwin. If the saved window no longer exists, enters `fallback`. 734static void ctx_restore_curwin (CtxSwitch * cs ,win_T * fallback ) 735{ 736win_T * save_curwin = win_find_by_handle (cs -> cs_curwin ); 737if (save_curwin == NULL ) { 738save_curwin = fallback ;// Hmm, original window disappeared. 739 } 740if (save_curwin != NULL ) { 741curwin = save_curwin ; 742curbuf = curwin -> w_buffer ; 743 } 744prevwin = win_find_by_handle (cs -> cs_prevwin ); 745} 746 747/// Undoes ctx_switch(): restores the previous location (if possible) and the kept state. 748/// 749/// No-op if `cs` was zero-initialized, even if ctx_switch() was not called on it: 750/// 751/// CtxSwitch cs = { 0 }; 752/// if (some_condition) { 753/// ctx_switch(&cs, NULL, NULL, buf, 0); 754/// } 755/// ... 756/// ctx_restore(&cs); // no-op if ctx_switch() was skipped. 757/// 758/// Legacy: restore_win()/restore_win_noblock(), aucmd_restbuf(), win_execute_after(). 759void ctx_restore (CtxSwitch * cs ) 760{ 761if (cs -> cs_mode == kCtxSwitchNone ) { 762return ;// zero-initialized: ctx_switch() was never called on `cs`. 763 } 764 765if (cs -> cs_mode == kCtxSwitchWin ) { 766// Window target: restore tabpage and curwin. 767if (cs -> cs_curtab != NULL && valid_tabpage (cs -> cs_curtab )) { 768if (cs -> cs_flags & kCtxNoDisplay ) { 769win_T * const old_tp_curwin = curtab -> tp_curwin ; 770 771unuse_tabpage (curtab ); 772// Don't change the curwin of the tabpage we temporarily visited. 773curtab -> tp_curwin = old_tp_curwin ; 774use_tabpage (cs -> cs_curtab ); 775 }else { 776goto_tabpage_tp (cs -> cs_curtab , false, false); 777 } 778 } 779 780ctx_restore_curwin (cs ,NULL ); 781 }else if (cs -> cs_ctxwin_idx >=0 ) { 782win_T * cwp = ctx_win_rest (cs ); 783 784ctx_restore_curwin (cs ,firstwin ); 785// May need to restore insert-mode for a prompt buffer. 786// Pairs with the leaving_window() in ctx_switch(). 787entering_window (curwin ); 788if (bt_prompt (curbuf )) { 789curbuf -> b_prompt_insert = cs -> cs_prompt_insert ; 790 } 791 792vars_clear (& cwp -> w_vars -> dv_hashtab );// free all w: variables 793hash_init (& cwp -> w_vars -> dv_hashtab );// re-use the hashtab 794 795ctx_localdirs_restore (cs ,cwp ,curtab , !(cs -> cs_flags & kCtxKeepDirs )); 796 797// Buffer contents may have changed; cursor is checked below, AFTER restoring Visual state. 798if (curwin -> w_topline > curbuf -> b_ml .ml_line_count ) { 799curwin -> w_topline = curbuf -> b_ml .ml_line_count ; 800curwin -> w_topfill = 0 ; 801 } 802 }else if (cs -> cs_mode == kCtxSwitchBuf ) { 803// Restore the buffer previously edited by curwin. 804if (curwin -> handle == cs -> cs_new_curwin 805&& curbuf != cs -> cs_new_curbuf .br_buf 806&& bufref_valid (& cs -> cs_new_curbuf ) 807&& cs -> cs_new_curbuf .br_buf -> b_ml .ml_mfp != NULL ) { 808if (curwin -> w_s == & curbuf -> b_s ) { 809curwin -> w_s = & cs -> cs_new_curbuf .br_buf -> b_s ; 810 } 811curbuf -> b_nwindows -- ; 812curbuf = cs -> cs_new_curbuf .br_buf ; 813curwin -> w_buffer = curbuf ; 814curbuf -> b_nwindows ++ ; 815 } 816 817ctx_restore_curwin (cs ,NULL ); 818 }// Else: only save CWD state. 819 820if (!cs -> cs_same_win ) { 821Visual .active = cs -> cs_visual_active ; 822 } 823if (cs -> cs_mode == kCtxSwitchBuf ) { 824check_cursor (curwin );// just in case lines got deleted 825if (Visual .active ) { 826check_pos (curbuf ,& Visual .start ); 827 } 828 } 829 830// Release what ctx_switch() engaged (any target kind). 831if (cs -> cs_flags & kCtxNoEvents ) { 832unblock_autocmds (); 833 } 834ctx_dirs_restore (cs );// No-op if ctx_dirs_save() saved nothing. 835// Re-apply the restored context's effective directory. 836if (cs -> cs_ctxwin_idx < 0 && _ctx_did_chdir ) { 837update_cwd (kCdCauseWindow ); 838 } 839_ctx_did_chdir = _ctx_did_chdir || cs -> cs_did_chdir ; 840if (cs -> cs_flags & kCtxValidate ) { 841// Update the status line if the cursor moved in the target window. 842win_T * const wp = win_find_by_handle (cs -> cs_target_win ); 843if (wp != NULL && !equalpos (cs -> cs_target_old_pos ,wp -> w_cursor )) { 844wp -> w_redr_status = true; 845 } 846// In case the code moved the cursor or changed the Visual area, check it is valid. 847check_cursor (curwin ); 848if (Visual .active ) { 849check_pos (curbuf ,& Visual .start ); 850 } 851 } 852if (cs -> cs_mode == kCtxSwitchBuf && cs -> cs_new_curwin != cs -> cs_curwin ) { 853assert (_ctx_switch_depth > 0 ); 854_ctx_switch_depth -- ; 855_ctx_saved_curwin = _ctx_switch_depth == 0 ?0 :_ctx_saved_curwin ; 856 } 857}