robin/laufey

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

Justin M. Keyesvim-patch: num -> bool patches #413750a414a7fbb

master
29.0 KiB1015 linesraw
1// eval/buffer.c: Buffer related builtin functions
2
3#include <stdbool.h>
4#include <string.h>
5
6#include "klib/kvec.h"
7#include "nvim/ascii_defs.h"
8#include "nvim/autocmd.h"
9#include "nvim/autocmd_defs.h"
10#include "nvim/buffer.h"
11#include "nvim/buffer_defs.h"
12#include "nvim/change.h"
13#include "nvim/context.h"
14#include "nvim/cursor.h"
15#include "nvim/drawscreen.h"
16#include "nvim/eval.h"
17#include "nvim/eval/buffer.h"
18#include "nvim/eval/funcs.h"
19#include "nvim/eval/typval.h"
20#include "nvim/eval/typval_defs.h"
21#include "nvim/eval/window.h"
22#include "nvim/ex_cmds.h"
23#include "nvim/extmark.h"
24#include "nvim/globals.h"
25#include "nvim/insert.h"
26#include "nvim/macros_defs.h"
27#include "nvim/mark.h"
28#include "nvim/memline.h"
29#include "nvim/memory.h"
30#include "nvim/move.h"
31#include "nvim/path.h"
32#include "nvim/pos_defs.h"
33#include "nvim/sign.h"
34#include "nvim/strings.h"
35#include "nvim/types_defs.h"
36#include "nvim/undo.h"
37#include "nvim/vim_defs.h"
38
39typedef struct {
40  win_T *cob_curwin_save;
41  CtxSwitch cob_aco;
42  int cob_using_aco;
43  int cob_save_VIsual_active;
44} cob_T;
45
46#include "eval/buffer.c.generated.h"
47
48/// Find a buffer by number or exact name.
49buf_T *find_buffer(typval_T *avar)
50{
51  buf_T *buf = NULL;
52
53  if (avar->v_type == VAR_NUMBER) {
54    buf = buflist_findnr((int)avar->vval.v_number);
55  } else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL) {
56    buf = buflist_findname_exp(avar->vval.v_string);
57    if (buf == NULL) {
58      // No full path name match, try a match with a URL or a "nofile"
59      // buffer, these don't use the full path.
60      FOR_ALL_BUFFERS(bp) {
61        if (bp->b_fname != NULL
62            && (path_with_url(bp->b_fname) || bt_nofilename(bp))
63            && strcmp(bp->b_fname, avar->vval.v_string) == 0) {
64          buf = bp;
65          break;
66        }
67      }
68    }
69  }
70  return buf;
71}
72
73/// If there is a window for "curbuf", make it the current window.
74static void find_win_for_curbuf(void)
75{
76  // The b_wininfo list should have the windows that recently contained the
77  // buffer, going over this is faster than going over all the windows.
78  // Do check the buffer is still there.
79  for (size_t i = 0; i < kv_size(curbuf->b_wininfo); i++) {
80    WinInfo *wip = kv_A(curbuf->b_wininfo, i);
81    if (wip->wi_win != NULL && wip->wi_win->w_buffer == curbuf) {
82      curwin = wip->wi_win;
83      break;
84    }
85  }
86}
87
88/// Used before making a change in "buf", which is not the current one: Make
89/// "buf" the current buffer and find a window for this buffer, so that side
90/// effects are done correctly (e.g., adjusting marks).
91///
92/// Information is saved in "cob" and MUST be restored by calling
93/// change_other_buffer_restore().
94static void change_other_buffer_prepare(cob_T *cob, buf_T *buf)
95{
96  CLEAR_POINTER(cob);
97
98  // Set "curbuf" to the buffer being changed.  Then make sure there is a
99  // window for it to handle any side effects.
100  cob->cob_save_VIsual_active = Visual.active;
101  Visual.active = false;
102  cob->cob_curwin_save = curwin;
103  curbuf = buf;
104  find_win_for_curbuf();  // simplest: find existing window for "buf"
105
106  if (curwin->w_buffer != buf) {
107    // No existing window for this buffer.  It is dangerous to have
108    // curwin->w_buffer differ from "curbuf", use the autocmd window.
109    curbuf = curwin->w_buffer;
110    ctx_switch(&cob->cob_aco, NULL, NULL, buf, 0);
111    cob->cob_using_aco = true;
112  }
113}
114
115static void change_other_buffer_restore(cob_T *cob)
116{
117  if (cob->cob_using_aco) {
118    ctx_restore(&cob->cob_aco);
119  } else {
120    curwin = cob->cob_curwin_save;
121    curbuf = curwin->w_buffer;
122  }
123  Visual.active = cob->cob_save_VIsual_active;
124}
125
126/// Set line or list of lines in buffer "buf" to "lines".
127/// Any type is allowed and converted to a string.
128static void set_buffer_lines(buf_T *buf, linenr_T lnum_arg, bool append, typval_T *lines,
129                             typval_T *rettv)
130  FUNC_ATTR_NONNULL_ARG(4, 5)
131{
132  linenr_T lnum = lnum_arg + (append ? 1 : 0);
133  int added = 0;
134
135  // When using the current buffer ml_mfp will be set if needed.  Useful when
136  // setline() is used on startup.  For other buffers the buffer must be
137  // loaded.
138  const bool is_curbuf = buf == curbuf;
139  if (buf == NULL || (!is_curbuf && buf->b_ml.ml_mfp == NULL) || lnum < 1) {
140    rettv->vval.v_number = 1;  // FAIL
141    return;
142  }
143
144  // After this don't use "return", goto "cleanup"!
145  cob_T cob;
146  if (!is_curbuf) {
147    // set "curbuf" to "buf" and find a window for this buffer
148    change_other_buffer_prepare(&cob, buf);
149  }
150
151  linenr_T append_lnum;
152  if (append) {
153    // appendbufline() uses the line number below which we insert
154    append_lnum = lnum - 1;
155  } else {
156    // setbufline() uses the line number above which we insert, we only
157    // append if it's below the last line
158    append_lnum = curbuf->b_ml.ml_line_count;
159  }
160
161  list_T *l = NULL;
162  listitem_T *li = NULL;
163  char *line = NULL;
164  if (lines->v_type == VAR_LIST) {
165    l = lines->vval.v_list;
166    if (l == NULL || tv_list_len(l) == 0) {
167      // not appending anything always succeeds
168      goto cleanup;
169    }
170    li = tv_list_first(l);
171  } else {
172    line = typval_tostring(lines, false);
173  }
174
175  // Default result is zero == OK.
176  while (true) {
177    if (lines->v_type == VAR_LIST) {
178      // List argument, get next string.
179      if (li == NULL) {
180        break;
181      }
182      xfree(line);
183      line = typval_tostring(TV_LIST_ITEM_TV(li), false);
184      li = TV_LIST_ITEM_NEXT(l, li);
185    }
186
187    rettv->vval.v_number = 1;  // FAIL
188    if (line == NULL || lnum > curbuf->b_ml.ml_line_count + 1) {
189      break;
190    }
191
192    // When coming here from Insert mode, sync undo, so that this can be
193    // undone separately from what was previously inserted.
194    if (u_sync_once == 2) {
195      u_sync_once = 1;  // notify that u_sync() was called
196      u_sync(true);
197    }
198
199    if (!append && lnum <= curbuf->b_ml.ml_line_count) {
200      // Existing line, replace it.
201      int old_len = (int)strlen(ml_get(lnum));
202      if (u_savesub(lnum) == OK
203          && ml_replace(lnum, line, true) == OK) {
204        inserted_bytes(lnum, 0, old_len, (int)strlen(line));
205        if (is_curbuf && lnum == curwin->w_cursor.lnum) {
206          check_cursor_col(curwin);
207        }
208        rettv->vval.v_number = 0;  // OK
209      }
210    } else if (added > 0 || u_save(lnum - 1, lnum) == OK) {
211      // append the line.
212      added++;
213      if (ml_append(lnum - 1, line, 0, false) == OK) {
214        rettv->vval.v_number = 0;  // OK
215      }
216    }
217
218    if (l == NULL) {  // only one string argument
219      break;
220    }
221    lnum++;
222  }
223  xfree(line);
224
225  if (added > 0) {
226    appended_lines_mark(append_lnum, added);
227
228    // Only adjust the cursor for buffers other than the current, unless it
229    // is the current window. For curbuf and other windows it has been done
230    // in mark_adjust_internal().
231    FOR_ALL_TAB_WINDOWS(tp, wp) {
232      if (wp->w_buffer == buf
233          && (wp->w_buffer != curbuf || wp == curwin)
234          && wp->w_cursor.lnum > append_lnum) {
235        wp->w_cursor.lnum += (linenr_T)added;
236      }
237    }
238    check_cursor_col(curwin);
239    update_topline(curwin);
240  }
241
242cleanup:
243  if (!is_curbuf) {
244    change_other_buffer_restore(&cob);
245  }
246}
247
248/// "append(lnum, string/list)" function
249void f_append(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
250{
251  const int did_emsg_before = did_emsg;
252  const linenr_T lnum = tv_get_lnum(&argvars[0]);
253  if (did_emsg == did_emsg_before) {
254    set_buffer_lines(curbuf, lnum, true, &argvars[1], rettv);
255  }
256}
257
258/// Set or append lines to a buffer.
259static void buf_set_append_line(typval_T *argvars, typval_T *rettv, bool append)
260{
261  const int did_emsg_before = did_emsg;
262  buf_T *const buf = tv_get_buf(&argvars[0], false);
263  if (buf == NULL) {
264    rettv->vval.v_number = 1;  // FAIL
265  } else {
266    const linenr_T lnum = tv_get_lnum_buf(&argvars[1], buf);
267    if (did_emsg == did_emsg_before) {
268      set_buffer_lines(buf, lnum, append, &argvars[2], rettv);
269    }
270  }
271}
272
273/// "appendbufline(buf, lnum, string/list)" function
274void f_appendbufline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
275{
276  buf_set_append_line(argvars, rettv, true);
277}
278
279/// Trim lines above the prompt to enforce 'scrollback' limit
280static void prompt_trim_scrollback(buf_T *buf)
281  FUNC_ATTR_NONNULL_ALL
282{
283  if (buf->b_p_scbk <= 0) {
284    return;
285  }
286
287  linenr_T prompt_line = buf->b_prompt_start.mark.lnum;
288  linenr_T above_prompt = prompt_line - 1;
289  if (above_prompt <= (linenr_T)buf->b_p_scbk) {
290    return;
291  }
292
293  linenr_T to_delete = above_prompt - (linenr_T)buf->b_p_scbk;
294  for (linenr_T i = 0; i < to_delete; i++) {
295    ml_delete_buf(buf, 1, false);
296  }
297  mark_adjust_buf(buf, 1, to_delete, MAXLNUM, -to_delete, true,
298                  kMarkAdjustNormal, kExtmarkUndo);
299  deleted_lines_buf(buf, 1, to_delete);
300
301  FOR_ALL_TAB_WINDOWS(tp, wp) {
302    if (wp->w_buffer == buf) {
303      wp->w_cursor.lnum = wp->w_cursor.lnum <= to_delete
304                          ? 1
305                          : wp->w_cursor.lnum - to_delete;
306      if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) {
307        wp->w_cursor.lnum = wp->w_buffer->b_ml.ml_line_count;
308      }
309    }
310  }
311  check_cursor_col(curwin);
312}
313
314/// Invokes the user-defined callback defined for the current prompt-buffer.
315void prompt_invoke_callback(void)
316{
317  typval_T rettv;
318  typval_T argv[2];
319  linenr_T lnum = curbuf->b_ml.ml_line_count;
320
321  char *user_input = prompt_get_input(curbuf);
322
323  if (!user_input) {
324    return;
325  }
326
327  // Add a new line for the prompt before invoking the callback, so that
328  // text can always be inserted above the last line.
329  ml_append(lnum, "", 0, false);
330  appended_lines_mark(lnum, 1);
331  curwin->w_cursor.lnum = lnum + 1;
332  curwin->w_cursor.col = 0;
333  curbuf->b_prompt_start.mark.lnum = lnum + 1;
334
335  if (curbuf->b_prompt_callback.type == kCallbackNone) {
336    xfree(user_input);
337    goto theend;
338  }
339
340  argv[0].v_type = VAR_STRING;
341  argv[0].vval.v_string = user_input;
342  argv[1].v_type = VAR_UNKNOWN;
343
344  callback_call(&curbuf->b_prompt_callback, 1, argv, &rettv);
345  tv_clear(&argv[0]);
346  tv_clear(&rettv);
347
348theend:
349  // clear undo history on submit
350  u_clearallandblockfree(curbuf);
351
352  curbuf->b_prompt_start.mark.lnum = curbuf->b_ml.ml_line_count;
353  curbuf->b_prompt_append_new_line = true;
354
355  prompt_trim_scrollback(curbuf);
356}
357
358/// @return  true when the interrupt callback was invoked.
359bool invoke_prompt_interrupt(void)
360{
361  typval_T rettv;
362  typval_T argv[1];
363
364  if (curbuf->b_prompt_interrupt.type == kCallbackNone) {
365    return false;
366  }
367  argv[0].v_type = VAR_UNKNOWN;
368
369  got_int = false;  // don't skip executing commands
370  int ret = callback_call(&curbuf->b_prompt_interrupt, 0, argv, &rettv);
371  tv_clear(&rettv);
372  return ret != FAIL;
373}
374
375/// "prompt_appendbuf({buffer}, string/list)" function
376void f_prompt_appendbuf(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
377  FUNC_ATTR_NONNULL_ALL
378{
379  const int did_emsg_before = did_emsg;
380
381  // Return an 1 by default, e.g. append failed or not a prompt buffer
382  rettv->v_type = VAR_NUMBER;
383  rettv->vval.v_number = 1;
384
385  buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
386  if (buf == NULL || !bt_prompt(buf)) {
387    return;
388  }
389
390  linenr_T lnum = MAX(0, buf->b_prompt_start.mark.lnum - 1);
391  typval_T *lines = &argvars[1];
392  bool did_concat = false;
393
394  if (!buf->b_prompt_append_new_line) {
395    // Since we are not creating a new line we need to append input to current line
396    const char *text = (lnum > 0) ? (const char *)ml_get_buf(buf, lnum) : "";
397    if (lines->v_type == VAR_LIST) {
398      list_T *l = lines->vval.v_list;
399      if (l != NULL && tv_list_len(l) > 0) {
400        listitem_T *li = tv_list_first(l);
401        const char *str = tv_get_string(&li->li_tv);
402        char *new_str = concat_str(text, str);
403        tv_clear(&li->li_tv);
404        li->li_tv.v_type = VAR_STRING;
405        li->li_tv.vval.v_string = new_str;
406        did_concat = true;
407      }
408    } else if (lines->v_type == VAR_STRING) {
409      const char *str = tv_get_string(lines);
410      char *new_str = concat_str(text, str);
411      tv_clear(lines);
412      lines->v_type = VAR_STRING;
413      lines->vval.v_string = new_str;
414    }
415  }
416
417  if (did_emsg == did_emsg_before) {
418    if (did_concat && tv_list_len(lines->vval.v_list) > 1) {
419      // Multi-element list with concat: first element (already concatenated)
420      // replaces the line at lnum, remaining elements are inserted after.
421      list_T *l = lines->vval.v_list;
422      listitem_T *li = tv_list_first(l);
423      set_buffer_lines(buf, lnum, false, &li->li_tv, rettv);
424
425      if (rettv->vval.v_number == 0) {
426        tv_list_item_remove(l, li);
427        set_buffer_lines(buf, lnum, true, lines, rettv);
428      }
429    } else {
430      set_buffer_lines(buf, lnum, buf->b_prompt_append_new_line, lines, rettv);
431    }
432  }
433
434  if (rettv->vval.v_number == 0) {
435    // Ok we've inserted the lines successfully now check if last string ended with '\n'
436    // to determine if we need to insert a new line before next append
437    buf->b_prompt_append_new_line = false;
438    if (lines->v_type == VAR_LIST) {
439      list_T *l = lines->vval.v_list;
440      if (l != NULL && tv_list_len(l) > 0) {
441        listitem_T *li = tv_list_last(l);
442        const char *str = tv_get_string(&li->li_tv);
443        size_t len = strlen(str);
444        if (len > 0 && str[len - 1] == '\n') {
445          buf->b_prompt_append_new_line = true;
446        }
447      }
448    } else if (lines->v_type == VAR_STRING) {
449      const char *str = tv_get_string(lines);
450      size_t len = strlen(str);
451
452      if (len > 0 && str[len - 1] == '\n') {
453        buf->b_prompt_append_new_line = true;
454      }
455    }
456
457    prompt_trim_scrollback(buf);
458  }
459}
460
461/// "bufadd(expr)" function
462void f_bufadd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
463{
464  char *name = (char *)tv_get_string(&argvars[0]);
465
466  rettv->vval.v_number = buflist_add(*name == NUL ? NULL : name, 0);
467}
468
469/// "bufexists(expr)" function
470void f_bufexists(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
471{
472  rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
473}
474
475/// "buflisted(expr)" function
476void f_buflisted(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
477{
478  buf_T *buf;
479
480  buf = find_buffer(&argvars[0]);
481  rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
482}
483
484/// "bufload(expr)" function
485void f_bufload(typval_T *argvars, typval_T *unused, EvalFuncData fptr)
486{
487  buf_T *buf = get_buf_arg(&argvars[0]);
488
489  if (buf != NULL) {
490    if (swap_exists_action != SEA_READONLY) {
491      swap_exists_action = SEA_NONE;
492    }
493    buf_ensure_loaded(buf);
494  }
495}
496
497/// "bufloaded(expr)" function
498void f_bufloaded(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
499{
500  buf_T *buf;
501
502  buf = find_buffer(&argvars[0]);
503  rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
504}
505
506/// "bufname(expr)" function
507void f_bufname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
508{
509  const buf_T *buf;
510  typval_T *const tv = &argvars[0];
511  rettv->v_type = VAR_STRING;
512  rettv->vval.v_string = NULL;
513  if (tv->v_type == VAR_UNKNOWN) {
514    buf = curbuf;
515  } else {
516    buf = tv_get_buf_from_arg(tv);
517  }
518  if (buf != NULL && buf->b_fname != NULL) {
519    rettv->vval.v_string = xstrdup(buf->b_fname);
520  }
521}
522
523/// "bufnr(expr)" function
524void f_bufnr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
525{
526  const buf_T *buf;
527  bool error = false;
528
529  rettv->vval.v_number = -1;
530
531  if (argvars[0].v_type == VAR_UNKNOWN) {
532    buf = curbuf;
533  } else {
534    // Don't use tv_get_buf_from_arg(); we continue if the buffer wasn't found
535    // and the second argument isn't zero, but we want to return early if the
536    // first argument isn't a string or number so only one error is shown.
537    if (!tv_check_str_or_nr(&argvars[0])) {
538      return;
539    }
540    emsg_off++;
541    buf = tv_get_buf(&argvars[0], false);
542    emsg_off--;
543  }
544
545  // If the buffer isn't found and the second argument is not zero create a
546  // new buffer.
547  const char *name;
548  if (buf == NULL
549      && argvars[1].v_type != VAR_UNKNOWN
550      && tv_get_bool_chk(&argvars[1], &error) != 0
551      && !error
552      && (name = tv_get_string_chk(&argvars[0])) != NULL) {
553    buf = buflist_new((char *)name, NULL, 1, 0);
554  }
555
556  if (buf != NULL) {
557    rettv->vval.v_number = buf->b_fnum;
558  }
559}
560
561static void buf_win_common(typval_T *argvars, typval_T *rettv, bool get_nr)
562{
563  const buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
564  if (buf == NULL) {  // no need to search if invalid arg or buffer not found
565    rettv->vval.v_number = -1;
566    return;
567  }
568
569  int winnr = 0;
570  int winid;
571  bool found_buf = false;
572  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
573    winnr += win_has_winnr(wp, curtab);
574    if (wp->w_buffer == buf && (!get_nr || win_has_winnr(wp, curtab))) {
575      found_buf = true;
576      winid = wp->handle;
577      break;
578    }
579  }
580  rettv->vval.v_number = (found_buf ? (get_nr ? winnr : winid) : -1);
581}
582
583/// "bufwinid(nr)" function
584void f_bufwinid(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
585{
586  buf_win_common(argvars, rettv, false);
587}
588
589/// "bufwinnr(nr)" function
590void f_bufwinnr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
591{
592  buf_win_common(argvars, rettv, true);
593}
594
595/// "deletebufline()" function
596void f_deletebufline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
597{
598  const int did_emsg_before = did_emsg;
599  rettv->vval.v_number = 1;   // FAIL by default
600  buf_T *const buf = tv_get_buf(&argvars[0], false);
601  if (buf == NULL) {
602    return;
603  }
604
605  linenr_T last;
606  const linenr_T first = tv_get_lnum_buf(&argvars[1], buf);
607  if (did_emsg > did_emsg_before) {
608    return;
609  }
610  if (argvars[2].v_type != VAR_UNKNOWN) {
611    last = tv_get_lnum_buf(&argvars[2], buf);
612  } else {
613    last = first;
614  }
615
616  if (buf->b_ml.ml_mfp == NULL || first < 1
617      || first > buf->b_ml.ml_line_count || last < first) {
618    return;
619  }
620
621  // After this don't use "return", goto "cleanup"!
622  const bool is_curbuf = buf == curbuf;
623  cob_T cob;
624  if (!is_curbuf) {
625    // set "curbuf" to "buf" and find a window for this buffer
626    change_other_buffer_prepare(&cob, buf);
627  }
628
629  if (last > curbuf->b_ml.ml_line_count) {
630    last = curbuf->b_ml.ml_line_count;
631  }
632  const int count = last - first + 1;
633
634  // When coming here from Insert mode, sync undo, so that this can be
635  // undone separately from what was previously inserted.
636  if (u_sync_once == 2) {
637    u_sync_once = 1;  // notify that u_sync() was called
638    u_sync(true);
639  }
640
641  if (u_save(first - 1, last + 1) == FAIL) {
642    goto cleanup;
643  }
644
645  for (linenr_T lnum = first; lnum <= last; lnum++) {
646    ml_delete_flags(first, ML_DEL_MESSAGE);
647  }
648
649  FOR_ALL_TAB_WINDOWS(tp, wp) {
650    if (wp->w_buffer == buf) {
651      if (wp->w_cursor.lnum > last) {
652        wp->w_cursor.lnum -= (linenr_T)count;
653      } else if (wp->w_cursor.lnum > first) {
654        wp->w_cursor.lnum = first;
655      }
656      if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) {
657        wp->w_cursor.lnum = wp->w_buffer->b_ml.ml_line_count;
658      }
659    }
660  }
661  check_cursor_col(curwin);
662  deleted_lines_mark(first, count);
663  rettv->vval.v_number = 0;  // OK
664
665cleanup:
666  if (!is_curbuf) {
667    change_other_buffer_restore(&cob);
668  }
669}
670
671/// @return  buffer options, variables and other attributes in a dictionary.
672static dict_T *get_buffer_info(buf_T *buf)
673{
674  dict_T *const dict = tv_dict_alloc();
675
676  tv_dict_add_nr(dict, S_LEN("bufnr"), buf->b_fnum);
677  tv_dict_add_str(dict, S_LEN("name"), buf->b_ffname != NULL ? buf->b_ffname : "");
678  tv_dict_add_nr(dict, S_LEN("lnum"),
679                 buf == curbuf ? curwin->w_cursor.lnum : buflist_findlnum(buf));
680  tv_dict_add_nr(dict, S_LEN("linecount"), buf->b_ml.ml_line_count);
681  tv_dict_add_nr(dict, S_LEN("loaded"), buf->b_ml.ml_mfp != NULL);
682  tv_dict_add_nr(dict, S_LEN("listed"), buf->b_p_bl);
683  tv_dict_add_nr(dict, S_LEN("changed"), bufIsChanged(buf));
684  tv_dict_add_nr(dict, S_LEN("changedtick"), buf_get_changedtick(buf));
685  tv_dict_add_nr(dict, S_LEN("hidden"), buf->b_ml.ml_mfp != NULL && buf->b_nwindows == 0);
686  tv_dict_add_nr(dict, S_LEN("command"), bt_cmdwin(buf));
687
688  // Get a reference to buffer variables
689  tv_dict_add_dict(dict, S_LEN("variables"), buf->b_vars);
690
691  // List of windows displaying this buffer
692  list_T *const windows = tv_list_alloc(kListLenMayKnow);
693  FOR_ALL_TAB_WINDOWS(tp, wp) {
694    if (wp->w_buffer == buf) {
695      tv_list_append_number(windows, (varnumber_T)wp->handle);
696    }
697  }
698  tv_dict_add_list(dict, S_LEN("windows"), windows);
699
700  if (buf_has_signs(buf)) {
701    // List of signs placed in this buffer
702    tv_dict_add_list(dict, S_LEN("signs"), get_buffer_signs(buf));
703  }
704
705  tv_dict_add_nr(dict, S_LEN("lastused"), buf->b_last_used);
706
707  return dict;
708}
709
710/// "getbufinfo()" function
711void f_getbufinfo(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
712{
713  buf_T *argbuf = NULL;
714  bool filtered = false;
715  bool sel_buflisted = false;
716  bool sel_bufloaded = false;
717  bool sel_bufmodified = false;
718
719  tv_list_alloc_ret(rettv, kListLenMayKnow);
720
721  // List of all the buffers or selected buffers
722  if (argvars[0].v_type == VAR_DICT) {
723    dict_T *sel_d = argvars[0].vval.v_dict;
724
725    if (sel_d != NULL) {
726      filtered = true;
727
728      sel_buflisted = tv_dict_get_bool(sel_d, "buflisted", false);
729      sel_bufloaded = tv_dict_get_bool(sel_d, "bufloaded", false);
730      sel_bufmodified = tv_dict_get_bool(sel_d, "bufmodified", false);
731    }
732  } else if (argvars[0].v_type != VAR_UNKNOWN) {
733    // Information about one buffer.  Argument specifies the buffer
734    argbuf = tv_get_buf_from_arg(&argvars[0]);
735    if (argbuf == NULL) {
736      return;
737    }
738  }
739
740  // Return information about all the buffers or a specified buffer
741  FOR_ALL_BUFFERS(buf) {
742    if (argbuf != NULL && argbuf != buf) {
743      continue;
744    }
745    if (filtered && ((sel_bufloaded && buf->b_ml.ml_mfp == NULL)
746                     || (sel_buflisted && !buf->b_p_bl)
747                     || (sel_bufmodified && !buf->b_changed))) {
748      continue;
749    }
750
751    dict_T *const d = get_buffer_info(buf);
752    tv_list_append_dict(rettv->vval.v_list, d);
753    if (argbuf != NULL) {
754      return;
755    }
756  }
757}
758
759/// Get line or list of lines from buffer "buf" into "rettv".
760///
761/// @param retlist  if true, then the lines are returned as a Vim List.
762///
763/// @return  range (from start to end) of lines in rettv from the specified
764///          buffer.
765static void get_buffer_lines(buf_T *buf, linenr_T start, linenr_T end, bool retlist,
766                             typval_T *rettv)
767{
768  rettv->v_type = (retlist ? VAR_LIST : VAR_STRING);
769  rettv->vval.v_string = NULL;
770
771  if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0 || end < start) {
772    if (retlist) {
773      tv_list_alloc_ret(rettv, 0);
774    }
775    return;
776  }
777
778  if (retlist) {
779    if (start < 1) {
780      start = 1;
781    }
782    if (end > buf->b_ml.ml_line_count) {
783      end = buf->b_ml.ml_line_count;
784    }
785    tv_list_alloc_ret(rettv, end - start + 1);
786    while (start <= end) {
787      tv_list_append_string(rettv->vval.v_list,
788                            ml_get_buf(buf, start), (int)ml_get_buf_len(buf, start));
789      start++;
790    }
791  } else {
792    rettv->v_type = VAR_STRING;
793    rettv->vval.v_string =
794      start >= 1 && start <= buf->b_ml.ml_line_count
795      ? xstrnsave(ml_get_buf(buf, start), (size_t)ml_get_buf_len(buf, start))
796      : NULL;
797  }
798}
799
800/// @param retlist  true: "getbufline()" function
801///                 false: "getbufoneline()" function
802static void getbufline(typval_T *argvars, typval_T *rettv, bool retlist)
803{
804  linenr_T lnum = 1;
805  linenr_T end = 1;
806  const int did_emsg_before = did_emsg;
807  buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
808  if (buf != NULL) {
809    lnum = tv_get_lnum_buf(&argvars[1], buf);
810    if (did_emsg > did_emsg_before) {
811      return;
812    }
813    end = (argvars[2].v_type == VAR_UNKNOWN
814           ? lnum
815           : tv_get_lnum_buf(&argvars[2], buf));
816  }
817
818  get_buffer_lines(buf, lnum, end, retlist, rettv);
819}
820
821/// "getbufline()" function
822void f_getbufline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
823{
824  getbufline(argvars, rettv, true);
825}
826
827/// "getbufoneline()" function
828void f_getbufoneline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
829{
830  getbufline(argvars, rettv, false);
831}
832
833/// "getline(lnum, [end])" function
834void f_getline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
835{
836  linenr_T end;
837  bool retlist;
838
839  const linenr_T lnum = tv_get_lnum(argvars);
840  if (argvars[1].v_type == VAR_UNKNOWN) {
841    end = lnum;
842    retlist = false;
843  } else {
844    end = tv_get_lnum(&argvars[1]);
845    retlist = true;
846  }
847
848  get_buffer_lines(curbuf, lnum, end, retlist, rettv);
849}
850
851/// "setbufline()" function
852void f_setbufline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
853{
854  buf_set_append_line(argvars, rettv, false);
855}
856
857/// "setline()" function
858void f_setline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
859{
860  const int did_emsg_before = did_emsg;
861  linenr_T lnum = tv_get_lnum(&argvars[0]);
862  if (did_emsg == did_emsg_before) {
863    set_buffer_lines(curbuf, lnum, false, &argvars[1], rettv);
864  }
865}
866
867/// "prompt_setcallback({buffer}, {callback})" function
868void f_prompt_setcallback(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
869{
870  Callback prompt_callback = CALLBACK_INIT;
871
872  if (check_secure()) {
873    return;
874  }
875  buf_T *buf = tv_get_buf(&argvars[0], false);
876  if (buf == NULL) {
877    return;
878  }
879
880  if (!callback_from_typval(&prompt_callback, &argvars[1])) {
881    return;
882  }
883
884  callback_free(&buf->b_prompt_callback);
885  buf->b_prompt_callback = prompt_callback;
886}
887
888/// "prompt_setinterrupt({buffer}, {callback})" function
889void f_prompt_setinterrupt(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
890{
891  Callback interrupt_callback = CALLBACK_INIT;
892
893  if (check_secure()) {
894    return;
895  }
896  buf_T *buf = tv_get_buf(&argvars[0], false);
897  if (buf == NULL) {
898    return;
899  }
900
901  if (!callback_from_typval(&interrupt_callback, &argvars[1])) {
902    return;
903  }
904
905  callback_free(&buf->b_prompt_interrupt);
906  buf->b_prompt_interrupt = interrupt_callback;
907}
908
909/// "prompt_getprompt({buffer})" function
910void f_prompt_getprompt(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
911  FUNC_ATTR_NONNULL_ALL
912{
913  // return an empty string by default, e.g. it's not a prompt buffer
914  rettv->v_type = VAR_STRING;
915  rettv->vval.v_string = NULL;
916
917  buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
918  if (buf == NULL) {
919    return;
920  }
921
922  if (!bt_prompt(buf)) {
923    return;
924  }
925
926  rettv->vval.v_string = xstrdup(buf_prompt_text(buf));
927}
928
929/// "prompt_getinput({buffer})" function
930void f_prompt_getinput(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
931  FUNC_ATTR_NONNULL_ALL
932{
933  // return an empty string by default, e.g. it's not a prompt buffer
934  rettv->v_type = VAR_STRING;
935  rettv->vval.v_string = NULL;
936
937  buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
938  if (buf == NULL) {
939    return;
940  }
941
942  if (!bt_prompt(buf)) {
943    return;
944  }
945
946  rettv->vval.v_string = prompt_get_input(buf);
947}
948
949/// "prompt_setprompt({buffer}, {text})" function
950void f_prompt_setprompt(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
951{
952  if (check_secure()) {
953    return;
954  }
955  buf_T *buf = tv_get_buf(&argvars[0], false);
956  if (buf == NULL) {
957    return;
958  }
959
960  const char *new_prompt = tv_get_string(&argvars[1]);
961  int new_prompt_len = (int)strlen(new_prompt);
962
963  // Update the prompt-text and prompt-marks if a plugin calls prompt_setprompt()
964  // even while user is editing their input.
965  if (bt_prompt(buf) && buf->b_ml.ml_mfp != NULL) {
966    // In case the mark is set to a nonexistent line.
967    if (buf->b_prompt_start.mark.lnum < 1
968        || buf->b_prompt_start.mark.lnum > curbuf->b_ml.ml_line_count) {
969      buf->b_prompt_start.mark.lnum = MAX(1, MIN(buf->b_prompt_start.mark.lnum,
970                                                 buf->b_ml.ml_line_count));
971      curbuf->b_prompt_append_new_line = true;
972    }
973
974    linenr_T prompt_lno = buf->b_prompt_start.mark.lnum;
975    char *old_prompt = buf_prompt_text(buf);
976    char *old_line = ml_get_buf(buf, prompt_lno);
977    colnr_T old_line_len = ml_get_buf_len(buf, prompt_lno);
978
979    int old_prompt_len = (int)strlen(old_prompt);
980    colnr_T cursor_col = curwin->w_cursor.col;
981
982    if (buf->b_prompt_start.mark.col < old_prompt_len
983        || buf->b_prompt_start.mark.col > old_line_len
984        || !strnequal(old_prompt, old_line + buf->b_prompt_start.mark.col - old_prompt_len,
985                      (size_t)old_prompt_len)) {
986      // If for some odd reason the old prompt is missing,
987      // replace prompt line with new-prompt (discards user-input).
988      ml_replace_buf(buf, prompt_lno, (char *)new_prompt, true, false);
989      extmark_splice_cols(buf, prompt_lno - 1, 0, old_line_len, new_prompt_len, kExtmarkNoUndo);
990      cursor_col = new_prompt_len;
991    } else {
992      // Replace prev-prompt + user-input with new-prompt + user-input
993      char *new_line = concat_str(new_prompt, old_line + buf->b_prompt_start.mark.col);
994      if (ml_replace_buf(buf, prompt_lno, new_line, false, false) != OK) {
995        xfree(new_line);
996      }
997      extmark_splice_cols(buf, prompt_lno - 1, 0, buf->b_prompt_start.mark.col, new_prompt_len,
998                          kExtmarkNoUndo);
999      cursor_col += new_prompt_len - buf->b_prompt_start.mark.col;
1000    }
1001
1002    if (curwin->w_buffer == buf && curwin->w_cursor.lnum == prompt_lno) {
1003      curwin->w_cursor.col = cursor_col;
1004      check_cursor_col(curwin);
1005    }
1006    changed_lines(buf, prompt_lno, 0, prompt_lno + 1, 0, true);
1007    // Undo history contains the old prompt.
1008    u_clearallandblockfree(buf);
1009  }
1010
1011  // Clear old prompt text and replace with the new one
1012  xfree(buf->b_prompt_text);
1013  buf->b_prompt_text = xstrdup(new_prompt);
1014  buf->b_prompt_start.mark.col = (colnr_T)new_prompt_len;
1015}