robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// ex_cmds.c: some functions for command line commands 2 3#include <assert.h> 4#include <ctype.h> 5#include <float.h> 6#include <inttypes.h> 7#include <limits.h> 8#include <math.h> 9#include <stdbool.h> 10#include <stddef.h> 11#include <stdio.h> 12#include <stdlib.h> 13#include <string.h> 14#include <time.h> 15 16#include "auto/config.h" 17#include "klib/kvec.h" 18#include "nvim/api/private/helpers.h" 19#include "nvim/arglist.h" 20#include "nvim/ascii_defs.h" 21#include "nvim/autocmd.h" 22#include "nvim/autocmd_defs.h" 23#include "nvim/buffer.h" 24#include "nvim/buffer_defs.h" 25#include "nvim/buffer_updates.h" 26#include "nvim/bufwrite.h" 27#include "nvim/change.h" 28#include "nvim/channel.h" 29#include "nvim/charset.h" 30#include "nvim/cmdexpand_defs.h" 31#include "nvim/cmdhist.h" 32#include "nvim/cursor.h" 33#include "nvim/decoration.h" 34#include "nvim/dialog.h" 35#include "nvim/diff.h" 36#include "nvim/digraph.h" 37#include "nvim/drawscreen.h" 38#include "nvim/errors.h" 39#include "nvim/eval/typval.h" 40#include "nvim/eval/typval_defs.h" 41#include "nvim/eval/vars.h" 42#include "nvim/ex_cmds.h" 43#include "nvim/ex_cmds2.h" 44#include "nvim/ex_cmds_defs.h" 45#include "nvim/ex_docmd.h" 46#include "nvim/ex_eval.h" 47#include "nvim/ex_getln.h" 48#include "nvim/extmark.h" 49#include "nvim/extmark_defs.h" 50#include "nvim/fileio.h" 51#include "nvim/fold.h" 52#include "nvim/gettext_defs.h" 53#include "nvim/globals.h" 54#include "nvim/help.h" 55#include "nvim/highlight_defs.h" 56#include "nvim/highlight_group.h" 57#include "nvim/indent.h" 58#include "nvim/input.h" 59#include "nvim/insert.h" 60#include "nvim/lua/executor.h" 61#include "nvim/macros_defs.h" 62#include "nvim/main.h" 63#include "nvim/mark.h" 64#include "nvim/mark_defs.h" 65#include "nvim/mbyte.h" 66#include "nvim/memline.h" 67#include "nvim/memline_defs.h" 68#include "nvim/memory.h" 69#include "nvim/message.h" 70#include "nvim/mouse.h" 71#include "nvim/move.h" 72#include "nvim/normal.h" 73#include "nvim/ops.h" 74#include "nvim/option.h" 75#include "nvim/option_defs.h" 76#include "nvim/option_vars.h" 77#include "nvim/os/fs.h" 78#include "nvim/os/fs_defs.h" 79#include "nvim/os/input.h" 80#include "nvim/os/os.h" 81#include "nvim/os/os_defs.h" 82#include "nvim/os/shell.h" 83#include "nvim/os/time.h" 84#include "nvim/path.h" 85#include "nvim/plines.h" 86#include "nvim/pos_defs.h" 87#include "nvim/profile.h" 88#include "nvim/quickfix.h" 89#include "nvim/regexp.h" 90#include "nvim/regexp_defs.h" 91#include "nvim/search.h" 92#include "nvim/spell.h" 93#include "nvim/state_defs.h" 94#include "nvim/strings.h" 95#include "nvim/terminal.h" 96#include "nvim/types_defs.h" 97#include "nvim/ui.h" 98#include "nvim/ui_defs.h" 99#include "nvim/undo.h" 100#include "nvim/vim_defs.h" 101#include "nvim/window.h" 102#include "nvim/winfloat.h" 103 104/// Case matching style to use for :substitute 105typedef enum { 106kSubHonorOptions = 0 ,///< Honor the user's 'ignorecase'/'smartcase' options 107kSubIgnoreCase ,///< Ignore case of the search 108kSubMatchCase ,///< Match case of the search 109}SubIgnoreType ; 110 111/// Flags kept between calls to :substitute. 112typedef struct { 113bool do_all ;///< do multiple substitutions per line 114bool do_ask ;///< ask for confirmation 115bool do_count ;///< count only 116bool do_error ;///< if false, ignore errors 117bool do_print ;///< print last line with subs 118bool do_list ;///< list last line with subs 119bool do_number ;///< list last line with line nr 120SubIgnoreType do_ic ;///< ignore case flag 121}subflags_T ; 122 123/// Partial result of a substitution during :substitute. 124/// Numbers refer to the buffer _after_ substitution 125typedef struct { 126lpos_T start ;// start of the match 127lpos_T end ;// end of the match 128linenr_T pre_match ;// where to begin showing lines before the match 129}SubResult ; 130 131// Collected results of a substitution for showing them in 132// the preview window 133typedef struct { 134kvec_t (SubResult )subresults ; 135linenr_T lines_needed ;// lines needed in the preview window 136}PreviewLines ; 137 138#include "ex_cmds.c.generated.h" 139 140static const char e_non_numeric_argument_to_z [] 141= N_ ("E144: Non-numeric argument to :z" ); 142 143/// ":ascii" and "ga" implementation 144void do_ascii (exarg_T * eap ) 145{ 146char * data = get_cursor_pos_ptr (); 147size_t len = (size_t )utfc_ptr2len (data ); 148 149if (len == 0 ) { 150msg ("NUL" ,0 ); 151return ; 152 } 153 154bool need_clear = true; 155msg_sb_eol (); 156msg_start (); 157 158int c = utf_ptr2char (data ); 159size_t off = 0 ; 160 161// TODO(bfredl): merge this with the main loop 162if (c < 0x80 ) { 163if (c == NL ) {// NUL is stored as NL. 164c = NUL ; 165 } 166const int cval = (c == CAR && get_fileformat (curbuf )== EOL_MAC 167 ?NL // NL is stored as CR. 168 :c ); 169char buf1 [20 ]; 170if (vim_isprintc (c )&& (c < ' ' || c > '~' )) { 171char buf3 [7 ]; 172transchar_nonprint (curbuf ,buf3 ,c ); 173vim_snprintf (buf1 ,sizeof (buf1 )," <%s>" ,buf3 ); 174 }else { 175buf1 [0 ]= NUL ; 176 } 177char buf2 [20 ]; 178buf2 [0 ]= NUL ; 179 180char * dig = get_digraph_for_char (cval ); 181if (dig != NULL ) { 182vim_snprintf (IObuff ,sizeof (IObuff ), 183_ ("<%s>%s%s %d, Hex %02x, Oct %03o, Digr %s" ), 184transchar (c ),buf1 ,buf2 ,cval ,cval ,cval ,dig ); 185 }else { 186vim_snprintf (IObuff ,sizeof (IObuff ), 187_ ("<%s>%s%s %d, Hex %02x, Octal %03o" ), 188transchar (c ),buf1 ,buf2 ,cval ,cval ,cval ); 189 } 190 191msg_multiline (cstr_as_string (IObuff ),0 , true, false,& need_clear ); 192 193off += (size_t )utf_ptr2len (data );// needed for overlong ascii? 194 } 195 196// Repeat for combining characters, also handle multiby here. 197while (off < len ) { 198c = utf_ptr2char (data + off ); 199 200size_t iobuff_len = 0 ; 201// This assumes every multi-byte char is printable... 202if (off > 0 ) { 203IObuff [iobuff_len ++ ]= ' ' ; 204 } 205IObuff [iobuff_len ++ ]= '<' ; 206if (utf_iscomposing_first (c )) { 207IObuff [iobuff_len ++ ]= ' ' ;// Draw composing char on top of a space. 208 } 209iobuff_len += (size_t )utf_char2bytes (c ,IObuff + iobuff_len ); 210 211char * dig = get_digraph_for_char (c ); 212if (dig != NULL ) { 213vim_snprintf (IObuff + iobuff_len ,sizeof (IObuff )- iobuff_len , 214 (c < 0x10000 215 ?_ ("> %d, Hex %04x, Oct %o, Digr %s" ) 216 :_ ("> %d, Hex %08x, Oct %o, Digr %s" )), 217c ,c ,c ,dig ); 218 }else { 219vim_snprintf (IObuff + iobuff_len ,sizeof (IObuff )- iobuff_len , 220 (c < 0x10000 221 ?_ ("> %d, Hex %04x, Octal %o" ) 222 :_ ("> %d, Hex %08x, Octal %o" )), 223c ,c ,c ); 224 } 225 226msg_multiline (cstr_as_string (IObuff ),0 , true, false,& need_clear ); 227 228off += (size_t )utf_ptr2len (data + off );// needed for overlong ascii? 229 } 230 231if (need_clear ) { 232msg_clr_eos (); 233 } 234msg_end (); 235} 236 237/// ":left", ":center" and ":right": align text. 238void ex_align (exarg_T * eap ) 239{ 240int indent = 0 ; 241int new_indent ; 242 243if (curwin -> w_p_rl ) { 244// switch left and right aligning 245if (eap -> cmdidx == CMD_right ) { 246eap -> cmdidx = CMD_left ; 247 }else if (eap -> cmdidx == CMD_left ) { 248eap -> cmdidx = CMD_right ; 249 } 250 } 251 252int width = atoi (eap -> arg ); 253pos_T save_curpos = curwin -> w_cursor ; 254if (eap -> cmdidx == CMD_left ) {// width is used for new indent 255if (width >=0 ) { 256indent = width ; 257 } 258 }else { 259// if 'textwidth' set, use it 260// else if 'wrapmargin' set, use it 261// if invalid value, use 80 262if (width <=0 ) { 263width = (int )curbuf -> b_p_tw ; 264 } 265if (width == 0 && curbuf -> b_p_wm > 0 ) { 266width = curwin -> w_view_width - (int )curbuf -> b_p_wm ; 267 } 268if (width <=0 ) { 269width = 80 ; 270 } 271 } 272 273if (u_save ((linenr_T )(eap -> line1 - 1 ), (linenr_T )(eap -> line2 + 1 ))== FAIL ) { 274return ; 275 } 276 277for (curwin -> w_cursor .lnum = eap -> line1 ; 278curwin -> w_cursor .lnum <=eap -> line2 ;curwin -> w_cursor .lnum ++ ) { 279if (eap -> cmdidx == CMD_left ) {// left align 280new_indent = indent ; 281 }else { 282int has_tab = false;// avoid uninit warnings 283int len = linelen (eap -> cmdidx == CMD_right ?& has_tab :NULL )- get_indent (); 284 285if (len <=0 ) {// skip blank lines 286continue ; 287 } 288 289if (eap -> cmdidx == CMD_center ) { 290new_indent = (width - len ) /2 ; 291 }else { 292new_indent = width - len ;// right align 293 294// Make sure that embedded TABs don't make the text go too far 295// to the right. 296if (has_tab ) { 297while (new_indent > 0 ) { 298set_indent (new_indent ,0 ); 299if (linelen (NULL ) <=width ) { 300// Now try to move the line as much as possible to 301// the right. Stop when it moves too far. 302do { 303set_indent (++ new_indent ,0 ); 304 }while (linelen (NULL ) <=width ); 305new_indent -- ; 306break ; 307 } 308new_indent -- ; 309 } 310 } 311 } 312 } 313new_indent = MAX (new_indent ,0 ); 314set_indent (new_indent ,0 );// set indent 315 } 316changed_lines (curbuf ,eap -> line1 ,0 ,eap -> line2 + 1 ,0 , true); 317curwin -> w_cursor = save_curpos ; 318beginline (BL_WHITE |BL_FIX ); 319} 320 321/// @return the length of the current line, excluding trailing white space. 322static int linelen (int * has_tab ) 323{ 324char * last ; 325 326// Get the line. If it's empty bail out early (could be the empty string 327// for an unloaded buffer). 328char * line = get_cursor_line_ptr (); 329if (* line == NUL ) { 330return 0 ; 331 } 332// find the first non-blank character 333char * first = skipwhite (line ); 334 335// find the character after the last non-blank character 336for (last = first + strlen (first ); 337last > first && ascii_iswhite (last [-1 ]);last -- ) {} 338char save = * last ; 339* last = NUL ; 340int len = linetabsize_str (line );// Get line length. 341if (has_tab != NULL ) {// Check for embedded TAB. 342* has_tab = vim_strchr (first ,TAB )!= NULL ; 343 } 344* last = save ; 345 346return len ; 347} 348 349// Buffer for two lines used during sorting. They are allocated to 350// contain the longest line being sorted. 351static char * sortbuf1 ; 352static char * sortbuf2 ; 353 354static bool sort_lc ;///< sort using locale 355static bool sort_ic ;///< ignore case 356static bool sort_nr ;///< sort on number 357static bool sort_rx ;///< sort on regex instead of skipping it 358static bool sort_flt ;///< sort on floating number 359 360static bool sort_abort ;///< flag to indicate if sorting has been interrupted 361 362/// Struct to store info to be sorted. 363typedef struct { 364linenr_T lnum ;///< line number 365union { 366struct { 367varnumber_T start_col_nr ;///< starting column number 368varnumber_T end_col_nr ;///< ending column number 369 }line ; 370struct { 371varnumber_T value ;///< value if sorting by integer 372bool is_number ;///< true when line contains a number 373 }num ; 374float_T value_flt ;///< value if sorting by float 375 }st_u ; 376}sorti_T ; 377 378static int string_compare (const void * s1 ,const void * s2 )FUNC_ATTR_NONNULL_ALL 379{ 380if (sort_lc ) { 381return strcoll ((const char * )s1 , (const char * )s2 ); 382 } 383return sort_ic ?STRICMP (s1 ,s2 ) :strcmp (s1 ,s2 ); 384} 385 386static int sort_compare (const void * s1 ,const void * s2 ) 387{ 388sorti_T l1 = * (sorti_T * )s1 ; 389sorti_T l2 = * (sorti_T * )s2 ; 390int result = 0 ; 391 392// If the user interrupts, there's no way to stop qsort() immediately, but 393// if we return 0 every time, qsort will assume it's done sorting and 394// exit. 395if (sort_abort ) { 396return 0 ; 397 } 398fast_breakcheck (); 399if (got_int ) { 400sort_abort = true; 401 } 402 403// When sorting numbers "start_col_nr" is the number, not the column 404// number. 405if (sort_nr ) { 406if (l1 .st_u .num .is_number != l2 .st_u .num .is_number ) { 407result = l1 .st_u .num .is_number > l2 .st_u .num .is_number ?1 :-1 ; 408 }else { 409result = l1 .st_u .num .value == l2 .st_u .num .value 410 ?0 411 :l1 .st_u .num .value > l2 .st_u .num .value ?1 :-1 ; 412 } 413 }else if (sort_flt ) { 414result = l1 .st_u .value_flt == l2 .st_u .value_flt 415 ?0 416 :l1 .st_u .value_flt > l2 .st_u .value_flt ?1 :-1 ; 417 }else { 418// We need to copy one line into "sortbuf1", because there is no 419// guarantee that the first pointer becomes invalid when obtaining the 420// second one. 421memcpy (sortbuf1 ,ml_get (l1 .lnum )+ l1 .st_u .line .start_col_nr , 422 (size_t )(l1 .st_u .line .end_col_nr - l1 .st_u .line .start_col_nr + 1 )); 423sortbuf1 [l1 .st_u .line .end_col_nr - l1 .st_u .line .start_col_nr ]= NUL ; 424memcpy (sortbuf2 ,ml_get (l2 .lnum )+ l2 .st_u .line .start_col_nr , 425 (size_t )(l2 .st_u .line .end_col_nr - l2 .st_u .line .start_col_nr + 1 )); 426sortbuf2 [l2 .st_u .line .end_col_nr - l2 .st_u .line .start_col_nr ]= NUL ; 427 428result = string_compare (sortbuf1 ,sortbuf2 ); 429 } 430 431// If two lines have the same value, preserve the original line order. 432if (result == 0 ) { 433return l1 .lnum - l2 .lnum ; 434 } 435return result ; 436} 437 438/// ":sort". 439void ex_sort (exarg_T * eap ) 440{ 441regmatch_T regmatch ; 442int maxlen = 0 ; 443size_t count = (size_t )(eap -> line2 - eap -> line1 )+ 1 ; 444size_t i ; 445bool unique = false; 446int sort_what = 0 ; 447 448// Sorting one line is really quick! 449if (count <=1 ) { 450return ; 451 } 452 453if (u_save ((linenr_T )(eap -> line1 - 1 ), (linenr_T )(eap -> line2 + 1 ))== FAIL ) { 454return ; 455 } 456sortbuf1 = NULL ; 457sortbuf2 = NULL ; 458regmatch .regprog = NULL ; 459sorti_T * nrs = xmalloc (count * sizeof (sorti_T )); 460 461sort_abort = sort_ic = sort_lc = sort_rx = sort_nr = sort_flt = false; 462size_t format_found = 0 ; 463bool change_occurred = false;// Buffer contents changed. 464 465for (char * p = eap -> arg ;* p != NUL ;p ++ ) { 466if (ascii_iswhite (* p )) { 467// Skip 468 }else if (* p == 'i' ) { 469sort_ic = true; 470 }else if (* p == 'l' ) { 471sort_lc = true; 472 }else if (* p == 'r' ) { 473sort_rx = true; 474 }else if (* p == 'n' ) { 475sort_nr = true; 476format_found ++ ; 477 }else if (* p == 'f' ) { 478sort_flt = true; 479format_found ++ ; 480 }else if (* p == 'b' ) { 481sort_what = STR2NR_BIN + STR2NR_FORCE ; 482format_found ++ ; 483 }else if (* p == 'o' ) { 484sort_what = STR2NR_OCT + STR2NR_FORCE ; 485format_found ++ ; 486 }else if (* p == 'x' ) { 487sort_what = STR2NR_HEX + STR2NR_FORCE ; 488format_found ++ ; 489 }else if (* p == 'u' ) { 490unique = true; 491 }else if (* p == '"' ) {// comment start 492break ; 493 }else if (check_nextcmd (p )!= NULL ) { 494eap -> nextcmd = check_nextcmd (p ); 495break ; 496 }else if (!ASCII_ISALPHA (* p )&& regmatch .regprog == NULL ) { 497char * s = skip_regexp_err (p + 1 ,* p , true); 498if (s == NULL ) { 499 gotosortend ; 500 } 501* s = NUL ; 502// Use last search pattern if sort pattern is empty. 503if (s == p + 1 ) { 504if (last_search_pat ()== NULL ) { 505emsg (_ (e_noprevre )); 506 gotosortend ; 507 } 508regmatch .regprog = vim_regcomp (last_search_pat (),RE_MAGIC ); 509 }else { 510regmatch .regprog = vim_regcomp (p + 1 ,RE_MAGIC ); 511 } 512if (regmatch .regprog == NULL ) { 513 gotosortend ; 514 } 515p = s ;// continue after the regexp 516regmatch .rm_ic = p_ic ; 517 }else { 518semsg (_ (e_invarg2 ),p ); 519 gotosortend ; 520 } 521 } 522 523// Can only have one of 'n', 'b', 'o' and 'x'. 524if (format_found > 1 ) { 525emsg (_ (e_invarg )); 526 gotosortend ; 527 } 528 529// From here on "sort_nr" is used as a flag for any integer number 530// sorting. 531sort_nr |=sort_what ; 532 533// Make an array with all line numbers. This avoids having to copy all 534// the lines into allocated memory. 535// When sorting on strings "start_col_nr" is the offset in the line, for 536// numbers sorting it's the number to sort on. This means the pattern 537// matching and number conversion only has to be done once per line. 538// Also get the longest line length for allocating "sortbuf". 539for (linenr_T lnum = eap -> line1 ;lnum <=eap -> line2 ;lnum ++ ) { 540char * s = ml_get (lnum ); 541int len = ml_get_len (lnum ); 542maxlen = MAX (maxlen ,len ); 543 544colnr_T start_col = 0 ; 545colnr_T end_col = len ; 546if (regmatch .regprog != NULL && vim_regexec (& regmatch ,s ,0 )) { 547if (sort_rx ) { 548start_col = (colnr_T )(regmatch .startp [0 ]- s ); 549end_col = (colnr_T )(regmatch .endp [0 ]- s ); 550 }else { 551start_col = (colnr_T )(regmatch .endp [0 ]- s ); 552 } 553 }else if (regmatch .regprog != NULL ) { 554end_col = 0 ; 555 } 556 557if (sort_nr || sort_flt ) { 558// Make sure vim_str2nr() doesn't read any digits past the end 559// of the match, by temporarily terminating the string there 560char * s2 = s + end_col ; 561char c = * s2 ;// temporary character storage 562* s2 = NUL ; 563// Sorting on number: Store the number itself. 564char * p = s + start_col ; 565if (sort_nr ) { 566if (sort_what & STR2NR_HEX ) { 567s = skiptohex (p ); 568 }else if (sort_what & STR2NR_BIN ) { 569s = (char * )skiptobin (p ); 570 }else { 571s = skiptodigit (p ); 572 } 573if (s > p && s [-1 ]== '-' ) { 574s -- ;// include preceding negative sign 575 } 576if (* s == NUL ) { 577// line without number should sort before any number 578nrs [lnum - eap -> line1 ].st_u .num .is_number = false; 579nrs [lnum - eap -> line1 ].st_u .num .value = 0 ; 580 }else { 581nrs [lnum - eap -> line1 ].st_u .num .is_number = true; 582vim_str2nr (s ,NULL ,NULL ,sort_what , 583& nrs [lnum - eap -> line1 ].st_u .num .value ,NULL ,0 , false,NULL ); 584 } 585 }else { 586s = skipwhite (p ); 587if (* s == '+' ) { 588s = skipwhite (s + 1 ); 589 } 590 591if (* s == NUL ) { 592// empty line should sort before any number 593nrs [lnum - eap -> line1 ].st_u .value_flt = - DBL_MAX ; 594 }else { 595nrs [lnum - eap -> line1 ].st_u .value_flt = strtod (s ,NULL ); 596 } 597 } 598* s2 = c ; 599 }else { 600// Store the column to sort at. 601nrs [lnum - eap -> line1 ].st_u .line .start_col_nr = start_col ; 602nrs [lnum - eap -> line1 ].st_u .line .end_col_nr = end_col ; 603 } 604 605nrs [lnum - eap -> line1 ].lnum = lnum ; 606 607if (regmatch .regprog != NULL ) { 608fast_breakcheck (); 609 } 610if (got_int ) { 611 gotosortend ; 612 } 613 } 614 615// Allocate a buffer that can hold the longest line. 616sortbuf1 = xmalloc ((size_t )maxlen + 1 ); 617sortbuf2 = xmalloc ((size_t )maxlen + 1 ); 618 619// Sort the array of line numbers. Note: can't be interrupted! 620qsort ((void * )nrs ,count ,sizeof (sorti_T ),sort_compare ); 621 622if (sort_abort ) { 623 gotosortend ; 624 } 625 626bcount_t old_count = 0 ; 627bcount_t new_count = 0 ; 628 629// Insert the lines in the sorted order below the last one. 630linenr_T lnum = eap -> line2 ; 631for (i = 0 ;i < count ;i ++ ) { 632const linenr_T get_lnum = nrs [eap -> forceit ?count - i - 1 :i ].lnum ; 633 634// If the original line number of the line being placed is not the same 635// as "lnum" (accounting for offset), we know that the buffer changed. 636if (get_lnum + ((linenr_T )count - 1 )!= lnum ) { 637change_occurred = true; 638 } 639 640char * s = ml_get (get_lnum ); 641colnr_T bytelen = ml_get_len (get_lnum )+ 1 ;// include EOL in bytelen 642old_count += bytelen ; 643if (!unique || i == 0 || string_compare (s ,sortbuf1 )!= 0 ) { 644// Copy the line into a buffer, it may become invalid in 645// ml_append(). And it's needed for "unique". 646STRCPY (sortbuf1 ,s ); 647if (ml_append (lnum ++ ,sortbuf1 ,0 , false)== FAIL ) { 648break ; 649 } 650new_count += bytelen ; 651 } 652fast_breakcheck (); 653if (got_int ) { 654 gotosortend ; 655 } 656 } 657 658// delete the original lines if appending worked 659if (i == count ) { 660for (i = 0 ;i < count ;i ++ ) { 661ml_delete (eap -> line1 ); 662 } 663 }else { 664count = 0 ; 665 } 666 667// Adjust marks for deleted (or added) lines and prepare for displaying. 668linenr_T deleted = (linenr_T )count - (lnum - eap -> line2 ); 669if (deleted > 0 ) { 670mark_adjust (eap -> line2 - deleted ,eap -> line2 ,MAXLNUM ,- deleted ,kExtmarkNOOP ); 671msgmore (- deleted ); 672 }else if (deleted < 0 ) { 673mark_adjust (eap -> line2 ,MAXLNUM ,- deleted ,0 ,kExtmarkNOOP ); 674 } 675 676if (change_occurred || deleted != 0 ) { 677extmark_splice (curbuf ,eap -> line1 - 1 ,0 , 678 (int )count ,0 ,old_count , 679lnum - eap -> line2 ,0 ,new_count ,kExtmarkUndo ); 680changed_lines (curbuf ,eap -> line1 ,0 ,eap -> line2 + 1 ,- deleted , true); 681 } 682 683curwin -> w_cursor .lnum = eap -> line1 ; 684beginline (BL_WHITE |BL_FIX ); 685 686sortend : 687xfree (nrs ); 688xfree (sortbuf1 ); 689xfree (sortbuf2 ); 690vim_regfree (regmatch .regprog ); 691if (got_int ) { 692emsg (_ (e_interr )); 693 } 694} 695 696/// ":uniq". 697void ex_uniq (exarg_T * eap ) 698{ 699regmatch_T regmatch ; 700int maxlen = 0 ; 701linenr_T count = eap -> line2 - eap -> line1 + 1 ; 702bool keep_only_unique = false; 703bool keep_only_not_unique = eap -> forceit ; 704linenr_T deleted = 0 ; 705 706// Uniq one line is really quick! 707if (count <=1 ) { 708return ; 709 } 710 711if (u_save ((linenr_T )(eap -> line1 - 1 ), (linenr_T )(eap -> line2 + 1 ))== FAIL ) { 712return ; 713 } 714sortbuf1 = NULL ; 715regmatch .regprog = NULL ; 716 717sort_abort = sort_ic = sort_lc = sort_rx = sort_nr = sort_flt = false; 718bool change_occurred = false;// Buffer contents changed. 719 720for (char * p = eap -> arg ;* p != NUL ;p ++ ) { 721if (ascii_iswhite (* p )) { 722// Skip 723 }else if (* p == 'i' ) { 724sort_ic = true; 725 }else if (* p == 'l' ) { 726sort_lc = true; 727 }else if (* p == 'r' ) { 728sort_rx = true; 729 }else if (* p == 'u' ) { 730// 'u' is only valid when '!' is not given. 731if (!keep_only_not_unique ) { 732keep_only_unique = true; 733 } 734 }else if (* p == '"' ) {// comment start 735break ; 736 }else if (eap -> nextcmd == NULL && check_nextcmd (p )!= NULL ) { 737eap -> nextcmd = check_nextcmd (p ); 738break ; 739 }else if (!ASCII_ISALPHA (* p )&& regmatch .regprog == NULL ) { 740char * s = skip_regexp_err (p + 1 ,* p , true); 741if (s == NULL ) { 742 gotouniqend ; 743 } 744* s = NUL ; 745// Use last search pattern if uniq pattern is empty. 746if (s == p + 1 ) { 747if (last_search_pat ()== NULL ) { 748emsg (_ (e_noprevre )); 749 gotouniqend ; 750 } 751regmatch .regprog = vim_regcomp (last_search_pat (),RE_MAGIC ); 752 }else { 753regmatch .regprog = vim_regcomp (p + 1 ,RE_MAGIC ); 754 } 755if (regmatch .regprog == NULL ) { 756 gotouniqend ; 757 } 758p = s ;// continue after the regexp 759regmatch .rm_ic = p_ic ; 760 }else { 761semsg (_ (e_invarg2 ),p ); 762 gotouniqend ; 763 } 764 } 765 766// Find the length of the longest line. 767for (linenr_T lnum = eap -> line1 ;lnum <=eap -> line2 ;lnum ++ ) { 768int len = ml_get_len (lnum ); 769if (maxlen < len ) { 770maxlen = len ; 771 } 772 773if (got_int ) { 774 gotouniqend ; 775 } 776 } 777 778// Allocate a buffer that can hold the longest line. 779sortbuf1 = xmalloc ((size_t )maxlen + 1 ); 780 781// Delete lines according to options. 782bool match_continue = false; 783bool next_is_unmatch = false; 784linenr_T done_lnum = eap -> line1 - 1 ; 785linenr_T delete_lnum = 0 ; 786for (linenr_T i = 0 ;i < count ;i ++ ) { 787linenr_T get_lnum = eap -> line1 + i ; 788 789char * s = ml_get (get_lnum ); 790int len = ml_get_len (get_lnum ); 791 792colnr_T start_col = 0 ; 793colnr_T end_col = len ; 794if (regmatch .regprog != NULL && vim_regexec (& regmatch ,s ,0 )) { 795if (sort_rx ) { 796start_col = (colnr_T )(regmatch .startp [0 ]- s ); 797end_col = (colnr_T )(regmatch .endp [0 ]- s ); 798 }else { 799start_col = (colnr_T )(regmatch .endp [0 ]- s ); 800 } 801 }else if (regmatch .regprog != NULL ) { 802end_col = 0 ; 803 } 804char save_c = NUL ;// temporary character storage 805if (end_col > 0 ) { 806save_c = s [end_col ]; 807s [end_col ]= NUL ; 808 } 809 810bool is_match = i > 0 ? !string_compare (& s [start_col ],sortbuf1 ) : false; 811delete_lnum = 0 ; 812if (next_is_unmatch ) { 813is_match = false; 814next_is_unmatch = false; 815 } 816 817if (!keep_only_unique && !keep_only_not_unique ) { 818if (is_match ) { 819delete_lnum = get_lnum ; 820 }else { 821STRCPY (sortbuf1 ,& s [start_col ]); 822 } 823 }else if (keep_only_not_unique ) { 824if (is_match ) { 825done_lnum = get_lnum - 1 ; 826delete_lnum = get_lnum ; 827match_continue = true; 828 }else { 829if (i > 0 && !match_continue && get_lnum - 1 > done_lnum ) { 830delete_lnum = get_lnum - 1 ; 831next_is_unmatch = true; 832 }else if (i >=count - 1 ) { 833delete_lnum = get_lnum ; 834 } 835match_continue = false; 836STRCPY (sortbuf1 ,& s [start_col ]); 837 } 838 }else {// keep_only_unique 839if (is_match ) { 840if (!match_continue ) { 841delete_lnum = get_lnum - 1 ; 842 }else { 843delete_lnum = get_lnum ; 844 } 845match_continue = true; 846 }else { 847if (i == 0 && match_continue ) { 848delete_lnum = get_lnum ; 849 } 850match_continue = false; 851STRCPY (sortbuf1 ,& s [start_col ]); 852 } 853 } 854 855if (end_col > 0 ) { 856s [end_col ]= save_c ; 857 } 858 859if (delete_lnum > 0 ) { 860ml_delete (delete_lnum ); 861i -= get_lnum - delete_lnum + 1 ; 862count -- ; 863deleted ++ ; 864change_occurred = true; 865 } 866 867fast_breakcheck (); 868if (got_int ) { 869 gotouniqend ; 870 } 871 } 872 873// Adjust marks for deleted lines and prepare for displaying. 874mark_adjust (eap -> line2 - deleted ,eap -> line2 ,MAXLNUM ,- deleted , 875change_occurred ?kExtmarkUndo :kExtmarkNOOP ); 876msgmore (- deleted ); 877 878if (change_occurred ) { 879changed_lines (curbuf ,eap -> line1 ,0 ,eap -> line2 + 1 ,- deleted , true); 880 } 881 882curwin -> w_cursor .lnum = eap -> line1 ; 883beginline (BL_WHITE |BL_FIX ); 884 885uniqend : 886xfree (sortbuf1 ); 887vim_regfree (regmatch .regprog ); 888if (got_int ) { 889emsg (_ (e_interr )); 890 } 891} 892 893/// :move command - move lines line1-line2 to line dest 894/// 895/// @return FAIL for failure, OK otherwise 896int do_move (linenr_T line1 ,linenr_T line2 ,linenr_T dest ) 897{ 898if (dest >=line1 && dest < line2 ) { 899emsg (_ ("E134: Cannot move a range of lines into itself" )); 900return FAIL ; 901 } 902 903// Do nothing if we are not actually moving any lines. This will prevent 904// the 'modified' flag from being set without cause. 905if (dest == line1 - 1 || dest == line2 ) { 906// Move the cursor as if lines were moved (see below) to be backwards 907// compatible. 908curwin -> w_cursor .lnum = dest >=line1 909 ?dest 910 :dest + (line2 - line1 )+ 1 ; 911return OK ; 912 } 913 914bcount_t start_byte = ml_find_line_or_offset (curbuf ,line1 ,NULL , true); 915bcount_t end_byte = ml_find_line_or_offset (curbuf ,line2 + 1 ,NULL , true); 916bcount_t extent_byte = end_byte - start_byte ; 917bcount_t dest_byte = ml_find_line_or_offset (curbuf ,dest + 1 ,NULL , true); 918 919linenr_T num_lines = line2 - line1 + 1 ;// Num lines moved 920 921// First we copy the old text to its new location -- webb 922// Also copy the flag that ":global" command uses. 923if (u_save (dest ,dest + 1 )== FAIL ) { 924return FAIL ; 925 } 926 927linenr_T l ; 928linenr_T extra ;// Num lines added before line1 929for (extra = 0 ,l = line1 ;l <=line2 ;l ++ ) { 930char * str = xstrnsave (ml_get (l + extra ), (size_t )ml_get_len (l + extra )); 931ml_append (dest + l - line1 ,str ,0 , false); 932xfree (str ); 933if (dest < line1 ) { 934extra ++ ; 935 } 936 } 937 938// Now we must be careful adjusting our marks so that we don't overlap our 939// mark_adjust() calls. 940// 941// We adjust the marks within the old text so that they refer to the 942// last lines of the file (temporarily), because we know no other marks 943// will be set there since these line numbers did not exist until we added 944// our new lines. 945// 946// Then we adjust the marks on lines between the old and new text positions 947// (either forwards or backwards). 948// 949// And Finally we adjust the marks we put at the end of the file back to 950// their final destination at the new text position -- webb 951linenr_T last_line = curbuf -> b_ml .ml_line_count ;// Last line in file after adding new text 952mark_adjust_nofold (line1 ,line2 ,last_line - line2 ,0 ,kExtmarkNOOP ); 953 954disable_fold_update ++ ; 955changed_lines (curbuf ,last_line - num_lines + 1 ,0 ,last_line + 1 ,num_lines , false); 956disable_fold_update -- ; 957 958int line_off = 0 ; 959bcount_t byte_off = 0 ; 960if (dest >=line2 ) { 961mark_adjust_nofold (line2 + 1 ,dest ,- num_lines ,0 ,kExtmarkNOOP ); 962FOR_ALL_TAB_WINDOWS (tab ,win ) { 963if (win -> w_buffer == curbuf ) { 964foldMoveRange (win ,& win -> w_folds ,line1 ,line2 ,dest ); 965 } 966 } 967if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 968curbuf -> b_op_start .lnum = dest - num_lines + 1 ; 969curbuf -> b_op_end .lnum = dest ; 970 } 971line_off = - num_lines ; 972byte_off = - extent_byte ; 973 }else { 974mark_adjust_nofold (dest + 1 ,line1 - 1 ,num_lines ,0 ,kExtmarkNOOP ); 975FOR_ALL_TAB_WINDOWS (tab ,win ) { 976if (win -> w_buffer == curbuf ) { 977foldMoveRange (win ,& win -> w_folds ,dest + 1 ,line1 - 1 ,line2 ); 978 } 979 } 980if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 981curbuf -> b_op_start .lnum = dest + 1 ; 982curbuf -> b_op_end .lnum = dest + num_lines ; 983 } 984 } 985if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 986curbuf -> b_op_start .col = curbuf -> b_op_end .col = 0 ; 987 } 988mark_adjust_nofold (last_line - num_lines + 1 ,last_line , 989- (last_line - dest - extra ),0 ,kExtmarkNOOP ); 990 991disable_fold_update ++ ; 992changed_lines (curbuf ,last_line - num_lines + 1 ,0 ,last_line + 1 ,- extra , false); 993disable_fold_update -- ; 994 995// send update regarding the new lines that were added 996buf_updates_send_changes (curbuf ,dest + 1 ,num_lines ,0 ); 997 998// Now we delete the original text -- webb 999if (u_save (line1 + extra - 1 ,line2 + extra + 1 )== FAIL ) { 1000return FAIL ; 1001 } 1002 1003for (l = line1 ;l <=line2 ;l ++ ) { 1004ml_delete_flags (line1 + extra ,ML_DEL_MESSAGE ); 1005 } 1006if (!global_busy && num_lines > p_report ) { 1007smsg (0 ,NGETTEXT ("%" PRId64 " line moved" , 1008"%" PRId64 " lines moved" ,num_lines ), 1009 (int64_t )num_lines ); 1010 } 1011 1012extmark_move_region (curbuf ,line1 - 1 ,0 ,start_byte , 1013line2 - line1 + 1 ,0 ,extent_byte , 1014dest + line_off ,0 ,dest_byte + byte_off , 1015kExtmarkUndo ); 1016 1017// Leave the cursor on the last of the moved lines. 1018if (dest >=line1 ) { 1019curwin -> w_cursor .lnum = dest ; 1020 }else { 1021curwin -> w_cursor .lnum = dest + (line2 - line1 )+ 1 ; 1022 } 1023 1024if (line1 < dest ) { 1025dest += num_lines + 1 ; 1026last_line = curbuf -> b_ml .ml_line_count ; 1027dest = MIN (dest ,last_line + 1 ); 1028changed_lines (curbuf ,line1 ,0 ,dest ,0 , false); 1029 }else { 1030changed_lines (curbuf ,dest + 1 ,0 ,line1 + num_lines ,0 , false); 1031 } 1032 1033// send nvim_buf_lines_event regarding lines that were deleted 1034buf_updates_send_changes (curbuf ,line1 + extra ,0 ,num_lines ); 1035 1036return OK ; 1037} 1038 1039/// ":copy" 1040void ex_copy (linenr_T line1 ,linenr_T line2 ,linenr_T n ) 1041{ 1042linenr_T count = line2 - line1 + 1 ; 1043if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 1044curbuf -> b_op_start .lnum = n + 1 ; 1045curbuf -> b_op_end .lnum = n + count ; 1046curbuf -> b_op_start .col = curbuf -> b_op_end .col = 0 ; 1047 } 1048 1049// there are three situations: 1050// 1. destination is above line1 1051// 2. destination is between line1 and line2 1052// 3. destination is below line2 1053// 1054// n = destination (when starting) 1055// curwin->w_cursor.lnum = destination (while copying) 1056// line1 = start of source (while copying) 1057// line2 = end of source (while copying) 1058if (u_save (n ,n + 1 )== FAIL ) { 1059return ; 1060 } 1061 1062curwin -> w_cursor .lnum = n ; 1063while (line1 <=line2 ) { 1064// need to make a copy because the line will be unlocked within ml_append() 1065char * p = xstrnsave (ml_get (line1 ), (size_t )ml_get_len (line1 )); 1066ml_append (curwin -> w_cursor .lnum ,p ,0 , false); 1067xfree (p ); 1068 1069// situation 2: skip already copied lines 1070if (line1 == n ) { 1071line1 = curwin -> w_cursor .lnum ; 1072 } 1073line1 ++ ; 1074if (curwin -> w_cursor .lnum < line1 ) { 1075line1 ++ ; 1076 } 1077if (curwin -> w_cursor .lnum < line2 ) { 1078line2 ++ ; 1079 } 1080curwin -> w_cursor .lnum ++ ; 1081 } 1082 1083appended_lines_mark (n ,count ); 1084if (Visual .active ) { 1085check_pos (curbuf ,& Visual .start ); 1086 } 1087 1088msgmore (count ); 1089} 1090 1091static char * prevcmd = NULL ;// the previous command 1092 1093#ifdef EXITFREE 1094void free_prev_shellcmd (void ) 1095{ 1096xfree (prevcmd ); 1097} 1098 1099#endif 1100 1101/// Check that "prevcmd" is not NULL. If it is NULL then give an error message 1102/// and return false. 1103static int prevcmd_is_set (void ) 1104{ 1105if (prevcmd == NULL ) { 1106emsg (_ (e_noprev )); 1107return false; 1108 } 1109return true; 1110} 1111 1112/// Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd" 1113/// Bangs in the argument are replaced with the previously entered command. 1114/// Remember the argument. 1115void do_bang (int addr_count ,exarg_T * eap ,bool forceit ,bool do_in ,bool do_out ) 1116FUNC_ATTR_NONNULL_ALL 1117{ 1118char * arg = eap -> arg ;// command 1119linenr_T line1 = eap -> line1 ;// start of range 1120linenr_T line2 = eap -> line2 ;// end of range 1121char * newcmd = NULL ;// the new command 1122bool free_newcmd = false;// need to free() newcmd 1123int scroll_save = msg_scroll ; 1124 1125// Disallow shell commands in secure mode 1126if (check_secure ()) { 1127return ; 1128 } 1129 1130if (addr_count == 0 ) {// :! 1131msg_scroll = false;// don't scroll here 1132autowrite_all (); 1133msg_scroll = scroll_save ; 1134 } 1135 1136// Try to find an embedded bang, like in ":!<cmd> ! [args]" 1137// ":!!" is indicated by the 'forceit' variable. 1138bool ins_prevcmd = forceit ; 1139 1140// Skip leading white space to avoid a strange error with some shells. 1141char * trailarg = skipwhite (arg ); 1142do { 1143size_t len = strlen (trailarg )+ 1 ; 1144if (newcmd != NULL ) { 1145len += strlen (newcmd ); 1146 } 1147if (ins_prevcmd ) { 1148if (!prevcmd_is_set ()) { 1149xfree (newcmd ); 1150return ; 1151 } 1152len += strlen (prevcmd ); 1153 } 1154char * t = xmalloc (len ); 1155* t = NUL ; 1156if (newcmd != NULL ) { 1157strcat (t ,newcmd ); 1158 } 1159if (ins_prevcmd ) { 1160strcat (t ,prevcmd ); 1161 } 1162char * p = t + strlen (t ); 1163strcat (t ,trailarg ); 1164xfree (newcmd ); 1165newcmd = t ; 1166 1167// Scan the rest of the argument for '!', which is replaced by the 1168// previous command. "\!" is replaced by "!" (this is vi compatible). 1169trailarg = NULL ; 1170while (* p ) { 1171if (* p == '!' ) { 1172if (p > newcmd && p [-1 ]== '\\' ) { 1173STRMOVE (p - 1 ,p ); 1174 }else { 1175trailarg = p ; 1176* trailarg ++ = NUL ; 1177ins_prevcmd = true; 1178break ; 1179 } 1180 } 1181p ++ ; 1182 } 1183 }while (trailarg != NULL ); 1184 1185// Only set "prevcmd" if there is a command to run, otherwise keep te one 1186// we have. 1187if (strlen (newcmd )> 0 ) { 1188xfree (prevcmd ); 1189prevcmd = newcmd ; 1190 }else { 1191free_newcmd = true; 1192 } 1193 1194if (bangredo ) {// put cmd in redo buffer for ! command 1195if (!prevcmd_is_set ()) { 1196 gototheend ; 1197 } 1198 1199// If % or # appears in the command, it must have been escaped. 1200// Reescape them, so that redoing them does not substitute them by the 1201// buffername. 1202char * cmd = vim_strsave_escaped (prevcmd ,"%#" ); 1203 1204redo_append_lit (cmd ,-1 ); 1205xfree (cmd ); 1206redo_append_str (S_LEN ("\n" )); 1207bangredo = false; 1208 } 1209// Add quotes around the command, for shells that need them. 1210if (* p_shq != NUL ) { 1211if (free_newcmd ) { 1212xfree (newcmd ); 1213 } 1214newcmd = xmalloc (strlen (prevcmd )+ 2 * strlen (p_shq )+ 1 ); 1215STRCPY (newcmd ,p_shq ); 1216strcat (newcmd ,prevcmd ); 1217strcat (newcmd ,p_shq ); 1218free_newcmd = true; 1219 } 1220if (addr_count == 0 ) {// :! 1221// echo the command 1222msg_start (); 1223msg_ext_no_fast (); 1224msg_ext_set_kind ("shell_cmd" ); 1225msg_putchar (':' ); 1226msg_putchar ('!' ); 1227msg_outtrans (newcmd ,0 , false); 1228msg_clr_eos (); 1229ui_cursor_goto (msg_row ,msg_col ); 1230 1231do_shell (newcmd ,0 ); 1232 }else {// :range! 1233// Careful: This may recursively call do_bang() again! (because of 1234// autocommands) 1235do_filter (line1 ,line2 ,eap ,newcmd ,do_in ,do_out ); 1236apply_autocmds (EVENT_SHELLFILTERPOST ,NULL ,NULL , false,curbuf ); 1237 } 1238 1239theend : 1240if (free_newcmd ) { 1241xfree (newcmd ); 1242 } 1243} 1244 1245/// do_filter: filter lines through a command given by the user 1246/// 1247/// We mostly use temp files and the call_shell() routine here. This would 1248/// normally be done using pipes on a Unix system, but this is more portable 1249/// to non-Unix systems. The call_shell() routine needs to be able 1250/// to deal with redirection somehow, and should handle things like looking 1251/// at the PATH env. variable, and adding reasonable extensions to the 1252/// command name given by the user. All reasonable versions of call_shell() 1253/// do this. 1254/// Alternatively, if on Unix and redirecting input or output, but not both, 1255/// and the 'shelltemp' option isn't set, use pipes. 1256/// We use input redirection if do_in is true. 1257/// We use output redirection if do_out is true. 1258/// 1259/// @param eap for forced 'ff' and 'fenc' 1260static void do_filter (linenr_T line1 ,linenr_T line2 ,exarg_T * eap ,char * cmd ,bool do_in , 1261bool do_out ) 1262{ 1263char * itmp = NULL ; 1264char * otmp = NULL ; 1265buf_T * old_curbuf = curbuf ; 1266int shell_flags = 0 ; 1267const pos_T orig_start = curbuf -> b_op_start ; 1268const pos_T orig_end = curbuf -> b_op_end ; 1269const int stmp = p_stmp ; 1270 1271if (* cmd == NUL ) {// no filter command 1272return ; 1273 } 1274 1275const int save_cmod_flags = cmdmod .cmod_flags ; 1276// Temporarily disable lockmarks since that's needed to propagate changed 1277// regions of the buffer for foldUpdate(), linecount, etc. 1278cmdmod .cmod_flags &= ~CMOD_LOCKMARKS ; 1279 1280pos_T cursor_save = curwin -> w_cursor ; 1281linenr_T linecount = line2 - line1 + 1 ; 1282curwin -> w_cursor .lnum = line1 ; 1283curwin -> w_cursor .col = 0 ; 1284changed_line_abv_curs (); 1285invalidate_botline_win (curwin ); 1286 1287// When using temp files: 1288// 1. * Form temp file names 1289// 2. * Write the lines to a temp file 1290// 3. Run the filter command on the temp file 1291// 4. * Read the output of the command into the buffer 1292// 5. * Delete the original lines to be filtered 1293// 6. * Remove the temp files 1294// 1295// When writing the input with a pipe or when catching the output with a 1296// pipe only need to do 3. 1297 1298if (do_out ) { 1299shell_flags |=kShellOptDoOut ; 1300 } 1301 1302if (!do_in && do_out && !stmp ) { 1303// Use a pipe to fetch stdout of the command, do not use a temp file. 1304shell_flags |=kShellOptRead ; 1305curwin -> w_cursor .lnum = line2 ; 1306 }else if (do_in && !do_out && !stmp ) { 1307// Use a pipe to write stdin of the command, do not use a temp file. 1308shell_flags |=kShellOptWrite ; 1309curbuf -> b_op_start .lnum = line1 ; 1310curbuf -> b_op_end .lnum = line2 ; 1311 }else if (do_in && do_out && !stmp ) { 1312// Use a pipe to write stdin and fetch stdout of the command, do not 1313// use a temp file. 1314shell_flags |=kShellOptRead |kShellOptWrite ; 1315curbuf -> b_op_start .lnum = line1 ; 1316curbuf -> b_op_end .lnum = line2 ; 1317curwin -> w_cursor .lnum = line2 ; 1318 }else if ((do_in && (itmp = vim_tempname ())== NULL ) 1319|| (do_out && (otmp = vim_tempname ())== NULL )) { 1320emsg (_ (e_notmp )); 1321 gotofilterend ; 1322 } 1323 1324// The writing and reading of temp files will not be shown. 1325// Vi also doesn't do this and the messages are not very informative. 1326no_wait_return ++ ;// don't call wait_return() while busy 1327if (itmp != NULL && buf_write (curbuf ,itmp ,NULL ,line1 ,line2 ,eap , 1328 false, false, false, true)== FAIL ) { 1329if (!ui_has (kUIMessages )) { 1330msg_putchar ('\n' );// Keep message from buf_write(). 1331 } 1332no_wait_return -- ; 1333if (!aborting ()) { 1334// will call wait_return() 1335semsg (_ ("E482: Can't create file %s" ),itmp ); 1336 } 1337 gotofilterend ; 1338 } 1339if (curbuf != old_curbuf ) { 1340 gotofilterend ; 1341 } 1342 1343if (!do_out && !ui_has (kUIMessages )) { 1344msg_putchar ('\n' ); 1345 } 1346 1347// Create the shell command in allocated memory. 1348char * cmd_buf = make_filter_cmd (cmd ,itmp ,otmp ,do_in ); 1349ui_cursor_goto (Rows - 1 ,0 ); 1350 1351if (do_out ) { 1352if (u_save (line2 , (linenr_T )(line2 + 1 ))== FAIL ) { 1353xfree (cmd_buf ); 1354 gotoerror ; 1355 } 1356redraw_curbuf_later (UPD_VALID ); 1357 } 1358linenr_T read_linecount = curbuf -> b_ml .ml_line_count ; 1359 1360// Pass on the kShellOptDoOut flag when the output is being redirected. 1361call_shell (cmd_buf ,kShellOptFilter |shell_flags ,NULL ); 1362xfree (cmd_buf ); 1363 1364did_check_timestamps = false; 1365need_check_timestamps = true; 1366 1367// When interrupting the shell command, it may still have produced some 1368// useful output. Reset got_int here, so that readfile() won't cancel 1369// reading. 1370os_breakcheck (); 1371got_int = false; 1372 1373if (do_out ) { 1374if (otmp != NULL ) { 1375if (readfile (otmp ,NULL ,line2 ,0 , (linenr_T )MAXLNUM ,eap , 1376READ_FILTER , false)!= OK ) { 1377if (!aborting ()) { 1378msg_putchar ('\n' ); 1379semsg (_ (e_cant_read_file_str ),otmp ); 1380 } 1381 gotoerror ; 1382 } 1383if (curbuf != old_curbuf ) { 1384 gotofilterend ; 1385 } 1386 } 1387 1388read_linecount = curbuf -> b_ml .ml_line_count - read_linecount ; 1389 1390if (shell_flags & kShellOptRead ) { 1391curbuf -> b_op_start .lnum = line2 + 1 ; 1392curbuf -> b_op_end .lnum = curwin -> w_cursor .lnum ; 1393appended_lines_mark (line2 ,read_linecount ); 1394 } 1395 1396if (do_in ) { 1397if ((cmdmod .cmod_flags & CMOD_KEEPMARKS ) 1398|| vim_strchr (p_cpo ,kCpoRemmark )== NULL ) { 1399// TODO(bfredl): Currently not active for extmarks. What would we 1400// do if columns don't match, assume added/deleted bytes at the 1401// end of each line? 1402if (read_linecount >=linecount ) { 1403// move all marks from old lines to new lines 1404mark_adjust (line1 ,line2 ,linecount ,0 ,kExtmarkNOOP ); 1405 }else { 1406// move marks from old lines to new lines, delete marks 1407// that are in deleted lines 1408mark_adjust (line1 ,line1 + read_linecount - 1 ,linecount ,0 , 1409kExtmarkNOOP ); 1410mark_adjust (line1 + read_linecount ,line2 ,MAXLNUM ,0 , 1411kExtmarkNOOP ); 1412 } 1413 } 1414 1415// Put cursor on first filtered line for ":range!cmd". 1416// Adjust '[ and '] (set by buf_write()). 1417curwin -> w_cursor .lnum = line1 ; 1418del_lines (linecount , true); 1419if (read_linecount == 0 ) { 1420// no filter output: clamp '[ and '] to a valid line 1421curbuf -> b_op_start .lnum = curbuf -> b_op_end .lnum = MIN (line1 ,curbuf -> b_ml .ml_line_count ); 1422curbuf -> b_op_start .col = curbuf -> b_op_end .col = 0 ; 1423 }else { 1424curbuf -> b_op_start .lnum -= linecount ;// adjust '[ 1425curbuf -> b_op_end .lnum -= linecount ;// adjust '] 1426 } 1427write_lnum_adjust (- linecount );// adjust last line 1428// for next write 1429foldUpdate (curwin ,curbuf -> b_op_start .lnum ,curbuf -> b_op_end .lnum ); 1430 }else { 1431// Put cursor on last new line for ":r !cmd". 1432linecount = curbuf -> b_op_end .lnum - curbuf -> b_op_start .lnum + 1 ; 1433curwin -> w_cursor .lnum = curbuf -> b_op_end .lnum ; 1434 } 1435 1436beginline (BL_WHITE |BL_FIX );// cursor on first non-blank 1437no_wait_return -- ; 1438 1439if (linecount > p_report ) { 1440if (do_in ) { 1441vim_snprintf (msg_buf ,sizeof (msg_buf ), 1442_ ("%" PRId64 " lines filtered" ), (int64_t )linecount ); 1443if (msg (msg_buf ,0 )&& !msg_scroll ) { 1444// save message to display it after redraw 1445set_keep_msg (msg_buf ,0 ); 1446 } 1447 }else { 1448msgmore (linecount ); 1449 } 1450 } 1451 }else { 1452error : 1453// put cursor back in same position for ":w !cmd" 1454curwin -> w_cursor = cursor_save ; 1455no_wait_return -- ; 1456if (!ui_has (kUIMessages )) { 1457wait_return (false); 1458 } 1459 } 1460 1461filterend : 1462 1463cmdmod .cmod_flags = save_cmod_flags ; 1464if (curbuf != old_curbuf ) { 1465no_wait_return -- ; 1466emsg (_ ("E135: *Filter* Autocommands must not change current buffer" )); 1467 }else if (cmdmod .cmod_flags & CMOD_LOCKMARKS ) { 1468curbuf -> b_op_start = orig_start ; 1469curbuf -> b_op_end = orig_end ; 1470 } 1471 1472if (itmp != NULL ) { 1473os_remove (itmp ); 1474 } 1475if (otmp != NULL ) { 1476os_remove (otmp ); 1477 } 1478xfree (itmp ); 1479xfree (otmp ); 1480} 1481 1482/// Call a shell to execute a command. 1483/// When "cmd" is NULL start an interactive shell. 1484/// 1485/// @param flags may be SHELL_DOOUT when output is redirected 1486void do_shell (char * cmd ,int flags ) 1487{ 1488// Disallow shell commands in secure mode 1489if (check_secure ()) { 1490msg_end (); 1491return ; 1492 } 1493 1494// For autocommands we want to get the output on the current screen, to 1495// avoid having to type return below. 1496msg_putchar ('\r' );// put cursor at start of line 1497msg_putchar ('\n' );// may shift screen one line up 1498 1499// warning message before calling the shell 1500if (p_warn 1501&& !autocmd_busy 1502&& msg_silent == 0 ) { 1503FOR_ALL_BUFFERS (buf ) { 1504if (bufIsChanged (buf )) { 1505msg_puts (_ ("[No write since last change]\n" )); 1506break ; 1507 } 1508 } 1509 } 1510 1511// This ui_cursor_goto is required for when the '\n' resulted in a "delete line 1512// 1" command to the terminal. 1513ui_cursor_goto (msg_row ,msg_col ); 1514call_shell (cmd ,flags ,NULL ); 1515if (msg_silent == 0 ) { 1516msg_didout = true; 1517 } 1518did_check_timestamps = false; 1519need_check_timestamps = true; 1520 1521// put the message cursor at the end of the screen, avoids wait_return() 1522// to overwrite the text that the external command showed 1523msg_row = Rows - 1 ; 1524msg_col = 0 ; 1525 1526apply_autocmds (EVENT_SHELLCMDPOST ,NULL ,NULL , false,curbuf ); 1527} 1528 1529#ifndef UNIX 1530static char * find_pipe (const char * cmd ) 1531{ 1532bool inquote = false; 1533 1534for (const char * p = cmd ;* p != NUL ;p ++ ) { 1535if (!inquote && * p == '|' ) { 1536return (char * )p ; 1537 } 1538if (* p == '"' ) { 1539inquote = !inquote ; 1540 }else if (rem_backslash (p )) { 1541p ++ ; 1542 } 1543 } 1544return NULL ; 1545} 1546#endif 1547 1548/// Create a shell command from a command string, input redirection file and 1549/// output redirection file. 1550/// 1551/// @param cmd Command to execute. 1552/// @param itmp NULL or the input file. 1553/// @param otmp NULL or the output file. 1554/// @param do_in true if stdin is needed. 1555/// @returns an allocated string with the shell command. 1556char * make_filter_cmd (char * cmd ,char * itmp ,char * otmp ,bool do_in ) 1557{ 1558bool is_fish_shell = 1559#ifdef UNIX 1560strncmp (invocation_path_tail (p_sh ,NULL ),"fish" ,4 )== 0 ; 1561#else 1562 false; 1563#endif 1564bool is_pwsh = strncmp (invocation_path_tail (p_sh ,NULL ),"pwsh" ,4 )== 0 1565|| strncmp (invocation_path_tail (p_sh ,NULL ),"powershell" , 156610 )== 0 ; 1567 1568size_t len = strlen (cmd )+ 1 ;// At least enough space for cmd + NULL. 1569 1570len += is_fish_shell ?sizeof ("begin; " "; end" )- 1 1571 : !is_pwsh ?sizeof ("(" ")" )- 1 1572 :0 ; 1573 1574if (itmp != NULL ) { 1575len += is_pwsh ?strlen (itmp )+ sizeof ("& { Get-Content " " | & " " }" )- 1 + 6 // +6: #20530 1576 :strlen (itmp )+ sizeof (" { " " < " " } " )- 1 ; 1577 } 1578 1579if (do_in && is_pwsh ) { 1580len += sizeof (" $input | " ); 1581 } 1582 1583if (otmp != NULL ) { 1584len += strlen (otmp )+ strlen (p_srr )+ 2 ;// two extra spaces (" "), 1585 } 1586 1587char * const buf = xmalloc (len ); 1588 1589if (is_pwsh ) { 1590if (itmp != NULL ) { 1591xstrlcpy (buf ,"& { Get-Content " ,len - 1 );// FIXME: should we add "-Encoding utf8"? 1592xstrlcat (buf ,itmp ,len - 1 ); 1593xstrlcat (buf ," | & " ,len - 1 );// FIXME: add `&` ourself or leave to user? 1594xstrlcat (buf ,cmd ,len - 1 ); 1595xstrlcat (buf ," }" ,len - 1 ); 1596 }else if (do_in ) { 1597xstrlcpy (buf ," $input | " ,len - 1 ); 1598xstrlcat (buf ,cmd ,len ); 1599 }else { 1600xstrlcpy (buf ,cmd ,len ); 1601 } 1602 }else { 1603#ifdef UNIX 1604// Put delimiters around the command (for concatenated commands) when 1605// redirecting input and/or output. 1606if (itmp != NULL || otmp != NULL ) { 1607char * fmt = is_fish_shell ?"begin; %s; end" 1608 :"(%s)" ; 1609vim_snprintf (buf ,len ,fmt ,cmd ); 1610 }else { 1611xstrlcpy (buf ,cmd ,len ); 1612 } 1613 1614if (itmp != NULL ) { 1615xstrlcat (buf ," < " ,len - 1 ); 1616xstrlcat (buf ,itmp ,len - 1 ); 1617 } 1618#else 1619// For shells that don't understand braces around commands, at least allow 1620// the use of commands in a pipe. 1621xstrlcpy (buf ,cmd ,len ); 1622if (itmp != NULL ) { 1623// If there is a pipe, we have to put the '<' in front of it. 1624// Don't do this when 'shellquote' is not empty, otherwise the 1625// redirection would be inside the quotes. 1626if (* p_shq == NUL ) { 1627char * const p = find_pipe (buf ); 1628if (p != NULL ) { 1629* p = NUL ; 1630 } 1631 } 1632xstrlcat (buf ," < " ,len ); 1633xstrlcat (buf ,itmp ,len ); 1634if (* p_shq == NUL ) { 1635const char * const p = find_pipe (cmd ); 1636if (p != NULL ) { 1637xstrlcat (buf ," " ,len - 1 );// Insert a space before the '|' for DOS 1638xstrlcat (buf ,p ,len - 1 ); 1639 } 1640 } 1641 } 1642#endif 1643 } 1644if (otmp != NULL ) { 1645append_redir (buf ,len ,p_srr ,otmp ); 1646 } 1647return buf ; 1648} 1649 1650/// Append output redirection for the given file to the end of the buffer 1651/// 1652/// @param[out] buf Buffer to append to. 1653/// @param[in] buflen Buffer length. 1654/// @param[in] opt Separator or format string to append: will append 1655/// `printf(' ' . opt, fname)` if `%s` is found in `opt` or 1656/// a space, opt, a space and then fname if `%s` is not found 1657/// there. 1658/// @param[in] fname File name to append. 1659void append_redir (char * const buf ,const size_t buflen ,const char * const opt , 1660const char * const fname ) 1661{ 1662char * const end = buf + strlen (buf ); 1663// find "%s" 1664const char * p = opt ; 1665for (; (p = strchr (p ,'%' ))!= NULL ;p ++ ) { 1666if (p [1 ]== 's' ) {// found %s 1667break ; 1668 }else if (p [1 ]== '%' ) {// skip %% 1669p ++ ; 1670 } 1671 } 1672if (p != NULL ) { 1673* end = ' ' ;// not really needed? Not with sh, ksh or bash 1674 1675// This looks incredibly suss because it is: we are allowing a user option to 1676// define a snprintf format string. Such code should normally not be written. 1677// The validity of these option values is checked in `validate_shellpipe_redir`. 1678PRAGMA_DIAG_PUSH_IGNORE_MISSING_FORMAT_ATTRIBUTE ; 1679vim_snprintf (end + 1 , (size_t )((ptrdiff_t )buflen - (end + 1 - buf )),opt ,fname ); 1680PRAGMA_DIAG_POP ; 1681 }else { 1682vim_snprintf (end , (size_t )((ptrdiff_t )buflen - (end - buf ))," %s %s" ,opt ,fname ); 1683 } 1684} 1685 1686void print_line_no_prefix (linenr_T lnum ,bool use_number ,bool list ) 1687{ 1688char numbuf [30 ]; 1689 1690if (curwin -> w_p_nu || use_number ) { 1691vim_snprintf (numbuf ,sizeof (numbuf ),"%*" PRIdLINENR " " , 1692number_width (curwin ),lnum ); 1693msg_puts_hl (numbuf ,HLF_N + 1 , false);// Highlight line nrs. 1694 } 1695msg_prt_line (ml_get (lnum ),list ); 1696} 1697 1698static bool global_need_msg_kind = false;// Start new message only once during :global. 1699 1700/// Print a text line. Also in silent mode ("ex -s"). 1701void print_line (linenr_T lnum ,bool use_number ,bool list ,bool first ) 1702{ 1703bool save_silent = silent_mode ; 1704 1705// apply :filter /pat/ 1706if (message_filtered (ml_get (lnum ))) { 1707return ; 1708 } 1709 1710silent_mode = false; 1711info_message = true;// use stdout, not stderr 1712if ((!global_busy || global_need_msg_kind )&& first ) { 1713msg_start (); 1714msg_ext_set_kind ("list_cmd" ); 1715global_need_msg_kind = false; 1716 }else if (!save_silent ) { 1717msg_putchar ('\n' );// don't want trailing newline with regular messaging 1718 } 1719print_line_no_prefix (lnum ,use_number ,list ); 1720if (save_silent ) { 1721msg_putchar ('\n' );// batch mode message should always end in newline 1722silent_mode = save_silent ; 1723 } 1724info_message = false; 1725} 1726 1727int rename_buffer (char * new_fname ) 1728{ 1729buf_T * buf = curbuf ; 1730apply_autocmds (EVENT_BUFFILEPRE ,NULL ,NULL , false,curbuf ); 1731// buffer changed, don't change name now 1732if (buf != curbuf ) { 1733return FAIL ; 1734 } 1735if (aborting ()) {// autocmds may abort script processing 1736return FAIL ; 1737 } 1738// The name of the current buffer will be changed. 1739// A new (unlisted) buffer entry needs to be made to hold the old file 1740// name, which will become the alternate file name. 1741// But don't set the alternate file name if the buffer didn't have a 1742// name. 1743char * fname = curbuf -> b_ffname ; 1744char * sfname = curbuf -> b_sfname ; 1745char * xfname = curbuf -> b_fname ; 1746curbuf -> b_ffname = NULL ; 1747curbuf -> b_sfname = NULL ; 1748if (setfname (curbuf ,new_fname ,NULL , true)== FAIL ) { 1749curbuf -> b_ffname = fname ; 1750curbuf -> b_sfname = sfname ; 1751return FAIL ; 1752 } 1753curbuf -> b_flags |=BF_NOTEDITED ; 1754if (xfname != NULL && * xfname != NUL ) { 1755buf = buflist_new (fname ,xfname ,curwin -> w_cursor .lnum ,0 ); 1756if (buf != NULL && (cmdmod .cmod_flags & CMOD_KEEPALT )== 0 ) { 1757curwin -> w_alt_fnum = buf -> b_fnum ; 1758 } 1759 } 1760xfree (fname ); 1761xfree (sfname ); 1762apply_autocmds (EVENT_BUFFILEPOST ,NULL ,NULL , false,curbuf ); 1763// Change directories when the 'acd' option is set. 1764do_autochdir (); 1765return OK ; 1766} 1767 1768/// ":file[!] [fname]". 1769void ex_file (exarg_T * eap ) 1770{ 1771// ":0file" removes the file name. Check for illegal uses ":3file", 1772// "0file name", etc. 1773if (eap -> addr_count > 0 1774&& (* eap -> arg != NUL 1775|| eap -> line2 > 0 1776|| eap -> addr_count > 1 )) { 1777emsg (_ (e_invarg )); 1778return ; 1779 } 1780 1781if (* eap -> arg != NUL || eap -> addr_count == 1 ) { 1782if (rename_buffer (eap -> arg )== FAIL ) { 1783return ; 1784 } 1785redraw_tabline = true; 1786 } 1787 1788// print file name if no argument or 'F' is not in 'shortmess' 1789if (* eap -> arg == NUL || !shortmess (kShmFileinfo )) { 1790fileinfo (false, false,eap -> forceit ); 1791 } 1792} 1793 1794/// ":update". 1795void ex_update (exarg_T * eap ) 1796{ 1797if (curbufIsChanged () 1798|| (!bt_nofilename (curbuf )&& curbuf -> b_ffname != NULL 1799&& !os_path_exists (curbuf -> b_ffname ))) { 1800do_write (eap ); 1801 } 1802} 1803 1804/// ":write" and ":saveas". 1805void ex_write (exarg_T * eap ) 1806{ 1807if (eap -> cmdidx == CMD_saveas ) { 1808// :saveas does not take a range, uses all lines. 1809eap -> line1 = 1 ; 1810eap -> line2 = curbuf -> b_ml .ml_line_count ; 1811 } 1812 1813if (eap -> usefilter ) {// input lines to shell command 1814do_bang (1 ,eap , false, true, false); 1815 }else { 1816do_write (eap ); 1817 } 1818} 1819 1820#ifdef UNIX 1821static int check_writable (const char * fname ) 1822{ 1823if (os_nodetype (fname )== NODE_OTHER ) { 1824semsg (_ ("E503: \"%s\" is not a file or writable device" ),fname ); 1825return FAIL ; 1826 } 1827return OK ; 1828} 1829#endif 1830 1831static int handle_mkdir_p_arg (exarg_T * eap ,char * fname ) 1832{ 1833if (eap -> mkdir_p && os_file_mkdir (fname ,0755 )< 0 ) { 1834return FAIL ; 1835 } 1836 1837return OK ; 1838} 1839 1840/// Write current buffer to file "eap->arg". 1841/// If "eap->append" is true, append to the file. 1842/// 1843/// If "*eap->arg == NUL" write to current file. 1844/// 1845/// @return FAIL for failure, OK otherwise. 1846int do_write (exarg_T * eap ) 1847{ 1848bool other ; 1849char * fname = NULL ;// init to shut up gcc 1850int retval = FAIL ; 1851char * free_fname = NULL ; 1852buf_T * alt_buf = NULL ; 1853 1854if (not_writing ()) {// check 'write' option 1855return FAIL ; 1856 } 1857 1858char * ffname = eap -> arg ; 1859if (* ffname == NUL ) { 1860if (eap -> cmdidx == CMD_saveas ) { 1861emsg (_ (e_argreq )); 1862 gototheend ; 1863 } 1864other = false; 1865 }else { 1866fname = ffname ; 1867free_fname = fix_fname (ffname ); 1868// When out-of-memory, keep unexpanded file name, because we MUST be 1869// able to write the file in this situation. 1870if (free_fname != NULL ) { 1871ffname = free_fname ; 1872 } 1873other = otherfile (ffname ); 1874 } 1875 1876// If we have a new file, put its name in the list of alternate file names. 1877if (other ) { 1878if (vim_strchr (p_cpo ,kCpoAltwrite )!= NULL 1879|| eap -> cmdidx == CMD_saveas ) { 1880alt_buf = setaltfname (ffname ,fname ,1 ); 1881 }else { 1882alt_buf = buflist_findname (ffname ); 1883 } 1884if (alt_buf != NULL && alt_buf -> b_ml .ml_mfp != NULL ) { 1885// Overwriting a file that is loaded in another buffer is not a 1886// good idea. 1887emsg (_ (e_bufloaded )); 1888 gototheend ; 1889 } 1890 } 1891 1892// Writing to the current file is not allowed in readonly mode 1893// and a file name is required. 1894// "nofile" and "nowrite" buffers cannot be written implicitly either. 1895if (!other && (bt_dontwrite_msg (curbuf ) 1896|| check_fname ()== FAIL 1897#ifdef UNIX 1898|| check_writable (curbuf -> b_ffname )== FAIL 1899#endif 1900|| check_readonly (& eap -> forceit ,curbuf ))) { 1901 gototheend ; 1902 } 1903 1904if (!other ) { 1905ffname = curbuf -> b_ffname ; 1906fname = curbuf -> b_fname ; 1907// Not writing the whole file is only allowed with '!'. 1908if ((eap -> line1 != 1 1909|| eap -> line2 != curbuf -> b_ml .ml_line_count ) 1910&& !eap -> forceit 1911&& !eap -> append 1912&& !p_wa ) { 1913if (p_confirm || (cmdmod .cmod_flags & CMOD_CONFIRM )) { 1914if (vim_dialog_yesno (VIM_QUESTION ,NULL , 1915_ ("Write partial file?" ),2 )!= VIM_YES ) { 1916 gototheend ; 1917 } 1918eap -> forceit = true; 1919 }else { 1920emsg (_ ("E140: Use ! to write partial buffer" )); 1921 gototheend ; 1922 } 1923 } 1924 } 1925 1926if (check_overwrite (eap ,curbuf ,fname ,ffname ,other )== OK ) { 1927if (eap -> cmdidx == CMD_saveas && alt_buf != NULL ) { 1928buf_T * was_curbuf = curbuf ; 1929 1930apply_autocmds (EVENT_BUFFILEPRE ,NULL ,NULL , false,curbuf ); 1931apply_autocmds (EVENT_BUFFILEPRE ,NULL ,NULL , false,alt_buf ); 1932if (curbuf != was_curbuf || aborting ()) { 1933// buffer changed, don't change name now 1934retval = FAIL ; 1935 gototheend ; 1936 } 1937// Exchange the file names for the current and the alternate 1938// buffer. This makes it look like we are now editing the buffer 1939// under the new name. Must be done before buf_write(), because 1940// if there is no file name and 'cpo' contains 'F', it will set 1941// the file name. 1942fname = alt_buf -> b_fname ; 1943alt_buf -> b_fname = curbuf -> b_fname ; 1944curbuf -> b_fname = fname ; 1945fname = alt_buf -> b_ffname ; 1946alt_buf -> b_ffname = curbuf -> b_ffname ; 1947curbuf -> b_ffname = fname ; 1948fname = alt_buf -> b_sfname ; 1949alt_buf -> b_sfname = curbuf -> b_sfname ; 1950curbuf -> b_sfname = fname ; 1951buf_name_changed (curbuf ); 1952apply_autocmds (EVENT_BUFFILEPOST ,NULL ,NULL , false,curbuf ); 1953apply_autocmds (EVENT_BUFFILEPOST ,NULL ,NULL , false,alt_buf ); 1954if (!alt_buf -> b_p_bl ) { 1955alt_buf -> b_p_bl = true; 1956apply_autocmds (EVENT_BUFADD ,NULL ,NULL , false,alt_buf ); 1957 } 1958if (curbuf != was_curbuf || aborting ()) { 1959// buffer changed, don't write the file 1960retval = FAIL ; 1961 gototheend ; 1962 } 1963 1964// If 'filetype' was empty try detecting it now. 1965if (* curbuf -> b_p_ft == NUL ) { 1966if (augroup_exists ("filetypedetect" )) { 1967do_doautocmd ("filetypedetect BufRead" , true,NULL ); 1968 } 1969do_modelines (0 ); 1970 } 1971 1972// Autocommands may have changed buffer names, esp. when 1973// 'autochdir' is set. 1974fname = curbuf -> b_sfname ; 1975 } 1976 1977if (handle_mkdir_p_arg (eap ,fname )== FAIL ) { 1978retval = FAIL ; 1979 gototheend ; 1980 } 1981 1982int name_was_missing = curbuf -> b_ffname == NULL ; 1983retval = buf_write (curbuf ,ffname ,fname ,eap -> line1 ,eap -> line2 , 1984eap ,eap -> append ,eap -> forceit , true, false); 1985 1986// After ":saveas fname" reset 'readonly'. 1987if (eap -> cmdidx == CMD_saveas ) { 1988if (retval == OK ) { 1989curbuf -> b_p_ro = false; 1990redraw_tabline = true; 1991 } 1992 } 1993 1994// Change directories when the 'acd' option is set and the file name 1995// got changed or set. 1996if (eap -> cmdidx == CMD_saveas || name_was_missing ) { 1997do_autochdir (); 1998 } 1999 } 2000 2001theend : 2002xfree (free_fname ); 2003return retval ; 2004} 2005 2006/// Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED, 2007/// BF_NEW or BF_READERR, check for overwriting current file. 2008/// May set eap->forceit if a dialog says it's OK to overwrite. 2009/// 2010/// @param fname file name to be used (can differ from buf->ffname) 2011/// @param ffname full path version of fname 2012/// @param other writing under other name 2013/// 2014/// @return OK if it's OK, FAIL if it is not. 2015int check_overwrite (exarg_T * eap ,buf_T * buf ,char * fname ,char * ffname ,bool other ) 2016{ 2017// Write to another file or b_flags set or not writing the whole file: 2018// overwriting only allowed with '!' 2019// If "other" is false and bt_nofilename(buf) is true, this must be 2020// writing an "acwrite" buffer to the same file as its b_ffname, and 2021// buf_write() will only allow writing with BufWriteCmd autocommands, 2022// so there is no need for an overwrite check. 2023if ((other 2024|| (!bt_nofilename (buf ) 2025&& ((buf -> b_flags & BF_NOTEDITED ) 2026|| ((buf -> b_flags & BF_NEW ) 2027&& vim_strchr (p_cpo ,kCpoOvernew )== NULL ) 2028|| (buf -> b_flags & BF_READERR )))) 2029&& !p_wa 2030&& os_path_exists (ffname )) { 2031if (!eap -> forceit && !eap -> append ) { 2032if (os_isdir (ffname )) { 2033semsg (_ (e_isadir2 ),ffname ); 2034return FAIL ; 2035 } 2036if (p_confirm || (cmdmod .cmod_flags & CMOD_CONFIRM )) { 2037char buff [DIALOG_MSG_SIZE ]; 2038snprintf (buff ,sizeof buff ,_ ("Overwrite existing file \"%s\"?" ),fname ); 2039if (vim_dialog_yesno (VIM_QUESTION ,NULL ,buff ,2 )!= VIM_YES ) { 2040return FAIL ; 2041 } 2042eap -> forceit = true; 2043 }else { 2044emsg (_ (e_exists )); 2045return FAIL ; 2046 } 2047 } 2048 2049// For ":w! filename" check that no swap file exists for "filename". 2050if (other && !emsg_silent ) { 2051char * dir ; 2052 2053// We only try the first entry in 'directory', without checking if 2054// it's writable. If the "." directory is not writable the write 2055// will probably fail anyway. 2056// Use 'shortname' of the current buffer, since there is no buffer 2057// for the written file. 2058if (* p_dir == NUL ) { 2059dir = xmalloc (5 ); 2060STRCPY (dir ,"." ); 2061 }else { 2062dir = xmalloc (MAXPATHL ); 2063char * p = p_dir ; 2064copy_option_part (& p ,dir ,MAXPATHL ,"," ); 2065 } 2066char * swapname = makeswapname (fname ,ffname ,curbuf ,dir ); 2067xfree (dir ); 2068if (os_path_exists (swapname )) { 2069if (p_confirm || (cmdmod .cmod_flags & CMOD_CONFIRM )) { 2070char buff [DIALOG_MSG_SIZE ]; 2071 2072vim_snprintf (buff ,sizeof buff , 2073_ ("Swap file \"%s\" exists, overwrite anyway?" ), 2074swapname ); 2075if (vim_dialog_yesno (VIM_QUESTION ,NULL ,buff ,2 ) 2076!= VIM_YES ) { 2077xfree (swapname ); 2078return FAIL ; 2079 } 2080eap -> forceit = true; 2081 }else { 2082semsg (_ ("E768: Swap file exists: %s (:silent! overrides)" ), 2083swapname ); 2084xfree (swapname ); 2085return FAIL ; 2086 } 2087 } 2088xfree (swapname ); 2089 } 2090 } 2091return OK ; 2092} 2093 2094/// Handle ":wnext", ":wNext" and ":wprevious" commands. 2095void ex_wnext (exarg_T * eap ) 2096{ 2097int i ; 2098 2099if (eap -> cmd [1 ]== 'n' ) { 2100i = curwin -> w_arg_idx + (int )eap -> line2 ; 2101 }else { 2102i = curwin -> w_arg_idx - (int )eap -> line2 ; 2103 } 2104eap -> line1 = 1 ; 2105eap -> line2 = curbuf -> b_ml .ml_line_count ; 2106if (do_write (eap )!= FAIL ) { 2107do_argfile (eap ,i ); 2108 } 2109} 2110 2111/// ":wall", ":wqall" and ":xall": Write all changed files (and exit). 2112void do_wqall (exarg_T * eap ) 2113{ 2114int error = 0 ; 2115int save_forceit = eap -> forceit ; 2116bool save_exiting = exiting ; 2117 2118if (eap -> cmdidx == CMD_xall || eap -> cmdidx == CMD_wqall ) { 2119if (before_quit_all (eap )== FAIL ) { 2120return ; 2121 } 2122exiting = true; 2123 } 2124 2125FOR_ALL_BUFFERS (buf ) { 2126if (exiting && !eap -> forceit 2127&& buf -> terminal 2128// TODO(zeertzjq): this always returns false for nvim_open_term() terminals. 2129// Use terminal_running() instead? 2130&& channel_job_running ((uint64_t )buf -> b_p_channel )) { 2131no_write_message_buf (buf ); 2132error ++ ; 2133continue ; 2134 }else if (!bufIsChanged (buf )|| bt_dontwrite (buf )) { 2135continue ; 2136 } 2137// Check if there is a reason the buffer cannot be written: 2138// 1. if the 'write' option is set 2139// 2. if there is no file name (even after browsing) 2140// 3. if the 'readonly' is set (even after a dialog) 2141// 4. if overwriting is allowed (even after a dialog) 2142if (not_writing ()) { 2143error ++ ; 2144break ; 2145 } 2146if (buf -> b_ffname == NULL ) { 2147semsg (_ ("E141: No file name for buffer %" PRId64 ), (int64_t )buf -> b_fnum ); 2148error ++ ; 2149 }else if (check_readonly (& eap -> forceit ,buf ) 2150|| check_overwrite (eap ,buf ,buf -> b_fname ,buf -> b_ffname , false)== FAIL ) { 2151error ++ ; 2152 }else { 2153bufref_T bufref ; 2154set_bufref (& bufref ,buf ); 2155if (handle_mkdir_p_arg (eap ,buf -> b_fname )== FAIL 2156|| buf_write_all (buf ,eap -> forceit )== FAIL ) { 2157error ++ ; 2158 } 2159// An autocommand may have deleted the buffer. 2160if (!bufref_valid (& bufref )) { 2161buf = firstbuf ; 2162 } 2163 } 2164eap -> forceit = save_forceit ;// check_overwrite() may set it 2165 } 2166if (exiting ) { 2167if (!error ) { 2168getout (0 );// exit Vim 2169 } 2170not_exiting (save_exiting ); 2171 } 2172} 2173 2174/// Check the 'write' option. 2175/// 2176/// @return true and give a message when it's not st. 2177static bool not_writing (void ) 2178{ 2179if (p_write ) { 2180return false; 2181 } 2182emsg (_ ("E142: File not written: Writing is disabled by 'write' option" )); 2183return true; 2184} 2185 2186/// Check if a buffer is read-only (either 'readonly' option is set or file is 2187/// read-only). Ask for overruling in a dialog. Return true and give an error 2188/// message when the buffer is readonly. 2189static int check_readonly (int * forceit ,buf_T * buf ) 2190{ 2191// Handle a file being readonly when the 'readonly' option is set or when 2192// the file exists and permissions are read-only. 2193if (!* forceit && (buf -> b_p_ro 2194|| (os_path_exists (buf -> b_ffname ) 2195&& !os_file_is_writable (buf -> b_ffname )))) { 2196if ((p_confirm || (cmdmod .cmod_flags & CMOD_CONFIRM ))&& buf -> b_fname != NULL ) { 2197char buff [DIALOG_MSG_SIZE ]; 2198 2199const char * fname = buf -> b_fname ?buf -> b_fname :_ ("Untitled" ); 2200if (buf -> b_p_ro ) { 2201snprintf (buff ,sizeof buff , 2202_ ("'readonly' option is set for \"%s\".\nDo you wish to write anyway?" ), 2203fname ); 2204 }else { 2205snprintf (buff ,sizeof buff , 2206_ ("File permissions of \"%s\" are read-only.\nIt may still be possible to " 2207"write it.\nDo you wish to try?" ), 2208fname ); 2209 } 2210 2211if (vim_dialog_yesno (VIM_QUESTION ,NULL ,buff ,2 )== VIM_YES ) { 2212// Set forceit, to force the writing of a readonly file 2213* forceit = true; 2214return false; 2215 } 2216return true; 2217 }else if (buf -> b_p_ro ) { 2218emsg (_ (e_readonly )); 2219 }else { 2220semsg (_ ("E505: \"%s\" is read-only (add ! to override)" ), 2221buf -> b_fname ); 2222 } 2223return true; 2224 } 2225 2226return false; 2227} 2228 2229/// Try to abandon the current file and edit a new or existing file. 2230/// 2231/// @param fnum the number of the file, if zero use "ffname_arg"/"sfname_arg". 2232/// @param lnum the line number for the cursor in the new file (if non-zero). 2233/// 2234/// @return: 2235/// GETFILE_ERROR for "normal" error, 2236/// GETFILE_NOT_WRITTEN for "not written" error, 2237/// GETFILE_SAME_FILE for success 2238/// GETFILE_OPEN_OTHER for successfully opening another file. 2239int getfile (int fnum ,char * ffname_arg ,char * sfname_arg ,bool setpm ,linenr_T lnum ,bool forceit ) 2240{ 2241if (!check_can_set_curbuf_forceit (forceit )) { 2242return GETFILE_ERROR ; 2243 } 2244 2245char * ffname = ffname_arg ; 2246char * sfname = sfname_arg ; 2247bool other ; 2248int retval ; 2249char * free_me = NULL ; 2250 2251if (text_locked ()) { 2252return GETFILE_ERROR ; 2253 } 2254if (curbuf_locked ()) { 2255return GETFILE_ERROR ; 2256 } 2257 2258if (fnum == 0 ) { 2259// make ffname full path, set sfname 2260fname_expand (curbuf ,& ffname ,& sfname ); 2261other = otherfile (ffname ); 2262free_me = ffname ;// has been allocated, free() later 2263 }else { 2264other = (fnum != curbuf -> b_fnum ); 2265 } 2266 2267if (other ) { 2268no_wait_return ++ ;// don't wait for autowrite message 2269 } 2270if (other && !forceit && curbuf -> b_nwindows == 1 && !buf_hide (curbuf ) 2271&& curbufIsChanged ()&& autowrite (curbuf ,forceit )== FAIL ) { 2272if (p_confirm && p_write ) { 2273dialog_changed (curbuf , false); 2274 } 2275if (curbufIsChanged ()) { 2276no_wait_return -- ; 2277no_write_message (); 2278retval = GETFILE_NOT_WRITTEN ;// File has been changed. 2279 gototheend ; 2280 } 2281 } 2282if (other ) { 2283no_wait_return -- ; 2284 } 2285if (setpm ) { 2286setpcmark (); 2287 } 2288if (!other ) { 2289if (lnum != 0 ) { 2290curwin -> w_cursor .lnum = lnum ; 2291 } 2292check_cursor_lnum (curwin ); 2293beginline (BL_SOL |BL_FIX ); 2294retval = GETFILE_SAME_FILE ;// it's in the same file 2295 }else if (do_ecmd (fnum ,ffname ,sfname ,NULL ,lnum , 2296 (buf_hide (curbuf ) ?ECMD_HIDE :0 ) 2297+ (forceit ?ECMD_FORCEIT :0 ),curwin )== OK ) { 2298retval = GETFILE_OPEN_OTHER ;// opened another file 2299 }else { 2300retval = GETFILE_ERROR ;// error encountered 2301 } 2302 2303theend : 2304xfree (free_me ); 2305return retval ; 2306} 2307 2308/// set v:swapcommand for the SwapExists autocommands. 2309/// 2310/// @param command [+cmd] to be executed (e.g. +10). 2311/// @param newlnum if > 0: put cursor on this line number (if possible) 2312// 2313/// @return 1 if swapcommand was actually set, 0 otherwise 2314bool set_swapcommand (char * command ,linenr_T newlnum ) 2315{ 2316if ((command == NULL && newlnum <=0 )|| * get_vim_var_str (VV_SWAPCOMMAND )!= NUL ) { 2317return false; 2318 } 2319const size_t valsize = (command != NULL ) ?strlen (command )+ 3 :30 ; 2320String val ; 2321val .data = xmalloc (valsize ); 2322val .size = (command != NULL ) 2323 ?vim_snprintf_safelen (val .data ,valsize ,":%s\r" ,command ) 2324 :vim_snprintf_safelen (val .data ,valsize ,"%" PRId64 "G" , (int64_t )newlnum ); 2325set_vim_var_string (VV_SWAPCOMMAND ,val .data , (ptrdiff_t )val .size ); 2326xfree (val .data ); 2327return true; 2328} 2329 2330/// start editing a new file 2331/// 2332/// @param fnum file number; if zero use ffname/sfname 2333/// @param ffname the file name 2334/// - full path if sfname used, 2335/// - any file name if sfname is NULL 2336/// - empty string to re-edit with the same file name (but may 2337/// be in a different directory) 2338/// - NULL to start an empty buffer 2339/// @param sfname the short file name (or NULL) 2340/// @param eap contains the command to be executed after loading the file 2341/// and forced 'ff' and 'fenc'. Can be NULL! 2342/// @param newlnum if > 0: put cursor on this line number (if possible) 2343/// ECMD_LASTL: use last position in loaded file 2344/// ECMD_LAST: use last position in all files 2345/// ECMD_ONE: use first line 2346/// @param flags ECMD_HIDE: if true don't free the current buffer 2347/// ECMD_SET_HELP: set b_help flag of (new) buffer before 2348/// opening file 2349/// ECMD_OLDBUF: use existing buffer if it exists 2350/// ECMD_FORCEIT: ! used for Ex command 2351/// ECMD_ADDBUF: don't edit, just add to buffer list 2352/// ECMD_ALTBUF: like ECMD_ADDBUF and also set the alternate 2353/// file 2354/// ECMD_NOWINENTER: Do not trigger BufWinEnter 2355/// @param oldwin Should be "curwin" when editing a new buffer in the current 2356/// window, NULL when splitting the window first. When not NULL 2357/// info of the previous buffer for "oldwin" is stored. 2358/// 2359/// @return FAIL for failure, OK otherwise 2360int do_ecmd (int fnum ,char * ffname ,char * sfname ,exarg_T * eap ,linenr_T newlnum ,int flags , 2361win_T * oldwin ) 2362{ 2363bool other_file ;// true if editing another file 2364int oldbuf ;// true if using existing buffer 2365bool auto_buf = false;// true if autocommands brought us 2366// into the buffer unexpectedly 2367char * new_name = NULL ; 2368bool did_set_swapcommand = false; 2369buf_T * buf ; 2370bufref_T bufref ; 2371bufref_T old_curbuf ; 2372char * free_fname = NULL ; 2373int retval = FAIL ; 2374linenr_T topline = 0 ; 2375int newcol = -1 ; 2376int solcol = -1 ; 2377char * command = NULL ; 2378bool did_get_winopts = false; 2379int readfile_flags = 0 ; 2380bool did_inc_redrawing_disabled = false; 2381OptInt * so_ptr = curwin -> w_p_so >=0 ?& curwin -> w_p_so :& p_so ; 2382 2383if (eap != NULL ) { 2384command = eap -> do_ecmd_cmd ; 2385 } 2386 2387set_bufref (& old_curbuf ,curbuf ); 2388 2389if (fnum != 0 ) { 2390if (fnum == curbuf -> b_fnum ) {// file is already being edited 2391return OK ;// nothing to do 2392 } 2393other_file = true; 2394 }else { 2395// if no short name given, use ffname for short name 2396if (sfname == NULL ) { 2397sfname = ffname ; 2398 } 2399#ifdef CASE_INSENSITIVE_FILENAME 2400if (sfname != NULL ) { 2401path_fix_case (sfname );// set correct case for sfname 2402 } 2403#endif 2404 2405if ((flags & (ECMD_ADDBUF |ECMD_ALTBUF )) 2406&& (ffname == NULL || * ffname == NUL )) { 2407 gototheend ; 2408 } 2409 2410if (ffname == NULL ) { 2411other_file = true; 2412 }else if (* ffname == NUL && curbuf -> b_ffname == NULL ) {// there is no file name 2413other_file = false; 2414 }else { 2415if (* ffname == NUL ) {// re-edit with same file name 2416ffname = curbuf -> b_ffname ; 2417sfname = curbuf -> b_fname ; 2418 } 2419free_fname = fix_fname (ffname );// may expand to full path name 2420if (free_fname != NULL ) { 2421ffname = free_fname ; 2422 } 2423other_file = otherfile (ffname ); 2424 } 2425 } 2426 2427// Re-editing a terminal buffer: skip most buffer re-initialization. 2428if (!other_file && curbuf -> terminal ) { 2429check_arg_idx (curwin );// Needed when called from do_argfile(). 2430maketitle ();// Title may show the arg index, e.g. "(2 of 5)". 2431retval = OK ; 2432 gototheend ; 2433 } 2434 2435// If the file was changed we may not be allowed to abandon it: 2436// - if we are going to re-edit the same file 2437// - or if we are the only window on this file and if ECMD_HIDE is false 2438if (((!other_file && !(flags & ECMD_OLDBUF )) 2439|| (curbuf -> b_nwindows == 1 2440&& !(flags & (ECMD_HIDE |ECMD_ADDBUF |ECMD_ALTBUF )))) 2441&& check_changed (curbuf , (p_awa ?CCGD_AW :0 ) 2442 | (other_file ?0 :CCGD_MULTWIN ) 2443 | ((flags & ECMD_FORCEIT ) ?CCGD_FORCEIT :0 ) 2444 | (eap == NULL ?0 :CCGD_EXCMD ))) { 2445if (fnum == 0 && other_file && ffname != NULL ) { 2446setaltfname (ffname ,sfname ,newlnum < 0 ?0 :newlnum ); 2447 } 2448 gototheend ; 2449 } 2450 2451// End Visual mode before switching to another buffer, so the text can be 2452// copied into the GUI selection buffer. 2453// Careful: may trigger ModeChanged() autocommand 2454 2455// Should we block autocommands here? 2456reset_VIsual (); 2457 2458// autocommands freed window :( 2459if (oldwin != NULL && !win_valid (oldwin )) { 2460oldwin = NULL ; 2461 } 2462 2463did_set_swapcommand = set_swapcommand (command ,newlnum ); 2464 2465// If we are starting to edit another file, open a (new) buffer. 2466// Otherwise we re-use the current buffer. 2467if (other_file ) { 2468const int prev_alt_fnum = curwin -> w_alt_fnum ; 2469 2470if (!(flags & (ECMD_ADDBUF |ECMD_ALTBUF ))) { 2471if ((cmdmod .cmod_flags & CMOD_KEEPALT )== 0 ) { 2472curwin -> w_alt_fnum = curbuf -> b_fnum ; 2473 } 2474if (oldwin != NULL ) { 2475buflist_altfpos (oldwin ); 2476 } 2477 } 2478 2479if (fnum ) { 2480buf = buflist_findnr (fnum ); 2481 }else { 2482if (flags & (ECMD_ADDBUF |ECMD_ALTBUF )) { 2483// Default the line number to zero to avoid that a wininfo item 2484// is added for the current window. 2485linenr_T tlnum = 0 ; 2486 2487if (command != NULL ) { 2488tlnum = (linenr_T )atol (command ); 2489if (tlnum <=0 ) { 2490tlnum = 1 ; 2491 } 2492 } 2493// Add BLN_NOCURWIN to avoid a new wininfo items are associated 2494// with the current window. 2495const buf_T * const newbuf 2496= buflist_new (ffname ,sfname ,tlnum ,BLN_LISTED |BLN_NOCURWIN ); 2497if (newbuf != NULL && (flags & ECMD_ALTBUF )) { 2498curwin -> w_alt_fnum = newbuf -> b_fnum ; 2499 } 2500 gototheend ; 2501 } 2502buf = buflist_new (ffname ,sfname ,0 , 2503BLN_CURBUF | (flags & ECMD_SET_HELP ?0 :BLN_LISTED )); 2504// Autocmds may change curwin and curbuf. 2505if (oldwin != NULL ) { 2506oldwin = curwin ; 2507 } 2508set_bufref (& old_curbuf ,curbuf ); 2509 } 2510if (buf == NULL ) { 2511 gototheend ; 2512 } 2513// autocommands try to edit a closing buffer, which like splitting, can 2514// result in more windows displaying it; abort 2515if (buf -> b_locked_split ) { 2516emsg (_ (e_cannot_switch_to_a_closing_buffer )); 2517 gototheend ; 2518 } 2519if (curwin -> w_alt_fnum == buf -> b_fnum && prev_alt_fnum != 0 ) { 2520// reusing the buffer, keep the old alternate file 2521curwin -> w_alt_fnum = prev_alt_fnum ; 2522 } 2523if (buf -> b_ml .ml_mfp == NULL ) { 2524// No memfile yet. 2525oldbuf = false; 2526 }else { 2527// Existing memfile. 2528oldbuf = true; 2529set_bufref (& bufref ,buf ); 2530buf_check_timestamp (buf ); 2531// Check if autocommands made buffer invalid or changed the current 2532// buffer. 2533if (!bufref_valid (& bufref )|| curbuf != old_curbuf .br_buf ) { 2534 gototheend ; 2535 } 2536if (aborting ()) { 2537// Autocmds may abort script processing. 2538 gototheend ; 2539 } 2540 } 2541 2542// May jump to last used line number for a loaded buffer or when asked 2543// for explicitly 2544if ((oldbuf && newlnum == ECMD_LASTL )|| newlnum == ECMD_LAST ) { 2545pos_T * pos = & buflist_findfmark (buf )-> mark ; 2546newlnum = pos -> lnum ; 2547solcol = pos -> col ; 2548 } 2549 2550// Make the (new) buffer the one used by the current window. 2551// If the old buffer becomes unused, free it if ECMD_HIDE is false. 2552// If the current buffer was empty and has no file name, curbuf 2553// is returned by buflist_new(), nothing to do here. 2554if (buf != curbuf ) { 2555// Be careful: The autocommands may delete any buffer and change 2556// the current buffer. 2557// - If the buffer we are going to edit is deleted, give up. 2558// - If the current buffer is deleted, prefer to load the new 2559// buffer when loading a buffer is required. This avoids 2560// loading another buffer which then must be closed again. 2561// - If we ended up in the new buffer already, need to skip a few 2562// things, set auto_buf. 2563if (buf -> b_fname != NULL ) { 2564new_name = xstrdup (buf -> b_fname ); 2565 } 2566const bufref_T save_au_new_curbuf = au_new_curbuf ; 2567set_bufref (& au_new_curbuf ,buf ); 2568apply_autocmds (EVENT_BUFLEAVE ,NULL ,NULL , false,curbuf ); 2569 2570if (!bufref_valid (& au_new_curbuf )) { 2571// New buffer has been deleted. 2572delbuf_msg (new_name );// Frees new_name. 2573au_new_curbuf = save_au_new_curbuf ; 2574 gototheend ; 2575 } 2576if (aborting ()) {// autocmds may abort script processing 2577xfree (new_name ); 2578au_new_curbuf = save_au_new_curbuf ; 2579 gototheend ; 2580 } 2581if (buf == curbuf ) {// already in new buffer 2582auto_buf = true; 2583 }else { 2584win_T * the_curwin = curwin ; 2585 2586// Set w_locked to avoid that autocommands close the window. 2587// Set b_locked for the same reason. 2588the_curwin -> w_locked ++ ; 2589buf -> b_locked ++ ; 2590 2591if (curbuf == old_curbuf .br_buf ) { 2592buf_copy_options (buf ,BCO_ENTER ); 2593 } 2594 2595// Close the link to the current buffer. This may set 2596// curwin->w_buffer to NULL. 2597u_sync (false); 2598close_buffer (curwin ,curbuf , 2599 (flags & ECMD_HIDE ) 2600|| (curbuf -> terminal && terminal_running (curbuf -> terminal )) 2601 ?0 :DOBUF_UNLOAD , 2602 false, false,oldwin != NULL ); 2603 2604// Autocommands may have closed the window. 2605if (win_valid (the_curwin )) { 2606the_curwin -> w_locked -- ; 2607 } 2608buf -> b_locked -- ; 2609 2610// autocmds may abort script processing 2611if (aborting ()&& curwin -> w_buffer != NULL ) { 2612xfree (new_name ); 2613au_new_curbuf = save_au_new_curbuf ; 2614 gototheend ; 2615 } 2616// Be careful again, like above. 2617if (!bufref_valid (& au_new_curbuf )) { 2618// New buffer was deleted. If curwin->w_buffer is NULL, we 2619// must enter some buffer. Hopefully the last one is OK. 2620if (curwin -> w_buffer == NULL ) { 2621buf = lastbuf ; 2622 }else { 2623delbuf_msg (new_name );// Frees new_name. 2624au_new_curbuf = save_au_new_curbuf ; 2625 gototheend ; 2626 } 2627 } 2628if (buf == curbuf ) {// already in new buffer 2629auto_buf = true; 2630 }else { 2631// <VN> We could instead free the synblock 2632// and re-attach to buffer, perhaps. 2633if (curwin -> w_buffer == NULL 2634|| curwin -> w_s == & (curwin -> w_buffer -> b_s )) { 2635curwin -> w_s = & (buf -> b_s ); 2636 } 2637 2638if (curwin -> w_buffer != NULL ) { 2639curwin -> w_buffer -> b_nwindows -- ; 2640 } 2641 2642curwin -> w_buffer = buf ; 2643curbuf = buf ; 2644curbuf -> b_nwindows ++ ; 2645 2646// Set 'fileformat', 'binary' and 'fenc' when forced. 2647if (!oldbuf && eap != NULL ) { 2648set_file_options (true,eap ); 2649set_forced_fenc (eap ); 2650 } 2651 } 2652 2653// May get the window options from the last time this buffer 2654// was in this window (or another window). If not used 2655// before, reset the local window options to the global 2656// values. Also restores old folding stuff. 2657get_winopts (curbuf ); 2658did_get_winopts = true; 2659 } 2660xfree (new_name ); 2661au_new_curbuf = save_au_new_curbuf ; 2662 } 2663 2664curwin -> w_pcmark .lnum = 1 ; 2665curwin -> w_pcmark .col = 0 ; 2666 }else {// !other_file 2667if ((flags & (ECMD_ADDBUF |ECMD_ALTBUF ))|| check_fname ()== FAIL ) { 2668 gototheend ; 2669 } 2670oldbuf = (flags & ECMD_OLDBUF ); 2671 } 2672 2673// Don't redraw until the cursor is in the right line, otherwise 2674// autocommands may cause ml_get errors. 2675RedrawingDisabled ++ ; 2676did_inc_redrawing_disabled = true; 2677 2678buf = curbuf ; 2679if ((flags & ECMD_SET_HELP )|| keep_help_flag ) { 2680prepare_help_buffer (); 2681 }else if (!curbuf -> b_help ) { 2682// Don't make a buffer listed if it's a help buffer. Useful when using 2683// CTRL-O to go back to a help file. 2684set_buflisted (true); 2685 } 2686 2687// If autocommands change buffers under our fingers, forget about 2688// editing the file. 2689if (buf != curbuf ) { 2690 gototheend ; 2691 } 2692if (aborting ()) {// autocmds may abort script processing 2693 gototheend ; 2694 } 2695 2696// Since we are starting to edit a file, consider the filetype to be 2697// unset. Helps for when an autocommand changes files and expects syntax 2698// highlighting to work in the other file. 2699curbuf -> b_did_filetype = false; 2700 2701// other_file oldbuf 2702// false false re-edit same file, buffer is re-used 2703// false true re-edit same file, nothing changes 2704// true false start editing new file, new buffer 2705// true true start editing in existing buffer (nothing to do) 2706if (!other_file && !oldbuf ) {// re-use the buffer 2707set_last_cursor (curwin );// may set b_last_cursor 2708if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL ) { 2709newlnum = curwin -> w_cursor .lnum ; 2710solcol = curwin -> w_cursor .col ; 2711 } 2712buf = curbuf ; 2713if (buf -> b_fname != NULL ) { 2714new_name = xstrdup (buf -> b_fname ); 2715 }else { 2716new_name = NULL ; 2717 } 2718set_bufref (& bufref ,buf ); 2719 2720// If the buffer was used before, store the current contents so that 2721// the reload can be undone. Do not do this if the (empty) buffer is 2722// being re-used for another file. 2723if (!(curbuf -> b_flags & BF_NEVERLOADED ) 2724&& (p_ur < 0 || curbuf -> b_ml .ml_line_count <=p_ur )) { 2725// Sync first so that this is a separate undo-able action. 2726u_sync (false); 2727if (u_savecommon (curbuf ,0 ,curbuf -> b_ml .ml_line_count + 1 ,0 , true) 2728== FAIL ) { 2729xfree (new_name ); 2730 gototheend ; 2731 } 2732u_unchanged (curbuf ); 2733buf_freeall (curbuf ,BFA_KEEP_UNDO ); 2734 2735// Tell readfile() not to clear or reload undo info. 2736readfile_flags = READ_KEEP_UNDO ; 2737 }else { 2738buf_freeall (curbuf ,0 );// Free all things for buffer. 2739 } 2740// If autocommands deleted the buffer we were going to re-edit, give 2741// up and jump to the end. 2742if (!bufref_valid (& bufref )) { 2743delbuf_msg (new_name );// Frees new_name. 2744 gototheend ; 2745 } 2746xfree (new_name ); 2747 2748// If autocommands change buffers under our fingers, forget about 2749// re-editing the file. Should do the buf_clear_file(), but perhaps 2750// the autocommands changed the buffer... 2751if (buf != curbuf ) { 2752 gototheend ; 2753 } 2754if (aborting ()) {// autocmds may abort script processing 2755 gototheend ; 2756 } 2757buf_clear_file (curbuf ); 2758curbuf -> b_op_start .lnum = 0 ;// clear '[ and '] marks 2759curbuf -> b_op_end .lnum = 0 ; 2760 } 2761 2762// If we get here we are sure to start editing 2763 2764// Assume success now 2765retval = OK ; 2766 2767// If the file name was changed, reset the not-edit flag so that ":write" 2768// works. 2769if (!other_file ) { 2770curbuf -> b_flags &= ~BF_NOTEDITED ; 2771 } 2772 2773// Check if we are editing the w_arg_idx file in the argument list. 2774check_arg_idx (curwin ); 2775 2776if (!auto_buf ) { 2777// Set cursor and init window before reading the file and executing 2778// autocommands. This allows for the autocommands to position the 2779// cursor. 2780curwin_init (); 2781 2782// It's possible that all lines in the buffer changed. Need to update 2783// automatic folding for all windows where it's used. 2784FOR_ALL_TAB_WINDOWS (tp ,win ) { 2785if (win -> w_buffer == curbuf ) { 2786foldUpdateAll (win ); 2787 } 2788 } 2789 2790// Change directories when the 'acd' option is set. 2791do_autochdir (); 2792 2793// Careful: open_buffer() and apply_autocmds() may change the current 2794// buffer and window. 2795pos_T orig_pos = curwin -> w_cursor ; 2796topline = curwin -> w_topline ; 2797if (!oldbuf ) {// need to read the file 2798swap_exists_action = SEA_DIALOG ; 2799curbuf -> b_flags |=BF_CHECK_RO ;// set/reset 'ro' flag 2800 2801// Open the buffer and read the file. 2802if (flags & ECMD_NOWINENTER ) { 2803readfile_flags |=READ_NOWINENTER ; 2804 } 2805if (should_abort (open_buffer (false,eap ,readfile_flags ))) { 2806retval = FAIL ; 2807 } 2808 2809if (swap_exists_action == SEA_QUIT ) { 2810retval = FAIL ; 2811 } 2812handle_swap_exists (& old_curbuf ); 2813 }else { 2814// Read the modelines, but only to set window-local options. Any 2815// buffer-local options have already been set and may have been 2816// changed by the user. 2817do_modelines (OPT_WINONLY ); 2818 2819apply_autocmds_retval (EVENT_BUFENTER ,NULL ,NULL , false,curbuf , 2820& retval ); 2821if ((flags & ECMD_NOWINENTER )== 0 ) { 2822apply_autocmds_retval (EVENT_BUFWINENTER ,NULL ,NULL , false,curbuf , 2823& retval ); 2824 } 2825 } 2826check_arg_idx (curwin ); 2827 2828// If autocommands change the cursor position or topline, we should 2829// keep it. Also when it moves within a line. But not when it moves 2830// to the first non-blank. 2831if (!equalpos (curwin -> w_cursor ,orig_pos )) { 2832const char * text = get_cursor_line_ptr (); 2833 2834if (curwin -> w_cursor .lnum != orig_pos .lnum 2835|| curwin -> w_cursor .col != (int )(skipwhite (text )- text )) { 2836newlnum = curwin -> w_cursor .lnum ; 2837newcol = curwin -> w_cursor .col ; 2838 } 2839 } 2840if (curwin -> w_topline == topline ) { 2841topline = 0 ; 2842 } 2843 2844// Even when cursor didn't move we need to recompute topline. 2845changed_line_abv_curs (); 2846 2847maketitle (); 2848if (retval != FAIL ) { 2849win_float_update_preview (curwin ); 2850 } 2851 } 2852 2853// Tell the diff stuff that this buffer is new and/or needs updating. 2854// Also needed when re-editing the same buffer, because unloading will 2855// have removed it as a diff buffer. 2856if (curwin -> w_p_diff ) { 2857diff_buf_add (curbuf ); 2858diff_invalidate (curbuf ); 2859 } 2860 2861// If the window options were changed may need to set the spell language. 2862// Can only do this after the buffer has been properly setup. 2863if (did_get_winopts && curwin -> w_p_spell && * curwin -> w_s -> b_p_spl != NUL ) { 2864parse_spelllang (curwin ); 2865 } 2866 2867if (command == NULL ) { 2868if (newcol >=0 ) {// position set by autocommands 2869curwin -> w_cursor .lnum = newlnum ; 2870curwin -> w_cursor .col = newcol ; 2871check_cursor (curwin ); 2872 }else if (newlnum > 0 ) {// line number from caller or old position 2873curwin -> w_cursor .lnum = newlnum ; 2874check_cursor_lnum (curwin ); 2875if (solcol >=0 && !p_sol ) { 2876// 'sol' is off: Use last known column. 2877curwin -> w_cursor .col = solcol ; 2878check_cursor_col (curwin ); 2879curwin -> w_cursor .coladd = 0 ; 2880curwin -> w_set_curswant = true; 2881 }else { 2882beginline (BL_SOL |BL_FIX ); 2883 } 2884 }else { 2885beginline (BL_WHITE |BL_FIX ); 2886 } 2887 } 2888 2889// Check if cursors in other windows on the same buffer are still valid 2890check_lnums (false); 2891 2892// Did not read the file, need to show some info about the file. 2893// Do this after setting the cursor. 2894if (oldbuf 2895&& !auto_buf ) { 2896int msg_scroll_save = msg_scroll ; 2897 2898// Obey the 'O' flag in 'cpoptions': overwrite any previous file 2899// message. 2900if (shortmess (kShmOverall )&& !msg_listdo_overwrite && !exiting && p_verbose == 0 ) { 2901msg_scroll = false; 2902 } 2903if (!msg_scroll ) {// wait a bit when overwriting an error msg 2904msg_check_for_delay (false); 2905 } 2906msg_start (); 2907msg_scroll = msg_scroll_save ; 2908msg_scrolled_ign = true; 2909 2910if (!shortmess (kShmFileinfo )) { 2911fileinfo (false, true, false); 2912 } 2913 2914msg_scrolled_ign = false; 2915 } 2916 2917curbuf -> b_last_used = time (NULL ); 2918 2919if (command != NULL ) { 2920do_cmdline (command ,NULL ,NULL ,DOCMD_VERBOSE ); 2921 } 2922 2923if (curbuf -> b_kmap_state & KEYMAP_INIT ) { 2924keymap_init (); 2925 } 2926 2927RedrawingDisabled -- ; 2928did_inc_redrawing_disabled = false; 2929if (!skip_redraw ) { 2930OptInt n = * so_ptr ; 2931if (topline == 0 && command == NULL ) { 2932* so_ptr = 999 ;// force cursor to be vertically centered in the window 2933 } 2934update_topline (curwin ); 2935curwin -> w_scbind_pos = plines_m_win_fill (curwin ,1 ,curwin -> w_topline ); 2936* so_ptr = n ; 2937redraw_curbuf_later (UPD_NOT_VALID );// redraw this buffer later 2938 } 2939 2940// Update to the working directory of the new current buffer. 2941update_cwd (kCdCauseBuffer ); 2942 2943// Change directories when the 'acd' option is set. 2944do_autochdir (); 2945 2946theend : 2947if (bufref_valid (& old_curbuf )&& old_curbuf .br_buf -> terminal != NULL ) { 2948terminal_check_size (old_curbuf .br_buf -> terminal ); 2949 } 2950if ((!bufref_valid (& old_curbuf )|| curbuf != old_curbuf .br_buf )&& curbuf -> terminal != NULL ) { 2951terminal_check_size (curbuf -> terminal ); 2952 } 2953 2954if (did_inc_redrawing_disabled ) { 2955RedrawingDisabled -- ; 2956 } 2957if (did_set_swapcommand ) { 2958set_vim_var_string (VV_SWAPCOMMAND ,NULL ,-1 ); 2959 } 2960xfree (free_fname ); 2961return retval ; 2962} 2963 2964static void delbuf_msg (char * name ) 2965{ 2966semsg (_ ("E143: Autocommands unexpectedly deleted new buffer %s" ), 2967name == NULL ?"" :name ); 2968xfree (name ); 2969au_new_curbuf .br_buf = NULL ; 2970au_new_curbuf .br_buf_free_count = 0 ; 2971} 2972 2973static int append_indent = 0 ;// autoindent for first line 2974 2975/// Get the next line of text for ":append", ":insert" and ":change": the text 2976/// after the bar, the next line of the command, or a line from the script or 2977/// the user. Returns NULL when there is no more. 2978static char * get_append_line (exarg_T * eap ,int indent ) 2979{ 2980char * theline ; 2981char * p ; 2982 2983if (* eap -> arg == '|' ) { 2984// Get the text after the trailing bar. 2985theline = xstrdup (eap -> arg + 1 ); 2986* eap -> arg = NUL ; 2987 }else if (eap -> ea_getline == NULL ) { 2988// No getline() function, use the lines that follow. This ends 2989// when there is no more. 2990if (eap -> nextcmd == NULL ) { 2991return NULL ; 2992 } 2993p = vim_strchr (eap -> nextcmd ,NL ); 2994if (p == NULL ) { 2995p = eap -> nextcmd + strlen (eap -> nextcmd ); 2996 } 2997theline = xmemdupz (eap -> nextcmd , (size_t )(p - eap -> nextcmd )); 2998if (* p != NUL ) { 2999p ++ ; 3000 }else { 3001p = NULL ; 3002 } 3003eap -> nextcmd = p ; 3004 }else { 3005int getline_State = State ; 3006// Set State to avoid the cursor shape to be set to MODE_INSERT 3007// state when getline() returns. 3008State = MODE_CMDLINE ; 3009theline = eap -> ea_getline (eap -> cstack -> cs_looplevel > 0 ?-1 :NUL , 3010eap -> cookie ,indent , true); 3011State = getline_State ; 3012 } 3013return theline ; 3014} 3015 3016/// ":insert" and ":append", also used by ":change" 3017void ex_append (exarg_T * eap ) 3018{ 3019char * theline ; 3020bool did_undo = false; 3021linenr_T lnum = eap -> line2 ; 3022int indent = 0 ; 3023char * p ; 3024bool empty = (curbuf -> b_ml .ml_flags & ML_EMPTY ); 3025 3026if (eap -> skip ) { 3027// Not executing the command, only read the lines up to the ".". 3028while ((theline = get_append_line (eap ,0 ))!= NULL ) { 3029bool end = theline [0 ]== '.' && theline [1 ]== NUL ; 3030xfree (theline ); 3031if (end ) { 3032break ; 3033 } 3034 } 3035return ; 3036 } 3037 3038// the ! flag toggles autoindent 3039if (eap -> forceit ) { 3040curbuf -> b_p_ai = !curbuf -> b_p_ai ; 3041 } 3042 3043// First autoindent comes from the line we start on 3044if (eap -> cmdidx != CMD_change && curbuf -> b_p_ai && lnum > 0 ) { 3045append_indent = get_indent_lnum (lnum ); 3046 } 3047 3048if (eap -> cmdidx != CMD_append ) { 3049lnum -- ; 3050 } 3051 3052// when the buffer is empty need to delete the dummy line 3053if (empty && lnum == 1 ) { 3054lnum = 0 ; 3055 } 3056 3057const int save_State = State ; 3058State = MODE_INSERT ;// behave like in Insert mode 3059if (curbuf -> b_p_iminsert == B_IMODE_LMAP ) { 3060State |=MODE_LANGMAP ; 3061 } 3062 3063while (true) { 3064msg_scroll = true; 3065need_wait_return = false; 3066if (curbuf -> b_p_ai ) { 3067if (append_indent >=0 ) { 3068indent = append_indent ; 3069append_indent = -1 ; 3070 }else if (lnum > 0 ) { 3071indent = get_indent_lnum (lnum ); 3072 } 3073 } 3074theline = get_append_line (eap ,indent ); 3075lines_left = Rows - 1 ; 3076if (theline == NULL ) { 3077break ; 3078 } 3079 3080// Look for the "." after automatic indent. 3081int vcol = 0 ; 3082for (p = theline ;indent > vcol ;p ++ ) { 3083if (* p == ' ' ) { 3084vcol ++ ; 3085 }else if (* p == TAB ) { 3086vcol += 8 - vcol %8 ; 3087 }else { 3088break ; 3089 } 3090 } 3091if ((p [0 ]== '.' && p [1 ]== NUL ) 3092|| (!did_undo && u_save (lnum ,lnum + 1 + (empty ?1 :0 )) 3093== FAIL )) { 3094xfree (theline ); 3095break ; 3096 } 3097 3098// don't use autoindent if nothing was typed. 3099if (p [0 ]== NUL ) { 3100theline [0 ]= NUL ; 3101 } 3102 3103did_undo = true; 3104ml_append (lnum ,theline ,0 , false); 3105if (empty ) { 3106// there are no marks below the inserted lines 3107appended_lines (lnum ,1 ); 3108 }else { 3109appended_lines_mark (lnum ,1 ); 3110 } 3111 3112xfree (theline ); 3113lnum ++ ; 3114 3115if (empty ) { 3116ml_delete (2 ); 3117empty = false; 3118 } 3119 } 3120State = save_State ; 3121ui_cursor_shape (); 3122 3123if (eap -> forceit ) { 3124curbuf -> b_p_ai = !curbuf -> b_p_ai ; 3125 } 3126 3127// "start" is set to eap->line2+1 unless that position is invalid (when 3128// eap->line2 pointed to the end of the buffer and nothing was appended) 3129// "end" is set to lnum when something has been appended, otherwise 3130// it is the same as "start" -- Acevedo 3131if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 3132curbuf -> b_op_start .lnum 3133= (eap -> line2 < curbuf -> b_ml .ml_line_count ) ?eap -> line2 + 1 :curbuf -> b_ml .ml_line_count ; 3134if (eap -> cmdidx != CMD_append ) { 3135curbuf -> b_op_start .lnum -- ; 3136 } 3137curbuf -> b_op_end .lnum = (eap -> line2 < lnum ) ?lnum :curbuf -> b_op_start .lnum ; 3138curbuf -> b_op_start .col = curbuf -> b_op_end .col = 0 ; 3139 } 3140curwin -> w_cursor .lnum = lnum ; 3141check_cursor_lnum (curwin ); 3142beginline (BL_SOL |BL_FIX ); 3143 3144need_wait_return = false;// don't use wait_return() now 3145} 3146 3147/// ":change" 3148void ex_change (exarg_T * eap ) 3149{ 3150linenr_T lnum ; 3151 3152if (eap -> skip ) { 3153ex_append (eap ); 3154return ; 3155 } 3156if (eap -> line2 >=eap -> line1 3157&& u_save (eap -> line1 - 1 ,eap -> line2 + 1 )== FAIL ) { 3158return ; 3159 } 3160 3161// the ! flag toggles autoindent 3162if (eap -> forceit ? !curbuf -> b_p_ai :curbuf -> b_p_ai ) { 3163append_indent = get_indent_lnum (eap -> line1 ); 3164 } 3165 3166for (lnum = eap -> line2 ;lnum >=eap -> line1 ;lnum -- ) { 3167if (curbuf -> b_ml .ml_flags & ML_EMPTY ) {// nothing to delete 3168break ; 3169 } 3170ml_delete (eap -> line1 ); 3171 } 3172 3173// make sure the cursor is not beyond the end of the file now 3174check_cursor_lnum (curwin ); 3175deleted_lines_mark (eap -> line1 , (eap -> line2 - lnum )); 3176 3177// ":append" on the line above the deleted lines. 3178eap -> line2 = eap -> line1 ; 3179ex_append (eap ); 3180} 3181 3182void ex_z (exarg_T * eap ) 3183{ 3184int64_t bigness ; 3185int minus = 0 ; 3186linenr_T start ,end ,curs ; 3187linenr_T lnum = eap -> line2 ; 3188 3189// Vi compatible: ":z!" uses display height, without a count uses 3190// 'scroll' 3191if (eap -> forceit ) { 3192bigness = Rows - 1 ; 3193 }else if (ONE_WINDOW ) { 3194bigness = curwin -> w_p_scr * 2 ; 3195 }else { 3196bigness = curwin -> w_view_height - 3 ; 3197 } 3198bigness = MAX (bigness ,1 ); 3199 3200char * x = eap -> arg ; 3201char * kind = x ; 3202if (* kind == '-' || * kind == '+' || * kind == '=' 3203|| * kind == '^' || * kind == '.' ) { 3204x ++ ; 3205 } 3206while (* x == '-' || * x == '+' ) { 3207x ++ ; 3208 } 3209 3210if (* x != 0 ) { 3211if (!ascii_isdigit (* x )) { 3212emsg (_ (e_non_numeric_argument_to_z )); 3213return ; 3214 } 3215bigness = atol (x ); 3216 3217// bigness could be < 0 if atol(x) overflows. 3218if (bigness > 2 * curbuf -> b_ml .ml_line_count || bigness < 0 ) { 3219bigness = 2 * curbuf -> b_ml .ml_line_count ; 3220 } 3221 3222p_window = (int )bigness ; 3223if (* kind == '=' ) { 3224bigness += 2 ; 3225 } 3226 } 3227 3228// the number of '-' and '+' multiplies the distance 3229if (* kind == '-' || * kind == '+' ) { 3230for (x = kind + 1 ;* x == * kind ;x ++ ) {} 3231 } 3232 3233switch (* kind ) { 3234case '-' : 3235start = lnum - (linenr_T )bigness * (linenr_T )(x - kind )+ 1 ; 3236end = start + (linenr_T )bigness - 1 ; 3237curs = end ; 3238break ; 3239 3240case '=' : 3241start = lnum - ((linenr_T )bigness + 1 ) /2 + 1 ; 3242end = lnum + ((linenr_T )bigness + 1 ) /2 - 1 ; 3243curs = lnum ; 3244minus = 1 ; 3245break ; 3246 3247case '^' : 3248start = lnum - (linenr_T )bigness * 2 ; 3249end = lnum - (linenr_T )bigness ; 3250curs = lnum - (linenr_T )bigness ; 3251break ; 3252 3253case '.' : 3254start = lnum - ((linenr_T )bigness + 1 ) /2 + 1 ; 3255end = lnum + ((linenr_T )bigness + 1 ) /2 - 1 ; 3256curs = end ; 3257break ; 3258 3259default :// '+' 3260start = lnum ; 3261if (* kind == '+' ) { 3262start += (linenr_T )bigness * (linenr_T )(x - kind - 1 )+ 1 ; 3263 }else if (eap -> addr_count == 0 ) { 3264start ++ ; 3265 } 3266end = start + (linenr_T )bigness - 1 ; 3267curs = end ; 3268break ; 3269 } 3270 3271start = MAX (start ,1 ); 3272end = MIN (end ,curbuf -> b_ml .ml_line_count ); 3273curs = MIN (MAX (curs ,1 ),curbuf -> b_ml .ml_line_count ); 3274 3275for (linenr_T i = start ;i <=end ;i ++ ) { 3276if (minus && i == lnum ) { 3277msg_putchar ('\n' ); 3278 3279for (int j = 1 ;j < Columns ;j ++ ) { 3280msg_putchar ('-' ); 3281 } 3282 } 3283 3284print_line (i ,eap -> flags & EXFLAG_NR ,eap -> flags & EXFLAG_LIST ,i == start ); 3285 3286if (minus && i == lnum ) { 3287msg_putchar ('\n' ); 3288 3289for (int j = 1 ;j < Columns ;j ++ ) { 3290msg_putchar ('-' ); 3291 } 3292 } 3293 } 3294 3295if (curwin -> w_cursor .lnum != curs ) { 3296curwin -> w_cursor .lnum = curs ; 3297curwin -> w_cursor .col = 0 ; 3298 } 3299} 3300 3301/// @return true if the secure flag is set and also give an error message. 3302/// Otherwise, return false. 3303bool check_secure (void ) 3304{ 3305if (secure ) { 3306secure = 2 ; 3307emsg (_ (e_curdir )); 3308return true; 3309 } 3310 3311// In the sandbox more things are not allowed, including the things 3312// disallowed in secure mode. 3313if (sandbox != 0 ) { 3314emsg (_ (e_sandbox )); 3315return true; 3316 } 3317return false; 3318} 3319 3320/// Previous substitute replacement string 3321static SubReplacementString old_sub = {NULL ,0 ,NULL }; 3322 3323static int global_need_beginline ;// call beginline() after ":g" 3324 3325/// Get old substitute replacement string 3326/// 3327/// @param[out] ret_sub Location where old string will be saved. 3328void sub_get_replacement (SubReplacementString * const ret_sub ) 3329FUNC_ATTR_NONNULL_ALL 3330{ 3331* ret_sub = old_sub ; 3332} 3333 3334/// Set substitute string and timestamp 3335/// 3336/// @warning `sub` must be in allocated memory. It is not copied. 3337/// 3338/// @param[in] sub New replacement string. 3339void sub_set_replacement (SubReplacementString sub ) 3340{ 3341xfree (old_sub .sub ); 3342if (sub .additional_data != old_sub .additional_data ) { 3343xfree (old_sub .additional_data ); 3344 } 3345old_sub = sub ; 3346} 3347 3348/// Recognize ":%s/\n//" and turn it into a join command, which is much 3349/// more efficient. 3350/// 3351/// @param[in] eap Ex arguments 3352/// @param[in] pat Search pattern 3353/// @param[in] sub Replacement string 3354/// @param[in] cmd Command from :s_flags 3355/// @param[in] save Save pattern to options, history 3356/// 3357/// @returns true if :substitute can be replaced with a join command 3358static bool sub_joining_lines (exarg_T * eap ,String pat ,const char * sub ,const char * cmd ,bool save , 3359bool keeppatterns ) 3360FUNC_ATTR_NONNULL_ARG (1 ,3 ,4 ) 3361{ 3362// TODO(vim): find a generic solution to make line-joining operations more 3363// efficient, avoid allocating a string that grows in size. 3364if (pat .data != NULL 3365&& strcmp (pat .data ,"\\n" )== 0 3366&& * sub == NUL 3367&& (* cmd == NUL || (cmd [1 ]== NUL 3368&& (* cmd == 'g' 3369|| * cmd == 'l' 3370|| * cmd == 'p' 3371|| * cmd == '#' )))) { 3372if (eap -> skip ) { 3373return true; 3374 } 3375curwin -> w_cursor .lnum = eap -> line1 ; 3376if (* cmd == 'l' ) { 3377eap -> flags = EXFLAG_LIST ; 3378 }else if (* cmd == '#' ) { 3379eap -> flags = EXFLAG_NR ; 3380 }else if (* cmd == 'p' ) { 3381eap -> flags = EXFLAG_PRINT ; 3382 } 3383 3384// The number of lines joined is the number of lines in the range 3385linenr_T joined_lines_count = eap -> line2 - eap -> line1 + 1 3386// plus one extra line if not at the end of file. 3387+ (eap -> line2 < curbuf -> b_ml .ml_line_count ?1 :0 ); 3388if (joined_lines_count > 1 ) { 3389do_join ((size_t )joined_lines_count , false, true, false, true); 3390sub_nsubs = joined_lines_count - 1 ; 3391sub_nlines = 1 ; 3392do_sub_msg (false); 3393ex_may_print (eap ); 3394 } 3395 3396if (save ) { 3397if (!keeppatterns ) { 3398save_re_pat (RE_SUBST ,pat .data ,pat .size ,p_magic ); 3399 } 3400// put pattern in history 3401add_to_history (HIST_SEARCH ,pat .data ,pat .size , true,NUL ); 3402 } 3403 3404return true; 3405 } 3406 3407return false; 3408} 3409 3410/// Allocate memory to store the replacement text for :substitute. 3411/// 3412/// Slightly more memory that is strictly necessary is allocated to reduce the 3413/// frequency of memory (re)allocation. 3414/// 3415/// @param[in,out] new_start pointer to the memory for the replacement text 3416/// @param[in,out] new_start_size pointer to allocated size of new_start->data 3417/// @param[in] needed_size amount of memory needed 3418static void sub_grow_buf (String * new_start ,size_t * new_start_size ,size_t needed_size ) 3419FUNC_ATTR_NONNULL_ALL 3420{ 3421if (new_start -> data == NULL ) { 3422// Get some space for a temporary buffer to do the 3423// substitution into (and some extra space to avoid 3424// too many calls to xmalloc()/free()). 3425* new_start_size = needed_size + 50 ; 3426new_start -> data = xcalloc (1 ,* new_start_size ); 3427new_start -> data [0 ]= NUL ; 3428new_start -> size = 0 ; 3429 }else { 3430// Check if the temporary buffer is long enough to do the 3431// substitution into. If not, make it larger (with a bit 3432// extra to avoid too many calls to xmalloc()/free()). 3433needed_size += new_start -> size ; 3434if (needed_size > * new_start_size ) { 3435size_t prev_new_start_size = * new_start_size ; 3436* new_start_size = needed_size + 50 ; 3437size_t added_len = * new_start_size - prev_new_start_size ; 3438new_start -> data = xrealloc (new_start -> data ,* new_start_size ); 3439memset (new_start -> data + prev_new_start_size ,0 ,added_len ); 3440 } 3441 } 3442} 3443 3444/// Parse cmd string for :substitute's {flags} and update subflags accordingly 3445/// 3446/// @param[in] cmd command string 3447/// @param[in,out] subflags current flags defined for the :substitute command 3448/// @param[in,out] which_pat pattern type from which to get default search 3449/// 3450/// @returns pointer to the end of the flags, which may be the end of the string 3451static char * sub_parse_flags (char * cmd ,subflags_T * subflags ,int * which_pat ) 3452FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 3453{ 3454// Find trailing options. When '&' is used, keep old options. 3455if (* cmd == '&' ) { 3456cmd ++ ; 3457 }else { 3458subflags -> do_all = p_gd ; 3459subflags -> do_ask = false; 3460subflags -> do_error = true; 3461subflags -> do_print = false; 3462subflags -> do_list = false; 3463subflags -> do_count = false; 3464subflags -> do_number = false; 3465subflags -> do_ic = kSubHonorOptions ; 3466 } 3467while (* cmd ) { 3468// Note that 'g' and 'c' are always inverted. 3469// 'r' is never inverted. 3470if (* cmd == 'g' ) { 3471subflags -> do_all = !subflags -> do_all ; 3472 }else if (* cmd == 'c' ) { 3473subflags -> do_ask = !subflags -> do_ask ; 3474 }else if (* cmd == 'n' ) { 3475subflags -> do_count = true; 3476 }else if (* cmd == 'e' ) { 3477subflags -> do_error = !subflags -> do_error ; 3478 }else if (* cmd == 'r' ) {// use last used regexp 3479* which_pat = RE_LAST ; 3480 }else if (* cmd == 'p' ) { 3481subflags -> do_print = true; 3482 }else if (* cmd == '#' ) { 3483subflags -> do_print = true; 3484subflags -> do_number = true; 3485 }else if (* cmd == 'l' ) { 3486subflags -> do_print = true; 3487subflags -> do_list = true; 3488 }else if (* cmd == 'i' ) {// ignore case 3489subflags -> do_ic = kSubIgnoreCase ; 3490 }else if (* cmd == 'I' ) {// don't ignore case 3491subflags -> do_ic = kSubMatchCase ; 3492 }else { 3493break ; 3494 } 3495cmd ++ ; 3496 } 3497if (subflags -> do_count ) { 3498subflags -> do_ask = false; 3499 } 3500 3501return cmd ; 3502} 3503 3504/// Skip over the "sub" part in :s/pat/sub/ where "delimiter" is the separating 3505/// character. 3506static char * skip_substitute (char * start ,int delimiter ) 3507{ 3508char * p = start ; 3509 3510while (p [0 ]) { 3511if (p [0 ]== delimiter ) {// end delimiter found 3512* p ++ = NUL ;// replace it with a NUL 3513break ; 3514 } 3515if (p [0 ]== '\\' && p [1 ]!= 0 ) {// skip escaped characters 3516p ++ ; 3517 } 3518MB_PTR_ADV (p ); 3519 } 3520return p ; 3521} 3522 3523static int check_regexp_delim (int c ) 3524FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 3525{ 3526if (isalpha (c )) { 3527emsg (_ ("E146: Regular expressions can't be delimited by letters" )); 3528return FAIL ; 3529 } 3530return OK ; 3531} 3532 3533/// Perform a substitution from line eap->line1 to line eap->line2 using the 3534/// command pointed to by eap->arg which should be of the form: 3535/// 3536/// /pattern/substitution/{flags} 3537/// 3538/// The usual escapes are supported as described in the regexp docs. 3539/// 3540/// @param tm Timeout limit 3541/// @param cmdpreview_ns The namespace to show 'inccommand' preview highlights. 3542/// If <= 0, preview shouldn't be shown. 3543/// @return 0, 1 or 2. See cmdpreview_may_show() for more information on the meaning. 3544static int do_sub (exarg_T * eap ,proftime_T tm ,const int cmdpreview_ns , 3545const handle_T cmdpreview_bufnr ) 3546{ 3547#define ADJUST_SUB_FIRSTLNUM () \ 3548 do { \ 3549/* For a multi-line match, make a copy of the last matched */ \ 3550/* line and continue in that one. */ \ 3551if (nmatch > 1 ) { \ 3552sub_firstlnum += (linenr_T )nmatch - 1 ; \ 3553xfree (sub_firstline .data ); \ 3554sub_firstline = cbuf_to_string (ml_get (sub_firstlnum ), \ 3555 (size_t )ml_get_len (sub_firstlnum )); \ 3556/* When going beyond the last line, stop substituting. */ \ 3557if (sub_firstlnum <=line2 ) { \ 3558do_again = true; \ 3559 }else { \ 3560subflags .do_all = false; \ 3561 } \ 3562 } \ 3563if (skip_match ) { \ 3564/* Already hit end of the buffer, sub_firstlnum is one */ \ 3565/* less than what it ought to be. */ \ 3566xfree (sub_firstline .data ); \ 3567sub_firstline = STATIC_CSTR_TO_STRING ("" ); \ 3568copycol = 0 ; \ 3569 } \ 3570 }while (0 ) 3571 3572int i = 0 ; 3573regmmatch_T regmatch ; 3574static subflags_T subflags = { 3575 .do_all = false, 3576 .do_ask = false, 3577 .do_count = false, 3578 .do_error = true, 3579 .do_print = false, 3580 .do_list = false, 3581 .do_number = false, 3582 .do_ic = kSubHonorOptions 3583 }; 3584char * sub = NULL ;// init for GCC 3585String pat = STRING_INIT ; 3586int delimiter ; 3587bool has_second_delim = false; 3588size_t sublen ; 3589bool got_quit = false; 3590bool got_match = false; 3591int which_pat ; 3592char * cmd = eap -> arg ; 3593linenr_T first_line = 0 ;// first changed line 3594linenr_T last_line = 0 ;// below last changed line AFTER the change 3595linenr_T old_line_count = curbuf -> b_ml .ml_line_count ; 3596String sub_firstline ;// allocated copy of first sub line 3597bool endcolumn = false;// cursor in last column when done 3598const bool keeppatterns = cmdmod .cmod_flags & CMOD_KEEPPATTERNS ; 3599PreviewLines preview_lines = {KV_INITIAL_VALUE ,0 }; 3600static int pre_hl_id = 0 ; 3601pos_T old_cursor = curwin -> w_cursor ; 3602int start_nsubs ; 3603 3604bool did_save = false; 3605 3606if (!global_busy ) { 3607sub_nsubs = 0 ; 3608sub_nlines = 0 ; 3609 } 3610start_nsubs = sub_nsubs ; 3611 3612if (eap -> cmdidx == CMD_tilde ) { 3613which_pat = RE_LAST ;// use last used regexp 3614 }else { 3615which_pat = RE_SUBST ;// use last substitute regexp 3616 } 3617// new pattern and substitution 3618if (eap -> cmd [0 ]== 's' && * cmd != NUL && !ascii_iswhite (* cmd ) 3619&& vim_strchr ("0123456789cegriIp|\"" , (uint8_t )(* cmd ))== NULL ) { 3620// don't accept alphanumeric for separator 3621if (check_regexp_delim (* cmd )== FAIL ) { 3622return 0 ; 3623 } 3624 3625// undocumented vi feature: 3626// "\/sub/" and "\?sub?" use last used search pattern (almost like 3627// //sub/r). "\&sub&" use last substitute pattern (like //sub/). 3628if (* cmd == '\\' ) { 3629cmd ++ ; 3630if (vim_strchr ("/?&" , (uint8_t )(* cmd ))== NULL ) { 3631emsg (_ (e_backslash )); 3632return 0 ; 3633 } 3634if (* cmd != '&' ) { 3635which_pat = RE_SEARCH ;// use last '/' pattern 3636 } 3637pat = STATIC_CSTR_AS_STRING ("" );// empty search pattern 3638delimiter = (uint8_t )(* cmd ++ );// remember delimiter character 3639has_second_delim = true; 3640 }else {// find the end of the regexp 3641which_pat = RE_LAST ;// use last used regexp 3642delimiter = (uint8_t )(* cmd ++ );// remember delimiter character 3643pat .data = cmd ;// remember start of search pat 3644cmd = skip_regexp_ex (cmd ,delimiter ,p_magic ,& eap -> arg ,NULL ,NULL ); 3645pat .size = (size_t )(cmd - pat .data ); 3646if (cmd [0 ]== delimiter ) {// end delimiter found 3647* cmd ++ = NUL ;// replace it with a NUL 3648has_second_delim = true; 3649 } 3650 } 3651 3652// Small incompatibility: vi sees '\n' as end of the command, but in 3653// Vim we want to use '\n' to find/substitute a NUL. 3654char * p = cmd ;// remember the start of the substitution 3655cmd = skip_substitute (cmd ,delimiter ); 3656sub = xstrdup (p ); 3657 3658if (!eap -> skip && !keeppatterns && cmdpreview_ns <=0 ) { 3659sub_set_replacement ((SubReplacementString ) { 3660 .sub = xstrdup (sub ), 3661 .timestamp = os_time (), 3662 .additional_data = NULL , 3663 }); 3664 } 3665 }else if (!eap -> skip ) {// use previous pattern and substitution 3666if (old_sub .sub == NULL ) {// there is no previous command 3667emsg (_ (e_nopresub )); 3668return 0 ; 3669 } 3670pat = NULL_STRING ;// search_regcomp() will use previous pattern 3671sub = xstrdup (old_sub .sub ); 3672 3673// Vi compatibility quirk: repeating with ":s" keeps the cursor in the 3674// last column after using "$". 3675endcolumn = (curwin -> w_curswant == MAXCOL ); 3676 } 3677 3678if (sub != NULL && sub_joining_lines (eap ,pat ,sub ,cmd ,cmdpreview_ns <=0 , 3679keeppatterns )) { 3680xfree (sub ); 3681return 0 ; 3682 } 3683 3684cmd = sub_parse_flags (cmd ,& subflags ,& which_pat ); 3685 3686bool save_do_all = subflags .do_all ;// remember user specified 'g' flag 3687bool save_do_ask = subflags .do_ask ;// remember user specified 'c' flag 3688 3689// check for a trailing count 3690cmd = skipwhite (cmd ); 3691if (ascii_isdigit (* cmd )) { 3692const char * const count_arg = cmd ; 3693i = getdigits_int (& cmd , false,INT_MAX ); 3694if (i <=0 && !eap -> skip && subflags .do_error ) { 3695emsg (_ (e_zerocount )); 3696xfree (sub ); 3697return 0 ; 3698 }else if (i >=INT_MAX ) { 3699semsg (_ (e_val_too_large_len ), (int )(cmd - count_arg ),count_arg ); 3700xfree (sub ); 3701return 0 ; 3702 } 3703eap -> line1 = eap -> line2 ; 3704eap -> line2 += (linenr_T )i - 1 ; 3705eap -> line2 = MIN (eap -> line2 ,curbuf -> b_ml .ml_line_count ); 3706 } 3707 3708// check for trailing command or garbage 3709cmd = skipwhite (cmd ); 3710if (* cmd && * cmd != '"' ) {// if not end-of-line or comment 3711eap -> nextcmd = check_nextcmd (cmd ); 3712if (eap -> nextcmd == NULL ) { 3713semsg (_ (e_trailing_arg ),cmd ); 3714xfree (sub ); 3715return 0 ; 3716 } 3717 } 3718 3719if (eap -> skip ) {// not executing commands, only parsing 3720xfree (sub ); 3721return 0 ; 3722 } 3723 3724if (!subflags .do_count && !MODIFIABLE (curbuf )) { 3725// Substitution is not allowed in non-'modifiable' buffer 3726emsg (_ (e_modifiable )); 3727xfree (sub ); 3728return 0 ; 3729 } 3730 3731bool magic = ((eap -> cmdidx == CMD_smagic ) 3732 ? true : ((eap -> cmdidx == CMD_snomagic ) ? false :p_magic )); 3733if (search_regcomp (pat .data ,pat .size ,NULL ,RE_SUBST ,which_pat , 3734 (cmdpreview_ns > 0 ?0 :SEARCH_HIS ),magic ,& regmatch )== FAIL ) { 3735if (subflags .do_error ) { 3736emsg (_ (e_invcmd )); 3737 } 3738xfree (sub ); 3739return 0 ; 3740 } 3741 3742// the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' 3743if (subflags .do_ic == kSubIgnoreCase ) { 3744regmatch .rmm_ic = true; 3745 }else if (subflags .do_ic == kSubMatchCase ) { 3746regmatch .rmm_ic = false; 3747 } 3748 3749sub_firstline = NULL_STRING ; 3750 3751assert (sub != NULL ); 3752 3753// If the substitute pattern starts with "\=" then it's an expression. 3754// Make a copy, a recursive function may free it. 3755// Otherwise, '~' in the substitute pattern is replaced with the old 3756// pattern. We do it here once to avoid it to be replaced over and over 3757// again. 3758if (sub [0 ]== '\\' && sub [1 ]== '=' ) { 3759char * p = xstrdup (sub ); 3760xfree (sub ); 3761sub = p ; 3762 }else { 3763char * p = regtilde (sub ,p_magic ,cmdpreview_ns > 0 ); 3764if (p != sub ) { 3765xfree (sub ); 3766sub = p ; 3767 } 3768 } 3769 3770// Check for a match on each line. 3771// If preview: limit to max('cmdwinheight', viewport). 3772linenr_T line2 = eap -> line2 ; 3773 3774int timed_out = false; 3775 3776for (linenr_T lnum = eap -> line1 ; 3777lnum <=line2 && !got_quit && !timed_out && !aborting () 3778&& (cmdpreview_ns <=0 || preview_lines .lines_needed <= (linenr_T )p_cwh 3779|| lnum <=curwin -> w_botline ); 3780lnum ++ ) { 3781int nmatch = vim_regexec_multi (& regmatch ,curwin ,curbuf ,lnum , 37820 ,& tm ,& timed_out ); 3783if (nmatch ) { 3784colnr_T copycol ; 3785colnr_T matchcol ; 3786colnr_T prev_matchcol = MAXCOL ; 3787String new_start = STRING_INIT ; 3788size_t new_start_size = 0 ; 3789char * new_end ; 3790bool did_sub = false; 3791int lastone ; 3792linenr_T nmatch_tl = 0 ;// nr of lines matched below lnum 3793int do_again ;// do it again after joining lines 3794bool skip_match = false; 3795linenr_T sub_firstlnum ;// nr of first sub line 3796 3797// Track where substitutions started (set once per line). 3798linenr_T lnum_start = 0 ; 3799 3800// Track per-line data for each match. 3801// Will be sent as a batch to `extmark_splice` after the substitution is done. 3802typedef struct { 3803int start_col ;// Position in new text where replacement goes 3804lpos_T start ;// Match start position in original text 3805lpos_T end ;// Match end position in original text 3806int matchcols ;// Columns deleted from original text 3807bcount_t matchbytes ;// Bytes deleted from original text 3808int subcols ;// Columns in replacement text 3809bcount_t subbytes ;// Bytes in replacement text 3810linenr_T lnum_before ;// Line number before this substitution 3811linenr_T lnum_after ;// Line number after this substitution 3812 }LineData ; 3813 3814kvec_t (LineData )line_matches = KV_INITIAL_VALUE ; 3815 3816// The new text is build up step by step, to avoid too much 3817// copying. There are these pieces: 3818// sub_firstline The old text, unmodified. 3819// copycol Column in the old text where we started 3820// looking for a match; from here old text still 3821// needs to be copied to the new text. 3822// matchcol Column number of the old text where to look 3823// for the next match. It's just after the 3824// previous match or one further. 3825// prev_matchcol Column just after the previous match (if any). 3826// Mostly equal to matchcol, except for the first 3827// match and after skipping an empty match. 3828// regmatch.*pos Where the pattern matched in the old text. 3829// new_start The new text, all that has been produced so 3830// far. 3831// new_end The new text, where to append new text. 3832// 3833// lnum The line number where we found the start of 3834// the match. Can be below the line we searched 3835// when there is a \n before a \zs in the 3836// pattern. 3837// sub_firstlnum The line number in the buffer where to look 3838// for a match. Can be different from "lnum" 3839// when the pattern or substitute string contains 3840// line breaks. 3841// 3842// Special situations: 3843// - When the substitute string contains a line break, the part up 3844// to the line break is inserted in the text, but the copy of 3845// the original line is kept. "sub_firstlnum" is adjusted for 3846// the inserted lines. 3847// - When the matched pattern contains a line break, the old line 3848// is taken from the line at the end of the pattern. The lines 3849// in the match are deleted later, "sub_firstlnum" is adjusted 3850// accordingly. 3851// 3852// The new text is built up in new_start[]. It has some extra 3853// room to avoid using xmalloc()/free() too often. new_start_size is 3854// the length of the allocated memory at new_start. 3855// 3856// Make a copy of the old line, so it won't be taken away when 3857// updating the screen or handling a multi-line match. The "old_" 3858// pointers point into this copy. 3859sub_firstlnum = lnum ; 3860copycol = 0 ; 3861matchcol = 0 ; 3862 3863// At first match, remember current cursor position. 3864if (!got_match ) { 3865setpcmark (); 3866got_match = true; 3867 } 3868 3869// Loop until nothing more to replace in this line. 3870// 1. Handle match with empty string. 3871// 2. If subflags.do_ask is set, ask for confirmation. 3872// 3. substitute the string. 3873// 4. if subflags.do_all is set, find next match 3874// 5. break if there isn't another match in this line 3875while (true) { 3876SubResult current_match = { 3877 .start = {0 ,0 }, 3878 .end = {0 ,0 }, 3879 .pre_match = 0 , 3880 }; 3881// lnum is where the match start, but maybe not the pattern match, 3882// since we can have \n before \zs in the pattern 3883 3884// Advance "lnum" to the line where the match starts. The 3885// match does not start in the first line when there is a line 3886// break before \zs. 3887if (regmatch .startpos [0 ].lnum > 0 ) { 3888current_match .pre_match = lnum ; 3889lnum += regmatch .startpos [0 ].lnum ; 3890sub_firstlnum += regmatch .startpos [0 ].lnum ; 3891nmatch -= regmatch .startpos [0 ].lnum ; 3892API_CLEAR_STRING (sub_firstline ); 3893 } 3894 3895// Now we're at the line where the pattern match starts 3896// Note: If not first match on a line, column can't be known here 3897current_match .start .lnum = sub_firstlnum ; 3898 3899// Match might be after the last line for "\n\zs" matching at 3900// the end of the last line. 3901if (lnum > curbuf -> b_ml .ml_line_count ) { 3902break ; 3903 } 3904if (sub_firstline .data == NULL ) { 3905sub_firstline = cbuf_to_string (ml_get (sub_firstlnum ), 3906 (size_t )ml_get_len (sub_firstlnum )); 3907 } 3908 3909// Save the line number of the last change for the final 3910// cursor position (just like Vi). 3911curwin -> w_cursor .lnum = lnum ; 3912do_again = false; 3913 3914// 1. Match empty string does not count, except for first 3915// match. This reproduces the strange vi behaviour. 3916// This also catches endless loops. 3917if (matchcol == prev_matchcol 3918&& regmatch .endpos [0 ].lnum == 0 3919&& matchcol == regmatch .endpos [0 ].col ) { 3920if (sub_firstline .data [matchcol ]== NUL ) { 3921// We already were at the end of the line. Don't look 3922// for a match in this line again. 3923skip_match = true; 3924 }else { 3925// search for a match at next column 3926matchcol += utfc_ptr2len (sub_firstline .data + matchcol ); 3927 } 3928// match will be pushed to preview_lines, bring it into a proper state 3929current_match .start .col = matchcol ; 3930current_match .end .lnum = sub_firstlnum ; 3931current_match .end .col = matchcol ; 3932 gotoskip ; 3933 } 3934 3935// Normally we continue searching for a match just after the 3936// previous match. 3937matchcol = regmatch .endpos [0 ].col ; 3938prev_matchcol = matchcol ; 3939 3940// 2. If subflags.do_count is set only increase the counter. 3941// If do_ask is set, ask for confirmation. 3942if (subflags .do_count ) { 3943// For a multi-line match, put matchcol at the NUL at 3944// the end of the line and set nmatch to one, so that 3945// we continue looking for a match on the next line. 3946// Avoids that ":s/\nB\@=//gc" get stuck. 3947if (nmatch > 1 ) { 3948matchcol = (colnr_T )sub_firstline .size ; 3949nmatch = 1 ; 3950skip_match = true; 3951 } 3952sub_nsubs ++ ; 3953did_sub = true; 3954// Skip the substitution, unless an expression is used, 3955// then it is evaluated in the sandbox. 3956if (!(sub [0 ]== '\\' && sub [1 ]== '=' )) { 3957 gotoskip ; 3958 } 3959 } 3960 3961if (subflags .do_ask && cmdpreview_ns <=0 ) { 3962int typed = 0 ; 3963int save_State = State ; 3964curwin -> w_cursor .col = regmatch .startpos [0 ].col ; 3965 3966if (curwin -> w_p_crb ) { 3967do_check_cursorbind (); 3968 } 3969 3970// When 'cpoptions' contains "u" don't sync undo when 3971// asking for confirmation. 3972if (vim_strchr (p_cpo ,kCpoUndo )!= NULL ) { 3973no_u_sync ++ ; 3974 } 3975 3976// Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. 3977while (subflags .do_ask ) { 3978String orig_line = STRING_INIT ; 3979int len_change = 0 ; 3980const bool save_p_lz = p_lz ; 3981int save_p_fen = curwin -> w_p_fen ; 3982 3983curwin -> w_p_fen = false; 3984// Invert the matched string. 3985// Remove the inversion afterwards. 3986int temp = RedrawingDisabled ; 3987RedrawingDisabled = 0 ; 3988 3989// avoid calling update_screen() in vgetorpeek() 3990p_lz = false; 3991 3992if (new_start .data != NULL ) { 3993// There already was a substitution, we would 3994// like to show this to the user. We cannot 3995// really update the line, it would change 3996// what matches. Temporarily replace the line 3997// and change it back afterwards. 3998orig_line = cbuf_to_string (ml_get (lnum ), (size_t )ml_get_len (lnum )); 3999String new_line = { 4000 .data = concat_str (new_start .data ,sub_firstline .data + copycol ), 4001 .size = new_start .size + (sub_firstline .size - (size_t )copycol ), 4002 }; 4003 4004// Position the cursor relative to the end of the line, the 4005// previous substitute may have inserted or deleted characters 4006// before the cursor. 4007len_change = (int )new_line .size - (int )orig_line .size ; 4008curwin -> w_cursor .col += len_change ; 4009ml_replace (lnum ,new_line .data , false); 4010 } 4011 4012Search .match_lines = regmatch .endpos [0 ].lnum - regmatch .startpos [0 ].lnum ; 4013Search .match_endcol = regmatch .endpos [0 ].col + len_change ; 4014if (Search .match_lines == 0 && Search .match_endcol == 0 ) { 4015// highlight at least one character for /^/ 4016Search .match_endcol = 1 ; 4017 } 4018Search .hl_match = true; 4019 4020update_topline (curwin ); 4021validate_cursor (curwin ); 4022redraw_later (curwin ,UPD_SOME_VALID ); 4023show_cursor_info_later (true); 4024update_screen (); 4025redraw_later (curwin ,UPD_SOME_VALID ); 4026 4027curwin -> w_p_fen = save_p_fen ; 4028 4029char * p = _ ("replace with %s? (y)es/(n)o/(a)ll/(q)uit/(l)ast/scroll up(^E)/down(^Y)" ); 4030snprintf (IObuff ,IOSIZE ,p ,sub ); 4031p = xstrdup (IObuff ); 4032typed = prompt_for_input (p ,HLF_R , true,NULL ); 4033Search .hl_match = false; 4034xfree (p ); 4035 4036msg_didout = false;// don't scroll up 4037gotocmdline (true); 4038p_lz = save_p_lz ; 4039RedrawingDisabled = temp ; 4040 4041// restore the line 4042if (orig_line .data != NULL ) { 4043ml_replace (lnum ,orig_line .data , false); 4044 } 4045 4046need_wait_return = false;// no hit-return prompt 4047if (typed == 'q' || typed == ESC || typed == Ctrl_C ) { 4048got_quit = true; 4049break ; 4050 } 4051if (typed == 'n' ) { 4052break ; 4053 } 4054if (typed == 'y' ) { 4055break ; 4056 } 4057if (typed == 'l' ) { 4058// last: replace and then stop 4059subflags .do_all = false; 4060line2 = lnum ; 4061break ; 4062 } 4063if (typed == 'a' ) { 4064subflags .do_ask = false; 4065break ; 4066 } 4067if (typed == Ctrl_E ) { 4068scrollup_clamp (); 4069 }else if (typed == Ctrl_Y ) { 4070scrolldown_clamp (); 4071 } 4072 } 4073State = save_State ; 4074setmouse (); 4075if (vim_strchr (p_cpo ,kCpoUndo )!= NULL ) { 4076no_u_sync -- ; 4077 } 4078 4079if (typed == 'n' ) { 4080// For a multi-line match, put matchcol at the NUL at 4081// the end of the line and set nmatch to one, so that 4082// we continue looking for a match on the next line. 4083// Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc" 4084// get stuck when pressing 'n'. 4085if (nmatch > 1 ) { 4086matchcol = (colnr_T )sub_firstline .size ; 4087skip_match = true; 4088 } 4089 gotoskip ; 4090 } 4091if (got_quit ) { 4092 gotoskip ; 4093 } 4094 } 4095 4096// Move the cursor to the start of the match, so that we can 4097// use "\=col("."). 4098curwin -> w_cursor .col = regmatch .startpos [0 ].col ; 4099 4100// When the match included the "$" of the last line it may 4101// go beyond the last line of the buffer. 4102if (nmatch > curbuf -> b_ml .ml_line_count - sub_firstlnum + 1 ) { 4103nmatch = curbuf -> b_ml .ml_line_count - sub_firstlnum + 1 ; 4104current_match .end .lnum = sub_firstlnum + (linenr_T )nmatch ; 4105skip_match = true; 4106// safety check 4107if (nmatch < 0 ) { 4108 gotoskip ; 4109 } 4110 } 4111 4112// Save the line numbers for the preview buffer 4113// NOTE: If the pattern matches a final newline, the next line will 4114// be shown also, but should not be highlighted. Intentional for now. 4115if (cmdpreview_ns > 0 && !has_second_delim ) { 4116current_match .start .col = regmatch .startpos [0 ].col ; 4117if (current_match .end .lnum == 0 ) { 4118current_match .end .lnum = sub_firstlnum + (linenr_T )nmatch - 1 ; 4119 } 4120current_match .end .col = regmatch .endpos [0 ].col ; 4121 4122ADJUST_SUB_FIRSTLNUM (); 4123lnum += (linenr_T )nmatch - 1 ; 4124 4125 gotoskip ; 4126 } 4127 4128// 3. Substitute the string. During 'inccommand' preview only do this if 4129// there is a replace pattern. 4130if (cmdpreview_ns <=0 || has_second_delim ) { 4131lnum_start = lnum ;// save the start lnum 4132int save_ma = curbuf -> b_p_ma ; 4133int save_sandbox = sandbox ; 4134if (subflags .do_count ) { 4135// prevent accidentally changing the buffer by a function 4136curbuf -> b_p_ma = false; 4137sandbox ++ ; 4138 } 4139// Save flags for recursion. They can change for e.g. 4140// :s/^/\=execute("s#^##gn") 4141subflags_T subflags_save = subflags ; 4142 4143// Disallow changing text or switching window in an expression. 4144textlock ++ ; 4145// Get length of substitution part, including the NUL. 4146// When it fails sublen is zero. 4147sublen = (size_t )vim_regsub_multi (& regmatch , 4148sub_firstlnum - regmatch .startpos [0 ].lnum , 4149sub ,sub_firstline .data ,0 , 4150REGSUB_BACKSLASH 4151 | (p_magic ?REGSUB_MAGIC :0 )); 4152textlock -- ; 4153 4154// If getting the substitute string caused an error, don't do 4155// the replacement. 4156// Don't keep flags set by a recursive call 4157subflags = subflags_save ; 4158if (sublen == 0 || aborting ()|| subflags .do_count ) { 4159curbuf -> b_p_ma = save_ma ; 4160sandbox = save_sandbox ; 4161 gotoskip ; 4162 } 4163 4164String tmp ; 4165// Need room for: 4166// - result so far in new_start (not for first sub in line) 4167// - original text up to match 4168// - length of substituted part 4169// - original text after match 4170if (nmatch == 1 ) { 4171tmp = sub_firstline ; 4172 }else { 4173linenr_T lastlnum = sub_firstlnum + (linenr_T )nmatch - 1 ; 4174tmp = cbuf_as_string (ml_get (lastlnum ), (size_t )ml_get_len (lastlnum )); 4175nmatch_tl += nmatch - 1 ; 4176 } 4177size_t copy_len = (size_t )(regmatch .startpos [0 ].col - copycol ); 4178sub_grow_buf (& new_start ,& new_start_size , 4179copy_len 4180+ (tmp .size - (size_t )regmatch .endpos [0 ].col )+ sublen + 1 ); 4181 4182// copy the text up to the part that matched 4183memmove (new_start .data + new_start .size , 4184sub_firstline .data + copycol ,copy_len ); 4185new_start .size += copy_len ; 4186 4187// new text added here 4188new_end = new_start .data + new_start .size ; 4189 4190if (new_start_size - copy_len < sublen ) { 4191sublen = new_start_size - copy_len - 1 ; 4192 } 4193 4194// Finally, at this point we can know where the match actually will 4195// start in the new text 4196int start_col = (int )new_start .size ; 4197current_match .start .col = start_col ; 4198 4199textlock ++ ; 4200size_t n = (size_t )vim_regsub_multi (& regmatch , 4201sub_firstlnum - regmatch .startpos [0 ].lnum , 4202sub ,new_end , (int )sublen , 4203REGSUB_COPY |REGSUB_BACKSLASH 4204 | (p_magic ?REGSUB_MAGIC :0 )); 4205if (n > 0 ) { 4206new_start .size += n - 1 ;// remove 1 for the NUL 4207 } 4208textlock -- ; 4209sub_nsubs ++ ; 4210did_sub = true; 4211 4212// Move the cursor to the start of the line, to avoid that it 4213// is beyond the end of the line after the substitution. 4214curwin -> w_cursor .col = 0 ; 4215 4216// Remember next character to be copied. 4217copycol = regmatch .endpos [0 ].col ; 4218 4219ADJUST_SUB_FIRSTLNUM (); 4220 4221// TODO(bfredl): this has some robustness issues, look into later. 4222bcount_t replaced_bytes = 0 ; 4223lpos_T start = regmatch .startpos [0 ]; 4224lpos_T end = regmatch .endpos [0 ]; 4225for (i = 0 ;i < nmatch - 1 ;i ++ ) { 4226replaced_bytes += (bcount_t )strlen (ml_get ((linenr_T )(lnum_start + i )))+ 1 ; 4227 } 4228replaced_bytes += end .col - start .col ; 4229 4230// Save the line number before processing newlines. 4231linenr_T lnum_before_newlines = lnum ; 4232 4233// Now the trick is to replace CTRL-M chars with a real line 4234// break. This would make it impossible to insert a CTRL-M in 4235// the text. The line break can be avoided by preceding the 4236// CTRL-M with a backslash. To be able to insert a backslash, 4237// they must be doubled in the string and are halved here. 4238// That is Vi compatible. 4239for (char * p1 = new_end ;* p1 ;p1 ++ ) { 4240if (p1 [0 ]== '\\' && p1 [1 ]!= NUL ) {// remove backslash 4241sublen -- ;// correct the byte counts for extmark_splice() 4242n = new_start .size - (size_t )(p1 - new_start .data ); 4243memmove (p1 ,p1 + 1 ,n + 1 ); 4244new_start .size -- ; 4245 }else if (* p1 == CAR ) { 4246if (u_inssub (lnum )== OK ) {// prepare for undo 4247colnr_T plen = (colnr_T )(p1 - new_start .data + 1 ); 4248* p1 = NUL ;// truncate up to the CR 4249ml_append (lnum - 1 ,new_start .data ,plen , false); 4250mark_adjust (lnum + 1 , (linenr_T )MAXLNUM ,1 ,0 ,kExtmarkNOOP ); 4251 4252if (subflags .do_ask ) { 4253appended_lines (lnum - 1 ,1 ); 4254 }else { 4255if (first_line == 0 ) { 4256first_line = lnum ; 4257 } 4258last_line = lnum + 1 ; 4259 } 4260// All line numbers increase. 4261sub_firstlnum ++ ; 4262lnum ++ ; 4263line2 ++ ; 4264// move the cursor to the new line, like Vi 4265curwin -> w_cursor .lnum ++ ; 4266// copy the rest 4267n = new_start .size - (size_t )plen ; 4268memmove (new_start .data ,p1 + 1 ,n + 1 ); 4269new_start .size = n ; 4270p1 = new_start .data - 1 ; 4271 } 4272 }else { 4273p1 += utfc_ptr2len (p1 )- 1 ; 4274 } 4275 } 4276colnr_T new_endcol = (colnr_T )new_start .size ; 4277current_match .end .col = new_endcol ; 4278current_match .end .lnum = lnum ; 4279 4280int matchcols = end .col - ((end .lnum == start .lnum ) 4281 ?start .col :0 ); 4282int subcols = new_endcol - ((lnum == lnum_start ) ?start_col :0 ); 4283if (!did_save ) { 4284// Required for Undo to work for extmarks. 4285u_save_cursor (); 4286did_save = true; 4287 } 4288 4289// Store extmark data for this match. 4290LineData * data = kv_pushp (line_matches ); 4291data -> start_col = start_col ; 4292data -> start = start ; 4293data -> end = end ; 4294data -> matchcols = matchcols ; 4295data -> matchbytes = replaced_bytes ; 4296data -> subcols = subcols ; 4297data -> subbytes = (colnr_T )sublen - 1 ; 4298data -> lnum_before = lnum_before_newlines ; 4299data -> lnum_after = lnum ; 4300 } 4301 4302// 4. If subflags.do_all is set, find next match. 4303// Prevent endless loop with patterns that match empty 4304// strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g. 4305// But ":s/\n/#/" is OK. 4306skip : 4307// We already know that we did the last subst when we are at 4308// the end of the line, except that a pattern like 4309// "bar\|\nfoo" may match at the NUL. "lnum" can be below 4310// "line2" when there is a \zs in the pattern after a line 4311// break. 4312lastone = (skip_match 4313|| got_int 4314|| got_quit 4315|| lnum > line2 4316|| !(subflags .do_all || do_again ) 4317|| (sub_firstline .data [matchcol ]== NUL && nmatch <=1 4318&& !re_multiline (regmatch .regprog ))); 4319nmatch = -1 ; 4320 4321// Replace the line in the buffer when needed. This is 4322// skipped when there are more matches. 4323// The check for nmatch_tl is needed for when multi-line 4324// matching must replace the lines before trying to do another 4325// match, otherwise "\@<=" won't work. 4326// When the match starts below where we start searching also 4327// need to replace the line first (using \zs after \n). 4328if (lastone 4329|| nmatch_tl > 0 4330|| (nmatch = vim_regexec_multi (& regmatch ,curwin , 4331curbuf ,sub_firstlnum , 4332matchcol ,& tm ,& timed_out ))== 0 4333|| regmatch .startpos [0 ].lnum > 0 ) { 4334if (new_start .data != NULL ) { 4335// Copy the rest of the line, that didn't match. 4336// "matchcol" has to be adjusted, we use the end of 4337// the line as reference, because the substitute may 4338// have changed the number of characters. Same for 4339// "prev_matchcol". 4340STRCPY (new_start .data + new_start .size ,sub_firstline .data + copycol ); 4341new_start .size += sub_firstline .size - (size_t )copycol ; 4342matchcol = (colnr_T )sub_firstline .size - matchcol ; 4343prev_matchcol = (colnr_T )sub_firstline .size - prev_matchcol ; 4344 4345if (u_savesub (lnum )!= OK ) { 4346break ; 4347 } 4348ml_replace (lnum ,new_start .data , true); 4349 4350// Call extmark_splice for each match on this line. 4351for (size_t match_idx = 0 ;match_idx < kv_size (line_matches );match_idx ++ ) { 4352LineData * match = & kv_A (line_matches ,match_idx ); 4353 4354extmark_splice (curbuf , (int )match -> lnum_before - 1 ,match -> start_col , 4355match -> end .lnum - match -> start .lnum ,match -> matchcols , 4356match -> matchbytes , 4357match -> lnum_after - match -> lnum_before , 4358match -> subcols , 4359match -> subbytes ,kExtmarkUndo ); 4360 } 4361 4362// Reset the match data for the next line. 4363kv_size (line_matches )= 0 ; 4364 4365if (nmatch_tl > 0 ) { 4366// Matched lines have now been substituted and are 4367// useless, delete them. The part after the match 4368// has been appended to new_start, we don't need 4369// it in the buffer. 4370lnum ++ ; 4371if (u_savedel (lnum ,nmatch_tl )!= OK ) { 4372break ; 4373 } 4374for (i = 0 ;i < nmatch_tl ;i ++ ) { 4375ml_delete (lnum ); 4376 } 4377mark_adjust (lnum ,lnum + nmatch_tl - 1 ,MAXLNUM ,- nmatch_tl ,kExtmarkNOOP ); 4378if (subflags .do_ask ) { 4379deleted_lines (lnum ,nmatch_tl ); 4380 } 4381lnum -- ; 4382line2 -= nmatch_tl ;// nr of lines decreases 4383nmatch_tl = 0 ; 4384 } 4385 4386// When asking, undo is saved each time, must also set 4387// changed flag each time. 4388if (subflags .do_ask ) { 4389changed_bytes (lnum ,0 ); 4390 }else { 4391if (first_line == 0 ) { 4392first_line = lnum ; 4393 } 4394last_line = lnum + 1 ; 4395 } 4396 4397sub_firstlnum = lnum ; 4398xfree (sub_firstline .data );// free the temp buffer 4399sub_firstline = new_start ; 4400new_start = NULL_STRING ; 4401matchcol = (colnr_T )sub_firstline .size - matchcol ; 4402prev_matchcol = (colnr_T )sub_firstline .size - prev_matchcol ; 4403copycol = 0 ; 4404 } 4405if (nmatch == -1 && !lastone ) { 4406nmatch = vim_regexec_multi (& regmatch ,curwin ,curbuf , 4407sub_firstlnum ,matchcol ,& tm ,& timed_out ); 4408 } 4409 4410// 5. break if there isn't another match in this line 4411if (nmatch <=0 ) { 4412// If the match found didn't start where we were 4413// searching, do the next search in the line where we 4414// found the match. 4415if (nmatch == -1 ) { 4416lnum -= regmatch .startpos [0 ].lnum ; 4417 } 4418 4419// uncrustify:off 4420 4421#define PUSH_PREVIEW_LINES () \ 4422 do { \ 4423 if (cmdpreview_ns > 0) { \ 4424 linenr_T match_lines = current_match.end.lnum \ 4425 - current_match.start.lnum +1; \ 4426 if (preview_lines.subresults.size > 0) { \ 4427 linenr_T last = kv_last(preview_lines.subresults).end.lnum; \ 4428 if (last == current_match.start.lnum) { \ 4429 preview_lines.lines_needed += match_lines - 1; \ 4430 } else { \ 4431 preview_lines.lines_needed += match_lines; \ 4432 } \ 4433 } else { \ 4434 preview_lines.lines_needed += match_lines; \ 4435 } \ 4436 kv_push(preview_lines.subresults, current_match); \ 4437 } \ 4438 } while (0) 4439 4440// uncrustify:on 4441 4442// Push the match to preview_lines. 4443PUSH_PREVIEW_LINES (); 4444 4445break ; 4446 } 4447 } 4448// Push the match to preview_lines. 4449PUSH_PREVIEW_LINES (); 4450 4451line_breakcheck (); 4452 } 4453 4454if (did_sub ) { 4455sub_nlines ++ ; 4456 } 4457xfree (new_start .data );// for when substitute was cancelled 4458API_CLEAR_STRING (sub_firstline );// free the copy of the original line 4459kv_destroy (line_matches );// clean up match data 4460 } 4461 4462line_breakcheck (); 4463 4464if (timed_out || profile_passed_limit (tm )) { 4465got_quit = true; 4466 } 4467 } 4468 4469curbuf -> deleted_bytes2 = 0 ; 4470 4471if (first_line != 0 ) { 4472// Need to subtract the number of added lines from "last_line" to get 4473// the line number before the change (same as adding the number of 4474// deleted lines). 4475i = curbuf -> b_ml .ml_line_count - old_line_count ; 4476changed_lines (curbuf ,first_line ,0 ,last_line - (linenr_T )i , (linenr_T )i , false); 4477 4478int64_t num_added = last_line - first_line ; 4479int64_t num_removed = num_added - i ; 4480buf_updates_send_changes (curbuf ,first_line ,num_added ,num_removed ); 4481 } 4482 4483xfree (sub_firstline .data );// may have to free allocated copy of the line 4484 4485// ":s/pat//n" doesn't move the cursor 4486if (subflags .do_count ) { 4487curwin -> w_cursor = old_cursor ; 4488 } 4489 4490if (sub_nsubs > start_nsubs ) { 4491if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 4492// Set the '[ and '] marks. 4493curbuf -> b_op_start .lnum = eap -> line1 ; 4494curbuf -> b_op_end .lnum = line2 ; 4495curbuf -> b_op_start .col = curbuf -> b_op_end .col = 0 ; 4496 } 4497 4498if (!global_busy ) { 4499// when interactive leave cursor on the match 4500if (!subflags .do_ask ) { 4501if (endcolumn ) { 4502coladvance (curwin ,MAXCOL ); 4503 }else { 4504beginline (BL_WHITE |BL_FIX ); 4505 } 4506 } 4507if (cmdpreview_ns <=0 && !do_sub_msg (subflags .do_count )&& subflags .do_ask && p_ch > 0 ) { 4508msg ("" ,0 ); 4509 } 4510 }else { 4511global_need_beginline = true; 4512 } 4513if (subflags .do_print ) { 4514print_line (curwin -> w_cursor .lnum ,subflags .do_number ,subflags .do_list , true); 4515 } 4516 }else if (!global_busy ) { 4517if (got_int ) { 4518// interrupted 4519emsg (_ (e_interr )); 4520 }else if (got_match ) { 4521// did find something but nothing substituted 4522if (p_ch > 0 && !ui_has (kUIMessages )) { 4523msg ("" ,0 ); 4524 } 4525 }else if (subflags .do_error ) { 4526// nothing found 4527semsg (_ (e_patnotf2 ),get_search_pat ()); 4528 } 4529 } 4530 4531if (subflags .do_ask && hasAnyFolding (curwin )) { 4532// Cursor position may require updating 4533changed_window_setting (curwin ); 4534 } 4535 4536vim_regfree (regmatch .regprog ); 4537xfree (sub ); 4538 4539// Restore the flag values, they can be used for ":&&". 4540subflags .do_all = save_do_all ; 4541subflags .do_ask = save_do_ask ; 4542 4543int retv = 0 ; 4544 4545// Show 'inccommand' preview if there are matched lines. 4546if (cmdpreview_ns > 0 && !aborting ()) { 4547if (got_quit || profile_passed_limit (tm )) {// Too slow, disable. 4548set_option_direct (kOptInccommand ,STATIC_CSTR_AS_OBJ ("" ),0 ,SID_NONE ); 4549 }else if (* p_icm != NUL && pat .data != NULL ) { 4550if (pre_hl_id == 0 ) { 4551pre_hl_id = syn_check_group (S_LEN ("Substitute" )); 4552 } 4553retv = show_sub (eap ,old_cursor ,& preview_lines ,pre_hl_id ,cmdpreview_ns ,cmdpreview_bufnr ); 4554 } 4555 } 4556 4557kv_destroy (preview_lines .subresults ); 4558return retv ; 4559#undef ADJUST_SUB_FIRSTLNUM 4560#undef PUSH_PREVIEW_LINES 4561} 4562 4563/// Give message for number of substitutions. 4564/// Can also be used after a ":global" command. 4565/// 4566/// @param count_only used 'n' flag for ":s" 4567/// 4568/// @return true if a message was given. 4569bool do_sub_msg (bool count_only ) 4570{ 4571// Only report substitutions when: 4572// - more than 'report' substitutions 4573// - command was typed by user, or number of changed lines > 'report' 4574// - giving messages is not disabled by 'lazyredraw' 4575if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1 )) 4576|| count_only ) 4577&& messaging ()) { 4578if (got_int ) { 4579STRCPY (msg_buf ,_ ("(Interrupted) " )); 4580 }else { 4581* msg_buf = NUL ; 4582 } 4583 4584char * msg_single = count_only 4585 ?NGETTEXT ("%" PRId64 " match on %" PRId64 " line" , 4586"%" PRId64 " matches on %" PRId64 " line" ,sub_nsubs ) 4587 :NGETTEXT ("%" PRId64 " substitution on %" PRId64 " line" , 4588"%" PRId64 " substitutions on %" PRId64 " line" ,sub_nsubs ); 4589char * msg_plural = count_only 4590 ?NGETTEXT ("%" PRId64 " match on %" PRId64 " lines" , 4591"%" PRId64 " matches on %" PRId64 " lines" ,sub_nsubs ) 4592 :NGETTEXT ("%" PRId64 " substitution on %" PRId64 " lines" , 4593"%" PRId64 " substitutions on %" PRId64 " lines" ,sub_nsubs ); 4594vim_snprintf_add (msg_buf ,sizeof (msg_buf ), 4595NGETTEXT (msg_single ,msg_plural ,sub_nlines ), 4596 (int64_t )sub_nsubs , (int64_t )sub_nlines ); 4597if (msg (msg_buf ,0 )) { 4598// save message to display it after redraw 4599set_keep_msg (msg_buf ,0 ); 4600 } 4601return true; 4602 } 4603if (got_int ) { 4604emsg (_ (e_interr )); 4605return true; 4606 } 4607return false; 4608} 4609 4610static void global_exe_one (char * const cmd ,const linenr_T lnum ) 4611{ 4612curwin -> w_cursor .lnum = lnum ; 4613curwin -> w_cursor .col = 0 ; 4614if (* cmd == NUL || * cmd == '\n' ) { 4615do_cmdline ("p" ,NULL ,NULL ,DOCMD_NOWAIT ); 4616 }else { 4617do_cmdline (cmd ,NULL ,NULL ,DOCMD_NOWAIT ); 4618 } 4619} 4620 4621/// Execute a global command of the form: 4622/// 4623/// g/pattern/X : execute X on all lines where pattern matches 4624/// v/pattern/X : execute X on all lines where pattern does not match 4625/// 4626/// where 'X' is an EX command 4627/// 4628/// The command character (as well as the trailing slash) is optional, and 4629/// is assumed to be 'p' if missing. 4630/// 4631/// This is implemented in two passes: first we scan the file for the pattern and 4632/// set a mark for each line that (not) matches. Secondly we execute the command 4633/// for each line that has a mark. This is required because after deleting 4634/// lines we do not know where to search for the next match. 4635void ex_global (exarg_T * eap ) 4636{ 4637linenr_T lnum ;// line number according to old situation 4638int type ;// first char of cmd: 'v' or 'g' 4639char * cmd ;// command argument 4640 4641char delim ;// delimiter, normally '/' 4642char * pat ; 4643size_t patlen ; 4644regmmatch_T regmatch ; 4645 4646// When nesting the command works on one line. This allows for 4647// ":g/found/v/notfound/command". 4648if (global_busy && (eap -> line1 != 1 4649|| eap -> line2 != curbuf -> b_ml .ml_line_count )) { 4650// will increment global_busy to break out of the loop 4651emsg (_ ("E147: Cannot do :global recursive with a range" )); 4652return ; 4653 } 4654 4655if (eap -> forceit ) {// ":global!" is like ":vglobal" 4656type = 'v' ; 4657 }else { 4658type = (uint8_t )(* eap -> cmd ); 4659 } 4660cmd = eap -> arg ; 4661int which_pat = RE_LAST ;// default: use last used regexp 4662 4663// undocumented vi feature: 4664// "\/" and "\?": use previous search pattern. 4665// "\&": use previous substitute pattern. 4666if (* cmd == '\\' ) { 4667cmd ++ ; 4668if (vim_strchr ("/?&" , (uint8_t )(* cmd ))== NULL ) { 4669emsg (_ (e_backslash )); 4670return ; 4671 } 4672if (* cmd == '&' ) { 4673which_pat = RE_SUBST ;// use previous substitute pattern 4674 }else { 4675which_pat = RE_SEARCH ;// use previous search pattern 4676 } 4677cmd ++ ; 4678pat = "" ; 4679patlen = 0 ; 4680 }else if (* cmd == NUL ) { 4681emsg (_ ("E148: Regular expression missing from global" )); 4682return ; 4683 }else if (check_regexp_delim (* cmd )== FAIL ) { 4684return ; 4685 }else { 4686delim = * cmd ;// get the delimiter 4687cmd ++ ;// skip delimiter if there is one 4688pat = cmd ;// remember start of pattern 4689cmd = skip_regexp_ex (cmd ,delim ,p_magic ,& eap -> arg ,NULL ,NULL ); 4690if (cmd [0 ]== delim ) {// end delimiter found 4691* cmd ++ = NUL ;// replace it with a NUL 4692 } 4693patlen = strlen (pat ); 4694 } 4695 4696char * used_pat ; 4697if (search_regcomp (pat ,patlen ,& used_pat ,RE_BOTH ,which_pat , 4698SEARCH_HIS ,p_magic ,& regmatch )== FAIL ) { 4699emsg (_ (e_invcmd )); 4700return ; 4701 } 4702 4703if (global_busy ) { 4704lnum = curwin -> w_cursor .lnum ; 4705int match = vim_regexec_multi (& regmatch ,curwin ,curbuf ,lnum ,0 ,NULL ,NULL ); 4706if ((type == 'g' && match )|| (type == 'v' && !match )) { 4707global_exe_one (cmd ,lnum ); 4708 } 4709 }else { 4710int ndone = 0 ; 4711// pass 1: set marks for each (not) matching line 4712for (lnum = eap -> line1 ;lnum <=eap -> line2 && !got_int ;lnum ++ ) { 4713// a match on this line? 4714int match = vim_regexec_multi (& regmatch ,curwin ,curbuf ,lnum ,0 ,NULL ,NULL ); 4715if (regmatch .regprog == NULL ) { 4716break ;// re-compiling regprog failed 4717 } 4718if ((type == 'g' && match )|| (type == 'v' && !match )) { 4719ml_setmarked (lnum ); 4720ndone ++ ; 4721 } 4722line_breakcheck (); 4723 } 4724 4725// pass 2: execute the command for each line that has been marked 4726if (got_int ) { 4727msg (_ (e_interr ),0 ); 4728 }else if (ndone == 0 ) { 4729if (type == 'v' ) { 4730smsg (0 ,_ ("Pattern found in every line: %s" ),used_pat ); 4731 }else { 4732smsg (0 ,_ ("Pattern not found: %s" ),used_pat ); 4733 } 4734 }else { 4735global_exe (cmd ); 4736 } 4737ml_clearmarked ();// clear rest of the marks 4738 } 4739vim_regfree (regmatch .regprog ); 4740} 4741 4742/// Execute `cmd` on lines marked with ml_setmarked(). 4743void global_exe (char * cmd ) 4744{ 4745linenr_T old_lcount ;// b_ml.ml_line_count before the command 4746buf_T * old_buf = curbuf ;// remember what buffer we started in 4747linenr_T lnum ;// line number according to old situation 4748 4749// Set current position only once for a global command. 4750// If global_busy is set, setpcmark() will not do anything. 4751// If there is an error, global_busy will be incremented. 4752setpcmark (); 4753 4754// When the command writes a message, don't overwrite the command. 4755msg_didout = true; 4756 4757sub_nsubs = 0 ; 4758sub_nlines = 0 ; 4759global_need_msg_kind = true; 4760global_need_beginline = false; 4761global_busy = 1 ; 4762old_lcount = curbuf -> b_ml .ml_line_count ; 4763 4764while (!got_int && (lnum = ml_firstmarked ())!= 0 && global_busy == 1 ) { 4765global_exe_one (cmd ,lnum ); 4766os_breakcheck (); 4767 } 4768 4769global_busy = 0 ; 4770if (global_need_beginline ) { 4771beginline (BL_WHITE |BL_FIX ); 4772 }else { 4773check_cursor (curwin );// cursor may be beyond the end of the line 4774 } 4775 4776// the cursor may not have moved in the text but a change in a previous 4777// line may move it on the screen 4778changed_line_abv_curs (); 4779 4780// If it looks like no message was written, allow overwriting the 4781// command with the report for number of changes. 4782if (msg_col == 0 && msg_scrolled == 0 ) { 4783msg_didout = false; 4784 } 4785 4786// If substitutes done, report number of substitutes, otherwise report 4787// number of extra or deleted lines. 4788// Don't report extra or deleted lines in the edge case where the buffer 4789// we are in after execution is different from the buffer we started in. 4790if (!do_sub_msg (false)&& curbuf == old_buf ) { 4791msgmore (curbuf -> b_ml .ml_line_count - old_lcount ); 4792 } 4793} 4794 4795#ifdef EXITFREE 4796void free_old_sub (void ) 4797{ 4798sub_set_replacement ((SubReplacementString ) {NULL ,0 ,NULL }); 4799} 4800 4801#endif 4802 4803/// Set up for a tagpreview. 4804/// 4805/// @param undo_sync Sync undo when leaving the window. 4806/// @param use_previewpopup Use a floating window (when 'previewpopup' is set). 4807/// 4808/// @return true when the preview window was created. 4809bool prepare_tagpreview (bool undo_sync ,bool use_previewpopup ) 4810{ 4811if (curwin -> w_p_pvw ) { 4812return false; 4813 } 4814 4815// If there is already a preview window open, use that one. 4816FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 4817if (wp -> w_p_pvw ) { 4818if (use_previewpopup ?wp -> w_kind != kWinPreview :wp -> w_floating ) { 4819continue ; 4820 } 4821if (use_previewpopup ) { 4822win_float_anchor_preview (wp );// Re-anchor to the new cursor position. 4823 } 4824win_enter (wp ,undo_sync ); 4825return false; 4826 } 4827 } 4828 4829if (use_previewpopup ) { 4830win_T * wp = win_float_special (false, true,kWinPreview ); 4831if (!wp ) { 4832return false; 4833 } 4834win_enter (wp ,undo_sync ); 4835return true; 4836 } 4837// There is no preview window open yet. Create one. 4838if (win_split (g_do_tagpreview > 0 ?g_do_tagpreview :0 ,0 )== FAIL ) { 4839return false; 4840 } 4841 4842curwin -> w_p_pvw = true; 4843curwin -> w_p_wfh = true; 4844RESET_BINDING (curwin );// don't take over 'scrollbind' and 'cursorbind' 4845curwin -> w_p_diff = false;// no 'diff' 4846 4847set_option_direct (kOptFoldcolumn ,STATIC_CSTR_AS_OBJ ("0" ),0 ,SID_NONE );// no 'foldcolumn' 4848return true; 4849} 4850 4851/// Shows the effects of the :substitute command being typed ('inccommand'). 4852/// If inccommand=split, shows a preview window and later restores the layout. 4853/// 4854/// @return 1 if preview window isn't needed, 2 if preview window is needed. 4855static int show_sub (exarg_T * eap ,pos_T old_cusr ,PreviewLines * preview_lines ,int hl_id , 4856int cmdpreview_ns ,handle_T cmdpreview_bufnr ) 4857FUNC_ATTR_NONNULL_ALL 4858{ 4859char * save_shm_p = xstrdup (p_shm ); 4860PreviewLines lines = * preview_lines ; 4861buf_T * orig_buf = curbuf ; 4862// We keep a special-purpose buffer around, but don't assume it exists. 4863buf_T * cmdpreview_buf = NULL ; 4864 4865// disable file info message 4866set_option_direct (kOptShortmess ,STATIC_CSTR_AS_OBJ ("F" ),0 ,SID_NONE ); 4867 4868// Place cursor on nearest matching line, to undo do_sub() cursor placement. 4869for (size_t i = 0 ;i < lines .subresults .size ;i ++ ) { 4870SubResult curres = lines .subresults .items [i ]; 4871if (curres .start .lnum >=old_cusr .lnum ) { 4872curwin -> w_cursor .lnum = curres .start .lnum ; 4873curwin -> w_cursor .col = curres .start .col ; 4874break ; 4875 }// Else: All matches are above, do_sub() already placed cursor. 4876 } 4877 4878// Update the topline to ensure that main window is on the correct line 4879update_topline (curwin ); 4880 4881// Width of the "| lnum|..." column which displays the line numbers. 4882int col_width = 0 ; 4883// Use preview window only when inccommand=split and range is not just the current line 4884bool preview = (* p_icm == 's' )&& (eap -> line1 != old_cusr .lnum || eap -> line2 != old_cusr .lnum ); 4885 4886if (preview ) { 4887cmdpreview_buf = buflist_findnr (cmdpreview_bufnr ); 4888assert (cmdpreview_buf != NULL ); 4889 4890if (lines .subresults .size > 0 ) { 4891SubResult last_match = kv_last (lines .subresults ); 4892// `last_match.end.lnum` may be 0 when using 'n' flag. 4893linenr_T highest_lnum = MAX (last_match .start .lnum ,last_match .end .lnum ); 4894assert (highest_lnum > 0 ); 4895col_width = (int )log10 (highest_lnum )+ 1 + 3 ; 4896 } 4897 } 4898 4899char * str = NULL ;// construct the line to show in here 4900colnr_T old_line_size = 0 ; 4901colnr_T line_size = 0 ; 4902linenr_T linenr_preview = 0 ;// last line added to preview buffer 4903linenr_T linenr_origbuf = 0 ;// last line added to original buffer 4904linenr_T next_linenr = 0 ;// next line to show for the match 4905 4906for (size_t matchidx = 0 ;matchidx < lines .subresults .size ;matchidx ++ ) { 4907SubResult match = lines .subresults .items [matchidx ]; 4908 4909if (cmdpreview_buf ) { 4910lpos_T p_start = {0 ,match .start .col };// match starts here in preview 4911lpos_T p_end = {0 ,match .end .col };// ... and ends here 4912 4913// You Might Gonna Need It 4914buf_ensure_loaded (cmdpreview_buf ); 4915 4916if (match .pre_match == 0 ) { 4917next_linenr = match .start .lnum ; 4918 }else { 4919next_linenr = match .pre_match ; 4920 } 4921// Don't add a line twice 4922if (next_linenr == linenr_origbuf ) { 4923next_linenr ++ ; 4924p_start .lnum = linenr_preview ;// might be redefined below 4925p_end .lnum = linenr_preview ;// might be redefined below 4926 } 4927 4928for (;next_linenr <=match .end .lnum ;next_linenr ++ ) { 4929if (next_linenr == match .start .lnum ) { 4930p_start .lnum = linenr_preview + 1 ; 4931 } 4932if (next_linenr == match .end .lnum ) { 4933p_end .lnum = linenr_preview + 1 ; 4934 } 4935char * line ; 4936if (next_linenr == orig_buf -> b_ml .ml_line_count + 1 ) { 4937line = "" ; 4938 }else { 4939line = ml_get_buf (orig_buf ,next_linenr ); 4940line_size = ml_get_buf_len (orig_buf ,next_linenr )+ col_width + 1 ; 4941 4942// Reallocate if line not long enough 4943if (line_size > old_line_size ) { 4944str = xrealloc (str , (size_t )line_size * sizeof (char )); 4945old_line_size = line_size ; 4946 } 4947 } 4948// Put "|lnum| line" into `str` and append it to the preview buffer. 4949snprintf (str , (size_t )line_size ,"|%*" PRIdLINENR "| %s" ,col_width - 3 , 4950next_linenr ,line ); 4951if (linenr_preview == 0 ) { 4952ml_replace_buf (cmdpreview_buf ,1 ,str , true, false); 4953 }else { 4954ml_append_buf (cmdpreview_buf ,linenr_preview ,str ,line_size , false); 4955 } 4956linenr_preview += 1 ; 4957 } 4958linenr_origbuf = match .end .lnum ; 4959 4960bufhl_add_hl_pos_offset (cmdpreview_buf ,cmdpreview_ns ,hl_id ,p_start ,p_end ,col_width ); 4961 } 4962bufhl_add_hl_pos_offset (orig_buf ,cmdpreview_ns ,hl_id ,match .start ,match .end ,0 ); 4963 } 4964 4965xfree (str ); 4966 4967set_option_direct (kOptShortmess ,CSTR_AS_OBJ (save_shm_p ),0 ,SID_NONE ); 4968xfree (save_shm_p ); 4969 4970return preview ?2 :1 ; 4971} 4972 4973/// :substitute command. 4974void ex_substitute (exarg_T * eap ) 4975{ 4976do_sub (eap ,profile_zero (),0 ,0 ); 4977} 4978 4979/// :substitute command preview callback. 4980int ex_substitute_preview (exarg_T * eap ,int cmdpreview_ns ,handle_T cmdpreview_bufnr ) 4981{ 4982// Only preview once the pattern delimiter has been typed 4983if (* eap -> arg && !ASCII_ISALNUM (* eap -> arg )) { 4984char * save_eap = eap -> arg ; 4985int retv = do_sub (eap ,profile_setlimit (p_rdt ),cmdpreview_ns ,cmdpreview_bufnr ); 4986eap -> arg = save_eap ; 4987return retv ; 4988 } 4989 4990return 0 ; 4991} 4992 4993/// Skip over the pattern argument of ":vimgrep /pat/[g][j]". 4994/// Put the start of the pattern in "*s", unless "s" is NULL. 4995/// 4996/// @param flags if not NULL, put the flags in it: VGR_GLOBAL, VGR_NOJUMP. 4997/// @param s if not NULL, terminate the pattern with a NUL. 4998/// 4999/// @return a pointer to the char just past the pattern plus flags. 5000char * skip_vimgrep_pat (char * p ,char ** s ,int * flags ) 5001{ 5002if (vim_isIDc ((uint8_t )(* p ))) { 5003// ":vimgrep pattern fname" 5004if (s != NULL ) { 5005* s = p ; 5006 } 5007p = skiptowhite (p ); 5008if (s != NULL && * p != NUL ) { 5009* p ++ = NUL ; 5010 } 5011 }else { 5012// ":vimgrep /pattern/[g][j] fname" 5013if (s != NULL ) { 5014* s = p + 1 ; 5015 } 5016int c = (uint8_t )(* p ); 5017p = skip_regexp (p + 1 ,c , true); 5018if (* p != c ) { 5019return NULL ; 5020 } 5021 5022// Truncate the pattern. 5023if (s != NULL ) { 5024* p = NUL ; 5025 } 5026p ++ ; 5027 5028// Find the flags 5029while (* p == 'g' || * p == 'j' || * p == 'f' ) { 5030if (flags != NULL ) { 5031if (* p == 'g' ) { 5032* flags |=VGR_GLOBAL ; 5033 }else if (* p == 'j' ) { 5034* flags |=VGR_NOJUMP ; 5035 }else { 5036* flags |=VGR_FUZZY ; 5037 } 5038 } 5039p ++ ; 5040 } 5041 } 5042return p ; 5043} 5044 5045/// `:oldfiles` (sync) and `:browse oldfiles` (async). 5046void ex_oldfiles (exarg_T * eap ) 5047{ 5048nlua_call_excmd ("vim._core.ex_cmd" ,"ex_oldfiles" ,eap ,& cmdmod ,NULL ); 5049}