robin/laufey

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

robinmerge: 716835c2d51fa783d7

master
46.8 KiB1474 linesraw
1// Some of this code was adapted from 'if_py_both.h' from the original
2// vim source
3
4#include <lauxlib.h>
5#include <stdbool.h>
6#include <stddef.h>
7#include <stdint.h>
8#include <string.h>
9
10#include "klib/kvec.h"
11#include "lua.h"
12#include "nvim/api/buffer.h"
13#include "nvim/api/keysets_defs.h"
14#include "nvim/api/private/defs.h"
15#include "nvim/api/private/dispatch.h"
16#include "nvim/api/private/helpers.h"
17#include "nvim/api/private/validate.h"
18#include "nvim/ascii_defs.h"
19#include "nvim/autocmd.h"
20#include "nvim/autocmd_defs.h"
21#include "nvim/buffer.h"
22#include "nvim/buffer_defs.h"
23#include "nvim/buffer_updates.h"
24#include "nvim/change.h"
25#include "nvim/context.h"
26#include "nvim/cursor.h"
27#include "nvim/ex_cmds.h"
28#include "nvim/extmark.h"
29#include "nvim/extmark_defs.h"
30#include "nvim/globals.h"
31#include "nvim/lua/executor.h"
32#include "nvim/mapping.h"
33#include "nvim/mark.h"
34#include "nvim/mark_defs.h"
35#include "nvim/marktree_defs.h"
36#include "nvim/memline.h"
37#include "nvim/memline_defs.h"
38#include "nvim/memory.h"
39#include "nvim/memory_defs.h"
40#include "nvim/move.h"
41#include "nvim/ops.h"
42#include "nvim/option_vars.h"
43#include "nvim/pos_defs.h"
44#include "nvim/state_defs.h"
45#include "nvim/types_defs.h"
46#include "nvim/undo.h"
47#include "nvim/undo_defs.h"
48#include "nvim/vim_defs.h"
49
50#include "api/buffer.c.generated.h"
51
52/// Ensures that a buffer is loaded.
53buf_T *api_buf_ensure_loaded(Buffer buf, Error *err)
54{
55  buf_T *b = find_buffer_by_handle(buf, err);
56  if (!b) {
57    return NULL;
58  }
59
60  if (b->b_ml.ml_mfp == NULL && !buf_ensure_loaded(b)) {
61    api_set_error(err, kErrorTypeException, "Failed to load buffer");
62    return NULL;
63  }
64
65  return b;
66}
67
68/// @brief <pre>help
69/// For more information on buffers, see |buffers|.
70///
71/// Unloaded Buffers: ~
72///
73/// Buffers may be unloaded by the |:bunload| command or the buffer's
74/// 'bufhidden' option. When a buffer is unloaded its file contents are freed
75/// from memory and vim cannot operate on the buffer lines until it is reloaded
76/// (usually by opening the buffer again in a new window). API methods such as
77/// |nvim_buf_get_lines()| and |nvim_buf_line_count()| will be affected.
78///
79/// You can use |nvim_buf_is_loaded()| or |nvim_buf_line_count()| to check
80/// whether a buffer is loaded.
81/// </pre>
82
83/// Returns the number of lines in the given buffer.
84///
85/// @param buf   Buffer id, or 0 for current buffer
86/// @param[out] err Error details, if any
87/// @return Line count, or 0 for unloaded buffer. |api-buffer|
88Integer nvim_buf_line_count(Buffer buf, Error *err)
89  FUNC_API_SINCE(1)
90{
91  buf_T *b = find_buffer_by_handle(buf, err);
92
93  if (!b) {
94    return 0;
95  }
96
97  // return sentinel value if the buffer isn't loaded
98  if (b->b_ml.ml_mfp == NULL) {
99    return 0;
100  }
101
102  return b->b_ml.ml_line_count;
103}
104
105/// Activates |api-buffer-updates| events on a channel, or as Lua callbacks.
106///
107/// Example (Lua): capture buffer updates in a global `events` variable
108/// (use "vim.print(events)" to see its contents):
109///
110/// ```lua
111/// events = {}
112/// vim.api.nvim_buf_attach(0, false, {
113///   on_lines = function(...)
114///     table.insert(events, {...})
115///   end,
116/// })
117/// ```
118///
119/// @see |nvim_buf_detach()|
120/// @see |api-buffer-updates-lua|
121///
122/// @param channel_id
123/// @param buf Buffer id, or 0 for current buffer
124/// @param send_buffer True if the initial notification should contain the
125///        whole buffer: first notification will be `nvim_buf_lines_event`.
126///        Else the first notification will be `nvim_buf_changedtick_event`.
127///        Not for Lua callbacks.
128/// @param  opts  Optional parameters.
129///             - on_bytes: Called on granular changes (compared to on_lines). Not called on buffer
130///               reload (`:checktime`, `:edit`, …), see `on_reload`. Returning [lua-truthy] deletes
131///               the callback. Args:
132///               - the string "bytes"
133///               - buffer id
134///               - b:changedtick
135///               - start row of the changed text (zero-indexed)
136///               - start column of the changed text
137///               - byte offset of the changed text (from the start of
138///                   the buffer)
139///               - old end row of the changed text (offset from start row)
140///               - old end column of the changed text
141///                 (if old end row = 0, offset from start column)
142///               - old end byte length of the changed text
143///               - new end row of the changed text (offset from start row)
144///               - new end column of the changed text
145///                 (if new end row = 0, offset from start column)
146///               - new end byte length of the changed text
147///             - on_changedtick: Called on [changetick] increment without text change. Args:
148///               - the string "changedtick"
149///               - buffer id
150///               - b:changedtick
151///             - on_detach: Called on detach, or when the buffer is unloaded or deleted. Not called
152///               when a callback returns [lua-truthy] to delete itself. Args:
153///               - the string "detach"
154///               - buffer id
155///             - on_lines: Called on linewise changes. Not called on buffer reload (`:checktime`,
156///               `:edit`, …), see `on_reload`. Returning [lua-truthy] deletes the callback. Args:
157///               - the string "lines"
158///               - buffer id
159///               - b:changedtick
160///               - first line that changed (zero-indexed)
161///               - last line that was changed
162///               - last line in the updated range
163///               - byte count of previous contents
164///               - deleted_codepoints (if `utf_sizes` is true)
165///               - deleted_codeunits (if `utf_sizes` is true)
166///             - on_reload: Called on whole-buffer load (`:checktime`, `:edit`, …). Clients should
167///               typically re-fetch the entire buffer contents. Args:
168///               - the string "reload"
169///               - buffer id
170///             - preview: also attach to command preview (i.e. 'inccommand')
171///               events.
172///             - utf_sizes: include UTF-32 and UTF-16 size of the replaced
173///               region, as args to `on_lines`.
174/// @param[out] err Error details, if any
175/// @return False if attach failed (invalid parameter, or buffer isn't loaded);
176///         otherwise True.
177Boolean nvim_buf_attach(uint64_t channel_id, Buffer buf, Boolean send_buffer,
178                        Dict(buf_attach) *opts, Error *err)
179  FUNC_API_SINCE(4)
180{
181  buf_T *b = find_buffer_by_handle(buf, err);
182
183  if (!b) {
184    return false;
185  }
186
187  BufUpdateCallbacks cb = BUF_UPDATE_CALLBACKS_INIT;
188
189  if (channel_id == LUA_INTERNAL_CALL) {
190    if (HAS_KEY(opts, buf_attach, on_lines)) {
191      cb.on_lines = opts->on_lines;
192      opts->on_lines = LUA_NOREF;
193    }
194
195    if (HAS_KEY(opts, buf_attach, on_bytes)) {
196      cb.on_bytes = opts->on_bytes;
197      opts->on_bytes = LUA_NOREF;
198    }
199
200    if (HAS_KEY(opts, buf_attach, on_changedtick)) {
201      cb.on_changedtick = opts->on_changedtick;
202      opts->on_changedtick = LUA_NOREF;
203    }
204
205    if (HAS_KEY(opts, buf_attach, on_detach)) {
206      cb.on_detach = opts->on_detach;
207      opts->on_detach = LUA_NOREF;
208    }
209
210    if (HAS_KEY(opts, buf_attach, on_reload)) {
211      cb.on_reload = opts->on_reload;
212      opts->on_reload = LUA_NOREF;
213    }
214
215    cb.utf_sizes = opts->utf_sizes;
216
217    cb.preview = opts->preview;
218  }
219
220  return buf_updates_register(b, channel_id, cb, send_buffer);
221}
222
223/// Deactivates buffer-update events on the channel.
224///
225/// @see |nvim_buf_attach()|
226/// @see |api-lua-detach| for detaching Lua callbacks
227///
228/// @param channel_id
229/// @param buf Buffer id, or 0 for current buffer
230/// @param[out] err Error details, if any
231/// @return False if detach failed (because the buffer isn't loaded);
232///         otherwise True.
233Boolean nvim_buf_detach(uint64_t channel_id, Buffer buf, Error *err)
234  FUNC_API_SINCE(4) FUNC_API_REMOTE_ONLY
235{
236  buf_T *b = find_buffer_by_handle(buf, err);
237
238  if (!b) {
239    return false;
240  }
241
242  buf_updates_unregister(b, channel_id);
243  return true;
244}
245
246/// Gets a line-range from the buffer.
247///
248/// Indexing is zero-based, end-exclusive. Negative indices are interpreted
249/// as length+1+index: -1 refers to the index past the end. So to get the
250/// last element use start=-2 and end=-1.
251///
252/// Out-of-bounds indices are clamped to the nearest valid value, unless
253/// `strict_indexing` is set.
254///
255/// @see |nvim_buf_get_text()|
256///
257/// @param channel_id
258/// @param buf           Buffer id, or 0 for current buffer
259/// @param start            First line index
260/// @param end              Last line index, exclusive
261/// @param strict_indexing  Whether out-of-bounds should be an error.
262/// @param[out] err         Error details, if any
263/// @return Array of lines, or empty array for unloaded buffer.
264ArrayOf(String) nvim_buf_get_lines(uint64_t channel_id,
265                                   Buffer buf,
266                                   Integer start,
267                                   Integer end,
268                                   Boolean strict_indexing,
269                                   Arena *arena,
270                                   lua_State *lstate,
271                                   Error *err)
272  FUNC_API_SINCE(1)
273{
274  Array rv = ARRAY_DICT_INIT;
275  buf_T *b = find_buffer_by_handle(buf, err);
276
277  if (!b) {
278    return rv;
279  }
280
281  // return sentinel value if the buffer isn't loaded
282  if (b->b_ml.ml_mfp == NULL) {
283    init_line_array(lstate, &rv, 0, arena);
284    return rv;
285  }
286
287  bool oob = false;
288  start = normalize_index(b, start, true, &oob);
289  end = normalize_index(b, end, true, &oob);
290
291  VALIDATE((!strict_indexing || !oob), "%s", "Index out of bounds", {
292    return rv;
293  });
294
295  size_t size = end >= start ? (size_t)(end - start) : 0;
296
297  init_line_array(lstate, &rv, size, arena);
298
299  buf_collect_lines(b, size, (linenr_T)start, 0, (channel_id != VIML_INTERNAL_CALL), &rv,
300                    lstate, arena);
301
302  return rv;
303}
304
305/// Sets (replaces) a line-range in the buffer.
306///
307/// Indexing is zero-based, end-exclusive. Negative indices are interpreted
308/// as length+1+index: -1 refers to the index past the end. So to change
309/// or delete the last line use start=-2 and end=-1.
310///
311/// To insert lines at a given index, set `start` and `end` to the same index.
312/// To delete a range of lines, set `replacement` to an empty array.
313///
314/// Out-of-bounds indices are clamped to the nearest valid value, unless
315/// `strict_indexing` is set.
316///
317/// @see |nvim_buf_set_text()|
318///
319/// @param channel_id
320/// @param buf           Buffer id, or 0 for current buffer
321/// @param start            First line index
322/// @param end              Last line index, exclusive
323/// @param strict_indexing  Whether out-of-bounds should be an error.
324/// @param replacement      Array of lines to use as replacement
325/// @param[out] err         Error details, if any
326void nvim_buf_set_lines(uint64_t channel_id, Buffer buf, Integer start, Integer end,
327                        Boolean strict_indexing, ArrayOf(String) replacement, Arena *arena,
328                        Error *err)
329  FUNC_API_SINCE(1)
330  FUNC_API_TEXTLOCK
331{
332  buf_T *b = api_buf_ensure_loaded(buf, err);
333
334  if (!b) {
335    return;
336  }
337
338  bool oob = false;
339  start = normalize_index(b, start, true, &oob);
340  end = normalize_index(b, end, true, &oob);
341
342  VALIDATE((!strict_indexing || !oob), "%s", "Index out of bounds", {
343    return;
344  });
345  VALIDATE((start <= end), "%s", "'start' is higher than 'end'", {
346    return;
347  });
348
349  bool disallow_nl = (channel_id != VIML_INTERNAL_CALL);
350  if (!check_string_array(replacement, "replacement string", disallow_nl, err)) {
351    return;
352  }
353
354  size_t new_len = replacement.size;
355  size_t old_len = (size_t)(end - start);
356  ptrdiff_t extra = 0;  // lines added to text, can be negative
357  char **lines = (new_len != 0) ? arena_alloc(arena, new_len * sizeof(char *), true) : NULL;
358
359  for (size_t i = 0; i < new_len; i++) {
360    const String l = replacement.items[i].data.string;
361
362    // Fill lines[i] with l's contents. Convert NULs to newlines as required by
363    // NL-used-for-NUL.
364    lines[i] = arena_memdupz(arena, l.data, l.size);
365    memchrsub(lines[i], NUL, NL, l.size);
366  }
367
368  TRY_WRAP(err, {
369    if (!MODIFIABLE(b)) {
370      api_set_error(err, kErrorTypeException, "Buffer is not 'modifiable'");
371      goto end;
372    }
373
374    if (u_save_buf(b, (linenr_T)(start - 1), (linenr_T)end) == FAIL) {
375      api_set_error(err, kErrorTypeException, "Failed to save undo information");
376      goto end;
377    }
378
379    bcount_t deleted_bytes = get_region_bytecount(b, (linenr_T)start, (linenr_T)end, 0, 0);
380
381    // If the size of the range is reducing (ie, new_len < old_len) we
382    // need to delete some old_len. We do this at the start, by
383    // repeatedly deleting line "start".
384    size_t to_delete = (new_len < old_len) ? old_len - new_len : 0;
385    for (size_t i = 0; i < to_delete; i++) {
386      if (ml_delete_buf(b, (linenr_T)start, false) == FAIL) {
387        api_set_error(err, kErrorTypeException, "Failed to delete line");
388        goto end;
389      }
390    }
391
392    if (to_delete > 0) {
393      extra -= (ptrdiff_t)to_delete;
394    }
395
396    // For as long as possible, replace the existing old_len with the
397    // new old_len. This is a more efficient operation, as it requires
398    // less memory allocation and freeing.
399    size_t to_replace = old_len < new_len ? old_len : new_len;
400    bcount_t inserted_bytes = 0;
401    for (size_t i = 0; i < to_replace; i++) {
402      int64_t lnum = start + (int64_t)i;
403
404      VALIDATE(lnum < MAXLNUM, "%s", "Index out of bounds", {
405        goto end;
406      });
407
408      if (ml_replace_buf(b, (linenr_T)lnum, lines[i], false, true) == FAIL) {
409        api_set_error(err, kErrorTypeException, "Failed to replace line");
410        goto end;
411      }
412
413      inserted_bytes += (bcount_t)strlen(lines[i]) + 1;
414    }
415
416    // Now we may need to insert the remaining new old_len
417    for (size_t i = to_replace; i < new_len; i++) {
418      int64_t lnum = start + (int64_t)i - 1;
419
420      VALIDATE(lnum < MAXLNUM, "%s", "Index out of bounds", {
421        goto end;
422      });
423
424      if (ml_append_buf(b, (linenr_T)lnum, lines[i], 0, false) == FAIL) {
425        api_set_error(err, kErrorTypeException, "Failed to insert line");
426        goto end;
427      }
428
429      inserted_bytes += (bcount_t)strlen(lines[i]) + 1;
430
431      extra++;
432    }
433
434    // Adjust marks. Invalidate any which lie in the
435    // changed range, and move any in the remainder of the buffer.
436    linenr_T adjust = end > start ? MAXLNUM : 0;
437    mark_adjust_buf(b, (linenr_T)start, (linenr_T)(end - 1), adjust, (linenr_T)extra,
438                    true, kMarkAdjustApi, kExtmarkNOOP);
439
440    if (Visual.active && b == curbuf && Visual.start.lnum >= (linenr_T)start) {
441      if (Visual.start.lnum >= (linenr_T)end) {
442        Visual.start.lnum += (linenr_T)extra;
443      }
444      check_visual_pos();
445    }
446
447    extmark_splice(b, (int)start - 1, 0, (int)(end - start), 0,
448                   deleted_bytes, (int)new_len, 0, inserted_bytes,
449                   kExtmarkUndo);
450
451    changed_lines(b, (linenr_T)start, 0, (linenr_T)end, (linenr_T)extra, true);
452
453    FOR_ALL_TAB_WINDOWS(tp, win) {
454      if (win->w_buffer == b) {
455        fix_cursor(win, (linenr_T)start, (linenr_T)end, (linenr_T)extra);
456      }
457    }
458    end:;
459  });
460}
461
462/// Sets (replaces) a range in the buffer
463///
464/// This is recommended over |nvim_buf_set_lines()| when only modifying parts of
465/// a line, as extmarks will be preserved on non-modified parts of the touched
466/// lines.
467///
468/// Indexing is zero-based. Row indices are end-inclusive, and column indices
469/// are end-exclusive.
470///
471/// To insert text at a given `(row, column)` location, use `start_row = end_row
472/// = row` and `start_col = end_col = col`. To delete the text in a range, use
473/// `replacement = {}`.
474///
475/// @note Prefer |nvim_buf_set_lines()| (for performance) to add or delete entire lines.
476/// @note Prefer |nvim_paste()| or |nvim_put()| to insert (instead of replace) text at cursor.
477///
478/// @param channel_id
479/// @param buf           Buffer id, or 0 for current buffer
480/// @param start_row        First line index
481/// @param start_col        Starting column (byte offset) on first line
482/// @param end_row          Last line index, inclusive
483/// @param end_col          Ending column (byte offset) on last line, exclusive
484/// @param replacement      Array of lines to use as replacement
485/// @param[out] err         Error details, if any
486void nvim_buf_set_text(uint64_t channel_id, Buffer buf, Integer start_row, Integer start_col,
487                       Integer end_row, Integer end_col, ArrayOf(String) replacement, Arena *arena,
488                       Error *err)
489  FUNC_API_SINCE(7)
490  FUNC_API_TEXTLOCK
491{
492  MAXSIZE_TEMP_ARRAY(scratch, 1);
493  if (replacement.size == 0) {
494    ADD_C(scratch, STATIC_CSTR_AS_OBJ(""));
495    replacement = scratch;
496  }
497
498  buf_T *b = api_buf_ensure_loaded(buf, err);
499  if (!b) {
500    return;
501  }
502
503  bool oob = false;
504
505  // check range is ordered and everything!
506  // start_row, end_row within buffer len (except add text past the end?)
507  start_row = normalize_index(b, start_row, false, &oob);
508  VALIDATE_RANGE((!oob), "start_row", {
509    return;
510  });
511
512  end_row = normalize_index(b, end_row, false, &oob);
513  VALIDATE_RANGE((!oob), "end_row", {
514    return;
515  });
516
517  // Another call to ml_get_buf() may free the lines, so we make copies
518  char *str_at_start = ml_get_buf(b, (linenr_T)start_row);
519  colnr_T len_at_start = ml_get_buf_len(b, (linenr_T)start_row);
520  str_at_start = arena_memdupz(arena, str_at_start, (size_t)len_at_start);
521  start_col = start_col < 0 ? len_at_start + start_col + 1 : start_col;
522  VALIDATE_RANGE((start_col >= 0 && start_col <= len_at_start), "start_col", {
523    return;
524  });
525
526  char *str_at_end = ml_get_buf(b, (linenr_T)end_row);
527  colnr_T len_at_end = ml_get_buf_len(b, (linenr_T)end_row);
528  str_at_end = arena_memdupz(arena, str_at_end, (size_t)len_at_end);
529  end_col = end_col < 0 ? len_at_end + end_col + 1 : end_col;
530  VALIDATE_RANGE((end_col >= 0 && end_col <= len_at_end), "end_col", {
531    return;
532  });
533
534  VALIDATE((start_row <= end_row && !(end_row == start_row && start_col > end_col)),
535           "%s", "'start' is higher than 'end'", {
536    return;
537  });
538
539  bool disallow_nl = (channel_id != VIML_INTERNAL_CALL);
540  if (!check_string_array(replacement, "replacement string", disallow_nl, err)) {
541    return;
542  }
543
544  size_t new_len = replacement.size;
545
546  bcount_t new_byte = 0;
547  bcount_t old_byte = 0;
548
549  // calculate byte size of old region before it gets modified/deleted
550  if (start_row == end_row) {
551    old_byte = (bcount_t)end_col - start_col;
552  } else {
553    old_byte += len_at_start - start_col;
554    for (int64_t i = 1; i < end_row - start_row; i++) {
555      int64_t lnum = start_row + i;
556      old_byte += ml_get_buf_len(b, (linenr_T)lnum) + 1;
557    }
558    old_byte += (bcount_t)end_col + 1;
559  }
560
561  String first_item = replacement.items[0].data.string;
562  String last_item = replacement.items[replacement.size - 1].data.string;
563
564  size_t firstlen = (size_t)start_col + first_item.size;
565  size_t last_part_len = (size_t)len_at_end - (size_t)end_col;
566  if (replacement.size == 1) {
567    firstlen += last_part_len;
568  }
569  char *first = arena_allocz(arena, firstlen);
570  char *last = NULL;
571  memcpy(first, str_at_start, (size_t)start_col);
572  memcpy(first + start_col, first_item.data, first_item.size);
573  memchrsub(first + start_col, NUL, NL, first_item.size);
574  if (replacement.size == 1) {
575    memcpy(first + start_col + first_item.size, str_at_end + end_col, last_part_len);
576  } else {
577    last = arena_allocz(arena, last_item.size + last_part_len);
578    memcpy(last, last_item.data, last_item.size);
579    memchrsub(last, NUL, NL, last_item.size);
580    memcpy(last + last_item.size, str_at_end + end_col, last_part_len);
581  }
582
583  char **lines = arena_alloc(arena, new_len * sizeof(char *), true);
584  lines[0] = first;
585  new_byte += (bcount_t)(first_item.size);
586  for (size_t i = 1; i < new_len - 1; i++) {
587    const String l = replacement.items[i].data.string;
588
589    // Fill lines[i] with l's contents. Convert NULs to newlines as required by
590    // NL-used-for-NUL.
591    lines[i] = arena_memdupz(arena, l.data, l.size);
592    memchrsub(lines[i], NUL, NL, l.size);
593    new_byte += (bcount_t)(l.size) + 1;
594  }
595  if (replacement.size > 1) {
596    lines[replacement.size - 1] = last;
597    new_byte += (bcount_t)(last_item.size) + 1;
598  }
599
600  TRY_WRAP(err, {
601    if (!MODIFIABLE(b)) {
602      api_set_error(err, kErrorTypeException, "Buffer is not 'modifiable'");
603      goto end;
604    }
605
606    // Small note about undo states: unlike set_lines, we want to save the
607    // undo state of one past the end_row, since end_row is inclusive.
608    if (u_save_buf(b, (linenr_T)start_row - 1, (linenr_T)end_row + 1) == FAIL) {
609      api_set_error(err, kErrorTypeException, "Failed to save undo information");
610      goto end;
611    }
612
613    ptrdiff_t extra = 0;  // lines added to text, can be negative
614    size_t old_len = (size_t)(end_row - start_row + 1);
615
616    // If the size of the range is reducing (ie, new_len < old_len) we
617    // need to delete some old_len. We do this at the start, by
618    // repeatedly deleting line "start".
619    size_t to_delete = (new_len < old_len) ? old_len - new_len : 0;
620    for (size_t i = 0; i < to_delete; i++) {
621      if (ml_delete_buf(b, (linenr_T)start_row, false) == FAIL) {
622        api_set_error(err, kErrorTypeException, "Failed to delete line");
623        goto end;
624      }
625    }
626
627    if (to_delete > 0) {
628      extra -= (ptrdiff_t)to_delete;
629    }
630
631    // For as long as possible, replace the existing old_len with the
632    // new old_len. This is a more efficient operation, as it requires
633    // less memory allocation and freeing.
634    size_t to_replace = old_len < new_len ? old_len : new_len;
635    for (size_t i = 0; i < to_replace; i++) {
636      int64_t lnum = start_row + (int64_t)i;
637
638      VALIDATE((lnum < MAXLNUM), "%s", "Index out of bounds", {
639        goto end;
640      });
641
642      if (ml_replace_buf(b, (linenr_T)lnum, lines[i], false, true) == FAIL) {
643        api_set_error(err, kErrorTypeException, "Failed to replace line");
644        goto end;
645      }
646    }
647
648    // Now we may need to insert the remaining new old_len
649    for (size_t i = to_replace; i < new_len; i++) {
650      int64_t lnum = start_row + (int64_t)i - 1;
651
652      VALIDATE((lnum < MAXLNUM), "%s", "Index out of bounds", {
653        goto end;
654      });
655
656      if (ml_append_buf(b, (linenr_T)lnum, lines[i], 0, false) == FAIL) {
657        api_set_error(err, kErrorTypeException, "Failed to insert line");
658        goto end;
659      }
660
661      extra++;
662    }
663
664    colnr_T col_extent = (colnr_T)(end_col
665                                   - ((end_row == start_row) ? start_col : 0));
666
667    // Adjust marks. Invalidate any which lie in the
668    // changed range, and move any in the remainder of the buffer.
669    // Do not adjust any cursors. need to use column-aware logic (below)
670    linenr_T adjust = end_row >= start_row ? MAXLNUM : 0;
671    mark_adjust_buf(b, (linenr_T)start_row, (linenr_T)end_row - 1, adjust, (linenr_T)extra,
672                    true, kMarkAdjustApi, kExtmarkNOOP);
673
674    if (Visual.active && b == curbuf && Visual.mode != Ctrl_V) {
675      fix_pos_col(b, &Visual.start, (linenr_T)start_row, (colnr_T)start_col, (linenr_T)end_row,
676                  (colnr_T)end_col, (linenr_T)new_len, (colnr_T)last_item.size, 1);
677      check_visual_pos();
678    }
679
680    extmark_splice(b, (int)start_row - 1, (colnr_T)start_col,
681                   (int)(end_row - start_row), col_extent, old_byte,
682                   (int)new_len - 1, (colnr_T)last_item.size, new_byte,
683                   kExtmarkUndo);
684
685    changed_lines(b, (linenr_T)start_row, (colnr_T)start_col, (linenr_T)end_row + 1,
686                  (linenr_T)extra, true);
687
688    FOR_ALL_TAB_WINDOWS(tp, win) {
689      if (win->w_buffer == b) {
690        if (win->w_cursor.lnum >= start_row && win->w_cursor.lnum <= end_row) {
691          fix_cursor_cols(win, (linenr_T)start_row, (colnr_T)start_col, (linenr_T)end_row,
692                          (colnr_T)end_col, (linenr_T)new_len, (colnr_T)last_item.size);
693        } else {
694          fix_cursor(win, (linenr_T)start_row, (linenr_T)end_row, (linenr_T)extra);
695        }
696      }
697    }
698    end:;
699  });
700}
701
702/// Gets a range from the buffer (may be partial lines, unlike |nvim_buf_get_lines()|).
703///
704/// Indexing is zero-based. Row indices are end-inclusive, and column indices
705/// are end-exclusive.
706///
707/// Prefer |nvim_buf_get_lines()| when retrieving entire lines.
708///
709/// @param channel_id
710/// @param buf     Buffer id, or 0 for current buffer
711/// @param start_row  First line index
712/// @param start_col  Starting column (byte offset) on first line
713/// @param end_row    Last line index, inclusive
714/// @param end_col    Ending column (byte offset) on last line, exclusive
715/// @param opts       Optional parameters. Currently unused.
716/// @param[out] err   Error details, if any
717/// @return Array of lines, or empty array for unloaded buffer.
718ArrayOf(String) nvim_buf_get_text(uint64_t channel_id, Buffer buf,
719                                  Integer start_row, Integer start_col,
720                                  Integer end_row, Integer end_col,
721                                  Dict(empty) *opts,
722                                  Arena *arena, lua_State *lstate, Error *err)
723  FUNC_API_SINCE(9)
724{
725  Array rv = ARRAY_DICT_INIT;
726
727  buf_T *b = find_buffer_by_handle(buf, err);
728
729  if (!b) {
730    return rv;
731  }
732
733  // return sentinel value if the buffer isn't loaded
734  if (b->b_ml.ml_mfp == NULL) {
735    init_line_array(lstate, &rv, 0, arena);
736    return rv;
737  }
738
739  bool oob = false;
740  start_row = normalize_index(b, start_row, false, &oob);
741  end_row = normalize_index(b, end_row, false, &oob);
742
743  VALIDATE((!oob), "%s", "Index out of bounds", {
744    return rv;
745  });
746
747  // nvim_buf_get_lines doesn't care if the start row is greater than the end
748  // row (it will just return an empty array), but nvim_buf_get_text does in
749  // order to maintain symmetry with nvim_buf_set_text.
750  VALIDATE((start_row <= end_row), "%s", "'start' is higher than 'end'", {
751    return rv;
752  });
753
754  bool replace_nl = (channel_id != VIML_INTERNAL_CALL);
755
756  size_t size = (size_t)(end_row - start_row) + 1;
757
758  init_line_array(lstate, &rv, size, arena);
759
760  if (start_row == end_row) {
761    String line = buf_get_text(b, start_row, start_col, end_col, err);
762    if (ERROR_SET(err)) {
763      goto end;
764    }
765    push_linestr(lstate, &rv, line.data, line.size, 0, replace_nl, arena);
766    return rv;
767  }
768
769  String str = buf_get_text(b, start_row, start_col, MAXCOL - 1, err);
770  if (ERROR_SET(err)) {
771    goto end;
772  }
773
774  push_linestr(lstate, &rv, str.data, str.size, 0, replace_nl, arena);
775
776  if (size > 2) {
777    buf_collect_lines(b, size - 2, (linenr_T)start_row + 1, 1, replace_nl, &rv, lstate, arena);
778  }
779
780  str = buf_get_text(b, end_row, 0, end_col, err);
781  if (ERROR_SET(err)) {
782    goto end;
783  }
784
785  push_linestr(lstate, &rv, str.data, str.size, (int)(size - 1), replace_nl, arena);
786
787end:
788  if (ERROR_SET(err)) {
789    return (Array)ARRAY_DICT_INIT;
790  }
791
792  return rv;
793}
794
795/// Returns the byte offset of a line (0-indexed). |api-indexing|
796///
797/// Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is one byte.
798/// 'fileformat' and 'fileencoding' are ignored. The line index just after the
799/// last line gives the total byte-count of the buffer. A final EOL byte is
800/// counted if it would be written, see 'eol'.
801///
802/// Unlike |line2byte()|, throws error for out-of-bounds indexing.
803/// Returns -1 for unloaded buffer.
804///
805/// @param buf     Buffer id, or 0 for current buffer
806/// @param index      Line index
807/// @param[out] err   Error details, if any
808/// @return Integer byte offset, or -1 for unloaded buffer.
809Integer nvim_buf_get_offset(Buffer buf, Integer index, Error *err)
810  FUNC_API_SINCE(5)
811{
812  buf_T *b = find_buffer_by_handle(buf, err);
813  if (!b) {
814    return 0;
815  }
816
817  // return sentinel value if the buffer isn't loaded
818  if (b->b_ml.ml_mfp == NULL) {
819    return -1;
820  }
821
822  VALIDATE((index >= 0 && index <= b->b_ml.ml_line_count), "%s", "Index out of bounds", {
823    return 0;
824  });
825
826  return ml_find_line_or_offset(b, (int)index + 1, NULL, true);
827}
828
829/// Gets a buffer-scoped (b:) variable.
830///
831/// @param buf     Buffer id, or 0 for current buffer
832/// @param name       Variable name
833/// @param[out] err   Error details, if any
834/// @return Variable value
835Object nvim_buf_get_var(Buffer buf, String name, Arena *arena, Error *err)
836  FUNC_API_SINCE(1)
837{
838  buf_T *b = find_buffer_by_handle(buf, err);
839
840  if (!b) {
841    return (Object)OBJECT_INIT;
842  }
843
844  return dict_get_value(b->b_vars, name, arena, err);
845}
846
847/// Gets a changed tick of a buffer
848///
849/// @param[in]  buf  Buffer id, or 0 for current buffer
850/// @param[out] err     Error details, if any
851///
852/// @return `b:changedtick` value.
853Integer nvim_buf_get_changedtick(Buffer buf, Error *err)
854  FUNC_API_SINCE(2)
855{
856  const buf_T *const b = find_buffer_by_handle(buf, err);
857
858  if (!b) {
859    return -1;
860  }
861
862  return buf_get_changedtick(b);
863}
864
865/// Gets a list of buffer-local |mapping| definitions.
866///
867/// @param  buf     Buffer id, or 0 for current buffer
868/// @param  mode       Mode short-name ("n", "i", "v", ...)
869/// @param[out]  err   Error details, if any
870/// @returns Array of |maparg()|-like dictionaries describing mappings.
871///          The "buf" key holds the associated buffer id.
872ArrayOf(DictAs(get_keymap)) nvim_buf_get_keymap(Buffer buf, String mode, Arena *arena,
873                                                Error *err)
874  FUNC_API_SINCE(3)
875{
876  buf_T *b = find_buffer_by_handle(buf, err);
877
878  if (!b) {
879    return (Array)ARRAY_DICT_INIT;
880  }
881
882  return keymap_array(mode, b, arena);
883}
884
885/// Sets a buffer-local |mapping| for the given mode.
886///
887/// @see |nvim_set_keymap()|
888///
889/// @param  buf  Buffer id, or 0 for current buffer
890void nvim_buf_set_keymap(uint64_t channel_id, Buffer buf, String mode, String lhs, String rhs,
891                         Dict(keymap) *opts, Error *err)
892  FUNC_API_SINCE(6)
893{
894  modify_keymap(channel_id, buf, MAPTYPE_MAP, mode, lhs, rhs, opts, err);
895}
896
897/// Unmaps a buffer-local |mapping| for the given mode.
898///
899/// @see |nvim_del_keymap()|
900///
901/// @param  buf   Buffer id, or 0 for current buffer
902/// @param  mode  Mode short-name ("n", "i", "v", ...)
903/// @param  lhs   Left-hand-side |{lhs}| of the mapping.
904/// @param  opts  Optional parameters.
905///               - lhs: When true, only match {lhs}, not {rhs}.
906void nvim_buf_del_keymap(uint64_t channel_id, Buffer buf, String mode, String lhs,
907                         Dict(keymap_del) *opts, Error *err)
908  FUNC_API_SINCE(6)
909{
910  String rhs = { .data = "", .size = 0 };
911  int maptype = opts && opts->lhs ? MAPTYPE_UNMAP_LHS : MAPTYPE_UNMAP;
912  modify_keymap(channel_id, buf, maptype, mode, lhs, rhs, NULL, err);
913}
914
915/// Sets a buffer-scoped (b:) variable
916///
917/// @param buf     Buffer id, or 0 for current buffer
918/// @param name       Variable name
919/// @param value      Variable value
920/// @param[out] err   Error details, if any
921void nvim_buf_set_var(Buffer buf, String name, Object value, Error *err)
922  FUNC_API_SINCE(1)
923{
924  buf_T *b = find_buffer_by_handle(buf, err);
925
926  if (!b) {
927    return;
928  }
929
930  dict_set_var(b->b_vars, name, value, false, false, NULL, err);
931}
932
933/// Removes a buffer-scoped (b:) variable
934///
935/// @param buf     Buffer id, or 0 for current buffer
936/// @param name       Variable name
937/// @param[out] err   Error details, if any
938void nvim_buf_del_var(Buffer buf, String name, Error *err)
939  FUNC_API_SINCE(1)
940{
941  buf_T *b = find_buffer_by_handle(buf, err);
942
943  if (!b) {
944    return;
945  }
946
947  dict_set_var(b->b_vars, name, NIL, true, false, NULL, err);
948}
949
950/// Gets the full/absolute filepath of the buffer, or the buffer name for non-file buffers.
951///
952/// If the buffer represents a directory, the name ends with a path separator,
953/// unless it was changed by |:file| or |nvim_buf_set_name()|.
954///
955/// @param buf     Buffer id, or 0 for current buffer
956/// @param[out] err   Error details, if any
957/// @return Buffer name
958String nvim_buf_get_name(Buffer buf, Error *err)
959  FUNC_API_SINCE(1)
960{
961  String rv = STRING_INIT;
962  buf_T *b = find_buffer_by_handle(buf, err);
963
964  if (!b || b->b_ffname == NULL) {
965    return rv;
966  }
967
968  return cstr_as_string(b->b_ffname);
969}
970
971/// Sets the full file name for a buffer, like |:file_f|
972///
973/// @param buf     Buffer id, or 0 for current buffer
974/// @param name       Buffer name
975/// @param[out] err   Error details, if any
976void nvim_buf_set_name(Buffer buf, String name, Error *err)
977  FUNC_API_SINCE(1)
978{
979  buf_T *b = find_buffer_by_handle(buf, err);
980
981  if (!b) {
982    return;
983  }
984
985  int ren_ret = OK;
986  TRY_WRAP(err, {
987    const bool is_curbuf = b == curbuf;
988    const int save_acd = p_acd;
989    if (!is_curbuf) {
990      // Don't update 'title' and 'autochdir' when setting file name for another buffer.
991      RedrawingDisabled++;
992      p_acd = false;
993    }
994
995    // Switch context to `b`: autocommands will be executed by rename_buffer
996    CtxSwitch aco = { 0 };
997    ctx_switch(&aco, NULL, NULL, b, 0);
998    ren_ret = rename_buffer(name.data);
999    ctx_restore(&aco);
1000
1001    if (!is_curbuf) {
1002      RedrawingDisabled--;
1003      p_acd = save_acd;
1004    }
1005  });
1006
1007  if (ERROR_SET(err)) {
1008    return;
1009  }
1010
1011  if (ren_ret == FAIL) {
1012    api_set_error(err, kErrorTypeException, "Failed to rename buffer");
1013  }
1014}
1015
1016/// Checks if a buffer is valid and loaded. See |api-buffer| for more info
1017/// about unloaded buffers.
1018///
1019/// @param buf Buffer id, or 0 for current buffer
1020/// @return true if the buffer is valid and loaded, false otherwise.
1021Boolean nvim_buf_is_loaded(Buffer buf)
1022  FUNC_API_SINCE(5)
1023{
1024  Error stub = ERROR_INIT;
1025  buf_T *b = find_buffer_by_handle(buf, &stub);
1026  api_clear_error(&stub);
1027  return b && b->b_ml.ml_mfp != NULL;
1028}
1029
1030/// Deletes a buffer and its metadata (like |:bwipeout|).
1031///
1032/// To get |:bdelete| behavior, reset 'buflisted' and pass `unload=true`:
1033/// ```lua
1034/// vim.bo.buflisted = false
1035/// vim.api.nvim_buf_delete(0, { unload = true })
1036/// ```
1037///
1038/// @param buf Buffer id, or 0 for current buffer
1039/// @param opts  Optional parameters. Keys:
1040///          - force:  Force deletion, ignore unsaved changes.
1041///          - unload: Unloaded only (|:bunload|), do not delete.
1042void nvim_buf_delete(Buffer buf, Dict(buf_delete) *opts, Error *err)
1043  FUNC_API_SINCE(7)
1044  FUNC_API_TEXTLOCK
1045{
1046  buf_T *b = find_buffer_by_handle(buf, err);
1047
1048  if (ERROR_SET(err)) {
1049    return;
1050  }
1051
1052  bool force = opts->force;
1053
1054  bool unload = opts->unload;
1055
1056  int result = do_buffer(unload ? DOBUF_UNLOAD : DOBUF_WIPE,
1057                         DOBUF_FIRST,
1058                         FORWARD,
1059                         b->handle,
1060                         force);
1061
1062  if (result == FAIL) {
1063    api_set_error(err, kErrorTypeException, "Failed to unload buffer.");
1064    return;
1065  }
1066}
1067
1068/// Checks if a buffer is valid.
1069///
1070/// @note Even if a buffer is valid it may have been unloaded. See |api-buffer|
1071/// for more info about unloaded buffers.
1072///
1073/// @param buf Buffer id, or 0 for current buffer
1074/// @return true if the buffer is valid, false otherwise.
1075Boolean nvim_buf_is_valid(Buffer buf)
1076  FUNC_API_SINCE(1)
1077{
1078  Error stub = ERROR_INIT;
1079  Boolean ret = find_buffer_by_handle(buf, &stub) != NULL;
1080  api_clear_error(&stub);
1081  return ret;
1082}
1083
1084/// Deletes a named mark in the buffer. See |mark-motions|.
1085///
1086/// @note only deletes marks set in the buffer, if the mark is not set
1087/// in the buffer it will return false.
1088/// @param buf     Buffer to set the mark on
1089/// @param name       Mark name
1090/// @return true if the mark was deleted, else false.
1091/// @see |nvim_buf_set_mark()|
1092/// @see |nvim_del_mark()|
1093Boolean nvim_buf_del_mark(Buffer buf, String name, Error *err)
1094  FUNC_API_SINCE(8)
1095{
1096  bool res = false;
1097  buf_T *b = find_buffer_by_handle(buf, err);
1098
1099  if (!b) {
1100    return res;
1101  }
1102
1103  VALIDATE_S((name.size == 1), "mark name (must be a single char)", name.data, {
1104    return res;
1105  });
1106
1107  fmark_T *fm = mark_get(b, curwin, NULL, kMarkAllNoResolve, *name.data);
1108
1109  // fm is NULL when there's no mark with the given name
1110  VALIDATE_S((fm != NULL), "mark name", name.data, {
1111    return res;
1112  });
1113
1114  // mark.lnum is 0 when the mark is not valid in the buffer, or is not set.
1115  if (fm->mark.lnum != 0 && fm->fnum == b->handle) {
1116    // since the mark belongs to the buffer delete it.
1117    res = set_mark(b, name, 0, 0, err);
1118  }
1119
1120  return res;
1121}
1122
1123/// Sets a named mark in the given buffer, all marks are allowed
1124/// file/uppercase, visual, last change, etc. See |mark-motions|.
1125///
1126/// Marks are (1,0)-indexed. |api-indexing|
1127///
1128/// @note Passing 0 as line deletes the mark
1129///
1130/// @param buf     Buffer to set the mark on
1131/// @param name       Mark name
1132/// @param line       Line number
1133/// @param col        Column/row number
1134/// @param opts       Optional parameters. Reserved for future use.
1135/// @return true if the mark was set, else false.
1136/// @see |nvim_buf_del_mark()|
1137/// @see |nvim_buf_get_mark()|
1138Boolean nvim_buf_set_mark(Buffer buf, String name, Integer line, Integer col, Dict(empty) *opts,
1139                          Error *err)
1140  FUNC_API_SINCE(8)
1141{
1142  bool res = false;
1143  buf_T *b = api_buf_ensure_loaded(buf, err);
1144
1145  if (!b) {
1146    return res;
1147  }
1148
1149  VALIDATE_S((name.size == 1), "mark name (must be a single char)", name.data, {
1150    return res;
1151  });
1152
1153  res = set_mark(b, name, line, col, err);
1154
1155  return res;
1156}
1157
1158/// Returns a `(row,col)` tuple representing the position of the named mark.
1159/// "End of line" column position is returned as |v:maxcol| (big number).
1160/// See |mark-motions|.
1161///
1162/// Marks are (1,0)-indexed. |api-indexing|
1163///
1164/// @param buf     Buffer id, or 0 for current buffer
1165/// @param name       Mark name
1166/// @param[out] err   Error details, if any
1167/// @return (row, col) tuple, (0, 0) if the mark is not set, or is an
1168/// uppercase/file mark set in another buffer.
1169/// @see |nvim_buf_set_mark()|
1170/// @see |nvim_buf_del_mark()|
1171ArrayOf(Integer, 2) nvim_buf_get_mark(Buffer buf, String name, Arena *arena, Error *err)
1172  FUNC_API_SINCE(1)
1173{
1174  Array rv = ARRAY_DICT_INIT;
1175  buf_T *b = find_buffer_by_handle(buf, err);
1176
1177  if (!b) {
1178    return rv;
1179  }
1180
1181  VALIDATE_S((name.size == 1), "mark name (must be a single char)", name.data, {
1182    return rv;
1183  });
1184
1185  fmark_T *fm;
1186  pos_T pos;
1187  char mark = *name.data;
1188
1189  fm = mark_get(b, curwin, NULL, kMarkAllNoResolve, mark);
1190  VALIDATE_S((fm != NULL), "mark name", name.data, {
1191    return rv;
1192  });
1193  // (0, 0) uppercase/file mark set in another buffer.
1194  if (fm->fnum != b->handle) {
1195    pos.lnum = 0;
1196    pos.col = 0;
1197  } else {
1198    pos = fm->mark;
1199  }
1200
1201  rv = arena_array(arena, 2);
1202  ADD_C(rv, INTEGER_OBJ(pos.lnum));
1203  ADD_C(rv, INTEGER_OBJ(pos.col));
1204
1205  return rv;
1206}
1207
1208/// Calls function `fn` in the context of buffer `buf` and returns its result (may be multiple
1209/// values).
1210///
1211/// This temporarily switches current buffer to `buf`.
1212/// If the current window already shows `buf`, the window is not switched.
1213/// If a window inside the current tabpage (including a float) already shows the
1214/// buffer, then one of those windows will be set as current window temporarily.
1215/// Otherwise a temporary scratch window (called the "autocmd window" for
1216/// historical reasons) will be used.
1217///
1218/// This is useful e.g. to call Vimscript functions that only work with the
1219/// current buffer/window currently, like `jobstart(…, {'term': v:true})`.
1220///
1221/// @param buf  Buffer id, or 0 for current buffer.
1222/// @param fn   Lua function to call inside the buffer.
1223/// @param err  Error details, if any.
1224/// @return     Value(s) returned by `fn()`.
1225Object nvim_buf_call(Buffer buf, LuaRef fn, lua_State *lstate, Error *err)
1226  FUNC_API_SINCE(7)
1227  FUNC_API_LUA_ONLY
1228{
1229  buf_T *b = find_buffer_by_handle(buf, err);
1230  if (!b) {
1231    return NIL;
1232  }
1233
1234  TRY_WRAP(err, {
1235    CtxSwitch cs = { 0 };
1236    ctx_switch(&cs, NULL, NULL, b, 0);
1237
1238    Array args = ARRAY_DICT_INIT;
1239    nlua_call_ref(fn, NULL, args, kRetMultiStack, NULL, err);
1240
1241    ctx_restore(&cs);
1242  });
1243
1244  return NIL;  // kRetMultiStack: values are already on the lua stack
1245}
1246
1247/// @nodoc
1248Dict nvim__buf_stats(Buffer buf, Arena *arena, Error *err)
1249{
1250  buf_T *b = find_buffer_by_handle(buf, err);
1251  if (!b) {
1252    return (Dict)ARRAY_DICT_INIT;
1253  }
1254
1255  Dict rv = arena_dict(arena, 7);
1256  // Number of times the cached line was flushed.
1257  // This should generally not increase while editing the same
1258  // line in the same mode.
1259  PUT_C(rv, "flush_count", INTEGER_OBJ(b->flush_count));
1260  // lnum of current line
1261  PUT_C(rv, "current_lnum", INTEGER_OBJ(b->b_ml.ml_line_lnum));
1262  // whether the line has unflushed changes.
1263  PUT_C(rv, "line_dirty", BOOLEAN_OBJ(b->b_ml.ml_flags & ML_LINE_DIRTY));
1264  // NB: this should be zero at any time API functions are called,
1265  // this exists to debug issues
1266  PUT_C(rv, "dirty_bytes", INTEGER_OBJ((Integer)b->deleted_bytes));
1267  PUT_C(rv, "dirty_bytes2", INTEGER_OBJ((Integer)b->deleted_bytes2));
1268  PUT_C(rv, "virt_blocks", INTEGER_OBJ((Integer)buf_meta_total(b, kMTMetaLines)));
1269
1270  u_header_T *uhp = NULL;
1271  if (b->b_u_curhead != NULL) {
1272    uhp = b->b_u_curhead;
1273  } else if (b->b_u_newhead) {
1274    uhp = b->b_u_newhead;
1275  }
1276  if (uhp) {
1277    PUT_C(rv, "uhp_extmark_size", INTEGER_OBJ((Integer)kv_size(uhp->uh_extmark)));
1278  }
1279
1280  return rv;
1281}
1282
1283// Check if deleting lines made the cursor position invalid.
1284// Changed lines from `lo` to `hi`; added `extra` lines (negative if deleted).
1285static void fix_cursor(win_T *win, linenr_T lo, linenr_T hi, linenr_T extra)
1286{
1287  if (win->w_cursor.lnum >= lo) {
1288    // Adjust cursor position if it's in/after the changed lines.
1289    if (win->w_cursor.lnum >= hi) {
1290      win->w_cursor.lnum += extra;
1291    } else if (extra < 0) {
1292      check_cursor_lnum(win);
1293    }
1294    check_cursor_col(win);
1295    changed_cline_bef_curs(win);
1296    win->w_valid &= ~(VALID_BOTLINE_AP);
1297    update_topline(win);
1298  } else {
1299    invalidate_botline_win(win);
1300  }
1301}
1302
1303/// Adjust pos's col/lnum after text replacement between
1304/// (start_row, start_col) and (end_row, end_col).
1305static void fix_pos_col(buf_T *buf, pos_T *pos, linenr_T start_row, colnr_T start_col,
1306                        linenr_T end_row, colnr_T end_col, linenr_T new_rows,
1307                        colnr_T new_cols_at_end_row, colnr_T mode_col_adj)
1308{
1309  if (pos->lnum < start_row) {
1310    return;
1311  }
1312
1313  linenr_T old_rows = end_row - start_row + 1;
1314  linenr_T lnum_shift = new_rows - old_rows;
1315
1316  if (pos->lnum > end_row) {
1317    pos->lnum += lnum_shift;
1318    return;
1319  }
1320
1321  colnr_T end_row_change_start = new_rows == 1 ? start_col : 0;
1322  colnr_T end_row_change_end = end_row_change_start + new_cols_at_end_row;
1323
1324  // check if pos is after replaced range or not
1325  if (pos->lnum == end_row && pos->col + mode_col_adj > end_col) {
1326    // if pos is after replaced range, it's shifted
1327    // to keep its position the same, relative to end_col
1328    pos->lnum += lnum_shift;
1329    pos->col += end_row_change_end - end_col;
1330    return;
1331  }
1332
1333  // if pos is inside replaced range
1334  // and the new range got smaller,
1335  // it's shifted to keep it inside the new range
1336  //
1337  // if pos is before range or range did not
1338  // get smaller, position is not changed
1339
1340  colnr_T old_coladd = pos->coladd;
1341
1342  // it's easier to work with a single value here.
1343  // col and coladd are fixed by a later call
1344  // to check_cursor_col when necessary
1345  pos->col += pos->coladd;
1346  pos->coladd = 0;
1347
1348  linenr_T new_end_row = start_row + new_rows - 1;
1349
1350  // make sure pos row is in the new row range
1351  if (pos->lnum > new_end_row) {
1352    pos->lnum = new_end_row;
1353
1354    // don't simply move pos up, but to the end
1355    // of new_end_row, if it's not at or after
1356    // it already (in case virtualedit is active)
1357    // column might be additionally adjusted below
1358    // to keep it inside col range if needed
1359    colnr_T len = ml_get_buf_len(buf, new_end_row);
1360    if (pos->col < len) {
1361      pos->col = len;
1362    }
1363  }
1364
1365  // if pos is at the last row and
1366  // it wasn't after eol before, move it exactly
1367  // to end_row_change_end
1368  if (pos->lnum == new_end_row
1369      && pos->col > end_row_change_end && old_coladd == 0) {
1370    pos->col = end_row_change_end;
1371
1372    // make sure pos is inside range, not after it,
1373    // except when doing so would move it before new range
1374    if (pos->col - mode_col_adj >= end_row_change_start) {
1375      pos->col -= mode_col_adj;
1376    }
1377  }
1378}
1379
1380/// Fix cursor position after replacing text
1381/// between (start_row, start_col) and (end_row, end_col).
1382///
1383/// win->w_cursor.lnum is assumed to be >= start_row and <= end_row.
1384static void fix_cursor_cols(win_T *win, linenr_T start_row, colnr_T start_col, linenr_T end_row,
1385                            colnr_T end_col, linenr_T new_rows, colnr_T new_cols_at_end_row)
1386{
1387  colnr_T mode_col_adj = (win == curwin && (State & MODE_INSERT)) ? 0 : 1;
1388  fix_pos_col(win->w_buffer, &win->w_cursor,
1389              start_row, start_col, end_row, end_col,
1390              new_rows, new_cols_at_end_row, mode_col_adj);
1391
1392  check_cursor_col(win);
1393  changed_cline_bef_curs(win);
1394  invalidate_botline_win(win);
1395}
1396
1397/// Initialise a string array either:
1398/// - on the Lua stack (as a table) (if lstate is not NULL)
1399/// - as an API array object (if lstate is NULL).
1400///
1401/// @param lstate  Lua state. When NULL the Array is initialized instead.
1402/// @param a       Array to initialize
1403/// @param size    Size of array
1404static inline void init_line_array(lua_State *lstate, Array *a, size_t size, Arena *arena)
1405{
1406  if (lstate) {
1407    lua_createtable(lstate, (int)size, 0);
1408  } else {
1409    *a = arena_array(arena, size);
1410  }
1411}
1412
1413/// Push a string onto either the Lua stack (as a table element) or an API array object.
1414///
1415/// For Lua, a table of the correct size must be created first.
1416/// API array objects must be pre allocated.
1417///
1418/// @param lstate      Lua state. When NULL the Array is pushed to instead.
1419/// @param a           Array to push onto when not using Lua
1420/// @param s           String to push
1421/// @param len         Size of string
1422/// @param idx         0-based index to place s (only used for Lua)
1423/// @param replace_nl  Replace newlines ('\n') with null (NUL)
1424static void push_linestr(lua_State *lstate, Array *a, const char *s, size_t len, int idx,
1425                         bool replace_nl, Arena *arena)
1426{
1427  if (lstate) {
1428    // Vim represents NULs as NLs
1429    if (s && replace_nl && strchr(s, '\n')) {
1430      // TODO(bfredl): could manage scratch space in the arena, for the NUL case
1431      char *tmp = xmemdupz(s, len);
1432      strchrsub(tmp, '\n', NUL);
1433      lua_pushlstring(lstate, tmp, len);
1434      xfree(tmp);
1435    } else {
1436      lua_pushlstring(lstate, s, len);
1437    }
1438    lua_rawseti(lstate, -2, idx + 1);
1439  } else {
1440    String str = STRING_INIT;
1441    if (len > 0) {
1442      str = CBUF_TO_ARENA_STR(arena, s, len);
1443      if (replace_nl) {
1444        // Vim represents NULs as NLs, but this may confuse clients.
1445        strchrsub(str.data, '\n', NUL);
1446      }
1447    }
1448
1449    ADD_C(*a, STRING_OBJ(str));
1450  }
1451}
1452
1453/// Collects `n` buffer lines into array `l` and/or lua_State `lstate`, optionally replacing
1454/// newlines with NUL.
1455///
1456/// @param buf Buffer to get lines from
1457/// @param n Number of lines to collect
1458/// @param replace_nl Replace newlines ("\n") with NUL
1459/// @param start Line number to start from
1460/// @param start_idx First index to push to (only used for Lua)
1461/// @param[out] l If not NULL, Lines are copied here
1462/// @param[out] lstate If not NULL, Lines are pushed into a table onto the stack
1463/// @param err[out] Error, if any
1464/// @return true unless `err` was set
1465void buf_collect_lines(buf_T *buf, size_t n, linenr_T start, int start_idx, bool replace_nl,
1466                       Array *l, lua_State *lstate, Arena *arena)
1467{
1468  for (size_t i = 0; i < n; i++) {
1469    linenr_T lnum = start + (linenr_T)i;
1470    char *bufstr = ml_get_buf(buf, lnum);
1471    size_t bufstrlen = (size_t)ml_get_buf_len(buf, lnum);
1472    push_linestr(lstate, l, bufstr, bufstrlen, start_idx + (int)i, replace_nl, arena);
1473  }
1474}