robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
17.8 KiB606 linesraw
1#include <stdbool.h>
2#include <stdint.h>
3#include <stdlib.h>
4
5#include "lua.h"
6#include "nvim/api/keysets_defs.h"
7#include "nvim/api/private/defs.h"
8#include "nvim/api/private/dispatch.h"
9#include "nvim/api/private/helpers.h"
10#include "nvim/api/private/validate.h"
11#include "nvim/api/window.h"
12#include "nvim/autocmd.h"
13#include "nvim/buffer_defs.h"
14#include "nvim/context.h"
15#include "nvim/cursor.h"
16#include "nvim/drawscreen.h"
17#include "nvim/errors.h"
18#include "nvim/eval/window.h"
19#include "nvim/ex_docmd.h"
20#include "nvim/gettext_defs.h"
21#include "nvim/globals.h"
22#include "nvim/lua/executor.h"
23#include "nvim/memory_defs.h"
24#include "nvim/message.h"
25#include "nvim/move.h"
26#include "nvim/plines.h"
27#include "nvim/pos_defs.h"
28#include "nvim/types_defs.h"
29#include "nvim/window.h"
30
31#include "api/window.c.generated.h"  // IWYU pragma: keep
32
33/// Gets the current buffer in a window
34///
35/// @param win   |window-ID|, or 0 for current window
36/// @param[out] err Error details, if any
37/// @return Buffer id
38Buffer nvim_win_get_buf(Window win, Error *err)
39  FUNC_API_SINCE(1)
40{
41  win_T *w = find_window_by_handle(win, err);
42
43  if (!w) {
44    return 0;
45  }
46
47  return w->w_buffer->handle;
48}
49
50/// Sets the current buffer in a window.
51///
52/// Note: As a side-effect, this executes |BufEnter| and |BufLeave| autocommands.
53/// @param win   |window-ID|, or 0 for current window
54/// @param buf   Buffer id
55/// @param[out] err Error details, if any
56void nvim_win_set_buf(Window win, Buffer buf, Error *err)
57  FUNC_API_SINCE(5)
58  FUNC_API_TEXTLOCK
59{
60  win_T *w = find_window_by_handle(win, err);
61  if (!w) {
62    return;
63  }
64  buf_T *b = find_buffer_by_handle(buf, err);
65  if (!b) {
66    return;
67  }
68
69  // 'winfixbuf' on the cmdwin window prevents replacing its buffer; no
70  // separate cmdwin guard needed.
71  win_set_buf(w, b, err);
72}
73
74/// Gets the (1,0)-indexed, buffer-relative cursor position for a given window
75/// (different windows showing the same buffer have independent cursor
76/// positions). |api-indexing|
77///
78/// @see |getcurpos()|
79///
80/// @param win   |window-ID|, or 0 for current window
81/// @param[out] err Error details, if any
82/// @return (row, col) tuple
83ArrayOf(Integer, 2) nvim_win_get_cursor(Window win, Arena *arena, Error *err)
84  FUNC_API_SINCE(1)
85{
86  Array rv = ARRAY_DICT_INIT;
87  win_T *w = find_window_by_handle(win, err);
88
89  if (w) {
90    rv = arena_array(arena, 2);
91    ADD_C(rv, INTEGER_OBJ(w->w_cursor.lnum));
92    ADD_C(rv, INTEGER_OBJ(w->w_cursor.col));
93  }
94
95  return rv;
96}
97
98/// Sets the (1,0)-indexed cursor position (byte offset) in the window. |api-indexing|
99/// This scrolls the window even if it is not the current one.
100///
101/// @param win   |window-ID|, or 0 for current window
102/// @param pos      (row, col) tuple representing the new position
103/// @param[out] err Error details, if any
104void nvim_win_set_cursor(Window win, ArrayOf(Integer, 2) pos, Error *err)
105  FUNC_API_SINCE(1)
106{
107  win_T *w = find_window_by_handle(win, err);
108
109  if (!w) {
110    return;
111  }
112
113  VALIDATE_EXP(!(pos.size != 2 || pos.items[0].type != kObjectTypeInteger
114                 || pos.items[1].type != kObjectTypeInteger), "pos", "[row, col] array", NULL, {
115    return;
116  });
117
118  int64_t row = pos.items[0].data.integer;
119  int64_t col = pos.items[1].data.integer;
120
121  VALIDATE_RANGE(!(row <= 0 || row > w->w_buffer->b_ml.ml_line_count), "cursor line", {
122    return;
123  });
124
125  VALIDATE_RANGE(!(col > MAXCOL || col < 0), "cursor column", {
126    return;
127  });
128
129  w->w_cursor.lnum = (linenr_T)row;
130  w->w_cursor.col = (colnr_T)col;
131  w->w_cursor.coladd = 0;
132  // When column is out of range silently correct it.
133  check_cursor_col(w);
134
135  // Make sure we stick in this column.
136  w->w_set_curswant = true;
137
138  // make sure cursor is in visible range and
139  // cursorcolumn and cursorline are updated even if w != curwin
140  CtxSwitch switchwin;
141  if (ctx_switch(&switchwin, w, NULL, NULL, kCtxNoEvents | kCtxNoDisplay)) {
142    update_topline(curwin);
143    validate_cursor(curwin);
144  }
145  ctx_restore(&switchwin);
146
147  redraw_later(w, UPD_VALID);
148  w->w_redr_status = true;
149}
150
151/// Gets the window height
152///
153/// @param win   |window-ID|, or 0 for current window
154/// @param[out] err Error details, if any
155/// @return Height as a count of rows
156Integer nvim_win_get_height(Window win, Error *err)
157  FUNC_API_SINCE(1)
158{
159  win_T *w = find_window_by_handle(win, err);
160
161  if (!w) {
162    return 0;
163  }
164
165  return w->w_height;
166}
167
168/// Gets the window width
169///
170/// @param win   |window-ID|, or 0 for current window
171/// @param[out] err Error details, if any
172/// @return Width as a count of columns
173Integer nvim_win_get_width(Window win, Error *err)
174  FUNC_API_SINCE(1)
175{
176  win_T *w = find_window_by_handle(win, err);
177
178  if (!w) {
179    return 0;
180  }
181
182  return w->w_width;
183}
184
185/// Gets a window-scoped (w:) variable
186///
187/// @param win   |window-ID|, or 0 for current window
188/// @param name     Variable name
189/// @param[out] err Error details, if any
190/// @return Variable value
191Object nvim_win_get_var(Window win, String name, Arena *arena, Error *err)
192  FUNC_API_SINCE(1)
193{
194  win_T *w = find_window_by_handle(win, err);
195
196  if (!w) {
197    return (Object)OBJECT_INIT;
198  }
199
200  return dict_get_value(w->w_vars, name, arena, err);
201}
202
203/// Sets a window-scoped (w:) variable
204///
205/// @param win   |window-ID|, or 0 for current window
206/// @param name     Variable name
207/// @param value    Variable value
208/// @param[out] err Error details, if any
209void nvim_win_set_var(Window win, String name, Object value, Error *err)
210  FUNC_API_SINCE(1)
211{
212  win_T *w = find_window_by_handle(win, err);
213
214  if (!w) {
215    return;
216  }
217
218  dict_set_var(w->w_vars, name, value, false, false, NULL, err);
219}
220
221/// Removes a window-scoped (w:) variable
222///
223/// @param win   |window-ID|, or 0 for current window
224/// @param name     Variable name
225/// @param[out] err Error details, if any
226void nvim_win_del_var(Window win, String name, Error *err)
227  FUNC_API_SINCE(1)
228{
229  win_T *w = find_window_by_handle(win, err);
230
231  if (!w) {
232    return;
233  }
234
235  dict_set_var(w->w_vars, name, NIL, true, false, NULL, err);
236}
237
238/// Gets the window position in display cells. First position is zero.
239///
240/// @param win   |window-ID|, or 0 for current window
241/// @param[out] err Error details, if any
242/// @return (row, col) tuple with the window position
243ArrayOf(Integer, 2) nvim_win_get_position(Window win, Arena *arena, Error *err)
244  FUNC_API_SINCE(1)
245{
246  Array rv = ARRAY_DICT_INIT;
247  win_T *w = find_window_by_handle(win, err);
248
249  if (w) {
250    rv = arena_array(arena, 2);
251    ADD_C(rv, INTEGER_OBJ(w->w_winrow));
252    ADD_C(rv, INTEGER_OBJ(w->w_wincol));
253  }
254
255  return rv;
256}
257
258/// Gets the window tabpage
259///
260/// @param win   |window-ID|, or 0 for current window
261/// @param[out] err Error details, if any
262/// @return Tabpage that contains the window
263Tabpage nvim_win_get_tabpage(Window win, Error *err)
264  FUNC_API_SINCE(1)
265{
266  Tabpage rv = 0;
267  win_T *w = find_window_by_handle(win, err);
268
269  if (w) {
270    rv = win_find_tabpage(w)->handle;
271  }
272
273  return rv;
274}
275
276/// Gets the window number
277///
278/// @param win   |window-ID|, or 0 for current window
279/// @param[out] err Error details, if any
280/// @return Window number
281Integer nvim_win_get_number(Window win, Error *err)
282  FUNC_API_SINCE(1)
283{
284  int rv = 0;
285  win_T *w = find_window_by_handle(win, err);
286
287  if (!w) {
288    return rv;
289  }
290
291  int tabnr;
292  win_get_tabwin(w->handle, &tabnr, &rv);
293
294  return rv;
295}
296
297/// Checks if a window is valid
298///
299/// @param win |window-ID|, or 0 for current window
300/// @return true if the window is valid, false otherwise
301Boolean nvim_win_is_valid(Window win)
302  FUNC_API_SINCE(1)
303{
304  Error stub = ERROR_INIT;
305  Boolean ret = find_window_by_handle(win, &stub) != NULL;
306  api_clear_error(&stub);
307  return ret;
308}
309
310/// Closes the window and hides the buffer it contains (like |:hide| with a |window-ID|; unrelated
311/// to the `hide` flag of |nvim_open_win()|, |nvim_win_get_config()|).
312///
313/// Compare |:close| and |nvim_win_close()|, which close the buffer instead of hiding it.
314///
315/// @param win   |window-ID|, or 0 for current window
316/// @param[out] err Error details, if any
317void nvim_win_hide(Window win, Error *err)
318  FUNC_API_SINCE(7)
319  FUNC_API_TEXTLOCK
320{
321  win_T *w = find_window_by_handle(win, err);
322  if (!w) {
323    return;
324  }
325
326  tabpage_T *tabpage = win_find_tabpage(w);
327  TRY_WRAP(err, {
328    // Never close the autocommand window.
329    if (is_ctx_win(w)) {
330      emsg(_(e_autocmd_close));
331    } else if (tabpage == curtab) {
332      win_close(w, false, false);
333    } else {
334      win_close_othertab(w, false, tabpage, false);
335    }
336  });
337}
338
339/// Closes the window (like |:close| with a |window-ID|).
340///
341/// @param win   |window-ID|, or 0 for current window
342/// @param force    Behave like `:close!` The last window of a buffer with
343///                 unwritten changes can be closed. The buffer will become
344///                 hidden, even if 'hidden' is not set.
345/// @param[out] err Error details, if any
346void nvim_win_close(Window win, Boolean force, Error *err)
347  FUNC_API_SINCE(6)
348  FUNC_API_TEXTLOCK
349{
350  win_T *w = find_window_by_handle(win, err);
351  if (!w) {
352    return;
353  }
354
355  tabpage_T *tabpage = win_find_tabpage(w);
356  TRY_WRAP(err, {
357    ex_win_close(force, w, tabpage == curtab ? NULL : tabpage);
358  });
359}
360
361/// Calls function `fn` in the context of window `win` and returns its result (may be multiple
362/// values).
363///
364/// @see |win_execute()|
365/// @see |nvim_buf_call()|
366///
367/// @param win  |window-ID|, or 0 for current window.
368/// @param fn   Lua function to call inside the window.
369/// @param err  Error details, if any.
370/// @return     Value(s) returned by `fn()`.
371Object nvim_win_call(Window win, LuaRef fn, lua_State *lstate, Error *err)
372  FUNC_API_SINCE(7)
373  FUNC_API_LUA_ONLY
374{
375  win_T *w = find_window_by_handle(win, err);
376  if (!w) {
377    return NIL;
378  }
379  tabpage_T *tabpage = win_find_tabpage(w);
380
381  TRY_WRAP(err, {
382    CtxSwitch cs = { 0 };
383    if (ctx_switch(&cs, w, tabpage, NULL, kCtxNoDisplay | kCtxKeepCwd | kCtxValidate)) {
384      Array args = ARRAY_DICT_INIT;
385      nlua_call_ref(fn, NULL, args, kRetMultiStack, NULL, err);
386    }
387    ctx_restore(&cs);
388  });
389  return NIL;  // kRetMultiStack: values are already on the lua stack
390}
391
392/// Set highlight namespace for a window. This will use highlights defined with
393/// |nvim_set_hl()| for this namespace, but fall back to global highlights (ns=0) when
394/// missing.
395///
396/// This takes precedence over the 'winhighlight' option.
397///
398/// @param win
399/// @param ns_id the namespace to use
400/// @param[out] err Error details, if any
401void nvim_win_set_hl_ns(Window win, Integer ns_id, Error *err)
402  FUNC_API_SINCE(10)
403{
404  win_T *w = find_window_by_handle(win, err);
405  if (!w) {
406    return;
407  }
408
409  // -1 is allowed as inherit global namespace
410  VALIDATE_S((ns_id >= -1), "namespace", "", {
411    return;
412  });
413
414  w->w_ns_hl = (NS)ns_id;
415  w->w_hl_needs_update = true;
416  redraw_later(w, UPD_NOT_VALID);
417}
418
419/// Computes the number of screen lines occupied by a range of text in a given window.
420/// Works for off-screen text and takes folds into account.
421///
422/// Diff filler or virtual lines above a line are counted as a part of that line,
423/// unless the line is on "start_row" and "start_vcol" is specified.
424///
425/// Diff filler or virtual lines below the last buffer line are counted in the result
426/// when "end_row" is omitted.
427///
428/// Line indexing is similar to |nvim_buf_get_text()|.
429///
430/// @param win  |window-ID|, or 0 for current window.
431/// @param opts    Optional parameters:
432///                - end_row: Ending line index, 0-based inclusive.
433///                           When omitted end at the very bottom.
434///                - end_vcol: Ending virtual column index on "end_row",
435///                            0-based exclusive, rounded up to full screen lines.
436///                            When 0 only include diff filler and virtual lines above
437///                            "end_row". When omitted include the whole line.
438///                - max_height: Don't add the height of lines below the row
439///                              for which this height is reached. Useful to e.g. limit the
440///                              height to the window height, avoiding unnecessary work. Or
441///                              to find out how many buffer lines beyond "start_row" take
442///                              up a certain number of logical lines (returned in
443///                              "end_row" and "end_vcol").
444///                - start_row: Starting line index, 0-based inclusive.
445///                             When omitted start at the very top.
446///                - start_vcol: Starting virtual column index on "start_row",
447///                              0-based inclusive, rounded down to full screen lines.
448///                              When omitted include the whole line.
449/// @return  Dict containing text height information, with these keys:
450///          - all: The total number of screen lines occupied by the range.
451///          - fill: The number of diff filler or virtual lines among them.
452///          - end_row: The row on which the returned height is reached (first row of
453///            a closed fold).
454///          - end_vcol: Ending virtual column in "end_row" where "max_height" or the returned
455///            height is reached. 0 if "end_row" is a closed fold.
456///
457/// @see |virtcol()| for text width.
458DictAs(win_text_height_ret) nvim_win_text_height(Window win, Dict(win_text_height) *opts,
459                                                 Arena *arena, Error *err)
460  FUNC_API_SINCE(12)
461{
462  Dict rv = arena_dict(arena, 2);
463
464  win_T *const w = find_window_by_handle(win, err);
465  if (!w) {
466    return rv;
467  }
468  buf_T *const buf = w->w_buffer;
469  const linenr_T line_count = buf->b_ml.ml_line_count;
470
471  linenr_T start_lnum = 1;
472  linenr_T end_lnum = line_count;
473  int64_t start_vcol = -1;
474  int64_t end_vcol = -1;
475
476  bool oob = false;
477
478  if (HAS_KEY(opts, win_text_height, start_row)) {
479    start_lnum = (linenr_T)normalize_index(buf, opts->start_row, false, &oob);
480  }
481
482  if (HAS_KEY(opts, win_text_height, end_row)) {
483    end_lnum = (linenr_T)normalize_index(buf, opts->end_row, false, &oob);
484  }
485
486  VALIDATE(!oob, "%s", "Line index out of bounds", {
487    return rv;
488  });
489  VALIDATE((start_lnum <= end_lnum), "%s", "'start_row' is higher than 'end_row'", {
490    return rv;
491  });
492
493  if (HAS_KEY(opts, win_text_height, start_vcol)) {
494    VALIDATE(HAS_KEY(opts, win_text_height, start_row),
495             "%s", "'start_vcol' specified without 'start_row'", {
496      return rv;
497    });
498    start_vcol = opts->start_vcol;
499    VALIDATE_RANGE((start_vcol >= 0 && start_vcol <= MAXCOL), "start_vcol", {
500      return rv;
501    });
502  }
503
504  if (HAS_KEY(opts, win_text_height, end_vcol)) {
505    VALIDATE(HAS_KEY(opts, win_text_height, end_row),
506             "%s", "'end_vcol' specified without 'end_row'", {
507      return rv;
508    });
509    end_vcol = opts->end_vcol;
510    VALIDATE_RANGE((end_vcol >= 0 && end_vcol <= MAXCOL), "end_vcol", {
511      return rv;
512    });
513  }
514
515  int64_t max = INT64_MAX;
516  if (HAS_KEY(opts, win_text_height, max_height)) {
517    VALIDATE_RANGE(opts->max_height > 0, "max_height", {
518      return rv;
519    });
520    max = opts->max_height;
521  }
522
523  if (start_lnum == end_lnum && start_vcol >= 0 && end_vcol >= 0) {
524    VALIDATE((start_vcol <= end_vcol), "%s", "'start_vcol' is higher than 'end_vcol'", {
525      return rv;
526    });
527  }
528
529  int64_t fill = 0;
530  int64_t all = win_text_height(w, start_lnum, start_vcol, &end_lnum, &end_vcol, &fill, max);
531  if (!HAS_KEY(opts, win_text_height, end_row)) {
532    const int64_t end_fill = win_get_fill(w, line_count + 1);
533    fill += end_fill;
534    all += end_fill;
535  }
536  PUT_C(rv, "all", INTEGER_OBJ(all));
537  PUT_C(rv, "fill", INTEGER_OBJ(fill));
538  PUT_C(rv, "end_row", INTEGER_OBJ(end_lnum - 1));
539  PUT_C(rv, "end_vcol", INTEGER_OBJ(end_vcol));
540  return rv;
541}
542
543/// Resizes a window, anchored to a given edge.
544///
545/// The window first takes space from the non-anchored side, and only then from the anchored side.
546/// The "anchor" decides the fixed edge, so a window can grow or shrink in any direction.
547///
548/// Can set height, width (only for a vertical split), or both. The "anchor" applies to the matching
549/// axis (top/bottom for height, left/right for width); the other axis uses its default anchor.
550///
551/// @param win        |window-ID|, or 0 for current window
552/// @param width      New width (columns), or -1 for "no change".
553/// @param height     New height (rows), or -1 for "no change".
554/// @param opts       Optional parameters.
555///                     - anchor: Edge that stays fixed while the opposite edge moves; the
556///                       neighbor on the moving side is resized first. One of:
557///                       - "top" (default) or "bottom"
558///                       - "left" (default) or "right"
559/// @param[out] err Error details, if any
560void nvim_win_resize(Window win, Integer width, Integer height, Dict(win_resize) *opts, Error *err)
561  FUNC_API_SINCE(15)
562{
563  win_T *w = find_window_by_handle(win, err);
564
565  if (!w) {
566    return;
567  }
568
569  VALIDATE_EXP((height >= 0 || height == -1), "height", "non-negative number or -1", NULL, {
570    return;
571  });
572  VALIDATE_EXP((width >= 0 || width == -1), "width", "non-negative number or -1", NULL, {
573    return;
574  });
575
576  VALIDATE_R((height >= 0 || width >= 0), "'height' or 'width'", {
577    return;
578  });
579
580  // default anchors
581  bool from_top = true;
582  bool from_left = true;
583
584  if (HAS_KEY(opts, win_resize, anchor)) {
585    char *anchor = opts->anchor.data;
586    bool is_height = strequal("top", anchor) || strequal("bottom", anchor);
587    bool is_width = strequal("left", anchor) || strequal("right", anchor);
588
589    VALIDATE_EXP(is_height || is_width, "anchor", "\"top\", \"bottom\", \"left\" or \"right\"",
590                 anchor, { return; });
591    // anchor must match a dimension that is actually being resized.
592    VALIDATE_CON(!(is_height && height == -1) && !(is_width && width == -1), anchor,
593                 is_width ? "width" : "height", {
594      return;
595    });
596
597    from_top = !strequal("bottom", anchor);
598    from_left = !strequal("right", anchor);
599  }
600  if (height >= 0) {
601    TRY_WRAP(err, win_setheight_win((int)height, w, from_top));
602  }
603  if (!ERROR_SET(err) && width >= 0) {
604    TRY_WRAP(err, win_setwidth_win((int)width, w, from_left));
605  }
606}