robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
27.5 KiB857 linesraw
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{
76  static uint32_t ns = 0;
77  if (ns == 0) {
78    ns = (uint32_t)nvim_create_namespace(STATIC_CSTR_AS_STRING("nvim.context"));
79  }
80  return 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{
86  const bool visual = flags & kCtxVisual;
87  const bool marks = flags & kCtxMarks;
88  pos[0] = visual ? &ctx->visual.vi_start : NULL;
89  pos[1] = visual ? &ctx->visual.vi_end : NULL;
90  pos[2] = marks ? &ctx->op_start : NULL;
91  pos[3] = marks ? &ctx->op_end : NULL;
92  pos[4] = marks ? &ctx->last_change.mark : NULL;
93  pos[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)
98  FUNC_ATTR_NONNULL_ALL
99{
100  buf_T *buf = handle_get_buffer(ctx->buf);
101  if (buf != NULL) {  // Else the extmarks died with the buffer.
102    for (size_t i = 0; i < ARRAY_SIZE(ctx->pos_marks); i++) {
103      if (ctx->pos_marks[i] != 0) {
104        extmark_del_id(buf, ctx_marks_ns(), ctx->pos_marks[i]);
105      }
106    }
107  }
108  api_free_string(ctx->regs);
109  api_free_string(ctx->jumps);
110  api_free_string(ctx->bufs);
111  api_free_string(ctx->gvars);
112  api_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)
121  FUNC_ATTR_NONNULL_ALL
122{
123  // Its extmarks live in its buffer: re-save a Context only there, else ctx_free() it first.
124  assert(ctx->buf == 0 || ctx->buf == curbuf->handle);
125  ctx->buf = curbuf->handle;
126  ctx->pos = (pos_T) {
127    .lnum = curwin->w_cursor.lnum,
128    .col = curwin->w_cursor.col,
129    .coladd = curwin->w_cursor.coladd,
130  };
131
132  if (flags & kCtxCursor) {
133    ctx->curswant = curwin->w_set_curswant ? -1 : curwin->w_curswant;
134  }
135
136  if (flags & kCtxVisual) {
137    ctx->visual = curbuf->b_visual;
138    ctx->visual_mode_eval = curbuf->b_visual_mode_eval;
139  }
140  if (flags & kCtxMarks) {
141    ctx->op_start = curbuf->b_op_start;
142    ctx->op_end = curbuf->b_op_end;
143    ctx->last_change = curbuf->b_last_change;
144    ctx->last_insert = curbuf->b_last_insert;
145  }
146  if (flags & (kCtxVisual | kCtxMarks)) {
147    // Track the positions by extmarks, so buffer edits before ctx_load() shift them.
148    pos_T *pos[6];
149    ctx_positions(ctx, flags, pos);
150    for (size_t i = 0; i < ARRAY_SIZE(pos); i++) {
151      if (pos[i] == NULL) {
152        continue;
153      }
154      if (pos[i]->lnum == 0) {  // Unset mark: no extmark.
155        if (ctx->pos_marks[i] != 0) {
156          extmark_del_id(curbuf, ctx_marks_ns(), ctx->pos_marks[i]);
157          ctx->pos_marks[i] = 0;
158        }
159        continue;
160      }
161      pos_T p = *pos[i];
162      check_pos(curbuf, &p);  // Vim clamps marks at use; an extmark needs a valid position.
163      extmark_set_pos(curbuf, ctx_marks_ns(), &ctx->pos_marks[i], p, true, true, false);
164    }
165  }
166
167  if (flags & kCtxRegs) {
168    ctx->regs = shada_encode_regs(false, 0);
169  }
170
171  if (flags & kCtxJumps) {
172    ctx->jumps = shada_encode_jumps();
173  }
174
175  if (flags & kCtxBufs) {
176    ctx->bufs = shada_encode_buflist();
177  }
178
179  if (flags & kCtxGVars) {
180    ctx->gvars = shada_encode_gvars();
181  }
182
183  if (flags & (kCtxFuncs | kCtxSFuncs)) {
184    const bool scriptonly = !(flags & kCtxFuncs);  // kCtxSFuncs: s: functions only
185    ctx->funcs = (Array)ARRAY_DICT_INIT;
186    Error err = ERROR_INIT;
187
188    HASHTAB_ITER(func_tbl_get(), hi, {
189      const char *const name = hi->hi_key;
190      bool islambda = (strncmp(name, "<lambda>", 8) == 0);
191      bool isscript = ((uint8_t)name[0] == K_SPECIAL);
192
193      if (!islambda && (!scriptonly || isscript)) {
194        size_t cmd_len = sizeof("func! ") + strlen(name);
195        char *cmd = xmalloc(cmd_len);
196        snprintf(cmd, cmd_len, "func! %s", name);
197        Dict(exec_opts) opts = { .output = true };
198        String func_body = exec_impl(VIML_INTERNAL_CALL, cstr_as_string(cmd), &opts, &err);
199        xfree(cmd);
200        if (!ERROR_SET(&err)) {
201          ADD(ctx->funcs, STRING_OBJ(func_body));
202        }
203        api_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)
216  FUNC_ATTR_NONNULL_ALL
217{
218  // TODO(jkeyes): restore window (add a `win` param?), mode?
219
220  if (flags & kCtxCursor) {
221    assert(handle_get_buffer(ctx->buf) == curbuf);
222    curwin->w_cursor = ctx->pos;  // The caller clamps it (check_cursor()).
223    // Unset curswant: derive from the position, like a new cursor.
224    if (ctx->curswant >= 0) {
225      curwin->w_curswant = ctx->curswant;
226      curwin->w_set_curswant = false;
227    } else {
228      curwin->w_set_curswant = true;
229    }
230  }
231
232  buf_T *buf = handle_get_buffer(ctx->buf);
233  if ((flags & (kCtxVisual | kCtxMarks)) && buf != NULL) {
234    pos_T *pos[6];
235    ctx_positions(ctx, flags, pos);
236    for (size_t i = 0; i < ARRAY_SIZE(pos); i++) {
237      if (pos[i] == NULL || ctx->pos_marks[i] == 0) {
238        continue;
239      }
240      // Shifted by edits since ctx_save(); a deleted mark keeps the saved position.
241      extmark_get_pos(buf, ctx_marks_ns(), ctx->pos_marks[i], pos[i]);
242    }
243    if (flags & kCtxVisual) {
244      buf->b_visual = ctx->visual;
245      buf->b_visual_mode_eval = ctx->visual_mode_eval;
246    }
247    if (flags & kCtxMarks) {
248      buf->b_op_start = ctx->op_start;
249      buf->b_op_end = ctx->op_end;
250      buf->b_last_change = ctx->last_change;
251      buf->b_last_insert = ctx->last_insert;
252    }
253  }
254
255  if (flags & kCtxRegs) {
256    if (!(loadflags & kCtxMergeReg)) {
257      // Avoid shada "merge" behavior for registers; restore "exact", don't merge.
258      for (int i = 0; i < NUM_SAVED_REGISTERS; i++) {
259        free_register(get_y_register(i));
260      }
261    }
262    shada_read_string(ctx->regs, kShaDaWantInfo | kShaDaForceit | kShaDaNanos | kShaDaNoHistory);
263  }
264
265  if (flags & kCtxJumps) {
266    shada_read_string(ctx->jumps, kShaDaWantInfo | kShaDaForceit | kShaDaNoHistory);
267  }
268
269  if (flags & kCtxBufs) {
270    shada_read_string(ctx->bufs, kShaDaWantInfo | kShaDaForceit | kShaDaNoHistory | kShaDaNoOpt);
271  }
272
273  if (flags & kCtxGVars) {
274    shada_read_string(ctx->gvars, kShaDaWantInfo | kShaDaForceit | kShaDaNoHistory | kShaDaNoOpt);
275  }
276
277  if (flags & kCtxFuncs) {
278    for (size_t i = 0; i < ctx->funcs.size; i++) {
279      do_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)
291  FUNC_ATTR_NONNULL_ALL
292{
293  String sbuf = STRING_INIT;
294
295  typval_T list_tv;
296  object_to_vim(ARRAY_OBJ(array), &list_tv, err);
297
298  assert(list_tv.v_type == VAR_LIST);
299  if (!encode_vim_list_to_buf(list_tv.vval.v_list, &sbuf.size, &sbuf.data)) {
300    api_set_error(err, kErrorTypeException, "%s",
301                  "E474: Failed to convert list to msgpack string buffer");
302  }
303
304  tv_clear(&list_tv);
305  return 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)
314  FUNC_ATTR_NONNULL_ALL
315{
316  assert(ctx != NULL);
317
318  Dict rv = arena_dict(arena, 5);
319
320  PUT_C(rv, "regs", ARRAY_OBJ(string_to_array(ctx->regs, false, arena)));
321  PUT_C(rv, "jumps", ARRAY_OBJ(string_to_array(ctx->jumps, false, arena)));
322  PUT_C(rv, "bufs", ARRAY_OBJ(string_to_array(ctx->bufs, false, arena)));
323  PUT_C(rv, "gvars", ARRAY_OBJ(string_to_array(ctx->gvars, false, arena)));
324  PUT_C(rv, "funcs", ARRAY_OBJ(copy_array(ctx->funcs, arena)));
325
326  return 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)
337  FUNC_ATTR_NONNULL_ALL
338{
339  assert(ctx != NULL);
340
341  CtxStateFlags types = 0;
342  for (size_t i = 0; i < dict.size && !ERROR_SET(err); i++) {
343    KeyValuePair item = dict.items[i];
344    if (item.value.type != kObjectTypeArray) {
345      continue;
346    }
347    if (strequal(item.key.data, "regs")) {
348      types |= kCtxRegs;
349      ctx->regs = array_to_string(item.value.data.array, err);
350    } else if (strequal(item.key.data, "jumps")) {
351      types |= kCtxJumps;
352      ctx->jumps = array_to_string(item.value.data.array, err);
353    } else if (strequal(item.key.data, "bufs")) {
354      types |= kCtxBufs;
355      ctx->bufs = array_to_string(item.value.data.array, err);
356    } else if (strequal(item.key.data, "gvars")) {
357      types |= kCtxGVars;
358      ctx->gvars = array_to_string(item.value.data.array, err);
359    } else if (strequal(item.key.data, "funcs")) {
360      types |= kCtxFuncs;
361      ctx->funcs = copy_object(item.value, NULL).data.array;
362    }
363  }
364
365  return 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.
373  XFREE_CLEAR(cw_win->w_localdir);
374  cs->cs_b_localdir = buf->b_localdir;
375  buf->b_localdir = NULL;
376  cs->cs_tp_localdir = curtab->tp_localdir;
377  curtab->tp_localdir = NULL;
378  cs->cs_globaldir = globaldir;
379  globaldir = 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{
389  const bool did_chdir = _ctx_did_chdir;
390  _ctx_did_chdir = persist && did_chdir;
391
392  win_T *dirs_win = win_find_by_handle(cs->cs_new_curwin);
393  if (dirs_win != NULL) {
394    xfree(dirs_win->w_localdir);
395    dirs_win->w_localdir = cs->cs_w_localdir;
396  } else {
397    xfree(cs->cs_w_localdir);
398  }
399
400  buf_T *b = bufref_valid(&cs->cs_new_curbuf) ? cs->cs_new_curbuf.br_buf : NULL;
401  if (b != NULL && !(persist && b->b_localdir != NULL)) {
402    xfree(b->b_localdir);
403    b->b_localdir = cs->cs_b_localdir;
404  } else {
405    xfree(cs->cs_b_localdir);
406  }
407
408  if (tp != NULL && !(persist && tp->tp_localdir != NULL)) {
409    xfree(tp->tp_localdir);
410    tp->tp_localdir = cs->cs_tp_localdir;
411  } else {
412    xfree(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.
417  if (cwp != NULL && (did_chdir || cwp->w_localdir != NULL)) {
418    update_cwd(kCdCauseWindow);
419  }
420
421  // Keep-case: the globaldir set during the switch (pre-switch cwd, see `post_chdir`).
422  if (!(persist && cs->cs_globaldir == NULL && globaldir != NULL)) {
423    xfree(globaldir);
424    globaldir = cs->cs_globaldir;
425    cs->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)
434  FUNC_ATTR_NONNULL_ARG(1, 2, 3)
435{
436  if (!(cs->cs_flags & (kCtxKeepCwd | kCtxKeepDirs))) {
437    return;
438  }
439
440  // `globaldir` is where to return when no local dir applies (NULL: the CWD is already there).
441  cs->cs_globaldir = globaldir == NULL ? NULL : xstrdup(globaldir);
442
443  // kCtxKeepDirs: also save copies of the target context's dir scopes.
444  if (cs->cs_flags & kCtxKeepDirs) {
445    buf_T *target_buf = buf != NULL ? buf : wp->w_buffer;
446    cs->cs_dirs_tab = tp->handle;
447    cs->cs_w_localdir = wp->w_localdir == NULL ? NULL : xstrdup(wp->w_localdir);
448    cs->cs_b_localdir = target_buf->b_localdir == NULL ? NULL : xstrdup(target_buf->b_localdir);
449    cs->cs_tp_localdir = tp->tp_localdir == NULL ? NULL : xstrdup(tp->tp_localdir);
450  }
451
452  char cwd[MAXPATHL];
453  if ((cs->cs_flags & kCtxKeepDirs) || curwin != wp) {
454    if (os_dirname(cwd, MAXPATHL) == OK) {
455      cs->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.
461  if (cs->cs_cwd != NULL && p_acd) {
462    do_autochdir();
463    char autocwd[MAXPATHL];
464    if (os_dirname(autocwd, MAXPATHL) == OK) {
465      cs->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{
474  if (cs->cs_ctxwin_idx >= 0) {
475    return;  // Hidden-buffer target: ctx_localdirs_restore() already restored dirs.
476  }
477
478  // kCtxKeepDirs: restore the saved dir scopes.
479  if (cs->cs_flags & kCtxKeepDirs) {
480    tabpage_T *dirs_tab = NULL;
481    FOR_ALL_TABS(tp) {
482      if (tp->handle == cs->cs_dirs_tab) {
483        dirs_tab = tp;
484        break;
485      }
486    }
487    ctx_localdirs_restore(cs, NULL, dirs_tab, false);
488  } else if (cs->cs_cwd != NULL && !_ctx_did_chdir) {
489    // Pairs with the CWD restore below.
490    xfree(globaldir);
491    globaldir = cs->cs_globaldir;
492    cs->cs_globaldir = NULL;
493  }
494  XFREE_CLEAR(cs->cs_globaldir);
495
496  // Restore the CWD itself. After an explicit chdir, ctx_restore() re-derives it instead.
497  if (cs->cs_apply_acd) {
498    do_autochdir();
499  } else if (cs->cs_cwd != NULL && ((cs->cs_flags & kCtxKeepDirs) || !_ctx_did_chdir)) {
500    os_chdir(cs->cs_cwd);
501    // Buffer names are relative to the CWD, so they must follow it back. #41424
502    shorten_fnames(true);
503  }
504  XFREE_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{
515  for (int i = 0; i < CTX_WIN_COUNT; i++) {
516    if (ctx_win[i].cw_used && ctx_win[i].cw_win == win) {
517      return true;
518    }
519  }
520  return 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{
531  bool need_append = true;  // Append `cw_win` to the window list.
532
533  // Allocate a window when needed.
534  int idx;
535  for (idx = 0; idx < CTX_WIN_COUNT; idx++) {
536    if (!ctx_win[idx].cw_used) {
537      break;
538    }
539  }
540  if (idx == CTX_WIN_COUNT) {
541    kv_push(ctx_win_vec, ((CtxWin){
542      .cw_win = NULL,
543      .cw_used = false,
544    }));
545  }
546  if (ctx_win[idx].cw_win == NULL) {
547    win_alloc_ctx_win(idx);
548    need_append = false;
549  }
550  win_T *cw_win = ctx_win[idx].cw_win;
551  ctx_win[idx].cw_used = true;
552  cs->cs_ctxwin_idx = idx;
553
554  cw_win->w_buffer = buf;
555  cw_win->w_s = &buf->b_s;
556  buf->b_nwindows++;
557  win_init_empty(cw_win);  // set cursor and topline to safe values
558
559  ctx_win_dirs_save(cs, cw_win, buf);
560
561  if (need_append) {
562    win_append(lastwin, cw_win, NULL);
563    pmap_put(int)(&window_handles, cw_win->handle, cw_win);
564    win_config_float(cw_win, cw_win->w_config);
565  }
566
567  return 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{
577  win_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.
581  block_autocmds();
582  if (curwin != cwp) {
583    FOR_ALL_TAB_WINDOWS(tp, wp) {
584      if (wp == cwp) {
585        if (tp != curtab) {
586          goto_tabpage_tp(tp, true, true);
587        }
588        win_goto(cwp);
589        goto win_found;
590      }
591    }
592  }
593win_found:
594  curbuf->b_nwindows--;
595  // Remove the window.
596  win_remove(curwin, NULL);
597  pmap_del(int)(&window_handles, curwin->handle, NULL);
598
599  // Mark window as "not used", but don't free, it can be used again.
600  ctx_win[cs->cs_ctxwin_idx].cw_used = false;
601
602  if (!valid_tabpage_win(curtab)) {
603    // no valid window in current tabpage
604    close_tabpage(curtab);
605  }
606
607  unblock_autocmds();
608  return 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{
615  return _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).
640  assert(((wp == NULL) != (buf == NULL)) || (wp == NULL && (flags & kCtxKeepDirs)));
641  assert(buf == NULL || tp == NULL);  // a buffer target never switches tabpage
642  CLEAR_POINTER(cs);
643  cs->cs_flags = flags;
644  cs->cs_mode = buf != NULL ? kCtxSwitchBuf : wp != NULL ? kCtxSwitchWin : kCtxSwitchDirs;
645  cs->cs_ctxwin_idx = -1;
646  cs->cs_did_chdir = _ctx_did_chdir;
647  _ctx_did_chdir = false;
648  if (cs->cs_mode == kCtxSwitchDirs) {
649    wp = 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).
654  if (buf != NULL) {
655    if (buf == curbuf) {  // be quick when buf is curbuf
656      wp = curwin;
657    } else {
658      FOR_ALL_WINDOWS_IN_TAB(wp2, curtab) {
659        if (wp2->w_buffer == buf) {
660          wp = wp2;
661          break;
662        }
663      }
664    }
665  }
666
667  if ((flags & kCtxValidate) && wp != NULL) {
668    cs->cs_target_win = wp->handle;
669    cs->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).
673  if (wp != NULL) {
674    ctx_dirs_save(cs, wp, tp == NULL ? curtab : tp, buf);
675  }
676
677  // Save the current state.
678  cs->cs_curwin = curwin->handle;
679  cs->cs_prevwin = prevwin == NULL ? 0 : prevwin->handle;
680  cs->cs_same_win = wp == curwin;
681  if (bt_prompt(curbuf)) {
682    cs->cs_prompt_insert = curbuf->b_prompt_insert;
683  }
684  if (!cs->cs_same_win) {
685    // Disable Visual selection, because redrawing may fail.
686    cs->cs_visual_active = Visual.active;
687    Visual.active = false;
688  }
689
690  if (flags & kCtxNoEvents) {
691    block_autocmds();
692  }
693  if (tp != NULL) {
694    cs->cs_curtab = curtab;
695    if (flags & kCtxNoDisplay) {
696      unuse_tabpage(curtab);
697      use_tabpage(tp);
698    } else {
699      goto_tabpage_tp(tp, false, false);
700    }
701  }
702
703  if (buf != NULL) {
704    if (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.
707      wp = ctx_win_prep(cs, buf);
708      // Leave the window we entered "from".
709      leaving_window(curwin);
710      // We will soon enter "buf" and may have to copy buffer options.
711      buf_copy_options(buf, BCO_ENTER | BCO_NOHELP);
712      prevwin = curwin;
713    }
714    assert(win_valid(wp));
715  } else if (!win_valid(wp)) {
716    return false;
717  }
718  curwin = wp;
719  curbuf = curwin->w_buffer;
720  cs->cs_new_curwin = curwin->handle;
721  set_bufref(&cs->cs_new_curbuf, curbuf);
722
723  if (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  }
727  if (flags & kCtxValidate) {
728    check_cursor(curwin);
729  }
730  return 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{
736  win_T *save_curwin = win_find_by_handle(cs->cs_curwin);
737  if (save_curwin == NULL) {
738    save_curwin = fallback;  // Hmm, original window disappeared.
739  }
740  if (save_curwin != NULL) {
741    curwin = save_curwin;
742    curbuf = curwin->w_buffer;
743  }
744  prevwin = 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{
761  if (cs->cs_mode == kCtxSwitchNone) {
762    return;  // zero-initialized: ctx_switch() was never called on `cs`.
763  }
764
765  if (cs->cs_mode == kCtxSwitchWin) {
766    // Window target: restore tabpage and curwin.
767    if (cs->cs_curtab != NULL && valid_tabpage(cs->cs_curtab)) {
768      if (cs->cs_flags & kCtxNoDisplay) {
769        win_T *const old_tp_curwin = curtab->tp_curwin;
770
771        unuse_tabpage(curtab);
772        // Don't change the curwin of the tabpage we temporarily visited.
773        curtab->tp_curwin = old_tp_curwin;
774        use_tabpage(cs->cs_curtab);
775      } else {
776        goto_tabpage_tp(cs->cs_curtab, false, false);
777      }
778    }
779
780    ctx_restore_curwin(cs, NULL);
781  } else if (cs->cs_ctxwin_idx >= 0) {
782    win_T *cwp = ctx_win_rest(cs);
783
784    ctx_restore_curwin(cs, firstwin);
785    // May need to restore insert-mode for a prompt buffer.
786    // Pairs with the leaving_window() in ctx_switch().
787    entering_window(curwin);
788    if (bt_prompt(curbuf)) {
789      curbuf->b_prompt_insert = cs->cs_prompt_insert;
790    }
791
792    vars_clear(&cwp->w_vars->dv_hashtab);         // free all w: variables
793    hash_init(&cwp->w_vars->dv_hashtab);          // re-use the hashtab
794
795    ctx_localdirs_restore(cs, cwp, curtab, !(cs->cs_flags & kCtxKeepDirs));
796
797    // Buffer contents may have changed; cursor is checked below, AFTER restoring Visual state.
798    if (curwin->w_topline > curbuf->b_ml.ml_line_count) {
799      curwin->w_topline = curbuf->b_ml.ml_line_count;
800      curwin->w_topfill = 0;
801    }
802  } else if (cs->cs_mode == kCtxSwitchBuf) {
803    // Restore the buffer previously edited by curwin.
804    if (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) {
808      if (curwin->w_s == &curbuf->b_s) {
809        curwin->w_s = &cs->cs_new_curbuf.br_buf->b_s;
810      }
811      curbuf->b_nwindows--;
812      curbuf = cs->cs_new_curbuf.br_buf;
813      curwin->w_buffer = curbuf;
814      curbuf->b_nwindows++;
815    }
816
817    ctx_restore_curwin(cs, NULL);
818  }  // Else: only save CWD state.
819
820  if (!cs->cs_same_win) {
821    Visual.active = cs->cs_visual_active;
822  }
823  if (cs->cs_mode == kCtxSwitchBuf) {
824    check_cursor(curwin);  // just in case lines got deleted
825    if (Visual.active) {
826      check_pos(curbuf, &Visual.start);
827    }
828  }
829
830  // Release what ctx_switch() engaged (any target kind).
831  if (cs->cs_flags & kCtxNoEvents) {
832    unblock_autocmds();
833  }
834  ctx_dirs_restore(cs);  // No-op if ctx_dirs_save() saved nothing.
835  // Re-apply the restored context's effective directory.
836  if (cs->cs_ctxwin_idx < 0 && _ctx_did_chdir) {
837    update_cwd(kCdCauseWindow);
838  }
839  _ctx_did_chdir = _ctx_did_chdir || cs->cs_did_chdir;
840  if (cs->cs_flags & kCtxValidate) {
841    // Update the status line if the cursor moved in the target window.
842    win_T *const wp = win_find_by_handle(cs->cs_target_win);
843    if (wp != NULL && !equalpos(cs->cs_target_old_pos, wp->w_cursor)) {
844      wp->w_redr_status = true;
845    }
846    // In case the code moved the cursor or changed the Visual area, check it is valid.
847    check_cursor(curwin);
848    if (Visual.active) {
849      check_pos(curbuf, &Visual.start);
850    }
851  }
852  if (cs->cs_mode == kCtxSwitchBuf && cs->cs_new_curwin != cs->cs_curwin) {
853    assert(_ctx_switch_depth > 0);
854    _ctx_switch_depth--;
855    _ctx_saved_curwin = _ctx_switch_depth == 0 ? 0 : _ctx_saved_curwin;
856  }
857}