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