robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
d51fa783d7
master
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{ 55buf_T * b = find_buffer_by_handle (buf ,err ); 56if (!b ) { 57return NULL ; 58 } 59 60if (b -> b_ml .ml_mfp == NULL && !buf_ensure_loaded (b )) { 61api_set_error (err ,kErrorTypeException ,"Failed to load buffer" ); 62return NULL ; 63 } 64 65return 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 ) 89FUNC_API_SINCE (1 ) 90{ 91buf_T * b = find_buffer_by_handle (buf ,err ); 92 93if (!b ) { 94return 0 ; 95 } 96 97// return sentinel value if the buffer isn't loaded 98if (b -> b_ml .ml_mfp == NULL ) { 99return 0 ; 100 } 101 102return 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 , 178Dict (buf_attach )* opts ,Error * err ) 179FUNC_API_SINCE (4 ) 180{ 181buf_T * b = find_buffer_by_handle (buf ,err ); 182 183if (!b ) { 184return false; 185 } 186 187BufUpdateCallbacks cb = BUF_UPDATE_CALLBACKS_INIT ; 188 189if (channel_id == LUA_INTERNAL_CALL ) { 190if (HAS_KEY (opts ,buf_attach ,on_lines )) { 191cb .on_lines = opts -> on_lines ; 192opts -> on_lines = LUA_NOREF ; 193 } 194 195if (HAS_KEY (opts ,buf_attach ,on_bytes )) { 196cb .on_bytes = opts -> on_bytes ; 197opts -> on_bytes = LUA_NOREF ; 198 } 199 200if (HAS_KEY (opts ,buf_attach ,on_changedtick )) { 201cb .on_changedtick = opts -> on_changedtick ; 202opts -> on_changedtick = LUA_NOREF ; 203 } 204 205if (HAS_KEY (opts ,buf_attach ,on_detach )) { 206cb .on_detach = opts -> on_detach ; 207opts -> on_detach = LUA_NOREF ; 208 } 209 210if (HAS_KEY (opts ,buf_attach ,on_reload )) { 211cb .on_reload = opts -> on_reload ; 212opts -> on_reload = LUA_NOREF ; 213 } 214 215cb .utf_sizes = opts -> utf_sizes ; 216 217cb .preview = opts -> preview ; 218 } 219 220return 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 ) 234FUNC_API_SINCE (4 )FUNC_API_REMOTE_ONLY 235{ 236buf_T * b = find_buffer_by_handle (buf ,err ); 237 238if (!b ) { 239return false; 240 } 241 242buf_updates_unregister (b ,channel_id ); 243return 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 , 265Buffer buf , 266Integer start , 267Integer end , 268Boolean strict_indexing , 269Arena * arena , 270lua_State * lstate , 271Error * err ) 272FUNC_API_SINCE (1 ) 273{ 274Array rv = ARRAY_DICT_INIT ; 275buf_T * b = find_buffer_by_handle (buf ,err ); 276 277if (!b ) { 278return rv ; 279 } 280 281// return sentinel value if the buffer isn't loaded 282if (b -> b_ml .ml_mfp == NULL ) { 283init_line_array (lstate ,& rv ,0 ,arena ); 284return rv ; 285 } 286 287bool oob = false; 288start = normalize_index (b ,start , true,& oob ); 289end = normalize_index (b ,end , true,& oob ); 290 291VALIDATE ((!strict_indexing || !oob ),"%s" ,"Index out of bounds" , { 292return rv ; 293 }); 294 295size_t size = end >=start ? (size_t )(end - start ) :0 ; 296 297init_line_array (lstate ,& rv ,size ,arena ); 298 299buf_collect_lines (b ,size , (linenr_T )start ,0 , (channel_id != VIML_INTERNAL_CALL ),& rv , 300lstate ,arena ); 301 302return 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 , 327Boolean strict_indexing ,ArrayOf (String )replacement ,Arena * arena , 328Error * err ) 329FUNC_API_SINCE (1 ) 330FUNC_API_TEXTLOCK 331{ 332buf_T * b = api_buf_ensure_loaded (buf ,err ); 333 334if (!b ) { 335return ; 336 } 337 338bool oob = false; 339start = normalize_index (b ,start , true,& oob ); 340end = normalize_index (b ,end , true,& oob ); 341 342VALIDATE ((!strict_indexing || !oob ),"%s" ,"Index out of bounds" , { 343return ; 344 }); 345VALIDATE ((start <=end ),"%s" ,"'start' is higher than 'end'" , { 346return ; 347 }); 348 349bool disallow_nl = (channel_id != VIML_INTERNAL_CALL ); 350if (!check_string_array (replacement ,"replacement string" ,disallow_nl ,err )) { 351return ; 352 } 353 354size_t new_len = replacement .size ; 355size_t old_len = (size_t )(end - start ); 356ptrdiff_t extra = 0 ;// lines added to text, can be negative 357char ** lines = (new_len != 0 ) ?arena_alloc (arena ,new_len * sizeof (char * ), true) :NULL ; 358 359for (size_t i = 0 ;i < new_len ;i ++ ) { 360const 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. 364lines [i ]= arena_memdupz (arena ,l .data ,l .size ); 365memchrsub (lines [i ],NUL ,NL ,l .size ); 366 } 367 368TRY_WRAP (err , { 369if (!MODIFIABLE (b )) { 370api_set_error (err ,kErrorTypeException ,"Buffer is not 'modifiable'" ); 371 gotoend ; 372 } 373 374if (u_save_buf (b , (linenr_T )(start - 1 ), (linenr_T )end )== FAIL ) { 375api_set_error (err ,kErrorTypeException ,"Failed to save undo information" ); 376 gotoend ; 377 } 378 379bcount_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". 384size_t to_delete = (new_len < old_len ) ?old_len - new_len :0 ; 385for (size_t i = 0 ;i < to_delete ;i ++ ) { 386if (ml_delete_buf (b , (linenr_T )start , false)== FAIL ) { 387api_set_error (err ,kErrorTypeException ,"Failed to delete line" ); 388 gotoend ; 389 } 390 } 391 392if (to_delete > 0 ) { 393extra -= (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. 399size_t to_replace = old_len < new_len ?old_len :new_len ; 400bcount_t inserted_bytes = 0 ; 401for (size_t i = 0 ;i < to_replace ;i ++ ) { 402int64_t lnum = start + (int64_t )i ; 403 404VALIDATE (lnum < MAXLNUM ,"%s" ,"Index out of bounds" , { 405 gotoend ; 406 }); 407 408if (ml_replace_buf (b , (linenr_T )lnum ,lines [i ], false, true)== FAIL ) { 409api_set_error (err ,kErrorTypeException ,"Failed to replace line" ); 410 gotoend ; 411 } 412 413inserted_bytes += (bcount_t )strlen (lines [i ])+ 1 ; 414 } 415 416// Now we may need to insert the remaining new old_len 417for (size_t i = to_replace ;i < new_len ;i ++ ) { 418int64_t lnum = start + (int64_t )i - 1 ; 419 420VALIDATE (lnum < MAXLNUM ,"%s" ,"Index out of bounds" , { 421 gotoend ; 422 }); 423 424if (ml_append_buf (b , (linenr_T )lnum ,lines [i ],0 , false)== FAIL ) { 425api_set_error (err ,kErrorTypeException ,"Failed to insert line" ); 426 gotoend ; 427 } 428 429inserted_bytes += (bcount_t )strlen (lines [i ])+ 1 ; 430 431extra ++ ; 432 } 433 434// Adjust marks. Invalidate any which lie in the 435// changed range, and move any in the remainder of the buffer. 436linenr_T adjust = end > start ?MAXLNUM :0 ; 437mark_adjust_buf (b , (linenr_T )start , (linenr_T )(end - 1 ),adjust , (linenr_T )extra , 438 true,kMarkAdjustApi ,kExtmarkNOOP ); 439 440if (Visual .active && b == curbuf && Visual .start .lnum >= (linenr_T )start ) { 441if (Visual .start .lnum >= (linenr_T )end ) { 442Visual .start .lnum += (linenr_T )extra ; 443 } 444check_visual_pos (); 445 } 446 447extmark_splice (b , (int )start - 1 ,0 , (int )(end - start ),0 , 448deleted_bytes , (int )new_len ,0 ,inserted_bytes , 449kExtmarkUndo ); 450 451changed_lines (b , (linenr_T )start ,0 , (linenr_T )end , (linenr_T )extra , true); 452 453FOR_ALL_TAB_WINDOWS (tp ,win ) { 454if (win -> w_buffer == b ) { 455fix_cursor (win , (linenr_T )start , (linenr_T )end , (linenr_T )extra ); 456 } 457 } 458end :; 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 , 487Integer end_row ,Integer end_col ,ArrayOf (String )replacement ,Arena * arena , 488Error * err ) 489FUNC_API_SINCE (7 ) 490FUNC_API_TEXTLOCK 491{ 492MAXSIZE_TEMP_ARRAY (scratch ,1 ); 493if (replacement .size == 0 ) { 494ADD_C (scratch ,STATIC_CSTR_AS_OBJ ("" )); 495replacement = scratch ; 496 } 497 498buf_T * b = api_buf_ensure_loaded (buf ,err ); 499if (!b ) { 500return ; 501 } 502 503bool oob = false; 504 505// check range is ordered and everything! 506// start_row, end_row within buffer len (except add text past the end?) 507start_row = normalize_index (b ,start_row , false,& oob ); 508VALIDATE_RANGE ((!oob ),"start_row" , { 509return ; 510 }); 511 512end_row = normalize_index (b ,end_row , false,& oob ); 513VALIDATE_RANGE ((!oob ),"end_row" , { 514return ; 515 }); 516 517// Another call to ml_get_buf() may free the lines, so we make copies 518char * str_at_start = ml_get_buf (b , (linenr_T )start_row ); 519colnr_T len_at_start = ml_get_buf_len (b , (linenr_T )start_row ); 520str_at_start = arena_memdupz (arena ,str_at_start , (size_t )len_at_start ); 521start_col = start_col < 0 ?len_at_start + start_col + 1 :start_col ; 522VALIDATE_RANGE ((start_col >=0 && start_col <=len_at_start ),"start_col" , { 523return ; 524 }); 525 526char * str_at_end = ml_get_buf (b , (linenr_T )end_row ); 527colnr_T len_at_end = ml_get_buf_len (b , (linenr_T )end_row ); 528str_at_end = arena_memdupz (arena ,str_at_end , (size_t )len_at_end ); 529end_col = end_col < 0 ?len_at_end + end_col + 1 :end_col ; 530VALIDATE_RANGE ((end_col >=0 && end_col <=len_at_end ),"end_col" , { 531return ; 532 }); 533 534VALIDATE ((start_row <=end_row && !(end_row == start_row && start_col > end_col )), 535"%s" ,"'start' is higher than 'end'" , { 536return ; 537 }); 538 539bool disallow_nl = (channel_id != VIML_INTERNAL_CALL ); 540if (!check_string_array (replacement ,"replacement string" ,disallow_nl ,err )) { 541return ; 542 } 543 544size_t new_len = replacement .size ; 545 546bcount_t new_byte = 0 ; 547bcount_t old_byte = 0 ; 548 549// calculate byte size of old region before it gets modified/deleted 550if (start_row == end_row ) { 551old_byte = (bcount_t )end_col - start_col ; 552 }else { 553old_byte += len_at_start - start_col ; 554for (int64_t i = 1 ;i < end_row - start_row ;i ++ ) { 555int64_t lnum = start_row + i ; 556old_byte += ml_get_buf_len (b , (linenr_T )lnum )+ 1 ; 557 } 558old_byte += (bcount_t )end_col + 1 ; 559 } 560 561String first_item = replacement .items [0 ].data .string ; 562String last_item = replacement .items [replacement .size - 1 ].data .string ; 563 564size_t firstlen = (size_t )start_col + first_item .size ; 565size_t last_part_len = (size_t )len_at_end - (size_t )end_col ; 566if (replacement .size == 1 ) { 567firstlen += last_part_len ; 568 } 569char * first = arena_allocz (arena ,firstlen ); 570char * last = NULL ; 571memcpy (first ,str_at_start , (size_t )start_col ); 572memcpy (first + start_col ,first_item .data ,first_item .size ); 573memchrsub (first + start_col ,NUL ,NL ,first_item .size ); 574if (replacement .size == 1 ) { 575memcpy (first + start_col + first_item .size ,str_at_end + end_col ,last_part_len ); 576 }else { 577last = arena_allocz (arena ,last_item .size + last_part_len ); 578memcpy (last ,last_item .data ,last_item .size ); 579memchrsub (last ,NUL ,NL ,last_item .size ); 580memcpy (last + last_item .size ,str_at_end + end_col ,last_part_len ); 581 } 582 583char ** lines = arena_alloc (arena ,new_len * sizeof (char * ), true); 584lines [0 ]= first ; 585new_byte += (bcount_t )(first_item .size ); 586for (size_t i = 1 ;i < new_len - 1 ;i ++ ) { 587const 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. 591lines [i ]= arena_memdupz (arena ,l .data ,l .size ); 592memchrsub (lines [i ],NUL ,NL ,l .size ); 593new_byte += (bcount_t )(l .size )+ 1 ; 594 } 595if (replacement .size > 1 ) { 596lines [replacement .size - 1 ]= last ; 597new_byte += (bcount_t )(last_item .size )+ 1 ; 598 } 599 600TRY_WRAP (err , { 601if (!MODIFIABLE (b )) { 602api_set_error (err ,kErrorTypeException ,"Buffer is not 'modifiable'" ); 603 gotoend ; 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. 608if (u_save_buf (b , (linenr_T )start_row - 1 , (linenr_T )end_row + 1 )== FAIL ) { 609api_set_error (err ,kErrorTypeException ,"Failed to save undo information" ); 610 gotoend ; 611 } 612 613ptrdiff_t extra = 0 ;// lines added to text, can be negative 614size_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". 619size_t to_delete = (new_len < old_len ) ?old_len - new_len :0 ; 620for (size_t i = 0 ;i < to_delete ;i ++ ) { 621if (ml_delete_buf (b , (linenr_T )start_row , false)== FAIL ) { 622api_set_error (err ,kErrorTypeException ,"Failed to delete line" ); 623 gotoend ; 624 } 625 } 626 627if (to_delete > 0 ) { 628extra -= (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. 634size_t to_replace = old_len < new_len ?old_len :new_len ; 635for (size_t i = 0 ;i < to_replace ;i ++ ) { 636int64_t lnum = start_row + (int64_t )i ; 637 638VALIDATE ((lnum < MAXLNUM ),"%s" ,"Index out of bounds" , { 639 gotoend ; 640 }); 641 642if (ml_replace_buf (b , (linenr_T )lnum ,lines [i ], false, true)== FAIL ) { 643api_set_error (err ,kErrorTypeException ,"Failed to replace line" ); 644 gotoend ; 645 } 646 } 647 648// Now we may need to insert the remaining new old_len 649for (size_t i = to_replace ;i < new_len ;i ++ ) { 650int64_t lnum = start_row + (int64_t )i - 1 ; 651 652VALIDATE ((lnum < MAXLNUM ),"%s" ,"Index out of bounds" , { 653 gotoend ; 654 }); 655 656if (ml_append_buf (b , (linenr_T )lnum ,lines [i ],0 , false)== FAIL ) { 657api_set_error (err ,kErrorTypeException ,"Failed to insert line" ); 658 gotoend ; 659 } 660 661extra ++ ; 662 } 663 664colnr_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) 670linenr_T adjust = end_row >=start_row ?MAXLNUM :0 ; 671mark_adjust_buf (b , (linenr_T )start_row , (linenr_T )end_row - 1 ,adjust , (linenr_T )extra , 672 true,kMarkAdjustApi ,kExtmarkNOOP ); 673 674if (Visual .active && b == curbuf && Visual .mode != Ctrl_V ) { 675fix_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 ); 677check_visual_pos (); 678 } 679 680extmark_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 , 683kExtmarkUndo ); 684 685changed_lines (b , (linenr_T )start_row , (colnr_T )start_col , (linenr_T )end_row + 1 , 686 (linenr_T )extra , true); 687 688FOR_ALL_TAB_WINDOWS (tp ,win ) { 689if (win -> w_buffer == b ) { 690if (win -> w_cursor .lnum >=start_row && win -> w_cursor .lnum <=end_row ) { 691fix_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 { 694fix_cursor (win , (linenr_T )start_row , (linenr_T )end_row , (linenr_T )extra ); 695 } 696 } 697 } 698end :; 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 , 719Integer start_row ,Integer start_col , 720Integer end_row ,Integer end_col , 721Dict (empty )* opts , 722Arena * arena ,lua_State * lstate ,Error * err ) 723FUNC_API_SINCE (9 ) 724{ 725Array rv = ARRAY_DICT_INIT ; 726 727buf_T * b = find_buffer_by_handle (buf ,err ); 728 729if (!b ) { 730return rv ; 731 } 732 733// return sentinel value if the buffer isn't loaded 734if (b -> b_ml .ml_mfp == NULL ) { 735init_line_array (lstate ,& rv ,0 ,arena ); 736return rv ; 737 } 738 739bool oob = false; 740start_row = normalize_index (b ,start_row , false,& oob ); 741end_row = normalize_index (b ,end_row , false,& oob ); 742 743VALIDATE ((!oob ),"%s" ,"Index out of bounds" , { 744return 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. 750VALIDATE ((start_row <=end_row ),"%s" ,"'start' is higher than 'end'" , { 751return rv ; 752 }); 753 754bool replace_nl = (channel_id != VIML_INTERNAL_CALL ); 755 756size_t size = (size_t )(end_row - start_row )+ 1 ; 757 758init_line_array (lstate ,& rv ,size ,arena ); 759 760if (start_row == end_row ) { 761String line = buf_get_text (b ,start_row ,start_col ,end_col ,err ); 762if (ERROR_SET (err )) { 763 gotoend ; 764 } 765push_linestr (lstate ,& rv ,line .data ,line .size ,0 ,replace_nl ,arena ); 766return rv ; 767 } 768 769String str = buf_get_text (b ,start_row ,start_col ,MAXCOL - 1 ,err ); 770if (ERROR_SET (err )) { 771 gotoend ; 772 } 773 774push_linestr (lstate ,& rv ,str .data ,str .size ,0 ,replace_nl ,arena ); 775 776if (size > 2 ) { 777buf_collect_lines (b ,size - 2 , (linenr_T )start_row + 1 ,1 ,replace_nl ,& rv ,lstate ,arena ); 778 } 779 780str = buf_get_text (b ,end_row ,0 ,end_col ,err ); 781if (ERROR_SET (err )) { 782 gotoend ; 783 } 784 785push_linestr (lstate ,& rv ,str .data ,str .size , (int )(size - 1 ),replace_nl ,arena ); 786 787end : 788if (ERROR_SET (err )) { 789return (Array )ARRAY_DICT_INIT ; 790 } 791 792return 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 ) 810FUNC_API_SINCE (5 ) 811{ 812buf_T * b = find_buffer_by_handle (buf ,err ); 813if (!b ) { 814return 0 ; 815 } 816 817// return sentinel value if the buffer isn't loaded 818if (b -> b_ml .ml_mfp == NULL ) { 819return -1 ; 820 } 821 822VALIDATE ((index >=0 && index <=b -> b_ml .ml_line_count ),"%s" ,"Index out of bounds" , { 823return 0 ; 824 }); 825 826return 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 ) 836FUNC_API_SINCE (1 ) 837{ 838buf_T * b = find_buffer_by_handle (buf ,err ); 839 840if (!b ) { 841return (Object )OBJECT_INIT ; 842 } 843 844return 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 ) 854FUNC_API_SINCE (2 ) 855{ 856const buf_T * const b = find_buffer_by_handle (buf ,err ); 857 858if (!b ) { 859return -1 ; 860 } 861 862return 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 , 873Error * err ) 874FUNC_API_SINCE (3 ) 875{ 876buf_T * b = find_buffer_by_handle (buf ,err ); 877 878if (!b ) { 879return (Array )ARRAY_DICT_INIT ; 880 } 881 882return 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 , 891Dict (keymap )* opts ,Error * err ) 892FUNC_API_SINCE (6 ) 893{ 894modify_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 , 907Dict (keymap_del )* opts ,Error * err ) 908FUNC_API_SINCE (6 ) 909{ 910String rhs = { .data = "" , .size = 0 }; 911int maptype = opts && opts -> lhs ?MAPTYPE_UNMAP_LHS :MAPTYPE_UNMAP ; 912modify_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 ) 922FUNC_API_SINCE (1 ) 923{ 924buf_T * b = find_buffer_by_handle (buf ,err ); 925 926if (!b ) { 927return ; 928 } 929 930dict_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 ) 939FUNC_API_SINCE (1 ) 940{ 941buf_T * b = find_buffer_by_handle (buf ,err ); 942 943if (!b ) { 944return ; 945 } 946 947dict_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 ) 959FUNC_API_SINCE (1 ) 960{ 961String rv = STRING_INIT ; 962buf_T * b = find_buffer_by_handle (buf ,err ); 963 964if (!b || b -> b_ffname == NULL ) { 965return rv ; 966 } 967 968return 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 ) 977FUNC_API_SINCE (1 ) 978{ 979buf_T * b = find_buffer_by_handle (buf ,err ); 980 981if (!b ) { 982return ; 983 } 984 985int ren_ret = OK ; 986TRY_WRAP (err , { 987const bool is_curbuf = b == curbuf ; 988const int save_acd = p_acd ; 989if (!is_curbuf ) { 990// Don't update 'title' and 'autochdir' when setting file name for another buffer. 991RedrawingDisabled ++ ; 992p_acd = false; 993 } 994 995// Switch context to `b`: autocommands will be executed by rename_buffer 996CtxSwitch aco = {0 }; 997ctx_switch (& aco ,NULL ,NULL ,b ,0 ); 998ren_ret = rename_buffer (name .data ); 999ctx_restore (& aco ); 1000 1001if (!is_curbuf ) { 1002RedrawingDisabled -- ; 1003p_acd = save_acd ; 1004 } 1005 }); 1006 1007if (ERROR_SET (err )) { 1008return ; 1009 } 1010 1011if (ren_ret == FAIL ) { 1012api_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 ) 1022FUNC_API_SINCE (5 ) 1023{ 1024Error stub = ERROR_INIT ; 1025buf_T * b = find_buffer_by_handle (buf ,& stub ); 1026api_clear_error (& stub ); 1027return 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 ) 1043FUNC_API_SINCE (7 ) 1044FUNC_API_TEXTLOCK 1045{ 1046buf_T * b = find_buffer_by_handle (buf ,err ); 1047 1048if (ERROR_SET (err )) { 1049return ; 1050 } 1051 1052bool force = opts -> force ; 1053 1054bool unload = opts -> unload ; 1055 1056int result = do_buffer (unload ?DOBUF_UNLOAD :DOBUF_WIPE , 1057DOBUF_FIRST , 1058FORWARD , 1059b -> handle , 1060force ); 1061 1062if (result == FAIL ) { 1063api_set_error (err ,kErrorTypeException ,"Failed to unload buffer." ); 1064return ; 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 ) 1076FUNC_API_SINCE (1 ) 1077{ 1078Error stub = ERROR_INIT ; 1079Boolean ret = find_buffer_by_handle (buf ,& stub )!= NULL ; 1080api_clear_error (& stub ); 1081return 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 ) 1094FUNC_API_SINCE (8 ) 1095{ 1096bool res = false; 1097buf_T * b = find_buffer_by_handle (buf ,err ); 1098 1099if (!b ) { 1100return res ; 1101 } 1102 1103VALIDATE_S ((name .size == 1 ),"mark name (must be a single char)" ,name .data , { 1104return res ; 1105 }); 1106 1107fmark_T * fm = mark_get (b ,curwin ,NULL ,kMarkAllNoResolve ,* name .data ); 1108 1109// fm is NULL when there's no mark with the given name 1110VALIDATE_S ((fm != NULL ),"mark name" ,name .data , { 1111return res ; 1112 }); 1113 1114// mark.lnum is 0 when the mark is not valid in the buffer, or is not set. 1115if (fm -> mark .lnum != 0 && fm -> fnum == b -> handle ) { 1116// since the mark belongs to the buffer delete it. 1117res = set_mark (b ,name ,0 ,0 ,err ); 1118 } 1119 1120return 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 , 1139Error * err ) 1140FUNC_API_SINCE (8 ) 1141{ 1142bool res = false; 1143buf_T * b = api_buf_ensure_loaded (buf ,err ); 1144 1145if (!b ) { 1146return res ; 1147 } 1148 1149VALIDATE_S ((name .size == 1 ),"mark name (must be a single char)" ,name .data , { 1150return res ; 1151 }); 1152 1153res = set_mark (b ,name ,line ,col ,err ); 1154 1155return 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 ) 1172FUNC_API_SINCE (1 ) 1173{ 1174Array rv = ARRAY_DICT_INIT ; 1175buf_T * b = find_buffer_by_handle (buf ,err ); 1176 1177if (!b ) { 1178return rv ; 1179 } 1180 1181VALIDATE_S ((name .size == 1 ),"mark name (must be a single char)" ,name .data , { 1182return rv ; 1183 }); 1184 1185fmark_T * fm ; 1186pos_T pos ; 1187char mark = * name .data ; 1188 1189fm = mark_get (b ,curwin ,NULL ,kMarkAllNoResolve ,mark ); 1190VALIDATE_S ((fm != NULL ),"mark name" ,name .data , { 1191return rv ; 1192 }); 1193// (0, 0) uppercase/file mark set in another buffer. 1194if (fm -> fnum != b -> handle ) { 1195pos .lnum = 0 ; 1196pos .col = 0 ; 1197 }else { 1198pos = fm -> mark ; 1199 } 1200 1201rv = arena_array (arena ,2 ); 1202ADD_C (rv ,INTEGER_OBJ (pos .lnum )); 1203ADD_C (rv ,INTEGER_OBJ (pos .col )); 1204 1205return 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 ) 1226FUNC_API_SINCE (7 ) 1227FUNC_API_LUA_ONLY 1228{ 1229buf_T * b = find_buffer_by_handle (buf ,err ); 1230if (!b ) { 1231return NIL ; 1232 } 1233 1234TRY_WRAP (err , { 1235CtxSwitch cs = {0 }; 1236ctx_switch (& cs ,NULL ,NULL ,b ,0 ); 1237 1238Array args = ARRAY_DICT_INIT ; 1239nlua_call_ref (fn ,NULL ,args ,kRetMultiStack ,NULL ,err ); 1240 1241ctx_restore (& cs ); 1242 }); 1243 1244return NIL ;// kRetMultiStack: values are already on the lua stack 1245} 1246 1247/// @nodoc 1248Dict nvim__buf_stats (Buffer buf ,Arena * arena ,Error * err ) 1249{ 1250buf_T * b = find_buffer_by_handle (buf ,err ); 1251if (!b ) { 1252return (Dict )ARRAY_DICT_INIT ; 1253 } 1254 1255Dict 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. 1259PUT_C (rv ,"flush_count" ,INTEGER_OBJ (b -> flush_count )); 1260// lnum of current line 1261PUT_C (rv ,"current_lnum" ,INTEGER_OBJ (b -> b_ml .ml_line_lnum )); 1262// whether the line has unflushed changes. 1263PUT_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 1266PUT_C (rv ,"dirty_bytes" ,INTEGER_OBJ ((Integer )b -> deleted_bytes )); 1267PUT_C (rv ,"dirty_bytes2" ,INTEGER_OBJ ((Integer )b -> deleted_bytes2 )); 1268PUT_C (rv ,"virt_blocks" ,INTEGER_OBJ ((Integer )buf_meta_total (b ,kMTMetaLines ))); 1269 1270u_header_T * uhp = NULL ; 1271if (b -> b_u_curhead != NULL ) { 1272uhp = b -> b_u_curhead ; 1273 }else if (b -> b_u_newhead ) { 1274uhp = b -> b_u_newhead ; 1275 } 1276if (uhp ) { 1277PUT_C (rv ,"uhp_extmark_size" ,INTEGER_OBJ ((Integer )kv_size (uhp -> uh_extmark ))); 1278 } 1279 1280return 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{ 1287if (win -> w_cursor .lnum >=lo ) { 1288// Adjust cursor position if it's in/after the changed lines. 1289if (win -> w_cursor .lnum >=hi ) { 1290win -> w_cursor .lnum += extra ; 1291 }else if (extra < 0 ) { 1292check_cursor_lnum (win ); 1293 } 1294check_cursor_col (win ); 1295changed_cline_bef_curs (win ); 1296win -> w_valid &= ~(VALID_BOTLINE_AP ); 1297update_topline (win ); 1298 }else { 1299invalidate_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 , 1306linenr_T end_row ,colnr_T end_col ,linenr_T new_rows , 1307colnr_T new_cols_at_end_row ,colnr_T mode_col_adj ) 1308{ 1309if (pos -> lnum < start_row ) { 1310return ; 1311 } 1312 1313linenr_T old_rows = end_row - start_row + 1 ; 1314linenr_T lnum_shift = new_rows - old_rows ; 1315 1316if (pos -> lnum > end_row ) { 1317pos -> lnum += lnum_shift ; 1318return ; 1319 } 1320 1321colnr_T end_row_change_start = new_rows == 1 ?start_col :0 ; 1322colnr_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 1325if (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 1328pos -> lnum += lnum_shift ; 1329pos -> col += end_row_change_end - end_col ; 1330return ; 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 1340colnr_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 1345pos -> col += pos -> coladd ; 1346pos -> coladd = 0 ; 1347 1348linenr_T new_end_row = start_row + new_rows - 1 ; 1349 1350// make sure pos row is in the new row range 1351if (pos -> lnum > new_end_row ) { 1352pos -> 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 1359colnr_T len = ml_get_buf_len (buf ,new_end_row ); 1360if (pos -> col < len ) { 1361pos -> 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 1368if (pos -> lnum == new_end_row 1369&& pos -> col > end_row_change_end && old_coladd == 0 ) { 1370pos -> 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 1374if (pos -> col - mode_col_adj >=end_row_change_start ) { 1375pos -> 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 , 1385colnr_T end_col ,linenr_T new_rows ,colnr_T new_cols_at_end_row ) 1386{ 1387colnr_T mode_col_adj = (win == curwin && (State & MODE_INSERT )) ?0 :1 ; 1388fix_pos_col (win -> w_buffer ,& win -> w_cursor , 1389start_row ,start_col ,end_row ,end_col , 1390new_rows ,new_cols_at_end_row ,mode_col_adj ); 1391 1392check_cursor_col (win ); 1393changed_cline_bef_curs (win ); 1394invalidate_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{ 1406if (lstate ) { 1407lua_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 , 1425bool replace_nl ,Arena * arena ) 1426{ 1427if (lstate ) { 1428// Vim represents NULs as NLs 1429if (s && replace_nl && strchr (s ,'\n' )) { 1430// TODO(bfredl): could manage scratch space in the arena, for the NUL case 1431char * tmp = xmemdupz (s ,len ); 1432strchrsub (tmp ,'\n' ,NUL ); 1433lua_pushlstring (lstate ,tmp ,len ); 1434xfree (tmp ); 1435 }else { 1436lua_pushlstring (lstate ,s ,len ); 1437 } 1438lua_rawseti (lstate ,-2 ,idx + 1 ); 1439 }else { 1440String str = STRING_INIT ; 1441if (len > 0 ) { 1442str = CBUF_TO_ARENA_STR (arena ,s ,len ); 1443if (replace_nl ) { 1444// Vim represents NULs as NLs, but this may confuse clients. 1445strchrsub (str .data ,'\n' ,NUL ); 1446 } 1447 } 1448 1449ADD_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 , 1466Array * l ,lua_State * lstate ,Arena * arena ) 1467{ 1468for (size_t i = 0 ;i < n ;i ++ ) { 1469linenr_T lnum = start + (linenr_T )i ; 1470char * bufstr = ml_get_buf (buf ,lnum ); 1471size_t bufstrlen = (size_t )ml_get_buf_len (buf ,lnum ); 1472push_linestr (lstate ,l ,bufstr ,bufstrlen ,start_idx + (int )i ,replace_nl ,arena ); 1473 } 1474}