robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// register.c: functions for managing registers 2 3#include "nvim/api/private/helpers.h" 4#include "nvim/autocmd.h" 5#include "nvim/buffer.h" 6#include "nvim/buffer_defs.h" 7#include "nvim/buffer_updates.h" 8#include "nvim/change.h" 9#include "nvim/charset.h" 10#include "nvim/clipboard.h" 11#include "nvim/cursor.h" 12#include "nvim/drawscreen.h" 13#include "nvim/errors.h" 14#include "nvim/eval.h" 15#include "nvim/eval/typval.h" 16#include "nvim/ex_cmds2.h" 17#include "nvim/ex_docmd.h" 18#include "nvim/ex_getln.h" 19#include "nvim/extmark.h" 20#include "nvim/file_search.h" 21#include "nvim/fold.h" 22#include "nvim/garray.h" 23#include "nvim/globals.h" 24#include "nvim/indent.h" 25#include "nvim/input.h" 26#include "nvim/insert.h" 27#include "nvim/insexpand.h" 28#include "nvim/keycodes.h" 29#include "nvim/mark.h" 30#include "nvim/mbyte.h" 31#include "nvim/mcursor.h" 32#include "nvim/memline.h" 33#include "nvim/message.h" 34#include "nvim/move.h" 35#include "nvim/normal.h" 36#include "nvim/ops.h" 37#include "nvim/option.h" 38#include "nvim/option_vars.h" 39#include "nvim/os/input.h" 40#include "nvim/os/time.h" 41#include "nvim/plines.h" 42#include "nvim/register.h" 43#include "nvim/search.h" 44#include "nvim/strings.h" 45#include "nvim/terminal.h" 46#include "nvim/types_defs.h" 47#include "nvim/ui.h" 48#include "nvim/undo.h" 49 50#include "register.c.generated.h" 51 52// Keep the last expression line here, for repeating. 53static char * expr_line = NULL ; 54 55static int execreg_lastc = NUL ; 56 57static yankreg_T y_regs [NUM_REGISTERS ]= {0 }; 58 59static yankreg_T * y_previous = NULL ;// ptr to last written yankreg 60 61static const char e_register_char_cannot_contain_multiple_lines [] 62= N_ ("E883: Register '%c' cannot contain multiple lines" ); 63 64/// @return the index of the register "" points to. 65int get_unname_register (void ) 66{ 67return y_previous == NULL ?-1 : (int )(y_previous - & y_regs [0 ]); 68} 69 70yankreg_T * get_y_register (int reg ) 71{ 72return & y_regs [reg ]; 73} 74 75/// What `p` pastes: the last-written register (x: -, yy: 0, "+yy: +, :let @"=…: 0). 76/// 77/// Exception: with clipboard=unnamed/unnamedplus, `p` tries the provider first. 78yankreg_T * get_y_previous (void ) 79FUNC_ATTR_PURE 80{ 81return y_previous ; 82} 83 84/// Get an expression for the "\"=expr1" or "CTRL-R =expr1" 85/// 86/// @return '=' when OK, NUL otherwise. 87int get_expr_register (void ) 88{ 89char * new_line = getcmdline ('=' ,0 ,0 , true); 90if (new_line == NULL ) { 91return NUL ; 92 } 93if (* new_line == NUL ) {// use previous line 94xfree (new_line ); 95 }else { 96set_expr_line (new_line ); 97 } 98return '=' ; 99} 100 101/// Set the expression for the '=' register. 102/// Argument must be an allocated string. 103void set_expr_line (char * new_line ) 104{ 105xfree (expr_line ); 106expr_line = new_line ; 107} 108 109/// Get the result of the '=' register expression. 110/// 111/// @return a pointer to allocated memory, or NULL for failure. 112char * get_expr_line (void ) 113{ 114static int nested = 0 ; 115 116if (expr_line == NULL ) { 117return NULL ; 118 } 119 120// Make a copy of the expression, because evaluating it may cause it to be 121// changed. 122char * expr_copy = xstrdup (expr_line ); 123 124// When we are invoked recursively limit the evaluation to 10 levels. 125// Then return the string as-is. 126if (nested >=10 ) { 127return expr_copy ; 128 } 129 130nested ++ ; 131char * rv = eval_to_string (expr_copy , true, false); 132nested -- ; 133xfree (expr_copy ); 134return rv ; 135} 136 137/// Get the '=' register expression itself, without evaluating it. 138char * get_expr_line_src (void ) 139{ 140if (expr_line == NULL ) { 141return NULL ; 142 } 143return xstrdup (expr_line ); 144} 145 146/// @return whether `regname` is a valid name of a yank register. 147/// 148/// @note: There is no check for 0 (default register), caller should do this. 149/// The black hole register '_' is regarded as valid. 150/// 151/// @param regname name of register 152/// @param writing allow only writable registers 153bool valid_yank_reg (int regname ,bool writing ) 154{ 155if ((regname > 0 && ASCII_ISALNUM (regname )) 156|| (!writing && vim_strchr ("/#.%:=" ,regname )!= NULL ) 157|| regname == '"' 158|| regname == '-' 159|| regname == '_' 160|| regname == '*' 161|| regname == '+' ) { 162return true; 163 } 164return false; 165} 166 167/// Check if the default register (used in an unnamed paste) should be a 168/// clipboard register. This happens when `clipboard=unnamed[plus]` is set 169/// and a provider is available. 170/// 171/// @returns the name of a clipboard register that should be used, or `NUL` if none. 172int get_default_register_name (void ) 173{ 174int name = NUL ; 175adjust_clipboard_name (& name , true, false); 176return name ; 177} 178 179/// Iterate over registers `regs` (only NUM_SAVED_REGISTERS, not clipboard "*"/"+"). 180/// 181/// @param[in] iter Iterator. Pass NULL to start iteration. 182/// @param[in] regs Registers list to be iterated. 183/// @param[out] name Register name. 184/// @param[out] reg Register contents. 185/// 186/// @return Pointer that must be passed to next `op_register_iter` call or 187/// NULL if iteration is over. 188const void * op_reg_iter (const void * const iter ,const yankreg_T * const regs ,char * const name , 189yankreg_T * const reg ,bool * is_unnamed ) 190FUNC_ATTR_NONNULL_ARG (3 ,4 ,5 )FUNC_ATTR_WARN_UNUSED_RESULT 191{ 192* name = NUL ; 193const yankreg_T * iter_reg = (iter == NULL 194 ?& (regs [0 ]) 195 : (const yankreg_T * const )iter ); 196while (iter_reg - & (regs [0 ])< NUM_SAVED_REGISTERS && reg_empty (iter_reg )) { 197iter_reg ++ ; 198 } 199if (iter_reg - & (regs [0 ])== NUM_SAVED_REGISTERS || reg_empty (iter_reg )) { 200return NULL ; 201 } 202int iter_off = (int )(iter_reg - & (regs [0 ])); 203* name = (char )get_register_name (iter_off ); 204* reg = * iter_reg ; 205* is_unnamed = (iter_reg == y_previous ); 206while (++ iter_reg - & (regs [0 ])< NUM_SAVED_REGISTERS ) { 207if (!reg_empty (iter_reg )) { 208return (void * )iter_reg ; 209 } 210 } 211return NULL ; 212} 213 214/// Iterate over global registers (only NUM_SAVED_REGISTERS, not clipboard "*"/"+"). 215/// 216/// @see op_register_iter 217const void * op_global_reg_iter (const void * const iter ,char * const name ,yankreg_T * const reg , 218bool * is_unnamed ) 219FUNC_ATTR_NONNULL_ARG (2 ,3 ,4 )FUNC_ATTR_WARN_UNUSED_RESULT 220{ 221return op_reg_iter (iter ,y_regs ,name ,reg ,is_unnamed ); 222} 223 224/// Gets the most-recent timestamp (nanoseconds) of all registers, or 0 if all are empty. Every 225/// register-write sets its timestamp, so this detects if any register changed (e.g. for caching). 226/// 227/// @param clipboard Include clipboard registers ("*"/"+"). 228Timestamp reg_max_ts (bool clipboard ) 229{ 230Timestamp max_ts = 0 ; 231const void * iter = NULL ; 232do { 233char name = NUL ; 234yankreg_T reg ; 235bool is_unnamed = false; 236iter = op_global_reg_iter (iter ,& name ,& reg ,& is_unnamed ); 237if (name == NUL ) { 238break ; 239 } 240max_ts = MAX (max_ts ,reg .timestamp ); 241 }while (iter != NULL ); 242if (clipboard ) { 243max_ts = MAX (max_ts ,get_y_register (op_reg_index ('*' ))-> timestamp ); 244max_ts = MAX (max_ts ,get_y_register (op_reg_index ('+' ))-> timestamp ); 245 } 246return max_ts ; 247} 248 249/// Get a number of non-empty registers 250size_t op_reg_amount (void ) 251FUNC_ATTR_WARN_UNUSED_RESULT 252{ 253size_t ret = 0 ; 254for (size_t i = 0 ;i < NUM_SAVED_REGISTERS ;i ++ ) { 255if (!reg_empty (y_regs + i )) { 256ret ++ ; 257 } 258 } 259return ret ; 260} 261 262/// Set register to a given value 263/// 264/// @param[in] name Register name. 265/// @param[in] reg Register value. 266/// @param[in] is_unnamed Whether to set the unnamed regiseter to reg 267/// 268/// @return true on success, false on failure. 269bool op_reg_set (const char name ,const yankreg_T reg ,bool is_unnamed ) 270{ 271int i = op_reg_index (name ); 272if (i == -1 ) { 273return false; 274 } 275free_register (& y_regs [i ]); 276y_regs [i ]= reg ; 277 278if (is_unnamed ) { 279y_previous = & y_regs [i ]; 280 } 281return true; 282} 283 284/// Get register with the given name 285/// 286/// @param[in] name Register name. 287/// 288/// @return Pointer to the register contents or NULL. 289const yankreg_T * op_reg_get (const char name ) 290{ 291int i = op_reg_index (name ); 292if (i == -1 ) { 293return NULL ; 294 } 295return & y_regs [i ]; 296} 297 298/// Set the previous yank register 299/// 300/// @param[in] name Register name. 301/// 302/// @return true on success, false on failure. 303bool op_reg_set_previous (const char name ) 304{ 305int i = op_reg_index (name ); 306if (i == -1 ) { 307return false; 308 } 309 310y_previous = & y_regs [i ]; 311return true; 312} 313 314/// Updates the "y_width" of a blockwise register based on its contents. 315/// Do nothing on a non-blockwise register. 316void update_yankreg_width (yankreg_T * reg ) 317{ 318if (reg -> y_type == kMTBlockWise ) { 319size_t maxlen = 0 ; 320for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 321size_t rowlen = mb_string2cells_len (reg -> y_array [i ].data ,reg -> y_array [i ].size ); 322maxlen = MAX (maxlen ,rowlen ); 323 } 324assert (maxlen <=INT_MAX ); 325reg -> y_width = MAX (reg -> y_width , (int )maxlen - 1 ); 326 } 327} 328 329/// @return yankreg_T to use, according to the value of `regname`. 330/// Cannot handle the '_' (black hole) register. 331/// Must only be called with a valid register name! 332/// 333/// @param regname The name of the register used or 0 for the unnamed register 334/// @param mode One of the following three flags: 335/// 336/// `YREG_PASTE`: 337/// Prepare for pasting the register `regname`. With no regname specified, 338/// read from last written register, or from unnamed clipboard (depending on the 339/// `clipboard=unnamed` option). Queries the clipboard provider if necessary. 340/// 341/// `YREG_YANK`: 342/// Preparare for yanking into `regname`. With no regname specified, 343/// yank into `"0` register. Update `y_previous` for next unnamed paste. 344/// 345/// `YREG_PUT`: 346/// Obtain the location that would be read when pasting `regname`. 347yankreg_T * get_yank_register (int regname ,int mode ) 348{ 349yankreg_T * reg ; 350 351if ((mode == YREG_PASTE || mode == YREG_PUT ) 352&& get_clipboard (regname ,& reg , false)) { 353// reg is set to clipboard contents. 354return reg ; 355 }else if (mode == YREG_PUT && (regname == '*' || regname == '+' )) { 356// in case clipboard not available and we aren't actually pasting, 357// return an empty register 358static yankreg_T empty_reg = { .y_array = NULL }; 359return & empty_reg ; 360 }else if (mode != YREG_YANK 361&& (regname == 0 || regname == '"' || regname == '*' || regname == '+' ) 362&& y_previous != NULL ) { 363// in case clipboard not available, paste from previous used register 364return y_previous ; 365 } 366 367int i = op_reg_index (regname ); 368// when not 0-9, a-z, A-Z or '-'/'+'/'*': use register 0 369if (i == -1 ) { 370i = 0 ; 371 } 372reg = & y_regs [i ]; 373 374if (mode == YREG_YANK ) { 375// remember the written register for unnamed paste 376y_previous = reg ; 377 } 378return reg ; 379} 380 381/// Check if the current yank register has kMTLineWise register type 382/// For valid, non-blackhole registers also provides pointer to the register 383/// structure prepared for pasting. 384/// 385/// @param regname The name of the register used or 0 for the unnamed register 386/// @param reg Pointer to store yankreg_T* for the requested register. Will be 387/// set to NULL for invalid or blackhole registers. 388bool yank_register_mline (int regname ,yankreg_T ** reg ) 389{ 390* reg = NULL ; 391if (regname != 0 && !valid_yank_reg (regname , false)) { 392return false; 393 } 394if (regname == '_' ) {// black hole is always empty 395return false; 396 } 397* reg = get_yank_register (regname ,YREG_PASTE ); 398return (* reg )-> y_type == kMTLineWise ; 399} 400 401/// @return a copy of contents in register `name` for use in do_put. Should be 402/// freed by caller. 403yankreg_T * copy_register (int name ) 404FUNC_ATTR_NONNULL_RET 405{ 406yankreg_T * reg = get_yank_register (name ,YREG_PASTE ); 407 408yankreg_T * copy = xmalloc (sizeof (yankreg_T )); 409* copy = * reg ; 410if (copy -> y_size == 0 ) { 411copy -> y_array = NULL ; 412 }else { 413copy -> y_array = xcalloc (copy -> y_size ,sizeof (String )); 414for (size_t i = 0 ;i < copy -> y_size ;i ++ ) { 415copy -> y_array [i ]= copy_string (reg -> y_array [i ],NULL ); 416 } 417 } 418return copy ; 419} 420 421/// Stuff string "p" into yank register "regname" as a single line (append if 422/// uppercase). "p" must have been allocated. 423/// 424/// @return FAIL for failure, OK otherwise 425static int stuff_yank (int regname ,char * p ) 426{ 427// check for read-only register 428if (regname != 0 && !valid_yank_reg (regname , true)) { 429xfree (p ); 430return FAIL ; 431 } 432if (regname == '_' ) {// black hole: don't do anything 433xfree (p ); 434return OK ; 435 } 436 437const size_t plen = strlen (p ); 438yankreg_T * reg = get_yank_register (regname ,YREG_YANK ); 439if (is_append_register (regname )&& reg -> y_array != NULL ) { 440String * pp = & (reg -> y_array [reg -> y_size - 1 ]); 441const size_t tmplen = pp -> size + plen ; 442char * tmp = xmalloc (tmplen + 1 ); 443memcpy (tmp ,pp -> data ,pp -> size ); 444memcpy (tmp + pp -> size ,p ,plen ); 445* (tmp + tmplen )= NUL ; 446xfree (p ); 447xfree (pp -> data ); 448* pp = cbuf_as_string (tmp ,tmplen ); 449 }else { 450free_register (reg ); 451reg -> additional_data = NULL ; 452reg -> y_array = xmalloc (sizeof (String )); 453reg -> y_array [0 ]= cbuf_as_string (p ,plen ); 454reg -> y_size = 1 ; 455reg -> y_type = kMTCharWise ; 456 } 457reg -> timestamp = (Timestamp )os_realtime (); 458return OK ; 459} 460 461/// Start or stop recording into a yank register. 462/// 463/// @return FAIL for failure, OK otherwise. 464int do_record (int c ) 465{ 466static int regname ; 467int retval ; 468 469if (reg_recording == 0 ) { 470// start recording 471// registers 0-9, a-z and " are allowed 472if (c < 0 || (!ASCII_ISALNUM (c )&& c != '"' )) { 473retval = FAIL ; 474 }else { 475reg_recording = c ; 476// TODO(bfredl): showmode based messaging is currently missing with cmdheight=0 477showmode (); 478regname = c ; 479retval = OK ; 480 481apply_autocmds (EVENT_RECORDINGENTER ,NULL ,NULL , false,curbuf ); 482 } 483 }else {// stop recording 484save_v_event_T save_v_event ; 485// Set the v:event dictionary with information about the recording. 486dict_T * dict = get_v_event (& save_v_event ); 487 488// The recorded text contents. 489char * p = get_recorded (); 490if (p != NULL ) { 491// Remove escaping for K_SPECIAL in multi-byte chars. 492vim_unescape_ks (p ); 493tv_dict_add_str (dict ,S_LEN ("regcontents" ),p ); 494 } 495 496// Name of requested register, or empty string for unnamed operation. 497char buf [NUMBUFLEN + 2 ]; 498buf [0 ]= (char )regname ; 499buf [1 ]= NUL ; 500tv_dict_add_str (dict ,S_LEN ("regname" ),buf ); 501tv_dict_set_keys_readonly (dict ); 502 503// Get the recorded key hits. K_SPECIAL will be escaped, this 504// needs to be removed again to put it in a register. exec_reg then 505// adds the escaping back later. 506apply_autocmds (EVENT_RECORDINGLEAVE ,NULL ,NULL , false,curbuf ); 507restore_v_event (dict ,& save_v_event ); 508reg_recorded = reg_recording ; 509reg_recording = 0 ; 510if (p_ch == 0 || ui_has (kUIMessages )) { 511showmode (); 512 }else { 513msg ("" ,0 ); 514 } 515if (p == NULL ) { 516retval = FAIL ; 517 }else { 518// We don't want to change the default register here, so save and 519// restore the current register name. 520yankreg_T * old_y_previous = y_previous ; 521 522retval = stuff_yank (regname ,p ); 523 524y_previous = old_y_previous ; 525 } 526 } 527return retval ; 528} 529 530/// Insert register contents "s" into the typeahead buffer, so that it will be 531/// executed again. 532/// 533/// @param esc when true then it is to be taken literally: Escape K_SPECIAL 534/// characters and no remapping. 535/// @param colon add ':' before the line 536static int put_in_typebuf (char * s ,bool esc ,bool colon ,int silent ) 537{ 538int retval = OK ; 539 540put_reedit_in_typebuf (silent ); 541if (colon ) { 542retval = ins_typebuf ("\n" ,REMAP_NONE ,0 , true,silent ); 543 } 544if (retval == OK ) { 545char * p ; 546 547if (esc ) { 548p = vim_strsave_escape_ks (s ); 549 }else { 550p = s ; 551 } 552if (p == NULL ) { 553retval = FAIL ; 554 }else { 555retval = ins_typebuf (p ,esc ?REMAP_NONE :REMAP_YES ,0 , true,silent ); 556 } 557if (esc ) { 558xfree (p ); 559 } 560 } 561if (colon && retval == OK ) { 562retval = ins_typebuf (":" ,REMAP_NONE ,0 , true,silent ); 563 } 564return retval ; 565} 566 567/// If "restart_edit" is not zero, put it in the typeahead buffer, so that it's 568/// used only after other typeahead has been processed. 569static void put_reedit_in_typebuf (int silent ) 570{ 571if (restart_edit == NUL ) { 572return ; 573 } 574 575uint8_t buf []= {K_SPECIAL ,KS_EXTRA ,KE_COMMAND , 576// :startinsert 577's' ,'t' ,'a' ,'r' ,'t' ,'i' ,CAR ,NUL }; 578if (restart_edit == 'R' ) { 579buf [8 ]= 'r' ;// :startreplace 580 }else if (restart_edit == 'V' ) { 581buf [8 ]= 'g' ;// :startgreplace 582 }else if (restart_edit == 'A' ) { 583buf [8 ]= '!' ;// :startinsert! 584 } 585if (ins_typebuf ((char * )buf ,REMAP_NONE ,0 , true,silent )== OK ) { 586restart_edit = NUL ; 587 } 588} 589 590/// When executing a register as a series of ex-commands, if the 591/// line-continuation character is used for a line, then join it with one or 592/// more previous lines. Note that lines are processed backwards starting from 593/// the last line in the register. 594/// 595/// @param lines list of lines in the register 596/// @param idx index of the line starting with \ or "\. Join this line with all the immediate 597/// predecessor lines that start with a \ and the first line that doesn't start 598/// with a \. Lines that start with a comment "\ character are ignored. 599/// @returns the concatenated line. The index of the line that should be 600/// processed next is returned in idx. 601static char * execreg_line_continuation (String * lines ,size_t * idx ) 602{ 603size_t cmd_start = * idx ; 604assert (cmd_start > 0 ); 605const size_t cmd_end = cmd_start ; 606 607garray_T ga ; 608ga_init (& ga , (int )sizeof (char ),400 ); 609 610// search backwards to find the first line of this command. 611// Any line not starting with \ or "\ is the start of the 612// command. 613while (-- cmd_start > 0 ) { 614char * p = skipwhite (lines [cmd_start ].data ); 615if (* p != '\\' && (p [0 ]!= '"' || p [1 ]!= '\\' || p [2 ]!= ' ' )) { 616break ; 617 } 618 } 619 620// join all the lines 621String * tmp = & lines [cmd_start ]; 622ga_concat_len (& ga ,tmp -> data ,tmp -> size ); 623for (size_t j = cmd_start + 1 ;j <=cmd_end ;j ++ ) { 624tmp = & lines [j ]; 625char * p = skipwhite (tmp -> data ); 626if (* p == '\\' ) { 627// Adjust the growsize to the current length to 628// speed up concatenating many lines. 629if (ga .ga_len > 400 ) { 630ga_set_growsize (& ga ,MIN (ga .ga_len ,8000 )); 631 } 632p ++ ; 633ga_concat_len (& ga ,p , (size_t )(tmp -> data + tmp -> size - p )); 634 } 635 } 636ga_append (& ga ,NUL ); 637char * str = xmemdupz (ga .ga_data , (size_t )ga .ga_len ); 638ga_clear (& ga ); 639 640* idx = cmd_start ; 641return str ; 642} 643 644/// Execute a yank register: copy it into the stuff buffer 645/// 646/// @param colon insert ':' before each line 647/// @param addcr always add '\n' to end of line 648/// @param silent set "silent" flag in typeahead buffer 649/// 650/// @return FAIL for failure, OK otherwise 651int do_execreg (int regname ,int colon ,int addcr ,int silent ) 652{ 653int retval = OK ; 654 655if (regname == '@' ) {// repeat previous one 656if (execreg_lastc == NUL ) { 657emsg (_ ("E748: No previously used register" )); 658return FAIL ; 659 } 660regname = execreg_lastc ; 661 } 662// check for valid regname 663if (regname == '%' || regname == '#' || !valid_yank_reg (regname , false)) { 664emsg_invreg (regname ); 665return FAIL ; 666 } 667execreg_lastc = regname ; 668 669if (regname == '_' ) {// black hole: don't stuff anything 670return OK ; 671 } 672 673if (regname == ':' ) {// use last command line 674if (last_cmdline == NULL ) { 675emsg (_ (e_nolastcmd )); 676return FAIL ; 677 } 678// don't keep the cmdline containing @: 679XFREE_CLEAR (new_last_cmdline ); 680// Escape all control characters with a CTRL-V 681char * p = vim_strsave_escaped_ext (last_cmdline , 682"\001\002\003\004\005\006\007" 683"\010\011\012\013\014\015\016\017" 684"\020\021\022\023\024\025\026\027" 685"\030\031\032\033\034\035\036\037" , 686Ctrl_V , false); 687// When in Visual mode "'<,'>" will be prepended to the command. 688// Remove it when it's already there. 689if (Visual .active && strncmp (p ,"'<,'>" ,5 )== 0 ) { 690retval = put_in_typebuf (p + 5 , true, true,silent ); 691 }else { 692retval = put_in_typebuf (p , true, true,silent ); 693 } 694xfree (p ); 695 }else if (regname == '=' ) { 696char * p = get_expr_line (); 697if (p == NULL ) { 698return FAIL ; 699 } 700retval = put_in_typebuf (p , true,colon ,silent ); 701xfree (p ); 702 }else if (regname == '.' ) {// use last inserted text 703char * p = get_last_insert_save (); 704if (p == NULL ) { 705emsg (_ (e_noinstext )); 706return FAIL ; 707 } 708retval = put_in_typebuf (p , false,colon ,silent ); 709xfree (p ); 710 }else { 711yankreg_T * reg = get_yank_register (regname ,YREG_PASTE ); 712if (reg -> y_array == NULL ) { 713return FAIL ; 714 } 715 716// Disallow remapping for ":@r". 717int remap = colon ?REMAP_NONE :REMAP_YES ; 718 719// Insert lines into typeahead buffer, from last one to first one. 720put_reedit_in_typebuf (silent ); 721for (size_t i = reg -> y_size ;i -- > 0 ;) {// from y_size - 1 to 0 included 722// insert NL between lines and after last line if type is kMTLineWise 723if (reg -> y_type == kMTLineWise || i < reg -> y_size - 1 || addcr ) { 724if (ins_typebuf ("\n" ,remap ,0 , true,silent )== FAIL ) { 725return FAIL ; 726 } 727 } 728 729// Handle line-continuation for :@<register> 730char * str = reg -> y_array [i ].data ; 731bool free_str = false; 732if (colon && i > 0 ) { 733char * p = skipwhite (str ); 734if (* p == '\\' || (p [0 ]== '"' && p [1 ]== '\\' && p [2 ]== ' ' )) { 735str = execreg_line_continuation (reg -> y_array ,& i ); 736free_str = true; 737 } 738 } 739char * escaped = vim_strsave_escape_ks (str ); 740if (free_str ) { 741xfree (str ); 742 } 743retval = ins_typebuf (escaped ,remap ,0 , true,silent ); 744xfree (escaped ); 745if (retval == FAIL ) { 746return FAIL ; 747 } 748if (colon 749&& ins_typebuf (":" ,remap ,0 , true,silent )== FAIL ) { 750return FAIL ; 751 } 752 } 753reg_executing = regname == 0 ?'"' :regname ;// disable the 'q' command 754pending_end_reg_executing = false; 755 } 756return retval ; 757} 758 759/// Insert a yank register: copy it into the Read buffer. 760/// Used by CTRL-R command and middle mouse button in insert mode. 761/// 762/// @param literally_arg insert literally, not as if typed 763/// 764/// @return FAIL for failure, OK otherwise 765int insert_reg (int regname ,yankreg_T * reg ,bool literally_arg ) 766{ 767int retval = OK ; 768bool allocated ; 769const bool literally = literally_arg || is_literal_register (regname ); 770 771// It is possible to get into an endless loop by having CTRL-R a in 772// register a and then, in insert mode, doing CTRL-R a. 773// If you hit CTRL-C, the loop will be broken here. 774os_breakcheck (); 775if (got_int ) { 776return FAIL ; 777 } 778 779// check for valid regname 780if (regname != NUL && !valid_yank_reg (regname , false)) { 781return FAIL ; 782 } 783 784char * arg ; 785if (regname == '.' ) {// Insert last inserted text. 786retval = stuff_inserted (NUL ,1 , true); 787 }else if (get_spec_reg (regname ,& arg ,& allocated , true)) { 788if (arg == NULL ) { 789return FAIL ; 790 } 791stuffescaped (arg ,literally ); 792if (allocated ) { 793xfree (arg ); 794 } 795 }else {// Name or number register. 796if (reg == NULL ) { 797reg = get_yank_register (regname ,YREG_PASTE ); 798 } 799if (reg -> y_array == NULL ) { 800retval = FAIL ; 801 }else { 802// Put (not stuff). Redo "<C-R>x" instead of the literal text. 803const bool put = reg -> y_type == kMTCharWise 804&& (regname == '-' 805// Multicursor: per-cursor registers. 806|| (mc_ins_cascading ()&& reg -> y_size == 1 807&& (ASCII_ISALNUM (regname )|| regname == '"' ))); 808for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 809if (put ) { 810Direction dir = BACKWARD ; 811if ((State & REPLACE_FLAG )!= 0 ) { 812pos_T curpos ; 813if (u_save_cursor ()== FAIL ) { 814return FAIL ; 815 } 816del_chars (mb_charlen (reg -> y_array [0 ].data ), true); 817curpos = curwin -> w_cursor ; 818if (oneright ()== FAIL ) { 819// hit end of line, need to put forward (after the current position) 820dir = FORWARD ; 821 } 822curwin -> w_cursor = curpos ; 823 } 824 825redo_append_char (Ctrl_R ); 826redo_append_char (regname ); 827do_put (regname ,NULL ,dir ,1 ,PUT_CURSEND ); 828 }else { 829stuffescaped (reg -> y_array [i ].data ,literally ); 830// Insert a newline between lines and after last line if 831// y_type is kMTLineWise. 832if (reg -> y_type == kMTLineWise || i < reg -> y_size - 1 ) { 833stuffcharReadbuff ('\n' ); 834 } 835 } 836 } 837 } 838 } 839 840return retval ; 841} 842 843/// If "regname" is a special register, return true and store a pointer to its 844/// value in "argp". 845/// 846/// @param allocated return: true when value was allocated 847/// @param errmsg give error message when failing 848/// 849/// @return true if "regname" is a special register, 850bool get_spec_reg (int regname ,char ** argp ,bool * allocated ,bool errmsg ) 851{ 852* argp = NULL ; 853* allocated = false; 854switch (regname ) { 855case '%' :// file name 856if (errmsg ) { 857check_fname ();// will give emsg if not set 858 } 859* argp = curbuf -> b_fname ; 860return true; 861 862case '#' :// alternate file name 863* argp = getaltfname (errmsg );// may give emsg if not set 864return true; 865 866case '=' :// result of expression 867* argp = get_expr_line (); 868* allocated = true; 869return true; 870 871case ':' :// last command line 872if (last_cmdline == NULL && errmsg ) { 873emsg (_ (e_nolastcmd )); 874 } 875* argp = last_cmdline ; 876return true; 877 878case '/' :// last search-pattern 879if (last_search_pat ()== NULL && errmsg ) { 880emsg (_ (e_noprevre )); 881 } 882* argp = last_search_pat (); 883return true; 884 885case '.' :// last inserted text 886* argp = get_last_insert_save (); 887* allocated = true; 888if (* argp == NULL && errmsg ) { 889emsg (_ (e_noinstext )); 890 } 891return true; 892 893case Ctrl_F :// Filename under cursor 894case Ctrl_P :// Path under cursor, expand via "path" 895if (!errmsg ) { 896return false; 897 } 898* argp = file_name_at_cursor (FNAME_MESS |FNAME_HYP | (regname == Ctrl_P ?FNAME_EXP :0 ), 8991 ,NULL ); 900* allocated = true; 901return true; 902 903case Ctrl_W :// word under cursor 904case Ctrl_A :// WORD (mnemonic All) under cursor 905if (!errmsg ) { 906return false; 907 } 908size_t cnt = find_ident_under_cursor (argp , (regname == Ctrl_W 909 ? (FIND_IDENT |FIND_STRING ) 910 :FIND_STRING ),NULL ); 911* argp = cnt ?xmemdupz (* argp ,cnt ) :NULL ; 912* allocated = true; 913return true; 914 915case Ctrl_L :// Line under cursor 916if (!errmsg ) { 917return false; 918 } 919 920* argp = ml_get_buf (curwin -> w_buffer ,curwin -> w_cursor .lnum ); 921return true; 922 923case '_' :// black hole: always empty 924* argp = "" ; 925return true; 926 } 927 928return false; 929} 930 931/// Paste a yank register into the command line. 932/// Only for non-special registers. 933/// Used by CTRL-R in command-line mode. 934/// insert_reg() can't be used here, because special characters from the 935/// register contents will be interpreted as commands. 936/// 937/// @param regname Register name. 938/// @param literally_arg Insert text literally instead of "as typed". 939/// @param remcr When true, don't add CR characters. 940/// 941/// @returns FAIL for failure, OK otherwise 942bool cmdline_paste_reg (int regname ,bool literally_arg ,bool remcr ) 943{ 944const bool literally = literally_arg || is_literal_register (regname ); 945 946yankreg_T * reg = get_yank_register (regname ,YREG_PASTE ); 947if (reg -> y_array == NULL ) { 948return FAIL ; 949 } 950 951for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 952cmdline_paste_str (reg -> y_array [i ].data ,literally ); 953 954// Insert ^M between lines, unless `remcr` is true. 955if (i < reg -> y_size - 1 && !remcr ) { 956cmdline_paste_str ("\r" ,literally ); 957 } 958 959// Check for CTRL-C, in case someone tries to paste a few thousand 960// lines and gets bored. 961os_breakcheck (); 962if (got_int ) { 963return FAIL ; 964 } 965 } 966return OK ; 967} 968 969/// Shift the delete registers: "9 is cleared, "8 becomes "9, etc. 970void shift_delete_registers (bool y_append ) 971{ 972free_register (& y_regs [9 ]);// free register "9 973for (int n = 9 ;n > 1 ;n -- ) { 974y_regs [n ]= y_regs [n - 1 ]; 975 } 976if (!y_append ) { 977y_previous = & y_regs [1 ]; 978 } 979y_regs [1 ].y_array = NULL ;// set register "1 to empty 980} 981 982#ifdef EXITFREE 983void clear_registers (void ) 984{ 985for (int i = 0 ;i < NUM_REGISTERS ;i ++ ) { 986free_register (& y_regs [i ]); 987 } 988} 989#endif 990 991/// Free contents of yankreg `reg`. 992/// Called for normal freeing and in case of error. 993/// 994/// @param reg must not be NULL (but `reg->y_array` might be) 995void free_register (yankreg_T * reg ) 996FUNC_ATTR_NONNULL_ALL 997{ 998XFREE_CLEAR (reg -> additional_data ); 999if (reg -> y_array != NULL ) { 1000for (size_t i = reg -> y_size ;i -- > 0 ;) {// from y_size - 1 to 0 included 1001API_CLEAR_STRING (reg -> y_array [i ]); 1002 } 1003XFREE_CLEAR (reg -> y_array ); 1004 } 1005* reg = (yankreg_T ){0 }; 1006} 1007 1008/// Copy a block range into a register. 1009/// 1010/// @param exclude_trailing_space if true, do not copy trailing whitespaces. 1011static void yank_copy_line (yankreg_T * reg ,struct block_def * bd ,size_t y_idx , 1012bool exclude_trailing_space ) 1013FUNC_ATTR_NONNULL_ALL 1014{ 1015if (exclude_trailing_space ) { 1016bd -> endspaces = 0 ; 1017 } 1018int size = bd -> startspaces + bd -> endspaces + bd -> textlen ; 1019assert (size >=0 ); 1020char * pnew = xmallocz ((size_t )size ); 1021reg -> y_array [y_idx ].data = pnew ; 1022memset (pnew ,' ' , (size_t )bd -> startspaces ); 1023pnew += bd -> startspaces ; 1024memmove (pnew ,bd -> textstart , (size_t )bd -> textlen ); 1025pnew += bd -> textlen ; 1026memset (pnew ,' ' , (size_t )bd -> endspaces ); 1027pnew += bd -> endspaces ; 1028if (exclude_trailing_space ) { 1029int s = bd -> textlen + bd -> endspaces ; 1030 1031while (s > 0 && ascii_iswhite (* (bd -> textstart + s - 1 ))) { 1032s = s - utf_head_off (bd -> textstart ,bd -> textstart + s - 1 )- 1 ; 1033pnew -- ; 1034 } 1035 } 1036* pnew = NUL ; 1037reg -> y_array [y_idx ].size = (size_t )(pnew - reg -> y_array [y_idx ].data ); 1038} 1039 1040void op_yank_reg (oparg_T * oap ,bool message ,yankreg_T * reg ,bool append ) 1041{ 1042yankreg_T newreg ;// new yank register when appending 1043MotionType yank_type = oap -> motion_type ; 1044size_t yanklines = (size_t )oap -> line_count ; 1045linenr_T yankendlnum = oap -> end .lnum ; 1046struct block_def bd ; 1047 1048yankreg_T * curr = reg ;// copy of current register 1049// append to existing contents 1050if (append && reg -> y_array != NULL ) { 1051reg = & newreg ; 1052 }else { 1053free_register (reg );// free previously yanked lines 1054 } 1055 1056// If the cursor was in column 1 before and after the movement, and the 1057// operator is not inclusive, the yank is always linewise. 1058if (oap -> motion_type == kMTCharWise 1059&& oap -> start .col == 0 1060&& !oap -> inclusive 1061&& (!oap -> is_VIsual || * p_sel == 'o' ) 1062&& oap -> end .col == 0 1063&& yanklines > 1 ) { 1064yank_type = kMTLineWise ; 1065yankendlnum -- ; 1066yanklines -- ; 1067 } 1068 1069reg -> y_size = yanklines ; 1070reg -> y_type = yank_type ;// set the yank register type 1071reg -> y_width = 0 ; 1072reg -> y_array = xcalloc (yanklines ,sizeof (String )); 1073reg -> additional_data = NULL ; 1074reg -> timestamp = (Timestamp )os_realtime (); 1075 1076size_t y_idx = 0 ;// index in y_array[] 1077linenr_T lnum = oap -> start .lnum ;// current line number 1078 1079if (yank_type == kMTBlockWise ) { 1080// Visual block mode 1081reg -> y_width = oap -> end_vcol - oap -> start_vcol ; 1082 1083if (curwin -> w_curswant == MAXCOL && reg -> y_width > 0 ) { 1084reg -> y_width -- ; 1085 } 1086 } 1087 1088for (;lnum <=yankendlnum ;lnum ++ ,y_idx ++ ) { 1089switch (reg -> y_type ) { 1090case kMTBlockWise : 1091block_prep (oap ,& bd ,lnum , false); 1092yank_copy_line (reg ,& bd ,y_idx ,oap -> excl_tr_ws ); 1093break ; 1094 1095case kMTLineWise : 1096reg -> y_array [y_idx ]= cbuf_to_string (ml_get (lnum ), (size_t )ml_get_len (lnum )); 1097break ; 1098 1099case kMTCharWise : 1100charwise_block_prep (oap -> start ,oap -> end ,& bd ,lnum ,oap -> inclusive ); 1101// make sure bd.textlen is not longer than the text 1102int tmp = (int )strlen (bd .textstart ); 1103if (tmp < bd .textlen ) { 1104bd .textlen = tmp ; 1105 } 1106yank_copy_line (reg ,& bd ,y_idx , false); 1107break ; 1108 1109// NOTREACHED 1110case kMTUnknown : 1111abort (); 1112 } 1113 } 1114 1115if (curr != reg ) {// append the new block to the old block 1116size_t j ; 1117String * new_ptr = xmalloc (sizeof (String )* (curr -> y_size + reg -> y_size )); 1118for (j = 0 ;j < curr -> y_size ;j ++ ) { 1119new_ptr [j ]= curr -> y_array [j ]; 1120 } 1121xfree (curr -> y_array ); 1122curr -> y_array = new_ptr ; 1123 1124if (yank_type == kMTLineWise ) { 1125// kMTLineWise overrides kMTCharWise and kMTBlockWise 1126curr -> y_type = kMTLineWise ; 1127 } 1128 1129// Concatenate the last line of the old block with the first line of 1130// the new block, unless being Vi compatible. 1131if (curr -> y_type == kMTCharWise 1132&& vim_strchr (p_cpo ,kCpoRegappend )== NULL ) { 1133char * pnew = xmalloc (curr -> y_array [curr -> y_size - 1 ].size 1134+ reg -> y_array [0 ].size + 1 ); 1135j -- ; 1136STRCPY (pnew ,curr -> y_array [j ].data ); 1137STRCPY (pnew + curr -> y_array [j ].size ,reg -> y_array [0 ].data ); 1138xfree (curr -> y_array [j ].data ); 1139curr -> y_array [j ]= cbuf_as_string (pnew , 1140curr -> y_array [j ].size + reg -> y_array [0 ].size ); 1141j ++ ; 1142API_CLEAR_STRING (reg -> y_array [0 ]); 1143y_idx = 1 ; 1144 }else { 1145y_idx = 0 ; 1146 } 1147while (y_idx < reg -> y_size ) { 1148curr -> y_array [j ++ ]= reg -> y_array [y_idx ++ ]; 1149 } 1150curr -> y_size = j ; 1151xfree (reg -> y_array ); 1152 } 1153 1154if (message ) {// Display message about yank? 1155if (yank_type == kMTCharWise && yanklines == 1 ) { 1156yanklines = 0 ; 1157 } 1158// Some versions of Vi use ">=" here, some don't... 1159if (yanklines > (size_t )p_report ) { 1160char namebuf [100 ]; 1161 1162if (oap -> regname == NUL ) { 1163* namebuf = NUL ; 1164 }else { 1165vim_snprintf (namebuf ,sizeof (namebuf ),_ (" into \"%c" ),oap -> regname ); 1166 } 1167 1168// redisplay now, so message is not deleted 1169update_topline (curwin ); 1170if (must_redraw ) { 1171update_screen (); 1172 } 1173if (yank_type == kMTBlockWise ) { 1174smsg (0 ,NGETTEXT ("block of %" PRId64 " line yanked%s" , 1175"block of %" PRId64 " lines yanked%s" ,yanklines ), 1176 (int64_t )yanklines ,namebuf ); 1177 }else { 1178smsg (0 ,NGETTEXT ("%" PRId64 " line yanked%s" , 1179"%" PRId64 " lines yanked%s" ,yanklines ), 1180 (int64_t )yanklines ,namebuf ); 1181 } 1182 } 1183 } 1184 1185if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 1186// Set "'[" and "']" marks. 1187curbuf -> b_op_start = oap -> start ; 1188curbuf -> b_op_end = oap -> end ; 1189if (yank_type == kMTLineWise ) { 1190curbuf -> b_op_start .col = 0 ; 1191curbuf -> b_op_end .col = MAXCOL ; 1192 } 1193if (yank_type != kMTLineWise && !oap -> inclusive ) { 1194// Exclude the end position. 1195decl (& curbuf -> b_op_end ); 1196 } 1197 } 1198} 1199 1200/// Format the register type as a string. 1201/// 1202/// @param reg_type The register type. 1203/// @param reg_width The width, only used if "reg_type" is kMTBlockWise. 1204/// @param[out] buf Buffer to store formatted string. The allocated size should 1205/// be at least NUMBUFLEN+2 to always fit the value. 1206/// @param bufsize The allocated size of the buffer. 1207/// 1208/// @return The length of the register type string. 1209size_t format_reg_type (MotionType reg_type ,colnr_T reg_width ,char * buf ,size_t bufsize ) 1210FUNC_ATTR_NONNULL_ALL 1211{ 1212assert (bufsize > 1 ); 1213switch (reg_type ) { 1214case kMTLineWise : 1215buf [0 ]= 'V' ; 1216buf [1 ]= NUL ; 1217return 1 ; 1218case kMTCharWise : 1219buf [0 ]= 'v' ; 1220buf [1 ]= NUL ; 1221return 1 ; 1222case kMTBlockWise : 1223return vim_snprintf_safelen (buf ,bufsize ,CTRL_V_STR "%" PRIdCOLNR ,reg_width + 1 ); 1224case kMTUnknown : 1225buf [0 ]= NUL ; 1226return 0 ; 1227 } 1228abort (); 1229} 1230 1231static void add_regtype_to_dict (yankreg_T * reg ,dict_T * dict ,char * buf ,size_t bufsize ) 1232{ 1233// "reg" is NULL when pasting a special register, which is charwise. 1234size_t len = format_reg_type (reg != NULL ?reg -> y_type :kMTCharWise , 1235reg != NULL ?reg -> y_width :0 ,buf ,bufsize ); 1236tv_dict_add_str_len (dict ,S_LEN ("regtype" ),buf , (int )len ); 1237} 1238 1239/// Execute autocommands for TextYankPost. 1240/// 1241/// @param oap Operator arguments. 1242/// @param reg The yank register used. 1243void do_autocmd_textyankpost (oparg_T * oap ,yankreg_T * reg ) 1244FUNC_ATTR_NONNULL_ALL 1245{ 1246static bool recursive = false; 1247 1248if (recursive || !has_event (EVENT_TEXTYANKPOST )) { 1249// No autocommand was defined, or we yanked from this autocommand. 1250return ; 1251 } 1252 1253recursive = true; 1254 1255save_v_event_T save_v_event ; 1256// Set the v:event dictionary with information about the yank. 1257dict_T * dict = get_v_event (& save_v_event ); 1258 1259// The yanked text contents. 1260list_T * const list = tv_list_alloc ((ptrdiff_t )reg -> y_size ); 1261for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 1262tv_list_append_string (list ,reg -> y_array [i ].data , (int )reg -> y_array [i ].size ); 1263 } 1264tv_list_set_lock (list ,VAR_FIXED ); 1265tv_dict_add_list (dict ,S_LEN ("regcontents" ),list ); 1266 1267// Register type. 1268char buf [NUMBUFLEN + 2 ]; 1269add_regtype_to_dict (reg ,dict ,buf ,ARRAY_SIZE (buf )); 1270 1271// Name of requested register, or empty string for unnamed operation. 1272buf [0 ]= (char )oap -> regname ; 1273buf [1 ]= NUL ; 1274tv_dict_add_str (dict ,S_LEN ("regname" ),buf ); 1275 1276// Motion type: inclusive or exclusive. 1277tv_dict_add_bool (dict ,S_LEN ("inclusive" ), 1278oap -> inclusive ?kBoolVarTrue :kBoolVarFalse ); 1279 1280// Kind of operation: yank, delete, change). 1281buf [0 ]= (char )get_op_char (oap -> op_type ); 1282buf [1 ]= NUL ; 1283tv_dict_add_str (dict ,S_LEN ("operator" ),buf ); 1284 1285// Selection type: visual or not. 1286tv_dict_add_bool (dict ,S_LEN ("visual" ), 1287oap -> is_VIsual ?kBoolVarTrue :kBoolVarFalse ); 1288 1289tv_dict_set_keys_readonly (dict ); 1290textlock ++ ; 1291apply_autocmds (EVENT_TEXTYANKPOST ,NULL ,NULL , false,curbuf ); 1292textlock -- ; 1293restore_v_event (dict ,& save_v_event ); 1294 1295recursive = false; 1296} 1297 1298/// Trigger TextPutPre or TextPutPost autocommand. 1299/// 1300/// @param reg May be NULL, if special register 1301/// @param insert Not NULL if special register, except '.' 1302/// @param post If Post or Pre 1303/// @param dir BACKWARD for 'P', FORWARD for 'p' 1304static void put_do_autocmd (int regname ,yankreg_T * reg ,const String * insert ,bool post , 1305Direction dir ) 1306{ 1307static bool recursive = false; 1308 1309if (recursive || (regname == '_' && reg == NULL )) { 1310return ; 1311 } 1312 1313if (regname != '.' && insert == NULL && reg == NULL ) { 1314// Can happen when pasting text in normal mode in a terminal buffer 1315return ; 1316 } 1317 1318save_v_event_T save_v_event ; 1319dict_T * v_event = get_v_event (& save_v_event ); 1320 1321list_T * list = tv_list_alloc (reg != NULL ? (ptrdiff_t )reg -> y_size :1 ); 1322 1323if (regname == '.' ) { 1324if (last_insert_ga .ga_data != NULL ) { 1325// Get the last inserted text to place in "regcontents" 1326tv_list_append_string (list ,last_insert_ga .ga_data ,last_insert_ga .ga_len ); 1327 } 1328 }else if (insert != NULL ) { 1329tv_list_append_string (list ,insert -> data , (ssize_t )insert -> size ); 1330 }else { 1331for (size_t n = 0 ;n < reg -> y_size ;n ++ ) { 1332tv_list_append_string (list ,reg -> y_array [n ].data , (ssize_t )reg -> y_array [n ].size ); 1333 } 1334 } 1335 1336tv_list_set_lock (list ,VAR_FIXED ); 1337tv_dict_add_list (v_event ,S_LEN ("regcontents" ),list ); 1338 1339char buf [NUMBUFLEN + 2 ]; 1340 1341// register name or empty string for unnamed operation 1342buf [0 ]= (char )regname ; 1343buf [1 ]= NUL ; 1344size_t buflen = (buf [0 ]== NUL ) ?0 :1 ; 1345tv_dict_add_str_len (v_event ,S_LEN ("regname" ),buf , (int )buflen ); 1346 1347// kind of operation (P, p) 1348buf [0 ]= dir == BACKWARD ?'P' :'p' ; 1349buf [1 ]= NUL ; 1350buflen = 1 ; 1351tv_dict_add_str_len (v_event ,S_LEN ("operator" ),buf , (int )buflen ); 1352 1353add_regtype_to_dict (reg ,v_event ,buf ,sizeof (buf )); 1354 1355tv_dict_add_bool (v_event ,S_LEN ("visual" ),Visual .active ); 1356 1357// Lock the dictionary and its keys 1358tv_dict_set_keys_readonly (v_event ); 1359 1360recursive = true; 1361textlock ++ ; 1362if (post ) { 1363apply_autocmds (EVENT_TEXTPUTPOST ,NULL ,NULL , false,curbuf ); 1364 }else { 1365apply_autocmds (EVENT_TEXTPUTPRE ,NULL ,NULL , false,curbuf ); 1366 } 1367textlock -- ; 1368recursive = false; 1369 1370// Empty the dictionary, v:event is still valid 1371restore_v_event (v_event ,& save_v_event ); 1372} 1373 1374/// Yanks the text between "oap->start" and "oap->end" into a yank register. 1375/// If we are to append (uppercase register), we first yank into a new yank 1376/// register and then concatenate the old and the new one. 1377/// Do not call this from a delete operation. Use op_yank_reg() instead. 1378/// 1379/// @param oap operator arguments 1380/// @param message show message when more than `&report` lines are yanked. 1381/// @returns whether the operation register was writable. 1382bool op_yank (oparg_T * oap ,bool message ) 1383FUNC_ATTR_NONNULL_ALL 1384{ 1385// check for read-only register 1386if (oap -> regname != 0 && !valid_yank_reg (oap -> regname , true)) { 1387beep_flush (); 1388return false; 1389 } 1390if (oap -> regname == '_' ) { 1391return true;// black hole: nothing to do 1392 } 1393 1394yankreg_T * reg = get_yank_register (oap -> regname ,YREG_YANK ); 1395op_yank_reg (oap ,message ,reg ,is_append_register (oap -> regname )); 1396set_clipboard (oap -> regname ,reg ); 1397do_autocmd_textyankpost (oap ,reg ); 1398return true; 1399} 1400 1401/// Put contents of register "regname" into the text. 1402/// Caller must check "regname" to be valid! 1403/// 1404/// @param flags PUT_FIXINDENT make indent look nice 1405/// PUT_CURSEND leave cursor after end of new text 1406/// PUT_LINE force linewise put (":put") 1407/// PUT_BLOCK_INNER in block mode, do not add trailing spaces 1408/// @param dir BACKWARD for 'P', FORWARD for 'p' 1409void do_put (int regname ,yankreg_T * reg ,int dir ,int count ,int flags ) 1410{ 1411size_t totlen = 0 ;// init for gcc 1412linenr_T lnum = 0 ; 1413MotionType y_type ; 1414size_t y_size ; 1415int y_width = 0 ; 1416colnr_T vcol = 0 ; 1417String * y_array = NULL ; 1418linenr_T nr_lines = 0 ; 1419bool allocated = false; 1420const pos_T orig_start = curbuf -> b_op_start ; 1421const pos_T orig_end = curbuf -> b_op_end ; 1422unsigned cur_ve_flags = get_ve_flags (curwin ); 1423 1424// Remove any preinserted text (issue vim/vim#19329) 1425if (ins_compl_preinsert_effect ()) { 1426ins_compl_delete (false); 1427 } 1428 1429curbuf -> b_op_start = curwin -> w_cursor ;// default for '[ mark 1430curbuf -> b_op_end = curwin -> w_cursor ;// default for '] mark 1431 1432// Using inserted text works differently, because the register includes 1433// special characters (newlines, etc.). 1434if (regname == '.' && !reg ) { 1435bool non_linewise_vis = (Visual .active && Visual .mode != 'V' ); 1436 1437// PUT_LINE has special handling below which means we use 'i' to start. 1438char command_start_char = non_linewise_vis 1439 ?'c' 1440 : (flags & PUT_LINE ?'i' : (dir == FORWARD ?'a' :'i' )); 1441 1442bool has_textput_events = has_event (EVENT_TEXTPUTPRE )|| has_event (EVENT_TEXTPUTPOST ); 1443if (has_textput_events ) { 1444add_last_insert ++ ; 1445 } 1446 1447// To avoid 'autoindent' on linewise puts, create a new line with `:put _`. 1448if (flags & PUT_LINE ) { 1449const int save_add_last_insert = add_last_insert ; 1450add_last_insert = 0 ; 1451stuffcharReadbuff (K_COMMAND ); 1452if (dir == FORWARD ) { 1453stuffReadbuffLen (S_LEN ("put _" )); 1454 }else { 1455stuffReadbuffLen (S_LEN ("put! _" )); 1456 } 1457stuffcharReadbuff (CAR ); 1458add_last_insert = save_add_last_insert ; 1459 } 1460 1461// If given a count when putting linewise, we stuff the readbuf with the 1462// dot register 'count' times split by newlines. 1463if (flags & PUT_LINE ) { 1464stuffcharReadbuff (command_start_char ); 1465for (;count > 0 ;count -- ) { 1466stuff_inserted (NUL ,1 ,count != 1 ); 1467if (count != 1 ) { 1468// To avoid 'autoindent' affecting the text, use Ctrl_U to remove any 1469// whitespace. Can't just insert Ctrl_U into readbuf1, this would go 1470// back to the previous line in the case of 'noautoindent' and 1471// 'backspace' includes "eol". So we insert a dummy space for Ctrl_U 1472// to consume. 1473static const char s []= {'\n' ,' ' ,Ctrl_U ,NUL }; 1474stuffReadbuffLen (S_LEN (s )); 1475 } 1476 } 1477 }else { 1478stuff_inserted (command_start_char ,count , false); 1479 } 1480 1481// Since the text is not inserted into the buffer immediately, just call 1482// TextPutPost after TextPutPre. 1483if (has_event (EVENT_TEXTPUTPRE )) { 1484put_do_autocmd ('.' ,NULL ,NULL , false,dir ); 1485 } 1486if (has_event (EVENT_TEXTPUTPOST )) { 1487put_do_autocmd ('.' ,NULL ,NULL , true,dir ); 1488 } 1489 1490if (has_textput_events && -- add_last_insert == 0 ) { 1491ga_clear (& last_insert_ga ); 1492 } 1493 1494// Putting the text is done later, so can't move the cursor to the next 1495// character. Simulate it with motion commands after the insert. 1496if (flags & PUT_CURSEND ) { 1497if (flags & PUT_LINE ) { 1498stuffReadbuff ("j0" ); 1499 }else { 1500// Avoid ringing the bell from attempting to move into the space after 1501// the current line. We can stuff the readbuffer with "l" if: 1502// 1) 'virtualedit' is "all" or "onemore" 1503// 2) We are not at the end of the line 1504// 3) We are not (one past the end of the line && on the last line) 1505// This allows a visual put over a selection one past the end of the 1506// line joining the current line with the one below. 1507 1508// curwin->w_cursor.col marks the byte position of the cursor in the 1509// currunt line. It increases up to a max of 1510// strlen(ml_get(curwin->w_cursor.lnum)). With 'virtualedit' and the 1511// cursor past the end of the line, curwin->w_cursor.coladd is 1512// incremented instead of curwin->w_cursor.col. 1513char * cursor_pos = get_cursor_pos_ptr (); 1514bool one_past_line = (* cursor_pos == NUL ); 1515bool eol = false; 1516if (!one_past_line ) { 1517eol = (* (cursor_pos + utfc_ptr2len (cursor_pos ))== NUL ); 1518 } 1519 1520bool ve_allows = (cur_ve_flags == kOptVeFlagAll || cur_ve_flags == kOptVeFlagOnemore ); 1521bool eof = curbuf -> b_ml .ml_line_count == curwin -> w_cursor .lnum 1522&& one_past_line ; 1523if (ve_allows || !(eol || eof )) { 1524stuffcharReadbuff ('l' ); 1525 } 1526 } 1527 }else if (flags & PUT_LINE ) { 1528stuffReadbuff ("g'[" ); 1529 } 1530 1531// So the 'u' command restores cursor position after ".p, save the cursor 1532// position now (though not saving any text). 1533if (command_start_char == 'a' ) { 1534if (u_save (curwin -> w_cursor .lnum ,curwin -> w_cursor .lnum + 1 )== FAIL ) { 1535return ; 1536 } 1537 } 1538 1539// Execute the stuffed keys here: the put resolves within the current command. 1540exec_stuffed (NULL ); 1541return ; 1542 } 1543 1544// For special registers '%' (file name), '#' (alternate file name) and 1545// ':' (last command line), etc. we have to create a fake yank register. 1546String insert_string = STRING_INIT ; 1547if (!reg && get_spec_reg (regname ,& insert_string .data ,& allocated , true)) { 1548if (insert_string .data == NULL ) { 1549return ; 1550 } 1551 } 1552 1553if (!curbuf -> terminal ) { 1554// Autocommands may be executed when saving lines for undo. This might 1555// make y_array invalid, so we start undo now to avoid that. 1556if (u_save (curwin -> w_cursor .lnum ,curwin -> w_cursor .lnum + 1 )== FAIL ) { 1557return ; 1558 } 1559 } 1560 1561if (insert_string .data != NULL ) { 1562insert_string .size = strlen (insert_string .data ); 1563y_type = kMTCharWise ; 1564if (regname == '=' ) { 1565// For the = register we need to split the string at NL 1566// characters. 1567// Loop twice: count the number of lines and save them. 1568while (true) { 1569y_size = 0 ; 1570char * ptr = insert_string .data ; 1571size_t ptrlen = insert_string .size ; 1572while (ptr != NULL ) { 1573if (y_array != NULL ) { 1574y_array [y_size ].data = ptr ; 1575 } 1576y_size ++ ; 1577char * tmp = vim_strchr (ptr ,'\n' ); 1578if (tmp == NULL ) { 1579if (y_array != NULL ) { 1580y_array [y_size - 1 ].size = ptrlen ; 1581 } 1582 }else { 1583if (y_array != NULL ) { 1584* tmp = NUL ; 1585y_array [y_size - 1 ].size = (size_t )(tmp - ptr ); 1586ptrlen -= y_array [y_size - 1 ].size + 1 ; 1587 } 1588tmp ++ ; 1589// A trailing '\n' makes the register linewise. 1590if (* tmp == NUL ) { 1591y_type = kMTLineWise ; 1592break ; 1593 } 1594 } 1595ptr = tmp ; 1596 } 1597if (y_array != NULL ) { 1598break ; 1599 } 1600y_array = xmalloc (y_size * sizeof (String )); 1601 } 1602 }else { 1603y_size = 1 ;// use fake one-line yank register 1604y_array = & insert_string ; 1605 } 1606if (has_event (EVENT_TEXTPUTPRE )) { 1607put_do_autocmd (regname ,NULL ,& insert_string , false,dir ); 1608 } 1609 }else { 1610if (has_event (EVENT_TEXTPUTPRE )) { 1611yankreg_T * const save_reg = reg ; 1612if (reg == NULL ) { 1613// Make sure to call this before we set the variables, as setreg() 1614// may be called and invalidate them. 1615reg = get_yank_register (regname ,YREG_PASTE ); 1616 } 1617put_do_autocmd (regname ,reg ,NULL , false,dir ); 1618reg = save_reg ; 1619 } 1620// in case of replacing visually selected text 1621// the yankreg might already have been saved to avoid 1622// just restoring the deleted text. 1623if (reg == NULL ) { 1624reg = get_yank_register (regname ,YREG_PASTE ); 1625 } 1626 1627y_type = reg -> y_type ; 1628y_width = reg -> y_width ; 1629y_size = reg -> y_size ; 1630y_array = reg -> y_array ; 1631 } 1632 1633if (curbuf -> terminal ) { 1634terminal_paste (count ,y_array ,y_size ); 1635 gotoend ; 1636 } 1637 1638colnr_T split_pos = 0 ; 1639if (y_type == kMTLineWise ) { 1640if (flags & PUT_LINE_SPLIT ) { 1641// "p" or "P" in Visual mode: split the lines to put the text in 1642// between. 1643if (u_save_cursor ()== FAIL ) { 1644 gotoend ; 1645 } 1646char * curline = get_cursor_line_ptr (); 1647char * p = get_cursor_pos_ptr (); 1648char * const p_orig = p ; 1649const size_t plen = (size_t )get_cursor_pos_len (); 1650if (dir == FORWARD && * p != NUL ) { 1651MB_PTR_ADV (p ); 1652 } 1653// we need this later for the correct extmark_splice() event 1654split_pos = (colnr_T )(p - curline ); 1655 1656char * ptr = xmemdupz (p ,plen - (size_t )(p - p_orig )); 1657ml_append (curwin -> w_cursor .lnum ,ptr ,0 , false); 1658xfree (ptr ); 1659 1660ptr = xmemdupz (get_cursor_line_ptr (), (size_t )split_pos ); 1661ml_replace (curwin -> w_cursor .lnum ,ptr , false); 1662nr_lines ++ ; 1663dir = FORWARD ; 1664 1665buf_updates_send_changes (curbuf ,curwin -> w_cursor .lnum ,1 ,1 ); 1666 } 1667if (flags & PUT_LINE_FORWARD ) { 1668// Must be "p" for a Visual block, put lines below the block. 1669curwin -> w_cursor = curbuf -> b_visual .vi_end ; 1670dir = FORWARD ; 1671 } 1672curbuf -> b_op_start = curwin -> w_cursor ;// default for '[ mark 1673curbuf -> b_op_end = curwin -> w_cursor ;// default for '] mark 1674 } 1675 1676if (flags & PUT_LINE ) {// :put command or "p" in Visual line mode. 1677y_type = kMTLineWise ; 1678 } 1679 1680if (y_size == 0 || y_array == NULL ) { 1681semsg (_ ("E353: Nothing in register %s" ), 1682regname == 0 ?"\"" :transchar (regname )); 1683 gotoend ; 1684 } 1685 1686if (y_type == kMTBlockWise ) { 1687lnum = curwin -> w_cursor .lnum + (linenr_T )y_size + 1 ; 1688lnum = MIN (lnum ,curbuf -> b_ml .ml_line_count + 1 ); 1689if (u_save (curwin -> w_cursor .lnum - 1 ,lnum )== FAIL ) { 1690 gotoend ; 1691 } 1692 }else if (y_type == kMTLineWise ) { 1693lnum = curwin -> w_cursor .lnum ; 1694// Correct line number for closed fold. Don't move the cursor yet, 1695// u_save() uses it. 1696if (dir == BACKWARD ) { 1697hasFolding (curwin ,lnum ,& lnum ,NULL ); 1698 }else { 1699hasFolding (curwin ,lnum ,NULL ,& lnum ); 1700 } 1701if (dir == FORWARD ) { 1702lnum ++ ; 1703 } 1704// In an empty buffer the empty line is going to be replaced, include 1705// it in the saved lines. 1706if ((buf_is_empty (curbuf ) 1707 ?u_save (0 ,2 ) :u_save (lnum - 1 ,lnum ))== FAIL ) { 1708 gotoend ; 1709 } 1710if (dir == FORWARD ) { 1711curwin -> w_cursor .lnum = lnum - 1 ; 1712 }else { 1713curwin -> w_cursor .lnum = lnum ; 1714 } 1715curbuf -> b_op_start = curwin -> w_cursor ;// for mark_adjust() 1716 }else if (u_save_cursor ()== FAIL ) { 1717 gotoend ; 1718 } 1719 1720if (cur_ve_flags == kOptVeFlagAll && y_type == kMTCharWise ) { 1721if (gchar_cursor ()== TAB ) { 1722int viscol = getviscol (); 1723OptInt ts = curbuf -> b_p_ts ; 1724// Don't need to insert spaces when "p" on the last position of a 1725// tab or "P" on the first position. 1726if (dir == FORWARD 1727 ?tabstop_padding (viscol ,ts ,curbuf -> b_p_vts_array )!= 1 1728 :curwin -> w_cursor .coladd > 0 ) { 1729coladvance_force (viscol ); 1730 }else { 1731curwin -> w_cursor .coladd = 0 ; 1732 } 1733 }else if (curwin -> w_cursor .coladd > 0 || gchar_cursor ()== NUL ) { 1734coladvance_force (getviscol ()+ (dir == FORWARD )); 1735 } 1736 } 1737 1738lnum = curwin -> w_cursor .lnum ; 1739colnr_T col = curwin -> w_cursor .col ; 1740 1741// Block mode 1742if (y_type == kMTBlockWise ) { 1743int incr = 0 ; 1744struct block_def bd ; 1745int c = gchar_cursor (); 1746colnr_T endcol2 = 0 ; 1747 1748if (dir == FORWARD && c != NUL ) { 1749if (cur_ve_flags == kOptVeFlagAll ) { 1750getvcol (curwin ,& curwin -> w_cursor ,& col ,NULL ,& endcol2 ,0 ); 1751 }else { 1752getvcol (curwin ,& curwin -> w_cursor ,NULL ,NULL ,& col ,0 ); 1753 } 1754 1755// move to start of next multi-byte character 1756curwin -> w_cursor .col += utfc_ptr2len (get_cursor_pos_ptr ()); 1757col ++ ; 1758 }else { 1759getvcol (curwin ,& curwin -> w_cursor ,& col ,NULL ,& endcol2 ,0 ); 1760 } 1761 1762col += curwin -> w_cursor .coladd ; 1763if (cur_ve_flags == kOptVeFlagAll 1764&& (curwin -> w_cursor .coladd > 0 || endcol2 == curwin -> w_cursor .col )) { 1765if (dir == FORWARD && c == NUL ) { 1766col ++ ; 1767 } 1768if (dir != FORWARD && c != NUL && curwin -> w_cursor .coladd > 0 ) { 1769curwin -> w_cursor .col ++ ; 1770 } 1771if (c == TAB ) { 1772if (dir == BACKWARD && curwin -> w_cursor .col ) { 1773curwin -> w_cursor .col -- ; 1774 } 1775if (dir == FORWARD && col - 1 == endcol2 ) { 1776curwin -> w_cursor .col ++ ; 1777 } 1778 } 1779 } 1780curwin -> w_cursor .coladd = 0 ; 1781bd .textcol = 0 ; 1782for (size_t i = 0 ;i < y_size ;i ++ ) { 1783int spaces = 0 ; 1784char shortline ; 1785// can just be 0 or 1, needed for blockwise paste beyond the current 1786// buffer end 1787int lines_appended = 0 ; 1788 1789bd .startspaces = 0 ; 1790bd .endspaces = 0 ; 1791vcol = 0 ; 1792int delcount = 0 ; 1793 1794// add a new line 1795if (curwin -> w_cursor .lnum > curbuf -> b_ml .ml_line_count ) { 1796if (ml_append (curbuf -> b_ml .ml_line_count ,"" ,1 , false)== FAIL ) { 1797break ; 1798 } 1799nr_lines ++ ; 1800lines_appended = 1 ; 1801 } 1802// get the old line and advance to the position to insert at 1803char * oldp = get_cursor_line_ptr (); 1804colnr_T oldlen = get_cursor_line_len (); 1805 1806CharsizeArg csarg ; 1807CSType cstype = init_charsize_arg (& csarg ,curwin ,curwin -> w_cursor .lnum ,oldp ); 1808StrCharInfo ci = utf_ptr2StrCharInfo (oldp ); 1809vcol = 0 ; 1810while (vcol < col && * ci .ptr != NUL ) { 1811ClusterInfo cli = utf_ClusterInfo (ci ); 1812incr = win_charsize (cstype ,vcol ,ci .ptr ,ci .chr .value ,& csarg ,cli .cells ).width ; 1813vcol += incr ; 1814ci = cli .next ; 1815 } 1816char * ptr = ci .ptr ; 1817bd .textcol = (colnr_T )(ptr - oldp ); 1818 1819shortline = (vcol < col )|| (vcol == col && !* ptr ); 1820 1821if (vcol < col ) {// line too short, pad with spaces 1822bd .startspaces = col - vcol ; 1823 }else if (vcol > col ) { 1824bd .endspaces = vcol - col ; 1825bd .startspaces = incr - bd .endspaces ; 1826bd .textcol -- ; 1827delcount = 1 ; 1828bd .textcol -= utf_head_off (oldp ,oldp + bd .textcol ); 1829if (oldp [bd .textcol ]!= TAB ) { 1830// Only a Tab can be split into spaces. Other 1831// characters will have to be moved to after the 1832// block, causing misalignment. 1833delcount = 0 ; 1834bd .endspaces = 0 ; 1835 } 1836 } 1837 1838const int yanklen = (int )y_array [i ].size ; 1839 1840if ((flags & PUT_BLOCK_INNER )== 0 ) { 1841// calculate number of spaces required to fill right side of block 1842spaces = y_width + 1 ; 1843 1844cstype = init_charsize_arg (& csarg ,curwin ,0 ,y_array [i ].data ); 1845ci = utf_ptr2StrCharInfo (y_array [i ].data ); 1846while (* ci .ptr != NUL ) { 1847ClusterInfo cli = utf_ClusterInfo (ci ); 1848spaces -= win_charsize (cstype ,0 ,ci .ptr ,ci .chr .value ,& csarg ,cli .cells ).width ; 1849ci = cli .next ; 1850 } 1851spaces = MAX (spaces ,0 ); 1852 } 1853 1854// Insert the new text. 1855// First check for multiplication overflow. 1856if (yanklen + spaces != 0 1857&& count > ((INT_MAX - (bd .startspaces + bd .endspaces )) / (yanklen + spaces ))) { 1858emsg (_ (e_resulting_text_too_long )); 1859break ; 1860 } 1861 1862totlen = (size_t )count * (size_t )(yanklen + spaces )+ (size_t )bd .startspaces + 1863 (size_t )bd .endspaces ; 1864char * newp = xmalloc (totlen + (size_t )oldlen + 1 ); 1865 1866// copy part up to cursor to new line 1867ptr = newp ; 1868memmove (ptr ,oldp , (size_t )bd .textcol ); 1869ptr += bd .textcol ; 1870 1871// may insert some spaces before the new text 1872memset (ptr ,' ' , (size_t )bd .startspaces ); 1873ptr += bd .startspaces ; 1874 1875// insert the new text 1876for (int j = 0 ;j < count ;j ++ ) { 1877memmove (ptr ,y_array [i ].data , (size_t )yanklen ); 1878ptr += yanklen ; 1879 1880// insert block's trailing spaces only if there's text behind 1881if ((j < count - 1 || !shortline )&& spaces > 0 ) { 1882memset (ptr ,' ' , (size_t )spaces ); 1883ptr += spaces ; 1884 }else { 1885totlen -= (size_t )spaces ;// didn't use these spaces 1886 } 1887 } 1888 1889// may insert some spaces after the new text 1890memset (ptr ,' ' , (size_t )bd .endspaces ); 1891ptr += bd .endspaces ; 1892 1893// move the text after the cursor to the end of the line. 1894int columns = oldlen - bd .textcol - delcount + 1 ; 1895assert (columns >=0 ); 1896memmove (ptr ,oldp + bd .textcol + delcount , (size_t )columns ); 1897ml_replace (curwin -> w_cursor .lnum ,newp , false); 1898extmark_splice_cols (curbuf , (int )curwin -> w_cursor .lnum - 1 ,bd .textcol , 1899delcount , (int )totlen + lines_appended ,kExtmarkUndo ); 1900 1901curwin -> w_cursor .lnum ++ ; 1902if (i == 0 ) { 1903curwin -> w_cursor .col += bd .startspaces ; 1904 } 1905 } 1906 1907changed_lines (curbuf ,lnum ,0 ,curbuf -> b_op_start .lnum + (linenr_T )y_size 1908- nr_lines ,nr_lines , true); 1909 1910// Set '[ mark. 1911curbuf -> b_op_start = curwin -> w_cursor ; 1912curbuf -> b_op_start .lnum = lnum ; 1913 1914// adjust '] mark 1915curbuf -> b_op_end .lnum = curwin -> w_cursor .lnum - 1 ; 1916curbuf -> b_op_end .col = MAX (bd .textcol + (colnr_T )totlen - 1 ,0 ); 1917curbuf -> b_op_end .coladd = 0 ; 1918if (flags & PUT_CURSEND ) { 1919curwin -> w_cursor = curbuf -> b_op_end ; 1920curwin -> w_cursor .col ++ ; 1921 1922// in Insert mode we might be after the NUL, correct for that 1923colnr_T len = get_cursor_line_len (); 1924curwin -> w_cursor .col = MIN (curwin -> w_cursor .col ,len ); 1925 }else { 1926curwin -> w_cursor .lnum = lnum ; 1927 } 1928 }else { 1929const int yanklen = (int )y_array [0 ].size ; 1930 1931// Character or Line mode 1932if (y_type == kMTCharWise ) { 1933// if type is kMTCharWise, FORWARD is the same as BACKWARD on the next 1934// char 1935if (dir == FORWARD && gchar_cursor ()!= NUL ) { 1936int bytelen = utfc_ptr2len (get_cursor_pos_ptr ()); 1937 1938// put it on the next of the multi-byte character. 1939col += bytelen ; 1940if (yanklen ) { 1941curwin -> w_cursor .col += bytelen ; 1942curbuf -> b_op_end .col += bytelen ; 1943 } 1944 } 1945curbuf -> b_op_start = curwin -> w_cursor ; 1946 }else if (dir == BACKWARD ) { 1947// Line mode: BACKWARD is the same as FORWARD on the previous line 1948lnum -- ; 1949 } 1950pos_T new_cursor = curwin -> w_cursor ; 1951 1952// simple case: insert into one line at a time 1953if (y_type == kMTCharWise && y_size == 1 ) { 1954linenr_T end_lnum = 0 ;// init for gcc 1955linenr_T start_lnum = lnum ; 1956int first_byte_off = 0 ; 1957 1958if (Visual .active ) { 1959end_lnum = MAX (curbuf -> b_visual .vi_end .lnum ,curbuf -> b_visual .vi_start .lnum ); 1960if (end_lnum > start_lnum ) { 1961// "col" is valid for the first line, in following lines 1962// the virtual column needs to be used. Matters for 1963// multi-byte characters. 1964pos_T pos = { 1965 .lnum = lnum , 1966 .col = col , 1967 .coladd = 0 , 1968 }; 1969getvcol (curwin ,& pos ,NULL ,& vcol ,NULL ,0 ); 1970 } 1971 } 1972 1973if (count == 0 || yanklen == 0 ) { 1974if (Visual .active ) { 1975lnum = end_lnum ; 1976 } 1977 }else if (count > INT_MAX /yanklen ) { 1978// multiplication overflow 1979emsg (_ (e_resulting_text_too_long )); 1980 }else { 1981totlen = (size_t )count * (size_t )yanklen ; 1982do { 1983char * oldp = ml_get (lnum ); 1984colnr_T oldlen = ml_get_len (lnum ); 1985if (lnum > start_lnum ) { 1986pos_T pos = { 1987 .lnum = lnum , 1988 }; 1989if (getvpos (curwin ,& pos ,vcol )== OK ) { 1990col = pos .col ; 1991 }else { 1992col = MAXCOL ; 1993 } 1994 } 1995if (Visual .active && col > oldlen ) { 1996lnum ++ ; 1997continue ; 1998 } 1999char * newp = xmalloc (totlen + (size_t )oldlen + 1 ); 2000memmove (newp ,oldp , (size_t )col ); 2001char * ptr = newp + col ; 2002for (size_t i = 0 ;i < (size_t )count ;i ++ ) { 2003memmove (ptr ,y_array [0 ].data , (size_t )yanklen ); 2004ptr += yanklen ; 2005 } 2006memmove (ptr ,oldp + col , (size_t )(oldlen - col )+ 1 );// +1 for NUL 2007ml_replace (lnum ,newp , false); 2008 2009// compute the byte offset for the last character 2010first_byte_off = utf_head_off (newp ,ptr - 1 ); 2011 2012// Place cursor on last putted char. 2013if (lnum == curwin -> w_cursor .lnum ) { 2014// make sure curwin->w_virtcol is updated 2015changed_cline_bef_curs (curwin ); 2016invalidate_botline_win (curwin ); 2017curwin -> w_cursor .col += (colnr_T )(totlen - 1 ); 2018 } 2019changed_bytes (lnum ,col ); 2020extmark_splice_cols (curbuf , (int )lnum - 1 ,col , 20210 , (int )totlen ,kExtmarkUndo ); 2022if (Visual .active ) { 2023lnum ++ ; 2024 } 2025 }while (Visual .active && lnum <=end_lnum ); 2026 2027if (Visual .active ) {// reset lnum to the last visual line 2028lnum -- ; 2029 } 2030 } 2031 2032// put '] at the first byte of the last character 2033curbuf -> b_op_end = curwin -> w_cursor ; 2034curbuf -> b_op_end .col -= first_byte_off ; 2035 2036// For "CTRL-O p" in Insert mode, put cursor after last char 2037if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND ))) { 2038curwin -> w_cursor .col ++ ; 2039 }else { 2040curwin -> w_cursor .col -= first_byte_off ; 2041 } 2042 }else { 2043linenr_T new_lnum = new_cursor .lnum ; 2044int indent ; 2045int orig_indent = 0 ; 2046int indent_diff = 0 ;// init for gcc 2047bool first_indent = true; 2048int lendiff = 0 ; 2049 2050if (flags & PUT_FIXINDENT ) { 2051orig_indent = get_indent (); 2052 } 2053 2054// Insert at least one line. When y_type is kMTCharWise, break the first 2055// line in two. 2056for (int cnt = 1 ;cnt <=count ;cnt ++ ) { 2057size_t i = 0 ; 2058if (y_type == kMTCharWise ) { 2059// Split the current line in two at the insert position. 2060// First insert y_array[size - 1] in front of second line. 2061// Then append y_array[0] to first line. 2062lnum = new_cursor .lnum ; 2063char * ptr = ml_get (lnum )+ col ; 2064size_t ptrlen = (size_t )ml_get_len (lnum )- (size_t )col ; 2065totlen = y_array [y_size - 1 ].size ; 2066char * newp = xmalloc (ptrlen + totlen + 1 ); 2067STRCPY (newp ,y_array [y_size - 1 ].data ); 2068STRCPY (newp + totlen ,ptr ); 2069// insert second line 2070ml_append (lnum ,newp ,0 , false); 2071new_lnum ++ ; 2072xfree (newp ); 2073 2074char * oldp = ml_get (lnum ); 2075newp = xmalloc ((size_t )col + (size_t )yanklen + 1 ); 2076// copy first part of line 2077memmove (newp ,oldp , (size_t )col ); 2078// append to first line 2079memmove (newp + col ,y_array [0 ].data , (size_t )yanklen + 1 ); 2080ml_replace (lnum ,newp , false); 2081 2082curwin -> w_cursor .lnum = lnum ; 2083i = 1 ; 2084 } 2085 2086for (;i < y_size ;i ++ ) { 2087if ((y_type != kMTCharWise || i < y_size - 1 )) { 2088if (ml_append (lnum ,y_array [i ].data ,0 , false)== FAIL ) { 2089 gotoerror ; 2090 } 2091new_lnum ++ ; 2092 } 2093lnum ++ ; 2094nr_lines ++ ; 2095if (flags & PUT_FIXINDENT ) { 2096pos_T old_pos = curwin -> w_cursor ; 2097curwin -> w_cursor .lnum = lnum ; 2098char * ptr = ml_get (lnum ); 2099if (cnt == count && i == y_size - 1 ) { 2100lendiff = ml_get_len (lnum ); 2101 } 2102if (* ptr == '#' && preprocs_left ()) { 2103indent = 0 ;// Leave # lines at start 2104 }else if (* ptr == NUL ) { 2105indent = 0 ;// Ignore empty lines 2106 }else if (first_indent ) { 2107indent_diff = orig_indent - get_indent (); 2108indent = orig_indent ; 2109first_indent = false; 2110 }else if ((indent = get_indent ()+ indent_diff )< 0 ) { 2111indent = 0 ; 2112 } 2113set_indent (indent ,SIN_NOMARK ); 2114curwin -> w_cursor = old_pos ; 2115// remember how many chars were removed 2116if (cnt == count && i == y_size - 1 ) { 2117lendiff -= ml_get_len (lnum ); 2118 } 2119 } 2120 } 2121 2122bcount_t totsize = 0 ; 2123int lastsize = 0 ; 2124if (y_type == kMTCharWise 2125|| (y_type == kMTLineWise && (flags & PUT_LINE_SPLIT ))) { 2126for (i = 0 ;i < y_size - 1 ;i ++ ) { 2127totsize += (bcount_t )y_array [i ].size + 1 ; 2128 } 2129lastsize = (int )y_array [y_size - 1 ].size ; 2130totsize += lastsize ; 2131 } 2132if (y_type == kMTCharWise ) { 2133extmark_splice (curbuf , (int )new_cursor .lnum - 1 ,col ,0 ,0 ,0 , 2134 (int )y_size - 1 ,lastsize ,totsize , 2135kExtmarkUndo ); 2136 }else if (y_type == kMTLineWise && (flags & PUT_LINE_SPLIT )) { 2137// Account for last pasted NL + last NL 2138extmark_splice (curbuf , (int )new_cursor .lnum - 1 ,split_pos ,0 ,0 ,0 , 2139 (int )y_size + 1 ,0 ,totsize + 2 ,kExtmarkUndo ); 2140 } 2141 2142if (cnt == 1 ) { 2143new_lnum = lnum ; 2144 } 2145 } 2146 2147error : 2148// Adjust marks. 2149if (y_type == kMTLineWise ) { 2150curbuf -> b_op_start .col = 0 ; 2151if (dir == FORWARD ) { 2152curbuf -> b_op_start .lnum ++ ; 2153 } 2154 } 2155 2156ExtmarkOp kind = (y_type == kMTLineWise && !(flags & PUT_LINE_SPLIT )) 2157 ?kExtmarkUndo :kExtmarkNOOP ; 2158mark_adjust (curbuf -> b_op_start .lnum + (y_type == kMTCharWise ), 2159 (linenr_T )MAXLNUM ,nr_lines ,0 ,kind ); 2160 2161// note changed text for displaying and folding 2162if (y_type == kMTCharWise ) { 2163changed_lines (curbuf ,curwin -> w_cursor .lnum ,col , 2164curwin -> w_cursor .lnum + 1 ,nr_lines , true); 2165 }else { 2166changed_lines (curbuf ,curbuf -> b_op_start .lnum ,0 , 2167curbuf -> b_op_start .lnum ,nr_lines , true); 2168 } 2169 2170// Put the '] mark on the first byte of the last inserted character. 2171// Correct the length for change in indent. 2172curbuf -> b_op_end .lnum = new_lnum ; 2173col = MAX (0 , (colnr_T )y_array [y_size - 1 ].size - lendiff ); 2174if (col > 1 ) { 2175curbuf -> b_op_end .col = col - 1 ; 2176if (y_array [y_size - 1 ].size > 0 ) { 2177curbuf -> b_op_end .col -= utf_head_off (y_array [y_size - 1 ].data , 2178y_array [y_size - 1 ].data 2179+ y_array [y_size - 1 ].size - 1 ); 2180 } 2181 }else { 2182curbuf -> b_op_end .col = 0 ; 2183 } 2184 2185if (flags & PUT_CURSLINE ) { 2186// ":put": put cursor on last inserted line 2187curwin -> w_cursor .lnum = lnum ; 2188beginline (BL_WHITE |BL_FIX ); 2189 }else if (flags & PUT_CURSEND ) { 2190// put cursor after inserted text 2191if (y_type == kMTLineWise ) { 2192if (lnum >=curbuf -> b_ml .ml_line_count ) { 2193curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 2194 }else { 2195curwin -> w_cursor .lnum = lnum + 1 ; 2196 } 2197curwin -> w_cursor .col = 0 ; 2198 }else { 2199curwin -> w_cursor .lnum = new_lnum ; 2200curwin -> w_cursor .col = col ; 2201curbuf -> b_op_end = curwin -> w_cursor ; 2202if (col > 1 ) { 2203curbuf -> b_op_end .col = col - 1 ; 2204 } 2205 } 2206 }else if (y_type == kMTLineWise ) { 2207// put cursor on first non-blank in first inserted line 2208curwin -> w_cursor .col = 0 ; 2209if (dir == FORWARD ) { 2210curwin -> w_cursor .lnum ++ ; 2211 } 2212beginline (BL_WHITE |BL_FIX ); 2213 }else {// put cursor on first inserted character 2214curwin -> w_cursor = new_cursor ; 2215 } 2216 } 2217 } 2218 2219msgmore (nr_lines ); 2220curwin -> w_set_curswant = true; 2221 2222// Make sure the cursor is not after the NUL. 2223int len = get_cursor_line_len (); 2224if (curwin -> w_cursor .col > len ) { 2225if (cur_ve_flags == kOptVeFlagAll ) { 2226curwin -> w_cursor .coladd = curwin -> w_cursor .col - len ; 2227 } 2228curwin -> w_cursor .col = len ; 2229 } 2230 2231end : 2232if (cmdmod .cmod_flags & CMOD_LOCKMARKS ) { 2233curbuf -> b_op_start = orig_start ; 2234curbuf -> b_op_end = orig_end ; 2235 } 2236 2237if (has_event (EVENT_TEXTPUTPOST )) { 2238if (insert_string .data == NULL ) { 2239put_do_autocmd (regname ,reg ,NULL , true,dir ); 2240 }else { 2241put_do_autocmd (regname ,NULL ,& insert_string , true,dir ); 2242 } 2243 } 2244 2245if (allocated ) { 2246xfree (insert_string .data ); 2247 } 2248if (regname == '=' ) { 2249xfree (y_array ); 2250 } 2251 2252if (!curbuf -> terminal ) {// XXX 2253Visual .active = false; 2254 } 2255 2256// If the cursor is past the end of the line put it at the end. 2257adjust_cursor_eol (); 2258} 2259 2260/// display a string for do_dis() 2261/// truncate at end of screen line 2262/// 2263/// @param skip_esc if true, ignore trailing ESC 2264static void dis_msg (const char * p ,bool skip_esc ) 2265FUNC_ATTR_NONNULL_ALL 2266{ 2267int n = Columns - 6 ; 2268while (* p != NUL 2269&& !(* p == ESC && skip_esc && * (p + 1 )== NUL ) 2270&& (n -= ptr2cells (p )) >=0 ) { 2271int l ; 2272if ((l = utfc_ptr2len (p ))> 1 ) { 2273msg_outtrans_len (p ,l ,0 , false); 2274p += l ; 2275 }else { 2276msg_outtrans_len (p ++ ,1 ,0 , false); 2277 } 2278 } 2279os_breakcheck (); 2280} 2281 2282/// ":dis" and ":registers": Display the contents of the yank registers. 2283void ex_display (exarg_T * eap ) 2284{ 2285char * p ; 2286yankreg_T * yb ; 2287char * arg = eap -> arg ; 2288int type ; 2289 2290if (arg != NULL && * arg == NUL ) { 2291arg = NULL ; 2292 } 2293int hl_id = HLF_8 ; 2294 2295msg_ext_set_kind ("list_cmd" ); 2296msg_ext_skip_flush = true; 2297// Highlight title 2298msg_puts_title (_ ("\nType Name Content" )); 2299for (int i = -1 ;i < NUM_REGISTERS && !got_int ;i ++ ) { 2300int name = get_register_name (i ); 2301if (arg != NULL && vim_strchr (arg ,name )== NULL ) { 2302continue ;// did not ask for this register 2303 } 2304 2305switch (get_reg_type (name ,NULL )) { 2306case kMTLineWise : 2307type = 'l' ;break ; 2308case kMTCharWise : 2309type = 'c' ;break ; 2310default : 2311type = 'b' ;break ; 2312 } 2313 2314if (i == -1 ) { 2315if (y_previous != NULL ) { 2316yb = y_previous ; 2317 }else { 2318yb = & (y_regs [0 ]); 2319 } 2320 }else { 2321yb = & (y_regs [i ]); 2322 } 2323 2324get_clipboard (name ,& yb , true); 2325 2326if (name == mb_tolower (redir_reg ) 2327|| (redir_reg == '"' && yb == y_previous )) { 2328continue ;// do not list register being written to, the 2329// pointer can be freed 2330 } 2331 2332if (yb -> y_array != NULL ) { 2333bool do_show = false; 2334 2335for (size_t j = 0 ; !do_show && j < yb -> y_size ;j ++ ) { 2336do_show = !message_filtered (yb -> y_array [j ].data ); 2337 } 2338 2339if (do_show || yb -> y_size == 0 ) { 2340msg_putchar ('\n' ); 2341msg_puts (" " ); 2342msg_putchar (type ); 2343msg_puts (" " ); 2344msg_putchar ('"' ); 2345msg_putchar (name ); 2346msg_puts (" " ); 2347 2348int n = Columns - 11 ; 2349for (size_t j = 0 ;j < yb -> y_size && n > 1 ;j ++ ) { 2350if (j ) { 2351msg_puts_hl ("^J" ,hl_id , false); 2352n -= 2 ; 2353 } 2354for (p = yb -> y_array [j ].data ; 2355* p != NUL && (n -= ptr2cells (p )) >=0 ;p ++ ) { 2356int clen = utfc_ptr2len (p ); 2357msg_outtrans_len (p ,clen ,0 , false); 2358p += clen - 1 ; 2359 } 2360 } 2361if (n > 1 && yb -> y_type == kMTLineWise ) { 2362msg_puts_hl ("^J" ,hl_id , false); 2363 } 2364 } 2365os_breakcheck (); 2366 } 2367 } 2368 2369// display last inserted text 2370String insert = get_last_insert (); 2371if ((p = insert .data )!= NULL 2372&& (arg == NULL || vim_strchr (arg ,'.' )!= NULL )&& !got_int 2373&& !message_filtered (p )) { 2374msg_puts ("\n c \". " ); 2375dis_msg (p , true); 2376 } 2377 2378// display last command line 2379if (last_cmdline != NULL && (arg == NULL || vim_strchr (arg ,':' )!= NULL ) 2380&& !got_int && !message_filtered (last_cmdline )) { 2381msg_puts ("\n c \": " ); 2382dis_msg (last_cmdline , false); 2383 } 2384 2385// display current file name 2386if (curbuf -> b_fname != NULL 2387&& (arg == NULL || vim_strchr (arg ,'%' )!= NULL )&& !got_int 2388&& !message_filtered (curbuf -> b_fname )) { 2389msg_puts ("\n c \"% " ); 2390dis_msg (curbuf -> b_fname , false); 2391 } 2392 2393// display alternate file name 2394if ((arg == NULL || vim_strchr (arg ,'#' )!= NULL )&& !got_int ) { 2395char * fname ; 2396linenr_T dummy ; 2397 2398if (buflist_name_nr (0 ,& fname ,& dummy )!= FAIL && !message_filtered (fname )) { 2399msg_puts ("\n c \"# " ); 2400dis_msg (fname , false); 2401 } 2402 } 2403 2404// display last search pattern 2405if (last_search_pat ()!= NULL 2406&& (arg == NULL || vim_strchr (arg ,'/' )!= NULL )&& !got_int 2407&& !message_filtered (last_search_pat ())) { 2408msg_puts ("\n c \"/ " ); 2409dis_msg (last_search_pat (), false); 2410 } 2411 2412// display last used expression 2413if (expr_line != NULL && (arg == NULL || vim_strchr (arg ,'=' )!= NULL ) 2414&& !got_int && !message_filtered (expr_line )) { 2415msg_puts ("\n c \"= " ); 2416dis_msg (expr_line , false); 2417 } 2418msg_ext_skip_flush = false; 2419} 2420 2421/// Used for getregtype() 2422/// 2423/// @return the type of a register or 2424/// kMTUnknown for error. 2425MotionType get_reg_type (int regname ,colnr_T * reg_width ) 2426{ 2427switch (regname ) { 2428case '%' :// file name 2429case '#' :// alternate file name 2430case '=' :// expression 2431case ':' :// last command line 2432case '/' :// last search-pattern 2433case '.' :// last inserted text 2434case Ctrl_F :// Filename under cursor 2435case Ctrl_P :// Path under cursor, expand via "path" 2436case Ctrl_W :// word under cursor 2437case Ctrl_A :// WORD (mnemonic All) under cursor 2438case '_' :// black hole: always empty 2439return kMTCharWise ; 2440 } 2441 2442if (regname != NUL && !valid_yank_reg (regname , false)) { 2443return kMTUnknown ; 2444 } 2445 2446yankreg_T * reg = get_yank_register (regname ,YREG_PASTE ); 2447 2448if (reg -> y_array != NULL ) { 2449if (reg_width != NULL && reg -> y_type == kMTBlockWise ) { 2450* reg_width = reg -> y_width ; 2451 } 2452return reg -> y_type ; 2453 } 2454return kMTUnknown ; 2455} 2456 2457/// When `flags` has `kGRegList` return a list with text `s`. 2458/// Otherwise just return `s`. 2459/// 2460/// @return a void * for use in get_reg_contents(). 2461static void * get_reg_wrap_one_line (char * s ,int flags ) 2462{ 2463if (!(flags & kGRegList )) { 2464return s ; 2465 } 2466list_T * const list = tv_list_alloc (1 ); 2467tv_list_append_allocated_string (list ,s ); 2468return list ; 2469} 2470 2471/// Gets the contents of a register. 2472/// @remark Used for `@r` in expressions and for `getreg()`. 2473/// 2474/// @param regname The register. 2475/// @param flags see @ref GRegFlags 2476/// 2477/// @returns The contents of the register as an allocated string. 2478/// @returns A linked list when `flags` contains @ref kGRegList. 2479/// @returns NULL for error. 2480void * get_reg_contents (int regname ,int flags ) 2481{ 2482// Don't allow using an expression register inside an expression. 2483if (regname == '=' ) { 2484if (flags & kGRegNoExpr ) { 2485return NULL ; 2486 } 2487if (flags & kGRegExprSrc ) { 2488return get_reg_wrap_one_line (get_expr_line_src (),flags ); 2489 } 2490return get_reg_wrap_one_line (get_expr_line (),flags ); 2491 } 2492 2493if (regname == '@' ) {// "@@" is used for unnamed register 2494regname = '"' ; 2495 } 2496 2497// check for valid regname 2498if (regname != NUL && !valid_yank_reg (regname , false)) { 2499return NULL ; 2500 } 2501 2502char * retval ; 2503bool allocated ; 2504if (get_spec_reg (regname ,& retval ,& allocated , false)) { 2505if (retval == NULL ) { 2506return NULL ; 2507 } 2508if (allocated ) { 2509return get_reg_wrap_one_line (retval ,flags ); 2510 } 2511return get_reg_wrap_one_line (xstrdup (retval ),flags ); 2512 } 2513 2514yankreg_T * reg = get_yank_register (regname ,YREG_PUT ); 2515if (reg -> y_array == NULL ) { 2516return NULL ; 2517 } 2518 2519if (flags & kGRegList ) { 2520list_T * const list = tv_list_alloc ((ptrdiff_t )reg -> y_size ); 2521for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 2522tv_list_append_string (list ,reg -> y_array [i ].data , (int )reg -> y_array [i ].size ); 2523 } 2524 2525return list ; 2526 } 2527 2528// Compute length of resulting string. 2529size_t len = 0 ; 2530for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 2531len += reg -> y_array [i ].size ; 2532// Insert a newline between lines and after last line if y_type is kMTLineWise. 2533if (reg -> y_type == kMTLineWise || i < reg -> y_size - 1 ) { 2534len ++ ; 2535 } 2536 } 2537 2538retval = xmalloc (len + 1 ); 2539 2540// Copy the lines of the yank register into the string. 2541len = 0 ; 2542for (size_t i = 0 ;i < reg -> y_size ;i ++ ) { 2543STRCPY (retval + len ,reg -> y_array [i ].data ); 2544len += reg -> y_array [i ].size ; 2545 2546// Insert a newline between lines and after the last line if y_type is kMTLineWise. 2547if (reg -> y_type == kMTLineWise || i < reg -> y_size - 1 ) { 2548retval [len ++ ]= '\n' ; 2549 } 2550 } 2551retval [len ]= NUL ; 2552 2553return retval ; 2554} 2555 2556static yankreg_T * init_write_reg (int name ,yankreg_T ** old_y_previous ,bool must_append ) 2557{ 2558if (!valid_yank_reg (name , true)) {// check for valid reg name 2559emsg_invreg (name ); 2560return NULL ; 2561 } 2562 2563// Don't want to change the current (unnamed) register. 2564* old_y_previous = y_previous ; 2565 2566yankreg_T * reg = get_yank_register (name ,YREG_YANK ); 2567if (!is_append_register (name )&& !must_append ) { 2568free_register (reg ); 2569 } 2570return reg ; 2571} 2572 2573/// str_to_reg - Put a string into a register. 2574/// 2575/// When the register is not empty, the string is appended. 2576/// 2577/// @param y_ptr pointer to yank register 2578/// @param yank_type The motion type (kMTUnknown to auto detect) 2579/// @param str string or list of strings to put in register 2580/// @param len length of the string (Ignored when str_list=true.) 2581/// @param blocklen width of visual block, or -1 for "I don't know." 2582/// @param str_list True if str is `char **`. 2583static void str_to_reg (yankreg_T * y_ptr ,MotionType yank_type ,const char * str ,size_t len , 2584colnr_T blocklen ,bool str_list ) 2585FUNC_ATTR_NONNULL_ALL 2586{ 2587if (y_ptr -> y_array == NULL ) {// NULL means empty register 2588y_ptr -> y_size = 0 ; 2589 } 2590 2591if (yank_type == kMTUnknown ) { 2592yank_type = ((str_list 2593|| (len > 0 && (str [len - 1 ]== NL || str [len - 1 ]== CAR ))) 2594 ?kMTLineWise :kMTCharWise ); 2595 } 2596 2597size_t newlines = 0 ; 2598bool extraline = false;// extra line at the end 2599bool append = false;// append to last line in register 2600 2601// Count the number of lines within the string 2602if (str_list ) { 2603for (char ** ss = (char ** )str ;* ss != NULL ;ss ++ ) { 2604newlines ++ ; 2605 } 2606 }else { 2607newlines = memcnt (str ,'\n' ,len ); 2608if (yank_type == kMTCharWise || len == 0 || str [len - 1 ]!= '\n' ) { 2609extraline = 1 ; 2610newlines ++ ;// count extra newline at the end 2611 } 2612if (y_ptr -> y_size > 0 && y_ptr -> y_type == kMTCharWise ) { 2613append = true; 2614newlines -- ;// uncount newline when appending first line 2615 } 2616 } 2617 2618// Without any lines make the register empty. 2619if (y_ptr -> y_size + newlines == 0 ) { 2620XFREE_CLEAR (y_ptr -> y_array ); 2621return ; 2622 } 2623 2624// Grow the register array to hold the pointers to the new lines. 2625String * pp = xrealloc (y_ptr -> y_array , (y_ptr -> y_size + newlines )* sizeof (String )); 2626y_ptr -> y_array = pp ; 2627 2628size_t lnum = y_ptr -> y_size ;// The current line number. 2629 2630// If called with `blocklen < 0`, we have to update the yank reg's width. 2631size_t maxlen = 0 ; 2632 2633// Find the end of each line and save it into the array. 2634if (str_list ) { 2635for (char ** ss = (char ** )str ;* ss != NULL ;ss ++ ,lnum ++ ) { 2636pp [lnum ]= cstr_to_string (* ss ); 2637if (yank_type == kMTBlockWise ) { 2638size_t charlen = mb_string2cells (* ss ); 2639maxlen = MAX (maxlen ,charlen ); 2640 } 2641 } 2642 }else { 2643size_t line_len ; 2644for (const char * start = str ,* end = str + len ; 2645start < end + extraline ; 2646start += line_len + 1 ,lnum ++ ) { 2647int charlen = 0 ; 2648 2649const char * line_end = start ; 2650while (line_end < end ) {// find the end of the line 2651if (* line_end == '\n' ) { 2652break ; 2653 } 2654if (yank_type == kMTBlockWise ) { 2655charlen += utf_ptr2cells_len (line_end , (int )(end - line_end )); 2656 } 2657 2658if (* line_end == NUL ) { 2659line_end ++ ;// registers can have NUL chars 2660 }else { 2661line_end += utfc_ptr2len_len (line_end , (int )(end - line_end )); 2662 } 2663 } 2664assert (line_end - start >=0 ); 2665line_len = (size_t )(line_end - start ); 2666maxlen = MAX (maxlen , (size_t )charlen ); 2667 2668// When appending, copy the previous line and free it after. 2669size_t extra = append ?pp [-- lnum ].size :0 ; 2670char * s = xmallocz (line_len + extra ); 2671if (extra > 0 ) { 2672memcpy (s ,pp [lnum ].data ,extra ); 2673 } 2674if (line_len > 0 ) { 2675memcpy (s + extra ,start ,line_len ); 2676 } 2677size_t s_len = extra + line_len ; 2678 2679if (append ) { 2680xfree (pp [lnum ].data ); 2681append = false;// only first line is appended 2682 } 2683pp [lnum ]= cbuf_as_string (s ,s_len ); 2684 2685// Convert NULs to '\n' to prevent truncation. 2686memchrsub (pp [lnum ].data ,NUL ,'\n' ,s_len ); 2687 } 2688 } 2689y_ptr -> y_type = yank_type ; 2690y_ptr -> y_size = lnum ; 2691XFREE_CLEAR (y_ptr -> additional_data ); 2692y_ptr -> timestamp = (Timestamp )os_realtime (); 2693if (yank_type == kMTBlockWise ) { 2694y_ptr -> y_width = (blocklen == -1 ? (colnr_T )maxlen - 1 :blocklen ); 2695 }else { 2696y_ptr -> y_width = 0 ; 2697 } 2698} 2699 2700static void finish_write_reg (int name ,yankreg_T * reg ,yankreg_T * old_y_previous ) 2701{ 2702// Send text of clipboard register to the clipboard. 2703set_clipboard (name ,reg ); 2704 2705// ':let @" = "val"' should change the meaning of the "" register 2706if (name != '"' ) { 2707y_previous = old_y_previous ; 2708 } 2709} 2710 2711/// store `str` in register `name` 2712/// 2713/// @see write_reg_contents_ex 2714void write_reg_contents (int name ,const char * str ,ssize_t len ,int must_append ) 2715{ 2716write_reg_contents_ex (name ,str ,len ,must_append ,kMTUnknown ,0 ); 2717} 2718 2719void write_reg_contents_lst (int name ,char ** strings ,bool must_append ,MotionType yank_type , 2720colnr_T block_len ) 2721{ 2722if (name == '/' || name == '=' || name == '#' ) { 2723char * s = strings [0 ]; 2724if (strings [0 ]== NULL ) { 2725s = "" ; 2726 }else if (strings [1 ]!= NULL ) { 2727semsg (_ (e_register_char_cannot_contain_multiple_lines ),name ); 2728return ; 2729 } 2730write_reg_contents_ex (name ,s ,-1 ,must_append ,yank_type ,block_len ); 2731return ; 2732 } 2733 2734// black hole: nothing to do 2735if (name == '_' ) { 2736return ; 2737 } 2738 2739yankreg_T * old_y_previous ,* reg ; 2740if (!(reg = init_write_reg (name ,& old_y_previous ,must_append ))) { 2741return ; 2742 } 2743 2744str_to_reg (reg ,yank_type , (char * )strings ,strlen ((char * )strings ), 2745block_len , true); 2746finish_write_reg (name ,reg ,old_y_previous ); 2747} 2748 2749/// write_reg_contents_ex - store `str` in register `name` 2750/// 2751/// If `str` ends in '\n' or '\r', use linewise, otherwise use charwise. 2752/// 2753/// @warning when `name` is '/', `len` and `must_append` are ignored. This 2754/// means that `str` MUST be NUL-terminated. 2755/// 2756/// @param name The name of the register 2757/// @param str The contents to write 2758/// @param len If >= 0, write `len` bytes of `str`. Otherwise, write 2759/// `strlen(str)` bytes. If `len` is larger than the 2760/// allocated size of `src`, the behaviour is undefined. 2761/// @param must_append If true, append the contents of `str` to the current 2762/// contents of the register. Note that regardless of 2763/// `must_append`, this function will append when `name` 2764/// is an uppercase letter. 2765/// @param yank_type The motion type (kMTUnknown to auto detect) 2766/// @param block_len width of visual block 2767void write_reg_contents_ex (int name ,const char * str ,ssize_t len ,bool must_append , 2768MotionType yank_type ,colnr_T block_len ) 2769{ 2770if (len < 0 ) { 2771len = (ssize_t )strlen (str ); 2772 } 2773 2774// Special case: '/' search pattern 2775if (name == '/' ) { 2776set_last_search_pat (str ,RE_SEARCH , true, true); 2777return ; 2778 } 2779 2780if (name == '#' ) { 2781if (len == 0 ) { 2782curwin -> w_alt_fnum = 0 ;// clear altfile 2783return ; 2784 } 2785 2786buf_T * buf ; 2787 2788if (ascii_isdigit (* str )) { 2789int num = atoi (str ); 2790 2791buf = buflist_findnr (num ); 2792if (buf == NULL ) { 2793semsg (_ (e_nobufnr ), (int64_t )num ); 2794 } 2795 }else { 2796buf = buflist_findnr (buflist_findpat (str ,str + len , true, false, false)); 2797 } 2798if (buf == NULL ) { 2799return ; 2800 } 2801curwin -> w_alt_fnum = buf -> b_fnum ; 2802return ; 2803 } 2804 2805if (name == '=' ) { 2806size_t offset = 0 ; 2807size_t totlen = (size_t )len ; 2808 2809if (must_append && expr_line ) { 2810// append has been specified and expr_line already exists, so we'll 2811// append the new string to expr_line. 2812size_t exprlen = strlen (expr_line ); 2813 2814totlen += exprlen ; 2815offset = exprlen ; 2816 } 2817 2818// modify the global expr_line, extend/shrink it if necessary (realloc). 2819// Copy the input string into the adjusted memory at the specified 2820// offset. 2821expr_line = xrealloc (expr_line ,totlen + 1 ); 2822memcpy (expr_line + offset ,str , (size_t )len ); 2823expr_line [totlen ]= NUL ; 2824 2825return ; 2826 } 2827 2828if (name == '_' ) {// black hole: nothing to do 2829return ; 2830 } 2831 2832yankreg_T * old_y_previous ,* reg ; 2833if (!(reg = init_write_reg (name ,& old_y_previous ,must_append ))) { 2834return ; 2835 } 2836str_to_reg (reg ,yank_type ,str , (size_t )len ,block_len , false); 2837finish_write_reg (name ,reg ,old_y_previous ); 2838} 2839 2840/// @param[out] reg Expected to be empty 2841bool prepare_yankreg_from_object (yankreg_T * reg ,String regtype ,size_t lines ) 2842{ 2843char type = regtype .data ?regtype .data [0 ] :NUL ; 2844 2845switch (type ) { 2846case 0 : 2847reg -> y_type = kMTUnknown ; 2848break ; 2849case 'v' : 2850case 'c' : 2851reg -> y_type = kMTCharWise ; 2852break ; 2853case 'V' : 2854case 'l' : 2855reg -> y_type = kMTLineWise ; 2856break ; 2857case 'b' : 2858case Ctrl_V : 2859reg -> y_type = kMTBlockWise ; 2860break ; 2861default : 2862return false; 2863 } 2864 2865reg -> y_width = 0 ; 2866if (regtype .size > 1 ) { 2867if (reg -> y_type != kMTBlockWise ) { 2868return false; 2869 } 2870 2871// allow "b7" for a block at least 7 spaces wide 2872if (!ascii_isdigit (regtype .data [1 ])) { 2873return false; 2874 } 2875const char * p = regtype .data + 1 ; 2876reg -> y_width = getdigits_int ((char ** )& p , false,1 )- 1 ; 2877if (regtype .size > (size_t )(p - regtype .data )) { 2878return false; 2879 } 2880 } 2881 2882reg -> additional_data = NULL ; 2883reg -> timestamp = 0 ; 2884return true; 2885} 2886 2887void finish_yankreg_from_object (yankreg_T * reg ,bool clipboard_adjust ) 2888{ 2889if (reg -> y_size > 0 && reg -> y_array [reg -> y_size - 1 ].size == 0 ) { 2890// a known-to-be charwise yank might have a final linebreak 2891// but otherwise there is no line after the final newline 2892if (reg -> y_type != kMTCharWise ) { 2893if (reg -> y_type == kMTUnknown || clipboard_adjust ) { 2894reg -> y_size -- ; 2895 } 2896if (reg -> y_type == kMTUnknown ) { 2897reg -> y_type = kMTLineWise ; 2898 } 2899 } 2900 }else { 2901if (reg -> y_type == kMTUnknown ) { 2902reg -> y_type = kMTCharWise ; 2903 } 2904 } 2905 2906update_yankreg_width (reg ); 2907}