blob: a8083b32eee6214b3a0f6ba4de0b55f3222f6007 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
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_EX_EXTRA
18static int linelen __ARGS((int *has_tab));
19#endif
20static void do_filter __ARGS((linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, int do_in, int do_out));
21#ifdef FEAT_VIMINFO
22static char_u *viminfo_filename __ARGS((char_u *));
23static void do_viminfo __ARGS((FILE *fp_in, FILE *fp_out, int want_info, int want_marks, int force_read));
24static int viminfo_encoding __ARGS((vir_T *virp));
25static int read_viminfo_up_to_marks __ARGS((vir_T *virp, int forceit, int writing));
26#endif
27
28static int check_overwrite __ARGS((exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int other));
29static int check_readonly __ARGS((int *forceit, buf_T *buf));
30#ifdef FEAT_AUTOCMD
31static void delbuf_msg __ARGS((char_u *name));
32#endif
Bram Moolenaar05159a02005-02-26 23:04:13 +000033static int do_sub_msg __ARGS((int count_only));
Bram Moolenaar071d4272004-06-13 20:20:40 +000034static int
35#ifdef __BORLANDC__
36 _RTLENTRYF
37#endif
38 help_compare __ARGS((const void *s1, const void *s2));
39
40/*
41 * ":ascii" and "ga".
42 */
43/*ARGSUSED*/
44 void
45do_ascii(eap)
46 exarg_T *eap;
47{
48 int c;
49 char buf1[20];
50 char buf2[20];
51 char_u buf3[7];
52#ifdef FEAT_MBYTE
53 int c1 = 0;
54 int c2 = 0;
55 int len;
56
57 if (enc_utf8)
58 c = utfc_ptr2char(ml_get_cursor(), &c1, &c2);
59 else
60#endif
61 c = gchar_cursor();
62 if (c == NUL)
63 {
64 MSG("NUL");
65 return;
66 }
67
68#ifdef FEAT_MBYTE
69 IObuff[0] = NUL;
70 if (!has_mbyte || (enc_dbcs != 0 && c < 0x100) || c < 0x80)
71#endif
72 {
73 if (c == NL) /* NUL is stored as NL */
74 c = NUL;
75 if (vim_isprintc_strict(c) && (c < ' '
76#ifndef EBCDIC
77 || c > '~'
78#endif
79 ))
80 {
81 transchar_nonprint(buf3, c);
82 sprintf(buf1, " <%s>", (char *)buf3);
83 }
84 else
85 buf1[0] = NUL;
86#ifndef EBCDIC
87 if (c >= 0x80)
88 sprintf(buf2, " <M-%s>", transchar(c & 0x7f));
89 else
90#endif
91 buf2[0] = NUL;
Bram Moolenaar555b2802005-05-19 21:08:39 +000092 vim_snprintf((char *)IObuff, IOSIZE,
93 _("<%s>%s%s %d, Hex %02x, Octal %03o"),
94 transchar(c), buf1, buf2, c, c, c);
Bram Moolenaar071d4272004-06-13 20:20:40 +000095#ifdef FEAT_MBYTE
96 c = c1;
97 c1 = c2;
98 c2 = 0;
99#endif
100 }
101
102#ifdef FEAT_MBYTE
103 /* Repeat for combining characters. */
104 while (has_mbyte && (c >= 0x100 || (enc_utf8 && c >= 0x80)))
105 {
106 len = (int)STRLEN(IObuff);
107 /* This assumes every multi-byte char is printable... */
108 if (len > 0)
109 IObuff[len++] = ' ';
110 IObuff[len++] = '<';
111 if (utf_iscomposing(c)
112#ifdef USE_GUI
113 && !gui.in_use
114#endif
115 )
116 IObuff[len++] = ' '; /* draw composing char on top of a space */
Bram Moolenaar555b2802005-05-19 21:08:39 +0000117 len += (*mb_char2bytes)(c, IObuff + len);
118 vim_snprintf((char *)IObuff + len, IOSIZE - len,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000119 c < 0x10000 ? _("> %d, Hex %04x, Octal %o")
120 : _("> %d, Hex %08x, Octal %o"), c, c, c);
121 c = c1;
122 c1 = c2;
123 c2 = 0;
124 }
125#endif
126
127 msg(IObuff);
128}
129
130#if defined(FEAT_EX_EXTRA) || defined(PROTO)
131/*
132 * ":left", ":center" and ":right": align text.
133 */
134 void
135ex_align(eap)
136 exarg_T *eap;
137{
138 pos_T save_curpos;
139 int len;
140 int indent = 0;
141 int new_indent;
142 int has_tab;
143 int width;
144
145#ifdef FEAT_RIGHTLEFT
146 if (curwin->w_p_rl)
147 {
148 /* switch left and right aligning */
149 if (eap->cmdidx == CMD_right)
150 eap->cmdidx = CMD_left;
151 else if (eap->cmdidx == CMD_left)
152 eap->cmdidx = CMD_right;
153 }
154#endif
155
156 width = atoi((char *)eap->arg);
157 save_curpos = curwin->w_cursor;
158 if (eap->cmdidx == CMD_left) /* width is used for new indent */
159 {
160 if (width >= 0)
161 indent = width;
162 }
163 else
164 {
165 /*
166 * if 'textwidth' set, use it
167 * else if 'wrapmargin' set, use it
168 * if invalid value, use 80
169 */
170 if (width <= 0)
171 width = curbuf->b_p_tw;
172 if (width == 0 && curbuf->b_p_wm > 0)
173 width = W_WIDTH(curwin) - curbuf->b_p_wm;
174 if (width <= 0)
175 width = 80;
176 }
177
178 if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)
179 return;
180
181 for (curwin->w_cursor.lnum = eap->line1;
182 curwin->w_cursor.lnum <= eap->line2; ++curwin->w_cursor.lnum)
183 {
184 if (eap->cmdidx == CMD_left) /* left align */
185 new_indent = indent;
186 else
187 {
188 len = linelen(eap->cmdidx == CMD_right ? &has_tab
189 : NULL) - get_indent();
190
191 if (len <= 0) /* skip blank lines */
192 continue;
193
194 if (eap->cmdidx == CMD_center)
195 new_indent = (width - len) / 2;
196 else
197 {
198 new_indent = width - len; /* right align */
199
200 /*
201 * Make sure that embedded TABs don't make the text go too far
202 * to the right.
203 */
204 if (has_tab)
205 while (new_indent > 0)
206 {
207 (void)set_indent(new_indent, 0);
208 if (linelen(NULL) <= width)
209 {
210 /*
211 * Now try to move the line as much as possible to
212 * the right. Stop when it moves too far.
213 */
214 do
215 (void)set_indent(++new_indent, 0);
216 while (linelen(NULL) <= width);
217 --new_indent;
218 break;
219 }
220 --new_indent;
221 }
222 }
223 }
224 if (new_indent < 0)
225 new_indent = 0;
226 (void)set_indent(new_indent, 0); /* set indent */
227 }
228 changed_lines(eap->line1, 0, eap->line2 + 1, 0L);
229 curwin->w_cursor = save_curpos;
230 beginline(BL_WHITE | BL_FIX);
231}
232
233/*
234 * Get the length of the current line, excluding trailing white space.
235 */
236 static int
237linelen(has_tab)
238 int *has_tab;
239{
240 char_u *line;
241 char_u *first;
242 char_u *last;
243 int save;
244 int len;
245
246 /* find the first non-blank character */
247 line = ml_get_curline();
248 first = skipwhite(line);
249
250 /* find the character after the last non-blank character */
251 for (last = first + STRLEN(first);
252 last > first && vim_iswhite(last[-1]); --last)
253 ;
254 save = *last;
255 *last = NUL;
256 len = linetabsize(line); /* get line length */
257 if (has_tab != NULL) /* check for embedded TAB */
258 *has_tab = (vim_strrchr(first, TAB) != NULL);
259 *last = save;
260
261 return len;
262}
263
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000264/* Buffer for one line used during sorting. It's allocated to contain the
265 * longest line being sorted. */
266static char_u *sortbuf;
267
268static int sort_ic; /* ignore case */
269
270static int
271#ifdef __BORLANDC__
272_RTLENTRYF
273#endif
274sort_compare __ARGS((const void *s1, const void *s2));
275
276 static int
277#ifdef __BORLANDC__
278_RTLENTRYF
279#endif
280sort_compare(s1, s2)
281 const void *s1;
282 const void *s2;
283{
284 lpos_T l1 = *(lpos_T *)s1;
285 lpos_T l2 = *(lpos_T *)s2;
286 char_u *s;
287
288 /* We need to copy one line into "sortbuf", because there is no guarantee
289 * that the first pointer becomes invalid when obtaining the second one. */
290 STRCPY(sortbuf, ml_get(l1.lnum) + l1.col);
291 s = ml_get(l2.lnum) + l2.col;
292 return sort_ic ? STRICMP(sortbuf, s) : STRCMP(sortbuf, s);
293}
294
295/*
296 * ":sort".
297 */
298 void
299ex_sort(eap)
300 exarg_T *eap;
301{
302 regmatch_T regmatch;
303 int len;
304 linenr_T lnum;
305 long maxlen = 0;
306 lpos_T *nrs;
307 size_t count = eap->line2 - eap->line1 + 1;
308 int i;
309 char_u *p;
310 char_u *s;
311 int unique = FALSE;
312 long deleted;
313
314 if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)
315 return;
316 sortbuf = NULL;
317 regmatch.regprog = NULL;
318 nrs = (lpos_T *)lalloc((long_u)(count * sizeof(lpos_T)), TRUE);
319 if (nrs == NULL)
320 goto theend;
321
322 for (p = eap->arg; *p != NUL; ++p)
323 {
324 if (vim_iswhite(*p))
325 ;
326 else if (*p == 'i')
327 sort_ic = TRUE;
328 else if (*p == 'u')
329 unique = TRUE;
Bram Moolenaar0e6830e2005-05-27 20:23:44 +0000330 else if (*p == '"') /* comment start */
331 break;
332 else if (check_nextcmd(p) != NULL)
333 {
334 eap->nextcmd = check_nextcmd(p);
335 break;
336 }
337 else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL)
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000338 {
339 s = skip_regexp(p + 1, *p, TRUE, NULL);
340 if (*s != *p)
341 {
342 EMSG(_(e_invalpat));
343 goto theend;
344 }
345 *s = NUL;
346 regmatch.regprog = vim_regcomp(p + 1, RE_MAGIC);
347 if (regmatch.regprog == NULL)
348 goto theend;
Bram Moolenaar0e6830e2005-05-27 20:23:44 +0000349 p = s; /* continue after the regexp */
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000350 regmatch.rm_ic = p_ic;
351 }
352 else
353 {
354 EMSG2(_(e_invarg2), p);
355 goto theend;
356 }
357 }
358
359 /*
360 * Make an array with all line numbers, so that we don't have to copy all
361 * the lines into allocated memory.
362 * Also get the longest line length.
363 */
364 for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
365 {
366 nrs[lnum - eap->line1].lnum = lnum;
367 nrs[lnum - eap->line1].col = 0;
368
369 s = ml_get(lnum);
370 if (regmatch.regprog != NULL && vim_regexec(&regmatch, s, 0))
371 nrs[lnum - eap->line1].col = regmatch.endp[0] - s;
372
373 len = STRLEN(s);
374 if (maxlen < len)
375 maxlen = len;
376 }
377
378 sortbuf = alloc((unsigned)maxlen + 1);
379 if (sortbuf == NULL)
380 goto theend;
381
382 /* sort the array of line numbers */
383 qsort((void *)nrs, count, sizeof(lpos_T), sort_compare);
384
385 /* Insert the lines in the sorted order below the last one. */
386 lnum = eap->line2;
387 for (i = 0; i < count; ++i)
388 {
389 s = ml_get(nrs[eap->forceit ? count - i - 1 : i].lnum);
390 if (!unique || i == 0
391 || (sort_ic ? STRICMP(s, sortbuf) : STRCMP(s, sortbuf)) != 0)
392 {
393 if (ml_append(lnum++, s, (colnr_T)0, FALSE) == FAIL)
394 break;
395 STRCPY(sortbuf, s);
396 }
397 }
398
399 /* delete the original lines if appending worked */
400 if (i == count)
401 for (i = 0; i < count; ++i)
402 ml_delete(eap->line1, FALSE);
403 else
404 count = 0;
405
406 deleted = count - (lnum - eap->line2);
407 if (deleted > 0)
408 mark_adjust(eap->line2 - deleted, eap->line2, (long)MAXLNUM, -deleted);
409 else if (deleted < 0)
410 mark_adjust(eap->line2, MAXLNUM, -deleted, 0L);
411 changed_lines(eap->line1, 0, eap->line2 + 1, -deleted);
412 curwin->w_cursor.lnum = eap->line1;
413 beginline(BL_WHITE | BL_FIX);
414
415theend:
416 vim_free(nrs);
417 vim_free(sortbuf);
418 vim_free(regmatch.regprog);
419}
420
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421/*
422 * ":retab".
423 */
424 void
425ex_retab(eap)
426 exarg_T *eap;
427{
428 linenr_T lnum;
429 int got_tab = FALSE;
430 long num_spaces = 0;
431 long num_tabs;
432 long len;
433 long col;
434 long vcol;
435 long start_col = 0; /* For start of white-space string */
436 long start_vcol = 0; /* For start of white-space string */
437 int temp;
438 long old_len;
439 char_u *ptr;
440 char_u *new_line = (char_u *)1; /* init to non-NULL */
441 int did_undo; /* called u_save for current line */
442 int new_ts;
443 int save_list;
444 linenr_T first_line = 0; /* first changed line */
445 linenr_T last_line = 0; /* last changed line */
446
447 save_list = curwin->w_p_list;
448 curwin->w_p_list = 0; /* don't want list mode here */
449
450 new_ts = getdigits(&(eap->arg));
451 if (new_ts < 0)
452 {
453 EMSG(_(e_positive));
454 return;
455 }
456 if (new_ts == 0)
457 new_ts = curbuf->b_p_ts;
458 for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)
459 {
460 ptr = ml_get(lnum);
461 col = 0;
462 vcol = 0;
463 did_undo = FALSE;
464 for (;;)
465 {
466 if (vim_iswhite(ptr[col]))
467 {
468 if (!got_tab && num_spaces == 0)
469 {
470 /* First consecutive white-space */
471 start_vcol = vcol;
472 start_col = col;
473 }
474 if (ptr[col] == ' ')
475 num_spaces++;
476 else
477 got_tab = TRUE;
478 }
479 else
480 {
481 if (got_tab || (eap->forceit && num_spaces > 1))
482 {
483 /* Retabulate this string of white-space */
484
485 /* len is virtual length of white string */
486 len = num_spaces = vcol - start_vcol;
487 num_tabs = 0;
488 if (!curbuf->b_p_et)
489 {
490 temp = new_ts - (start_vcol % new_ts);
491 if (num_spaces >= temp)
492 {
493 num_spaces -= temp;
494 num_tabs++;
495 }
496 num_tabs += num_spaces / new_ts;
497 num_spaces -= (num_spaces / new_ts) * new_ts;
498 }
499 if (curbuf->b_p_et || got_tab ||
500 (num_spaces + num_tabs < len))
501 {
502 if (did_undo == FALSE)
503 {
504 did_undo = TRUE;
505 if (u_save((linenr_T)(lnum - 1),
506 (linenr_T)(lnum + 1)) == FAIL)
507 {
508 new_line = NULL; /* flag out-of-memory */
509 break;
510 }
511 }
512
513 /* len is actual number of white characters used */
514 len = num_spaces + num_tabs;
515 old_len = (long)STRLEN(ptr);
516 new_line = lalloc(old_len - col + start_col + len + 1,
517 TRUE);
518 if (new_line == NULL)
519 break;
520 if (start_col > 0)
521 mch_memmove(new_line, ptr, (size_t)start_col);
522 mch_memmove(new_line + start_col + len,
523 ptr + col, (size_t)(old_len - col + 1));
524 ptr = new_line + start_col;
525 for (col = 0; col < len; col++)
526 ptr[col] = (col < num_tabs) ? '\t' : ' ';
527 ml_replace(lnum, new_line, FALSE);
528 if (first_line == 0)
529 first_line = lnum;
530 last_line = lnum;
531 ptr = new_line;
532 col = start_col + len;
533 }
534 }
535 got_tab = FALSE;
536 num_spaces = 0;
537 }
538 if (ptr[col] == NUL)
539 break;
540 vcol += chartabsize(ptr + col, (colnr_T)vcol);
541#ifdef FEAT_MBYTE
542 if (has_mbyte)
543 col += (*mb_ptr2len_check)(ptr + col);
544 else
545#endif
546 ++col;
547 }
548 if (new_line == NULL) /* out of memory */
549 break;
550 line_breakcheck();
551 }
552 if (got_int)
553 EMSG(_(e_interr));
554
555 if (curbuf->b_p_ts != new_ts)
556 redraw_curbuf_later(NOT_VALID);
557 if (first_line != 0)
558 changed_lines(first_line, 0, last_line + 1, 0L);
559
560 curwin->w_p_list = save_list; /* restore 'list' */
561
562 curbuf->b_p_ts = new_ts;
563 coladvance(curwin->w_curswant);
564
565 u_clearline();
566}
567#endif
568
569/*
570 * :move command - move lines line1-line2 to line dest
571 *
572 * return FAIL for failure, OK otherwise
573 */
574 int
575do_move(line1, line2, dest)
576 linenr_T line1;
577 linenr_T line2;
578 linenr_T dest;
579{
580 char_u *str;
581 linenr_T l;
582 linenr_T extra; /* Num lines added before line1 */
583 linenr_T num_lines; /* Num lines moved */
584 linenr_T last_line; /* Last line in file after adding new text */
585
586 if (dest >= line1 && dest < line2)
587 {
588 EMSG(_("E134: Move lines into themselves"));
589 return FAIL;
590 }
591
592 num_lines = line2 - line1 + 1;
593
594 /*
595 * First we copy the old text to its new location -- webb
596 * Also copy the flag that ":global" command uses.
597 */
598 if (u_save(dest, dest + 1) == FAIL)
599 return FAIL;
600 for (extra = 0, l = line1; l <= line2; l++)
601 {
602 str = vim_strsave(ml_get(l + extra));
603 if (str != NULL)
604 {
605 ml_append(dest + l - line1, str, (colnr_T)0, FALSE);
606 vim_free(str);
607 if (dest < line1)
608 extra++;
609 }
610 }
611
612 /*
613 * Now we must be careful adjusting our marks so that we don't overlap our
614 * mark_adjust() calls.
615 *
616 * We adjust the marks within the old text so that they refer to the
617 * last lines of the file (temporarily), because we know no other marks
618 * will be set there since these line numbers did not exist until we added
619 * our new lines.
620 *
621 * Then we adjust the marks on lines between the old and new text positions
622 * (either forwards or backwards).
623 *
624 * And Finally we adjust the marks we put at the end of the file back to
625 * their final destination at the new text position -- webb
626 */
627 last_line = curbuf->b_ml.ml_line_count;
628 mark_adjust(line1, line2, last_line - line2, 0L);
629 if (dest >= line2)
630 {
631 mark_adjust(line2 + 1, dest, -num_lines, 0L);
632 curbuf->b_op_start.lnum = dest - num_lines + 1;
633 curbuf->b_op_end.lnum = dest;
634 }
635 else
636 {
637 mark_adjust(dest + 1, line1 - 1, num_lines, 0L);
638 curbuf->b_op_start.lnum = dest + 1;
639 curbuf->b_op_end.lnum = dest + num_lines;
640 }
641 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
642 mark_adjust(last_line - num_lines + 1, last_line,
643 -(last_line - dest - extra), 0L);
644
645 /*
646 * Now we delete the original text -- webb
647 */
648 if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL)
649 return FAIL;
650
651 for (l = line1; l <= line2; l++)
652 ml_delete(line1 + extra, TRUE);
653
654 if (!global_busy && num_lines > p_report)
655 {
656 if (num_lines == 1)
657 MSG(_("1 line moved"));
658 else
659 smsg((char_u *)_("%ld lines moved"), num_lines);
660 }
661
662 /*
663 * Leave the cursor on the last of the moved lines.
664 */
665 if (dest >= line1)
666 curwin->w_cursor.lnum = dest;
667 else
668 curwin->w_cursor.lnum = dest + (line2 - line1) + 1;
669
670 if (line1 < dest)
671 changed_lines(line1, 0, dest + num_lines + 1, 0L);
672 else
673 changed_lines(dest + 1, 0, line1 + num_lines, 0L);
674
675 return OK;
676}
677
678/*
679 * ":copy"
680 */
681 void
682ex_copy(line1, line2, n)
683 linenr_T line1;
684 linenr_T line2;
685 linenr_T n;
686{
687 linenr_T count;
688 char_u *p;
689
690 count = line2 - line1 + 1;
691 curbuf->b_op_start.lnum = n + 1;
692 curbuf->b_op_end.lnum = n + count;
693 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
694
695 /*
696 * there are three situations:
697 * 1. destination is above line1
698 * 2. destination is between line1 and line2
699 * 3. destination is below line2
700 *
701 * n = destination (when starting)
702 * curwin->w_cursor.lnum = destination (while copying)
703 * line1 = start of source (while copying)
704 * line2 = end of source (while copying)
705 */
706 if (u_save(n, n + 1) == FAIL)
707 return;
708
709 curwin->w_cursor.lnum = n;
710 while (line1 <= line2)
711 {
712 /* need to use vim_strsave() because the line will be unlocked within
713 * ml_append() */
714 p = vim_strsave(ml_get(line1));
715 if (p != NULL)
716 {
717 ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);
718 vim_free(p);
719 }
720 /* situation 2: skip already copied lines */
721 if (line1 == n)
722 line1 = curwin->w_cursor.lnum;
723 ++line1;
724 if (curwin->w_cursor.lnum < line1)
725 ++line1;
726 if (curwin->w_cursor.lnum < line2)
727 ++line2;
728 ++curwin->w_cursor.lnum;
729 }
730
731 appended_lines_mark(n, count);
732
733 msgmore((long)count);
734}
735
736/*
737 * Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd"
738 * Bangs in the argument are replaced with the previously entered command.
739 * Remember the argument.
740 *
741 * RISCOS: Bangs only replaced when followed by a space, since many
742 * pathnames contain one.
743 */
744 void
745do_bang(addr_count, eap, forceit, do_in, do_out)
746 int addr_count;
747 exarg_T *eap;
748 int forceit;
749 int do_in, do_out;
750{
751 char_u *arg = eap->arg; /* command */
752 linenr_T line1 = eap->line1; /* start of range */
753 linenr_T line2 = eap->line2; /* end of range */
754 static char_u *prevcmd = NULL; /* the previous command */
755 char_u *newcmd = NULL; /* the new command */
756 int free_newcmd = FALSE; /* need to free() newcmd */
757 int ins_prevcmd;
758 char_u *t;
759 char_u *p;
760 char_u *trailarg;
761 int len;
762 int scroll_save = msg_scroll;
763
764 /*
765 * Disallow shell commands for "rvim".
766 * Disallow shell commands from .exrc and .vimrc in current directory for
767 * security reasons.
768 */
769 if (check_restricted() || check_secure())
770 return;
771
772 if (addr_count == 0) /* :! */
773 {
774 msg_scroll = FALSE; /* don't scroll here */
775 autowrite_all();
776 msg_scroll = scroll_save;
777 }
778
779 /*
780 * Try to find an embedded bang, like in :!<cmd> ! [args]
781 * (:!! is indicated by the 'forceit' variable)
782 */
783 ins_prevcmd = forceit;
784 trailarg = arg;
785 do
786 {
787 len = (int)STRLEN(trailarg) + 1;
788 if (newcmd != NULL)
789 len += (int)STRLEN(newcmd);
790 if (ins_prevcmd)
791 {
792 if (prevcmd == NULL)
793 {
794 EMSG(_(e_noprev));
795 vim_free(newcmd);
796 return;
797 }
798 len += (int)STRLEN(prevcmd);
799 }
800 if ((t = alloc(len)) == NULL)
801 {
802 vim_free(newcmd);
803 return;
804 }
805 *t = NUL;
806 if (newcmd != NULL)
807 STRCAT(t, newcmd);
808 if (ins_prevcmd)
809 STRCAT(t, prevcmd);
810 p = t + STRLEN(t);
811 STRCAT(t, trailarg);
812 vim_free(newcmd);
813 newcmd = t;
814
815 /*
816 * Scan the rest of the argument for '!', which is replaced by the
817 * previous command. "\!" is replaced by "!" (this is vi compatible).
818 */
819 trailarg = NULL;
820 while (*p)
821 {
822 if (*p == '!'
823#ifdef RISCOS
824 && (p[1] == ' ' || p[1] == NUL)
825#endif
826 )
827 {
828 if (p > newcmd && p[-1] == '\\')
829 mch_memmove(p - 1, p, (size_t)(STRLEN(p) + 1));
830 else
831 {
832 trailarg = p;
833 *trailarg++ = NUL;
834 ins_prevcmd = TRUE;
835 break;
836 }
837 }
838 ++p;
839 }
840 } while (trailarg != NULL);
841
842 vim_free(prevcmd);
843 prevcmd = newcmd;
844
845 if (bangredo) /* put cmd in redo buffer for ! command */
846 {
847 AppendToRedobuffLit(prevcmd);
848 AppendToRedobuff((char_u *)"\n");
849 bangredo = FALSE;
850 }
851 /*
852 * Add quotes around the command, for shells that need them.
853 */
854 if (*p_shq != NUL)
855 {
856 newcmd = alloc((unsigned)(STRLEN(prevcmd) + 2 * STRLEN(p_shq) + 1));
857 if (newcmd == NULL)
858 return;
859 STRCPY(newcmd, p_shq);
860 STRCAT(newcmd, prevcmd);
861 STRCAT(newcmd, p_shq);
862 free_newcmd = TRUE;
863 }
864 if (addr_count == 0) /* :! */
865 {
866 /* echo the command */
867 msg_start();
868 msg_putchar(':');
869 msg_putchar('!');
870 msg_outtrans(newcmd);
871 msg_clr_eos();
872 windgoto(msg_row, msg_col);
873
874 do_shell(newcmd, 0);
875 }
876 else /* :range! */
877 /* Careful: This may recursively call do_bang() again! (because of
878 * autocommands) */
879 do_filter(line1, line2, eap, newcmd, do_in, do_out);
880 if (free_newcmd)
881 vim_free(newcmd);
882}
883
884/*
885 * do_filter: filter lines through a command given by the user
886 *
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000887 * We mostly use temp files and the call_shell() routine here. This would
888 * normally be done using pipes on a UNIX machine, but this is more portable
889 * to non-unix machines. The call_shell() routine needs to be able
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890 * to deal with redirection somehow, and should handle things like looking
891 * at the PATH env. variable, and adding reasonable extensions to the
892 * command name given by the user. All reasonable versions of call_shell()
893 * do this.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000894 * Alternatively, if on Unix and redirecting input or output, but not both,
895 * and the 'shelltemp' option isn't set, use pipes.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 * We use input redirection if do_in is TRUE.
897 * We use output redirection if do_out is TRUE.
898 */
899 static void
900do_filter(line1, line2, eap, cmd, do_in, do_out)
901 linenr_T line1, line2;
902 exarg_T *eap; /* for forced 'ff' and 'fenc' */
903 char_u *cmd;
904 int do_in, do_out;
905{
906 char_u *itmp = NULL;
907 char_u *otmp = NULL;
908 linenr_T linecount;
909 linenr_T read_linecount;
910 pos_T cursor_save;
911 char_u *cmd_buf;
912#ifdef FEAT_AUTOCMD
913 buf_T *old_curbuf = curbuf;
914#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000915 int shell_flags = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916
917 if (*cmd == NUL) /* no filter command */
918 return;
919
920#ifdef WIN3264
921 /*
922 * Check if external commands are allowed now.
923 */
924 if (can_end_termcap_mode(TRUE) == FALSE)
925 return;
926#endif
927
928 cursor_save = curwin->w_cursor;
929 linecount = line2 - line1 + 1;
930 curwin->w_cursor.lnum = line1;
931 curwin->w_cursor.col = 0;
932 changed_line_abv_curs();
933 invalidate_botline();
934
935 /*
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000936 * When using temp files:
937 * 1. * Form temp file names
938 * 2. * Write the lines to a temp file
939 * 3. Run the filter command on the temp file
940 * 4. * Read the output of the command into the buffer
941 * 5. * Delete the original lines to be filtered
942 * 6. * Remove the temp files
943 *
944 * When writing the input with a pipe or when catching the output with a
945 * pipe only need to do 3.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946 */
947
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000948 if (do_out)
949 shell_flags |= SHELL_DOOUT;
950
951#if !defined(USE_SYSTEM) && defined(UNIX)
952 if (!do_in && do_out && !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000954 /* Use a pipe to fetch stdout of the command, do not use a temp file. */
955 shell_flags |= SHELL_READ;
956 curwin->w_cursor.lnum = line2;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000958 else if (do_in && !do_out && !p_stmp)
959 {
960 /* Use a pipe to write stdin of the command, do not use a temp file. */
961 shell_flags |= SHELL_WRITE;
962 curbuf->b_op_start.lnum = line1;
963 curbuf->b_op_end.lnum = line2;
964 }
965 else if (do_in && do_out && !p_stmp)
966 {
967 /* Use a pipe to write stdin and fetch stdout of the command, do not
968 * use a temp file. */
969 shell_flags |= SHELL_READ|SHELL_WRITE;
970 curbuf->b_op_start.lnum = line1;
971 curbuf->b_op_end.lnum = line2;
972 curwin->w_cursor.lnum = line2;
973 }
974 else
975#endif
976 if ((do_in && (itmp = vim_tempname('i')) == NULL)
977 || (do_out && (otmp = vim_tempname('o')) == NULL))
978 {
979 EMSG(_(e_notmp));
980 goto filterend;
981 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
983/*
984 * The writing and reading of temp files will not be shown.
985 * Vi also doesn't do this and the messages are not very informative.
986 */
987 ++no_wait_return; /* don't call wait_return() while busy */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000988 if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989 FALSE, FALSE, FALSE, TRUE) == FAIL)
990 {
991 msg_putchar('\n'); /* keep message from buf_write() */
992 --no_wait_return;
993#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
994 if (!aborting())
995#endif
996 (void)EMSG2(_(e_notcreate), itmp); /* will call wait_return */
997 goto filterend;
998 }
999#ifdef FEAT_AUTOCMD
1000 if (curbuf != old_curbuf)
1001 goto filterend;
1002#endif
1003
1004 if (!do_out)
1005 msg_putchar('\n');
1006
1007 cmd_buf = make_filter_cmd(cmd, itmp, otmp);
1008 if (cmd_buf == NULL)
1009 goto filterend;
1010
1011 windgoto((int)Rows - 1, 0);
1012 cursor_on();
1013
1014 /*
1015 * When not redirecting the output the command can write anything to the
1016 * screen. If 'shellredir' is equal to ">", screen may be messed up by
1017 * stderr output of external command. Clear the screen later.
1018 * If do_in is FALSE, this could be something like ":r !cat", which may
1019 * also mess up the screen, clear it later.
1020 */
1021 if (!do_out || STRCMP(p_srr, ">") == 0 || !do_in)
1022 redraw_later_clear();
1023
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001024 if (do_out)
1025 {
1026 if (u_save((linenr_T)(line2), (linenr_T)(line2 + 1)) == FAIL)
1027 goto error;
1028 redraw_curbuf_later(VALID);
1029 }
1030 read_linecount = curbuf->b_ml.ml_line_count;
1031
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032 /*
1033 * When call_shell() fails wait_return() is called to give the user a
1034 * chance to read the error messages. Otherwise errors are ignored, so you
1035 * can see the error messages from the command that appear on stdout; use
1036 * 'u' to fix the text
1037 * Switch to cooked mode when not redirecting stdin, avoids that something
1038 * like ":r !cat" hangs.
1039 * Pass on the SHELL_DOOUT flag when the output is being redirected.
1040 */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001041 if (call_shell(cmd_buf, SHELL_FILTER | SHELL_COOKED | shell_flags))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 {
1043 redraw_later_clear();
1044 wait_return(FALSE);
1045 }
1046 vim_free(cmd_buf);
1047
1048 did_check_timestamps = FALSE;
1049 need_check_timestamps = TRUE;
1050
1051 /* When interrupting the shell command, it may still have produced some
1052 * useful output. Reset got_int here, so that readfile() won't cancel
1053 * reading. */
1054 ui_breakcheck();
1055 got_int = FALSE;
1056
1057 if (do_out)
1058 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001059 if (otmp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001061 if (readfile(otmp, NULL, line2, (linenr_T)0, (linenr_T)MAXLNUM,
1062 eap, READ_FILTER) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001064#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1065 if (!aborting())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001067 {
1068 msg_putchar('\n');
1069 EMSG2(_(e_notread), otmp);
1070 }
1071 goto error;
1072 }
1073#ifdef FEAT_AUTOCMD
1074 if (curbuf != old_curbuf)
1075 goto filterend;
1076#endif
1077 }
1078
1079 read_linecount = curbuf->b_ml.ml_line_count - read_linecount;
1080
1081 if (shell_flags & SHELL_READ)
1082 {
1083 curbuf->b_op_start.lnum = line2 + 1;
1084 curbuf->b_op_end.lnum = curwin->w_cursor.lnum;
1085 appended_lines_mark(line2, read_linecount);
1086 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087
1088 if (do_in)
1089 {
1090 if (cmdmod.keepmarks || vim_strchr(p_cpo, CPO_REMMARK) == NULL)
1091 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 if (read_linecount >= linecount)
1093 /* move all marks from old lines to new lines */
1094 mark_adjust(line1, line2, linecount, 0L);
1095 else
1096 {
1097 /* move marks from old lines to new lines, delete marks
1098 * that are in deleted lines */
1099 mark_adjust(line1, line1 + read_linecount - 1,
1100 linecount, 0L);
1101 mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0L);
1102 }
1103 }
1104
1105 /*
1106 * Put cursor on first filtered line for ":range!cmd".
1107 * Adjust '[ and '] (set by buf_write()).
1108 */
1109 curwin->w_cursor.lnum = line1;
1110 del_lines(linecount, TRUE);
1111 curbuf->b_op_start.lnum -= linecount; /* adjust '[ */
1112 curbuf->b_op_end.lnum -= linecount; /* adjust '] */
1113 write_lnum_adjust(-linecount); /* adjust last line
1114 for next write */
Bram Moolenaar8c711452005-01-14 21:53:12 +00001115#ifdef FEAT_FOLDING
1116 foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum);
1117#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 }
1119 else
1120 {
1121 /*
1122 * Put cursor on last new line for ":r !cmd".
1123 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001125 curwin->w_cursor.lnum = curbuf->b_op_end.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126 }
Bram Moolenaar8c711452005-01-14 21:53:12 +00001127
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128 beginline(BL_WHITE | BL_FIX); /* cursor on first non-blank */
1129 --no_wait_return;
1130
1131 if (linecount > p_report)
1132 {
1133 if (do_in)
1134 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00001135 vim_snprintf((char *)msg_buf, sizeof(msg_buf),
1136 _("%ld lines filtered"), (long)linecount);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137 if (msg(msg_buf) && !msg_scroll)
1138 {
1139 /* save message to display it after redraw */
1140 set_keep_msg(msg_buf);
1141 keep_msg_attr = 0;
1142 }
1143 }
1144 else
1145 msgmore((long)linecount);
1146 }
1147 }
1148 else
1149 {
1150error:
1151 /* put cursor back in same position for ":w !cmd" */
1152 curwin->w_cursor = cursor_save;
1153 --no_wait_return;
1154 wait_return(FALSE);
1155 }
1156
1157filterend:
1158
1159#ifdef FEAT_AUTOCMD
1160 if (curbuf != old_curbuf)
1161 {
1162 --no_wait_return;
1163 EMSG(_("E135: *Filter* Autocommands must not change current buffer"));
1164 }
1165#endif
1166 if (itmp != NULL)
1167 mch_remove(itmp);
1168 if (otmp != NULL)
1169 mch_remove(otmp);
1170 vim_free(itmp);
1171 vim_free(otmp);
1172}
1173
1174/*
1175 * Call a shell to execute a command.
1176 * When "cmd" is NULL start an interactive shell.
1177 */
1178 void
1179do_shell(cmd, flags)
1180 char_u *cmd;
1181 int flags; /* may be SHELL_DOOUT when output is redirected */
1182{
1183 buf_T *buf;
1184#ifndef FEAT_GUI_MSWIN
1185 int save_nwr;
1186#endif
1187#ifdef MSWIN
1188 int winstart = FALSE;
1189#endif
1190
1191 /*
1192 * Disallow shell commands for "rvim".
1193 * Disallow shell commands from .exrc and .vimrc in current directory for
1194 * security reasons.
1195 */
1196 if (check_restricted() || check_secure())
1197 {
1198 msg_end();
1199 return;
1200 }
1201
1202#ifdef MSWIN
1203 /*
1204 * Check if external commands are allowed now.
1205 */
1206 if (can_end_termcap_mode(TRUE) == FALSE)
1207 return;
1208
1209 /*
1210 * Check if ":!start" is used.
1211 */
1212 if (cmd != NULL)
1213 winstart = (STRNICMP(cmd, "start ", 6) == 0);
1214#endif
1215
1216 /*
1217 * For autocommands we want to get the output on the current screen, to
1218 * avoid having to type return below.
1219 */
1220 msg_putchar('\r'); /* put cursor at start of line */
1221#ifdef FEAT_AUTOCMD
1222 if (!autocmd_busy)
1223#endif
1224 {
1225#ifdef MSWIN
1226 if (!winstart)
1227#endif
1228 stoptermcap();
1229 }
1230#ifdef MSWIN
1231 if (!winstart)
1232#endif
1233 msg_putchar('\n'); /* may shift screen one line up */
1234
1235 /* warning message before calling the shell */
1236 if (p_warn
1237#ifdef FEAT_AUTOCMD
1238 && !autocmd_busy
1239#endif
1240 && msg_silent == 0)
1241 for (buf = firstbuf; buf; buf = buf->b_next)
1242 if (bufIsChanged(buf))
1243 {
1244#ifdef FEAT_GUI_MSWIN
1245 if (!winstart)
1246 starttermcap(); /* don't want a message box here */
1247#endif
1248 MSG_PUTS(_("[No write since last change]\n"));
1249#ifdef FEAT_GUI_MSWIN
1250 if (!winstart)
1251 stoptermcap();
1252#endif
1253 break;
1254 }
1255
1256 /* This windgoto is required for when the '\n' resulted in a "delete line
1257 * 1" command to the terminal. */
1258 if (!swapping_screen())
1259 windgoto(msg_row, msg_col);
1260 cursor_on();
1261 (void)call_shell(cmd, SHELL_COOKED | flags);
1262 did_check_timestamps = FALSE;
1263 need_check_timestamps = TRUE;
1264
1265 /*
1266 * put the message cursor at the end of the screen, avoids wait_return()
1267 * to overwrite the text that the external command showed
1268 */
1269 if (!swapping_screen())
1270 {
1271 msg_row = Rows - 1;
1272 msg_col = 0;
1273 }
1274
1275#ifdef FEAT_AUTOCMD
1276 if (autocmd_busy)
1277 {
1278 if (msg_silent == 0)
1279 redraw_later_clear();
1280 }
1281 else
1282#endif
1283 {
1284 /*
1285 * For ":sh" there is no need to call wait_return(), just redraw.
1286 * Also for the Win32 GUI (the output is in a console window).
1287 * Otherwise there is probably text on the screen that the user wants
1288 * to read before redrawing, so call wait_return().
1289 */
1290#ifndef FEAT_GUI_MSWIN
1291 if (cmd == NULL
1292# ifdef WIN3264
1293 || (winstart && !need_wait_return)
1294# endif
1295 )
1296 {
1297 if (msg_silent == 0)
1298 redraw_later_clear();
1299 need_wait_return = FALSE;
1300 }
1301 else
1302 {
1303 /*
1304 * If we switch screens when starttermcap() is called, we really
1305 * want to wait for "hit return to continue".
1306 */
1307 save_nwr = no_wait_return;
1308 if (swapping_screen())
1309 no_wait_return = FALSE;
1310# ifdef AMIGA
1311 wait_return(term_console ? -1 : msg_silent == 0); /* see below */
1312# else
1313 wait_return(msg_silent == 0);
1314# endif
1315 no_wait_return = save_nwr;
1316 }
1317#endif /* FEAT_GUI_W32 */
1318
1319#ifdef MSWIN
1320 if (!winstart) /* if winstart==TRUE, never stopped termcap! */
1321#endif
1322 starttermcap(); /* start termcap if not done by wait_return() */
1323
1324 /*
1325 * In an Amiga window redrawing is caused by asking the window size.
1326 * If we got an interrupt this will not work. The chance that the
1327 * window size is wrong is very small, but we need to redraw the
1328 * screen. Don't do this if ':' hit in wait_return(). THIS IS UGLY
1329 * but it saves an extra redraw.
1330 */
1331#ifdef AMIGA
1332 if (skip_redraw) /* ':' hit in wait_return() */
1333 {
1334 if (msg_silent == 0)
1335 redraw_later_clear();
1336 }
1337 else if (term_console)
1338 {
1339 OUT_STR(IF_EB("\033[0 q", ESC_STR "[0 q")); /* get window size */
1340 if (got_int && msg_silent == 0)
1341 redraw_later_clear(); /* if got_int is TRUE, redraw needed */
1342 else
1343 must_redraw = 0; /* no extra redraw needed */
1344 }
1345#endif
1346 }
1347
1348 /* display any error messages now */
1349 display_errors();
1350}
1351
1352/*
1353 * Create a shell command from a command string, input redirection file and
1354 * output redirection file.
1355 * Returns an allocated string with the shell command, or NULL for failure.
1356 */
1357 char_u *
1358make_filter_cmd(cmd, itmp, otmp)
1359 char_u *cmd; /* command */
1360 char_u *itmp; /* NULL or name of input file */
1361 char_u *otmp; /* NULL or name of output file */
1362{
1363 char_u *buf;
1364 long_u len;
1365
1366 len = (long_u)STRLEN(cmd) + 3; /* "()" + NUL */
1367 if (itmp != NULL)
1368 len += (long_u)STRLEN(itmp) + 9; /* " { < " + " } " */
1369 if (otmp != NULL)
1370 len += (long_u)STRLEN(otmp) + (long_u)STRLEN(p_srr) + 2; /* " " */
1371 buf = lalloc(len, TRUE);
1372 if (buf == NULL)
1373 return NULL;
1374
1375#if (defined(UNIX) && !defined(ARCHIE)) || defined(OS2)
1376 /*
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001377 * Put braces around the command (for concatenated commands) when
1378 * redirecting input and/or output.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379 */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001380 if (itmp != NULL || otmp != NULL)
1381 sprintf((char *)buf, "(%s)", (char *)cmd);
1382 else
1383 STRCPY(buf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384 if (itmp != NULL)
1385 {
1386 STRCAT(buf, " < ");
1387 STRCAT(buf, itmp);
1388 }
1389#else
1390 /*
1391 * for shells that don't understand braces around commands, at least allow
1392 * the use of commands in a pipe.
1393 */
1394 STRCPY(buf, cmd);
1395 if (itmp != NULL)
1396 {
1397 char_u *p;
1398
1399 /*
1400 * If there is a pipe, we have to put the '<' in front of it.
1401 * Don't do this when 'shellquote' is not empty, otherwise the
1402 * redirection would be inside the quotes.
1403 */
1404 if (*p_shq == NUL)
1405 {
1406 p = vim_strchr(buf, '|');
1407 if (p != NULL)
1408 *p = NUL;
1409 }
1410# ifdef RISCOS
1411 STRCAT(buf, " { < "); /* Use RISC OS notation for input. */
1412 STRCAT(buf, itmp);
1413 STRCAT(buf, " } ");
1414# else
1415 STRCAT(buf, " <"); /* " < " causes problems on Amiga */
1416 STRCAT(buf, itmp);
1417# endif
1418 if (*p_shq == NUL)
1419 {
1420 p = vim_strchr(cmd, '|');
1421 if (p != NULL)
1422 {
1423 STRCAT(buf, " "); /* insert a space before the '|' for DOS */
1424 STRCAT(buf, p);
1425 }
1426 }
1427 }
1428#endif
1429 if (otmp != NULL)
1430 append_redir(buf, p_srr, otmp);
1431
1432 return buf;
1433}
1434
1435/*
1436 * Append output redirection for file "fname" to the end of string buffer "buf"
1437 * Works with the 'shellredir' and 'shellpipe' options.
1438 * The caller should make sure that there is enough room:
1439 * STRLEN(opt) + STRLEN(fname) + 3
1440 */
1441 void
1442append_redir(buf, opt, fname)
1443 char_u *buf;
1444 char_u *opt;
1445 char_u *fname;
1446{
1447 char_u *p;
1448
1449 buf += STRLEN(buf);
1450 /* find "%s", skipping "%%" */
1451 for (p = opt; (p = vim_strchr(p, '%')) != NULL; ++p)
1452 if (p[1] == 's')
1453 break;
1454 if (p != NULL)
1455 {
1456 *buf = ' '; /* not really needed? Not with sh, ksh or bash */
1457 sprintf((char *)buf + 1, (char *)opt, (char *)fname);
1458 }
1459 else
1460 sprintf((char *)buf,
1461#ifdef FEAT_QUICKFIX
1462# ifndef RISCOS
1463 opt != p_sp ? " %s%s" :
1464# endif
1465 " %s %s",
1466#else
1467# ifndef RISCOS
1468 " %s%s", /* " > %s" causes problems on Amiga */
1469# else
1470 " %s %s", /* But is needed for 'shellpipe' and RISC OS */
1471# endif
1472#endif
1473 (char *)opt, (char *)fname);
1474}
1475
1476#ifdef FEAT_VIMINFO
1477
1478static int no_viminfo __ARGS((void));
1479static int viminfo_errcnt;
1480
1481 static int
1482no_viminfo()
1483{
1484 /* "vim -i NONE" does not read or write a viminfo file */
1485 return (use_viminfo != NULL && STRCMP(use_viminfo, "NONE") == 0);
1486}
1487
1488/*
1489 * Report an error for reading a viminfo file.
1490 * Count the number of errors. When there are more than 10, return TRUE.
1491 */
1492 int
1493viminfo_error(errnum, message, line)
1494 char *errnum;
1495 char *message;
1496 char_u *line;
1497{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001498 vim_snprintf((char *)IObuff, IOSIZE, _("%sviminfo: %s in line: "),
1499 errnum, message);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500 STRNCAT(IObuff, line, IOSIZE - STRLEN(IObuff));
Bram Moolenaar758711c2005-02-02 23:11:38 +00001501 if (IObuff[STRLEN(IObuff) - 1] == '\n')
1502 IObuff[STRLEN(IObuff) - 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 emsg(IObuff);
1504 if (++viminfo_errcnt >= 10)
1505 {
1506 EMSG(_("E136: viminfo: Too many errors, skipping rest of file"));
1507 return TRUE;
1508 }
1509 return FALSE;
1510}
1511
1512/*
1513 * read_viminfo() -- Read the viminfo file. Registers etc. which are already
1514 * set are not over-written unless force is TRUE. -- webb
1515 */
1516 int
1517read_viminfo(file, want_info, want_marks, forceit)
1518 char_u *file;
1519 int want_info;
1520 int want_marks;
1521 int forceit;
1522{
1523 FILE *fp;
1524 char_u *fname;
1525
1526 if (no_viminfo())
1527 return FAIL;
1528
1529 fname = viminfo_filename(file); /* may set to default if NULL */
1530 if (fname == NULL)
1531 return FAIL;
1532 fp = mch_fopen((char *)fname, READBIN);
1533
1534 if (p_verbose > 0)
Bram Moolenaar555b2802005-05-19 21:08:39 +00001535 smsg((char_u *)_("Reading viminfo file \"%s\"%s%s%s"),
1536 fname,
1537 want_info ? _(" info") : "",
1538 want_marks ? _(" marks") : "",
1539 fp == NULL ? _(" FAILED") : "");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540
1541 vim_free(fname);
1542 if (fp == NULL)
1543 return FAIL;
1544
1545 viminfo_errcnt = 0;
1546 do_viminfo(fp, NULL, want_info, want_marks, forceit);
1547
1548 fclose(fp);
1549
1550 return OK;
1551}
1552
1553/*
1554 * write_viminfo() -- Write the viminfo file. The old one is read in first so
1555 * that effectively a merge of current info and old info is done. This allows
1556 * multiple vims to run simultaneously, without losing any marks etc. If
1557 * forceit is TRUE, then the old file is not read in, and only internal info is
1558 * written to the file. -- webb
1559 */
1560 void
1561write_viminfo(file, forceit)
1562 char_u *file;
1563 int forceit;
1564{
1565 char_u *fname;
1566 FILE *fp_in = NULL; /* input viminfo file, if any */
1567 FILE *fp_out = NULL; /* output viminfo file */
1568 char_u *tempname = NULL; /* name of temp viminfo file */
1569 struct stat st_new; /* mch_stat() of potential new file */
1570 char_u *wp;
1571#if defined(UNIX) || defined(VMS)
1572 mode_t umask_save;
1573#endif
1574#ifdef UNIX
1575 int shortname = FALSE; /* use 8.3 file name */
1576 struct stat st_old; /* mch_stat() of existing viminfo file */
1577#endif
1578
1579 if (no_viminfo())
1580 return;
1581
1582 fname = viminfo_filename(file); /* may set to default if NULL */
1583 if (fname == NULL)
1584 return;
1585
1586 fp_in = mch_fopen((char *)fname, READBIN);
1587 if (fp_in == NULL)
1588 {
1589 /* if it does exist, but we can't read it, don't try writing */
1590 if (mch_stat((char *)fname, &st_new) == 0)
1591 goto end;
1592#if defined(UNIX) || defined(VMS)
1593 /*
1594 * For Unix we create the .viminfo non-accessible for others,
1595 * because it may contain text from non-accessible documents.
1596 */
1597 umask_save = umask(077);
1598#endif
1599 fp_out = mch_fopen((char *)fname, WRITEBIN);
1600#if defined(UNIX) || defined(VMS)
1601 (void)umask(umask_save);
1602#endif
1603 }
1604 else
1605 {
1606 /*
1607 * There is an existing viminfo file. Create a temporary file to
1608 * write the new viminfo into, in the same directory as the
1609 * existing viminfo file, which will be renamed later.
1610 */
1611#ifdef UNIX
1612 /*
1613 * For Unix we check the owner of the file. It's not very nice to
1614 * overwrite a user's viminfo file after a "su root", with a
1615 * viminfo file that the user can't read.
1616 */
1617 st_old.st_dev = st_old.st_ino = 0;
1618 st_old.st_mode = 0600;
1619 if (mch_stat((char *)fname, &st_old) == 0 && getuid() &&
1620 !(st_old.st_uid == getuid()
1621 ? (st_old.st_mode & 0200)
1622 : (st_old.st_gid == getgid()
1623 ? (st_old.st_mode & 0020)
1624 : (st_old.st_mode & 0002))))
1625 {
1626 int tt;
1627
1628 /* avoid a wait_return for this message, it's annoying */
1629 tt = msg_didany;
1630 EMSG2(_("E137: Viminfo file is not writable: %s"), fname);
1631 msg_didany = tt;
1632 goto end;
1633 }
1634#endif
1635
1636 /*
1637 * Make tempname.
1638 * May try twice: Once normal and once with shortname set, just in
1639 * case somebody puts his viminfo file in an 8.3 filesystem.
1640 */
1641 for (;;)
1642 {
1643 tempname = buf_modname(
1644#ifdef UNIX
1645 shortname,
1646#else
1647# ifdef SHORT_FNAME
1648 TRUE,
1649# else
1650# ifdef FEAT_GUI_W32
1651 gui_is_win32s(),
1652# else
1653 FALSE,
1654# endif
1655# endif
1656#endif
1657 fname,
1658#ifdef VMS
1659 (char_u *)"-tmp",
1660#else
1661# ifdef RISCOS
1662 (char_u *)"/tmp",
1663# else
1664 (char_u *)".tmp",
1665# endif
1666#endif
1667 FALSE);
1668 if (tempname == NULL) /* out of memory */
1669 break;
1670
1671 /*
1672 * Check if tempfile already exists. Never overwrite an
1673 * existing file!
1674 */
1675 if (mch_stat((char *)tempname, &st_new) == 0)
1676 {
1677#ifdef UNIX
1678 /*
1679 * Check if tempfile is same as original file. May happen
1680 * when modname() gave the same file back. E.g. silly
1681 * link, or file name-length reached. Try again with
1682 * shortname set.
1683 */
1684 if (!shortname && st_new.st_dev == st_old.st_dev &&
1685 st_new.st_ino == st_old.st_ino)
1686 {
1687 vim_free(tempname);
1688 tempname = NULL;
1689 shortname = TRUE;
1690 continue;
1691 }
1692#endif
1693 /*
1694 * Try another name. Change one character, just before
1695 * the extension. This should also work for an 8.3
1696 * file name, when after adding the extension it still is
1697 * the same file as the original.
1698 */
1699 wp = tempname + STRLEN(tempname) - 5;
1700 if (wp < gettail(tempname)) /* empty file name? */
1701 wp = gettail(tempname);
1702 for (*wp = 'z'; mch_stat((char *)tempname, &st_new) == 0;
1703 --*wp)
1704 {
1705 /*
1706 * They all exist? Must be something wrong! Don't
1707 * write the viminfo file then.
1708 */
1709 if (*wp == 'a')
1710 {
1711 vim_free(tempname);
1712 tempname = NULL;
1713 break;
1714 }
1715 }
1716 }
1717 break;
1718 }
1719
1720 if (tempname != NULL)
1721 {
1722 fp_out = mch_fopen((char *)tempname, WRITEBIN);
1723
1724 /*
1725 * If we can't create in the same directory, try creating a
1726 * "normal" temp file.
1727 */
1728 if (fp_out == NULL)
1729 {
1730 vim_free(tempname);
1731 if ((tempname = vim_tempname('o')) != NULL)
1732 fp_out = mch_fopen((char *)tempname, WRITEBIN);
1733 }
1734#ifdef UNIX
1735 /*
1736 * Set file protection same as original file, but strip s-bit
1737 * and make sure the owner can read/write it.
1738 */
1739 if (fp_out != NULL)
1740 {
1741 (void)mch_setperm(tempname,
1742 (long)((st_old.st_mode & 0777) | 0600));
1743 /* this only works for root: */
1744 (void)chown((char *)tempname, st_old.st_uid, st_old.st_gid);
1745 }
1746#endif
1747 }
1748 }
1749
1750 /*
1751 * Check if the new viminfo file can be written to.
1752 */
1753 if (fp_out == NULL)
1754 {
1755 EMSG2(_("E138: Can't write viminfo file %s!"),
1756 (fp_in == NULL || tempname == NUL) ? fname : tempname);
1757 if (fp_in != NULL)
1758 fclose(fp_in);
1759 goto end;
1760 }
1761
1762 if (p_verbose > 0)
Bram Moolenaar555b2802005-05-19 21:08:39 +00001763 smsg((char_u *)_("Writing viminfo file \"%s\""), fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764
1765 viminfo_errcnt = 0;
1766 do_viminfo(fp_in, fp_out, !forceit, !forceit, FALSE);
1767
1768 fclose(fp_out); /* errors are ignored !? */
1769 if (fp_in != NULL)
1770 {
1771 fclose(fp_in);
1772 /*
1773 * In case of an error, don't overwrite the original viminfo file.
1774 */
1775 if (viminfo_errcnt || vim_rename(tempname, fname) == -1)
1776 mch_remove(tempname);
1777 }
1778end:
1779 vim_free(fname);
1780 vim_free(tempname);
1781}
1782
1783/*
1784 * Get the viminfo file name to use.
1785 * If "file" is given and not empty, use it (has already been expanded by
1786 * cmdline functions).
1787 * Otherwise use "-i file_name", value from 'viminfo' or the default, and
1788 * expand environment variables.
1789 * Returns an allocated string. NULL when out of memory.
1790 */
1791 static char_u *
1792viminfo_filename(file)
1793 char_u *file;
1794{
1795 if (file == NULL || *file == NUL)
1796 {
1797 if (use_viminfo != NULL)
1798 file = use_viminfo;
1799 else if ((file = find_viminfo_parameter('n')) == NULL || *file == NUL)
1800 {
1801#ifdef VIMINFO_FILE2
1802 /* don't use $HOME when not defined (turned into "c:/"!). */
1803# ifdef VMS
1804 if (mch_getenv((char_u *)"SYS$LOGIN") == NULL)
1805# else
1806 if (mch_getenv((char_u *)"HOME") == NULL)
1807# endif
1808 {
1809 /* don't use $VIM when not available. */
1810 expand_env((char_u *)"$VIM", NameBuff, MAXPATHL);
1811 if (STRCMP("$VIM", NameBuff) != 0) /* $VIM was expanded */
1812 file = (char_u *)VIMINFO_FILE2;
1813 else
1814 file = (char_u *)VIMINFO_FILE;
1815 }
1816 else
1817#endif
1818 file = (char_u *)VIMINFO_FILE;
1819 }
1820 expand_env(file, NameBuff, MAXPATHL);
1821 file = NameBuff;
1822 }
1823 return vim_strsave(file);
1824}
1825
1826/*
1827 * do_viminfo() -- Should only be called from read_viminfo() & write_viminfo().
1828 */
1829 static void
1830do_viminfo(fp_in, fp_out, want_info, want_marks, force_read)
1831 FILE *fp_in;
1832 FILE *fp_out;
1833 int want_info;
1834 int want_marks;
1835 int force_read;
1836{
1837 int count = 0;
1838 int eof = FALSE;
1839 vir_T vir;
1840
1841 if ((vir.vir_line = alloc(LSIZE)) == NULL)
1842 return;
1843 vir.vir_fd = fp_in;
1844#ifdef FEAT_MBYTE
1845 vir.vir_conv.vc_type = CONV_NONE;
1846#endif
1847
1848 if (fp_in != NULL)
1849 {
1850 if (want_info)
1851 eof = read_viminfo_up_to_marks(&vir, force_read, fp_out != NULL);
1852 else
1853 /* Skip info, find start of marks */
1854 while (!(eof = viminfo_readline(&vir))
1855 && vir.vir_line[0] != '>')
1856 ;
1857 }
1858 if (fp_out != NULL)
1859 {
1860 /* Write the info: */
1861 fprintf(fp_out, _("# This viminfo file was generated by Vim %s.\n"),
1862 VIM_VERSION_MEDIUM);
1863 fprintf(fp_out, _("# You may edit it if you're careful!\n\n"));
1864#ifdef FEAT_MBYTE
1865 fprintf(fp_out, _("# Value of 'encoding' when this file was written\n"));
1866 fprintf(fp_out, "*encoding=%s\n\n", p_enc);
1867#endif
1868 write_viminfo_search_pattern(fp_out);
1869 write_viminfo_sub_string(fp_out);
1870#ifdef FEAT_CMDHIST
1871 write_viminfo_history(fp_out);
1872#endif
1873 write_viminfo_registers(fp_out);
1874#ifdef FEAT_EVAL
1875 write_viminfo_varlist(fp_out);
1876#endif
1877 write_viminfo_filemarks(fp_out);
1878 write_viminfo_bufferlist(fp_out);
1879 count = write_viminfo_marks(fp_out);
1880 }
1881 if (fp_in != NULL && want_marks)
1882 copy_viminfo_marks(&vir, fp_out, count, eof);
1883
1884 vim_free(vir.vir_line);
1885#ifdef FEAT_MBYTE
1886 if (vir.vir_conv.vc_type != CONV_NONE)
1887 convert_setup(&vir.vir_conv, NULL, NULL);
1888#endif
1889}
1890
1891/*
1892 * read_viminfo_up_to_marks() -- Only called from do_viminfo(). Reads in the
1893 * first part of the viminfo file which contains everything but the marks that
1894 * are local to a file. Returns TRUE when end-of-file is reached. -- webb
1895 */
1896 static int
1897read_viminfo_up_to_marks(virp, forceit, writing)
1898 vir_T *virp;
1899 int forceit;
1900 int writing;
1901{
1902 int eof;
1903 buf_T *buf;
1904
1905#ifdef FEAT_CMDHIST
1906 prepare_viminfo_history(forceit ? 9999 : 0);
1907#endif
1908 eof = viminfo_readline(virp);
1909 while (!eof && virp->vir_line[0] != '>')
1910 {
1911 switch (virp->vir_line[0])
1912 {
1913 /* Characters reserved for future expansion, ignored now */
1914 case '+': /* "+40 /path/dir file", for running vim without args */
1915 case '|': /* to be defined */
1916 case '^': /* to be defined */
1917 case '<': /* long line - ignored */
1918 /* A comment or empty line. */
1919 case NUL:
1920 case '\r':
1921 case '\n':
1922 case '#':
1923 eof = viminfo_readline(virp);
1924 break;
1925 case '*': /* "*encoding=value" */
1926 eof = viminfo_encoding(virp);
1927 break;
1928 case '!': /* global variable */
1929#ifdef FEAT_EVAL
1930 eof = read_viminfo_varlist(virp, writing);
1931#else
1932 eof = viminfo_readline(virp);
1933#endif
1934 break;
1935 case '%': /* entry for buffer list */
1936 eof = read_viminfo_bufferlist(virp, writing);
1937 break;
1938 case '"':
1939 eof = read_viminfo_register(virp, forceit);
1940 break;
1941 case '/': /* Search string */
1942 case '&': /* Substitute search string */
1943 case '~': /* Last search string, followed by '/' or '&' */
1944 eof = read_viminfo_search_pattern(virp, forceit);
1945 break;
1946 case '$':
1947 eof = read_viminfo_sub_string(virp, forceit);
1948 break;
1949 case ':':
1950 case '?':
1951 case '=':
1952 case '@':
1953#ifdef FEAT_CMDHIST
1954 eof = read_viminfo_history(virp);
1955#else
1956 eof = viminfo_readline(virp);
1957#endif
1958 break;
1959 case '-':
1960 case '\'':
1961 eof = read_viminfo_filemark(virp, forceit);
1962 break;
1963 default:
1964 if (viminfo_error("E575: ", _("Illegal starting char"),
1965 virp->vir_line))
1966 eof = TRUE;
1967 else
1968 eof = viminfo_readline(virp);
1969 break;
1970 }
1971 }
1972
1973#ifdef FEAT_CMDHIST
1974 /* Finish reading history items. */
1975 finish_viminfo_history();
1976#endif
1977
1978 /* Change file names to buffer numbers for fmarks. */
1979 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1980 fmarks_check_names(buf);
1981
1982 return eof;
1983}
1984
1985/*
1986 * Compare the 'encoding' value in the viminfo file with the current value of
1987 * 'encoding'. If different and the 'c' flag is in 'viminfo', setup for
1988 * conversion of text with iconv() in viminfo_readstring().
1989 */
1990 static int
1991viminfo_encoding(virp)
1992 vir_T *virp;
1993{
1994#ifdef FEAT_MBYTE
1995 char_u *p;
1996 int i;
1997
1998 if (get_viminfo_parameter('c') != 0)
1999 {
2000 p = vim_strchr(virp->vir_line, '=');
2001 if (p != NULL)
2002 {
2003 /* remove trailing newline */
2004 ++p;
2005 for (i = 0; vim_isprintc(p[i]); ++i)
2006 ;
2007 p[i] = NUL;
2008
2009 convert_setup(&virp->vir_conv, p, p_enc);
2010 }
2011 }
2012#endif
2013 return viminfo_readline(virp);
2014}
2015
2016/*
2017 * Read a line from the viminfo file.
2018 * Returns TRUE for end-of-file;
2019 */
2020 int
2021viminfo_readline(virp)
2022 vir_T *virp;
2023{
2024 return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
2025}
2026
2027/*
2028 * check string read from viminfo file
2029 * remove '\n' at the end of the line
2030 * - replace CTRL-V CTRL-V with CTRL-V
2031 * - replace CTRL-V 'n' with '\n'
2032 *
2033 * Check for a long line as written by viminfo_writestring().
2034 *
2035 * Return the string in allocated memory (NULL when out of memory).
2036 */
2037/*ARGSUSED*/
2038 char_u *
2039viminfo_readstring(virp, off, convert)
2040 vir_T *virp;
2041 int off; /* offset for virp->vir_line */
2042 int convert; /* convert the string */
2043{
2044 char_u *retval;
2045 char_u *s, *d;
2046 long len;
2047
2048 if (virp->vir_line[off] == Ctrl_V && vim_isdigit(virp->vir_line[off + 1]))
2049 {
2050 len = atol((char *)virp->vir_line + off + 1);
2051 retval = lalloc(len, TRUE);
2052 if (retval == NULL)
2053 {
2054 /* Line too long? File messed up? Skip next line. */
2055 (void)vim_fgets(virp->vir_line, 10, virp->vir_fd);
2056 return NULL;
2057 }
2058 (void)vim_fgets(retval, (int)len, virp->vir_fd);
2059 s = retval + 1; /* Skip the leading '<' */
2060 }
2061 else
2062 {
2063 retval = vim_strsave(virp->vir_line + off);
2064 if (retval == NULL)
2065 return NULL;
2066 s = retval;
2067 }
2068
2069 /* Change CTRL-V CTRL-V to CTRL-V and CTRL-V n to \n in-place. */
2070 d = retval;
2071 while (*s != NUL && *s != '\n')
2072 {
2073 if (s[0] == Ctrl_V && s[1] != NUL)
2074 {
2075 if (s[1] == 'n')
2076 *d++ = '\n';
2077 else
2078 *d++ = Ctrl_V;
2079 s += 2;
2080 }
2081 else
2082 *d++ = *s++;
2083 }
2084 *d = NUL;
2085
2086#ifdef FEAT_MBYTE
2087 if (convert && virp->vir_conv.vc_type != CONV_NONE && *retval != NUL)
2088 {
2089 d = string_convert(&virp->vir_conv, retval, NULL);
2090 if (d != NULL)
2091 {
2092 vim_free(retval);
2093 retval = d;
2094 }
2095 }
2096#endif
2097
2098 return retval;
2099}
2100
2101/*
2102 * write string to viminfo file
2103 * - replace CTRL-V with CTRL-V CTRL-V
2104 * - replace '\n' with CTRL-V 'n'
2105 * - add a '\n' at the end
2106 *
2107 * For a long line:
2108 * - write " CTRL-V <length> \n " in first line
2109 * - write " < <string> \n " in second line
2110 */
2111 void
2112viminfo_writestring(fd, p)
2113 FILE *fd;
2114 char_u *p;
2115{
2116 int c;
2117 char_u *s;
2118 int len = 0;
2119
2120 for (s = p; *s != NUL; ++s)
2121 {
2122 if (*s == Ctrl_V || *s == '\n')
2123 ++len;
2124 ++len;
2125 }
2126
2127 /* If the string will be too long, write its length and put it in the next
2128 * line. Take into account that some room is needed for what comes before
2129 * the string (e.g., variable name). Add something to the length for the
2130 * '<', NL and trailing NUL. */
2131 if (len > LSIZE / 2)
2132 fprintf(fd, IF_EB("\026%d\n<", CTRL_V_STR "%d\n<"), len + 3);
2133
2134 while ((c = *p++) != NUL)
2135 {
2136 if (c == Ctrl_V || c == '\n')
2137 {
2138 putc(Ctrl_V, fd);
2139 if (c == '\n')
2140 c = 'n';
2141 }
2142 putc(c, fd);
2143 }
2144 putc('\n', fd);
2145}
2146#endif /* FEAT_VIMINFO */
2147
2148/*
2149 * Implementation of ":fixdel", also used by get_stty().
2150 * <BS> resulting <Del>
2151 * ^? ^H
2152 * not ^? ^?
2153 */
2154/*ARGSUSED*/
2155 void
2156do_fixdel(eap)
2157 exarg_T *eap;
2158{
2159 char_u *p;
2160
2161 p = find_termcode((char_u *)"kb");
2162 add_termcode((char_u *)"kD", p != NULL
2163 && *p == DEL ? (char_u *)CTRL_H_STR : DEL_STR, FALSE);
2164}
2165
2166 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002167print_line_no_prefix(lnum, use_number, list)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002168 linenr_T lnum;
2169 int use_number;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002170 int list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171{
Bram Moolenaar592e0a22004-07-03 16:05:59 +00002172 char_u numbuf[30];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173
2174 if (curwin->w_p_nu || use_number)
2175 {
Bram Moolenaar592e0a22004-07-03 16:05:59 +00002176 sprintf((char *)numbuf, "%*ld ", number_width(curwin), (long)lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 msg_puts_attr(numbuf, hl_attr(HLF_N)); /* Highlight line nrs */
2178 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002179 msg_prt_line(ml_get(lnum), list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180}
2181
2182/*
2183 * Print a text line. Also in silent mode ("ex -s").
2184 */
2185 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002186print_line(lnum, use_number, list)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187 linenr_T lnum;
2188 int use_number;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002189 int list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190{
2191 int save_silent = silent_mode;
2192
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 msg_start();
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002194 silent_mode = FALSE;
2195 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
2196 print_line_no_prefix(lnum, use_number, list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 if (save_silent)
2198 {
2199 msg_putchar('\n');
2200 cursor_on(); /* msg_start() switches it off */
2201 out_flush();
2202 silent_mode = save_silent;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002203 info_message = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 }
2205}
2206
2207/*
2208 * ":file[!] [fname]".
2209 */
2210 void
2211ex_file(eap)
2212 exarg_T *eap;
2213{
2214 char_u *fname, *sfname, *xfname;
2215 buf_T *buf;
2216
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002217 /* ":0file" removes the file name. Check for illegal uses ":3file",
2218 * "0file name", etc. */
2219 if (eap->addr_count > 0
2220 && (*eap->arg != NUL
2221 || eap->line2 > 0
2222 || eap->addr_count > 1))
2223 {
2224 EMSG(_(e_invarg));
2225 return;
2226 }
2227
2228 if (*eap->arg != NUL || eap->addr_count == 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 {
2230#ifdef FEAT_AUTOCMD
2231 buf = curbuf;
2232 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
2233 /* buffer changed, don't change name now */
2234 if (buf != curbuf)
2235 return;
2236# ifdef FEAT_EVAL
2237 if (aborting()) /* autocmds may abort script processing */
2238 return;
2239# endif
2240#endif
2241 /*
2242 * The name of the current buffer will be changed.
2243 * A new (unlisted) buffer entry needs to be made to hold the old file
2244 * name, which will become the alternate file name.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002245 * But don't set the alternate file name if the buffer didn't have a
2246 * name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 */
2248 fname = curbuf->b_ffname;
2249 sfname = curbuf->b_sfname;
2250 xfname = curbuf->b_fname;
2251 curbuf->b_ffname = NULL;
2252 curbuf->b_sfname = NULL;
2253 if (setfname(curbuf, eap->arg, NULL, TRUE) == FAIL)
2254 {
2255 curbuf->b_ffname = fname;
2256 curbuf->b_sfname = sfname;
2257 return;
2258 }
2259 curbuf->b_flags |= BF_NOTEDITED;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002260 if (xfname != NULL && *xfname != NUL)
2261 {
2262 buf = buflist_new(fname, xfname, curwin->w_cursor.lnum, 0);
2263 if (buf != NULL && !cmdmod.keepalt)
2264 curwin->w_alt_fnum = buf->b_fnum;
2265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 vim_free(fname);
2267 vim_free(sfname);
2268#ifdef FEAT_AUTOCMD
2269 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
2270#endif
2271 }
2272 /* print full file name if :cd used */
2273 fileinfo(FALSE, FALSE, eap->forceit);
2274}
2275
2276/*
2277 * ":update".
2278 */
2279 void
2280ex_update(eap)
2281 exarg_T *eap;
2282{
2283 if (curbufIsChanged())
2284 (void)do_write(eap);
2285}
2286
2287/*
2288 * ":write" and ":saveas".
2289 */
2290 void
2291ex_write(eap)
2292 exarg_T *eap;
2293{
2294 if (eap->usefilter) /* input lines to shell command */
2295 do_bang(1, eap, FALSE, TRUE, FALSE);
2296 else
2297 (void)do_write(eap);
2298}
2299
2300/*
2301 * write current buffer to file 'eap->arg'
2302 * if 'eap->append' is TRUE, append to the file
2303 *
2304 * if *eap->arg == NUL write to current file
2305 *
2306 * return FAIL for failure, OK otherwise
2307 */
2308 int
2309do_write(eap)
2310 exarg_T *eap;
2311{
2312 int other;
2313 char_u *fname = NULL; /* init to shut up gcc */
2314 char_u *ffname;
2315 int retval = FAIL;
2316 char_u *free_fname = NULL;
2317#ifdef FEAT_BROWSE
2318 char_u *browse_file = NULL;
2319#endif
2320 buf_T *alt_buf = NULL;
2321
2322 if (not_writing()) /* check 'write' option */
2323 return FAIL;
2324
2325 ffname = eap->arg;
2326#ifdef FEAT_BROWSE
2327 if (cmdmod.browse)
2328 {
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002329 browse_file = do_browse(BROWSE_SAVE, (char_u *)_("Save As"), ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 NULL, NULL, NULL, curbuf);
2331 if (browse_file == NULL)
2332 goto theend;
2333 ffname = browse_file;
2334 }
2335#endif
2336 if (*ffname == NUL)
2337 {
2338 if (eap->cmdidx == CMD_saveas)
2339 {
2340 EMSG(_(e_argreq));
2341 goto theend;
2342 }
2343 other = FALSE;
2344 }
2345 else
2346 {
2347 fname = ffname;
2348 free_fname = fix_fname(ffname);
2349 /*
2350 * When out-of-memory, keep unexpanded file name, because we MUST be
2351 * able to write the file in this situation.
2352 */
2353 if (free_fname != NULL)
2354 ffname = free_fname;
2355 other = otherfile(ffname);
2356 }
2357
2358 /*
2359 * If we have a new file, put its name in the list of alternate file names.
2360 */
2361 if (other)
2362 {
2363 if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL
2364 || eap->cmdidx == CMD_saveas)
2365 alt_buf = setaltfname(ffname, fname, (linenr_T)1);
2366 else
2367 alt_buf = buflist_findname(ffname);
2368 if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL)
2369 {
2370 /* Overwriting a file that is loaded in another buffer is not a
2371 * good idea. */
2372 EMSG(_("E139: File is loaded in another buffer"));
2373 goto theend;
2374 }
2375 }
2376
2377 /*
2378 * Writing to the current file is not allowed in readonly mode
2379 * and a file name is required.
2380 * "nofile" and "nowrite" buffers cannot be written implicitly either.
2381 */
2382 if (!other && (
2383#ifdef FEAT_QUICKFIX
2384 bt_dontwrite_msg(curbuf) ||
2385#endif
2386 check_fname() == FAIL || check_readonly(&eap->forceit, curbuf)))
2387 goto theend;
2388
2389 if (!other)
2390 {
2391 ffname = curbuf->b_ffname;
2392 fname = curbuf->b_fname;
2393 /*
2394 * Not writing the whole file is only allowed with '!'.
2395 */
2396 if ( (eap->line1 != 1
2397 || eap->line2 != curbuf->b_ml.ml_line_count)
2398 && !eap->forceit
2399 && !eap->append
2400 && !p_wa)
2401 {
2402#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2403 if (p_confirm || cmdmod.confirm)
2404 {
2405 if (vim_dialog_yesno(VIM_QUESTION, NULL,
2406 (char_u *)_("Write partial file?"), 2) != VIM_YES)
2407 goto theend;
2408 eap->forceit = TRUE;
2409 }
2410 else
2411#endif
2412 {
2413 EMSG(_("E140: Use ! to write partial buffer"));
2414 goto theend;
2415 }
2416 }
2417 }
2418
2419 if (check_overwrite(eap, curbuf, fname, ffname, other) == OK)
2420 {
2421 if (eap->cmdidx == CMD_saveas && alt_buf != NULL)
2422 {
2423#ifdef FEAT_AUTOCMD
2424 buf_T *was_curbuf = curbuf;
2425
2426 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
Bram Moolenaar269ec652004-07-29 08:43:53 +00002427 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428# ifdef FEAT_EVAL
2429 if (curbuf != was_curbuf || aborting())
2430# else
2431 if (curbuf != was_curbuf)
2432# endif
2433 {
2434 /* buffer changed, don't change name now */
2435 retval = FAIL;
2436 goto theend;
2437 }
2438#endif
2439 /* Exchange the file names for the current and the alternate
2440 * buffer. This makes it look like we are now editing the buffer
2441 * under the new name. Must be done before buf_write(), because
2442 * if there is no file name and 'cpo' contains 'F', it will set
2443 * the file name. */
2444 fname = alt_buf->b_fname;
2445 alt_buf->b_fname = curbuf->b_fname;
2446 curbuf->b_fname = fname;
2447 fname = alt_buf->b_ffname;
2448 alt_buf->b_ffname = curbuf->b_ffname;
2449 curbuf->b_ffname = fname;
2450 fname = alt_buf->b_sfname;
2451 alt_buf->b_sfname = curbuf->b_sfname;
2452 curbuf->b_sfname = fname;
2453 buf_name_changed(curbuf);
2454#ifdef FEAT_AUTOCMD
2455 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
Bram Moolenaar269ec652004-07-29 08:43:53 +00002456 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, alt_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 if (!alt_buf->b_p_bl)
2458 {
2459 alt_buf->b_p_bl = TRUE;
2460 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, alt_buf);
2461 }
2462# ifdef FEAT_EVAL
2463 if (curbuf != was_curbuf || aborting())
2464# else
2465 if (curbuf != was_curbuf)
2466# endif
2467 {
2468 /* buffer changed, don't write the file */
2469 retval = FAIL;
2470 goto theend;
2471 }
2472#endif
2473 }
2474
2475 retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2,
2476 eap, eap->append, eap->forceit, TRUE, FALSE);
2477 }
2478
2479theend:
2480#ifdef FEAT_BROWSE
2481 vim_free(browse_file);
2482#endif
2483 vim_free(free_fname);
2484 return retval;
2485}
2486
2487/*
2488 * Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED,
2489 * BF_NEW or BF_READERR, check for overwriting current file.
2490 * May set eap->forceit if a dialog says it's OK to overwrite.
2491 * Return OK if it's OK, FAIL if it is not.
2492 */
2493/*ARGSUSED*/
2494 static int
2495check_overwrite(eap, buf, fname, ffname, other)
2496 exarg_T *eap;
2497 buf_T *buf;
2498 char_u *fname; /* file name to be used (can differ from
2499 buf->ffname) */
2500 char_u *ffname; /* full path version of fname */
2501 int other; /* writing under other name */
2502{
2503 /*
2504 * write to other file or b_flags set or not writing the whole file:
2505 * overwriting only allowed with '!'
2506 */
2507 if ( (other
2508 || (buf->b_flags & BF_NOTEDITED)
2509 || ((buf->b_flags & BF_NEW)
2510 && vim_strchr(p_cpo, CPO_OVERNEW) == NULL)
2511 || (buf->b_flags & BF_READERR))
2512 && !eap->forceit
2513 && !eap->append
2514 && !p_wa
2515 && vim_fexists(ffname))
2516 {
2517#ifdef UNIX
2518 /* with UNIX it is possible to open a directory */
2519 if (mch_isdir(ffname))
2520 {
2521 EMSG2(_(e_isadir2), ffname);
2522 return FAIL;
2523 }
2524#endif
2525#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2526 if (p_confirm || cmdmod.confirm)
2527 {
2528 char_u buff[IOSIZE];
2529
2530 dialog_msg(buff, _("Overwrite existing file \"%.*s\"?"), fname);
2531 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES)
2532 return FAIL;
2533 eap->forceit = TRUE;
2534 }
2535 else
2536#endif
2537 {
2538 EMSG(_(e_exists));
2539 return FAIL;
2540 }
2541 }
2542 return OK;
2543}
2544
2545/*
2546 * Handle ":wnext", ":wNext" and ":wprevious" commands.
2547 */
2548 void
2549ex_wnext(eap)
2550 exarg_T *eap;
2551{
2552 int i;
2553
2554 if (eap->cmd[1] == 'n')
2555 i = curwin->w_arg_idx + (int)eap->line2;
2556 else
2557 i = curwin->w_arg_idx - (int)eap->line2;
2558 eap->line1 = 1;
2559 eap->line2 = curbuf->b_ml.ml_line_count;
2560 if (do_write(eap) != FAIL)
2561 do_argfile(eap, i);
2562}
2563
2564/*
2565 * ":wall", ":wqall" and ":xall": Write all changed files (and exit).
2566 */
2567 void
2568do_wqall(eap)
2569 exarg_T *eap;
2570{
2571 buf_T *buf;
2572 int error = 0;
2573 int save_forceit = eap->forceit;
2574
2575 if (eap->cmdidx == CMD_xall || eap->cmdidx == CMD_wqall)
2576 exiting = TRUE;
2577
2578 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2579 {
2580 if (bufIsChanged(buf))
2581 {
2582 /*
2583 * Check if there is a reason the buffer cannot be written:
2584 * 1. if the 'write' option is set
2585 * 2. if there is no file name (even after browsing)
2586 * 3. if the 'readonly' is set (even after a dialog)
2587 * 4. if overwriting is allowed (even after a dialog)
2588 */
2589 if (not_writing())
2590 {
2591 ++error;
2592 break;
2593 }
2594#ifdef FEAT_BROWSE
2595 /* ":browse wall": ask for file name if there isn't one */
2596 if (buf->b_ffname == NULL && cmdmod.browse)
2597 browse_save_fname(buf);
2598#endif
2599 if (buf->b_ffname == NULL)
2600 {
2601 EMSGN(_("E141: No file name for buffer %ld"), (long)buf->b_fnum);
2602 ++error;
2603 }
2604 else if (check_readonly(&eap->forceit, buf)
2605 || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname,
2606 FALSE) == FAIL)
2607 {
2608 ++error;
2609 }
2610 else
2611 {
2612 if (buf_write_all(buf, eap->forceit) == FAIL)
2613 ++error;
2614#ifdef FEAT_AUTOCMD
2615 /* an autocommand may have deleted the buffer */
2616 if (!buf_valid(buf))
2617 buf = firstbuf;
2618#endif
2619 }
2620 eap->forceit = save_forceit; /* check_overwrite() may set it */
2621 }
2622 }
2623 if (exiting)
2624 {
2625 if (!error)
2626 getout(0); /* exit Vim */
2627 not_exiting();
2628 }
2629}
2630
2631/*
2632 * Check the 'write' option.
2633 * Return TRUE and give a message when it's not st.
2634 */
2635 int
2636not_writing()
2637{
2638 if (p_write)
2639 return FALSE;
2640 EMSG(_("E142: File not written: Writing is disabled by 'write' option"));
2641 return TRUE;
2642}
2643
2644/*
2645 * Check if a buffer is read-only. Ask for overruling in a dialog.
2646 * Return TRUE and give an error message when the buffer is readonly.
2647 */
2648 static int
2649check_readonly(forceit, buf)
2650 int *forceit;
2651 buf_T *buf;
2652{
2653 if (!*forceit && buf->b_p_ro)
2654 {
2655#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2656 if ((p_confirm || cmdmod.confirm) && buf->b_fname != NULL)
2657 {
2658 char_u buff[IOSIZE];
2659
2660 dialog_msg(buff, _("'readonly' option is set for \"%.*s\".\nDo you wish to write anyway?"),
2661 buf->b_fname);
2662
2663 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES)
2664 {
2665 /* Set forceit, to force the writing of a readonly file */
2666 *forceit = TRUE;
2667 return FALSE;
2668 }
2669 else
2670 return TRUE;
2671 }
2672 else
2673#endif
2674 EMSG(_(e_readonly));
2675 return TRUE;
2676 }
2677 return FALSE;
2678}
2679
2680/*
2681 * try to abandon current file and edit a new or existing file
2682 * 'fnum' is the number of the file, if zero use ffname/sfname
2683 *
2684 * return 1 for "normal" error, 2 for "not written" error, 0 for success
2685 * -1 for succesfully opening another file
2686 * 'lnum' is the line number for the cursor in the new file (if non-zero).
2687 */
2688 int
2689getfile(fnum, ffname, sfname, setpm, lnum, forceit)
2690 int fnum;
2691 char_u *ffname;
2692 char_u *sfname;
2693 int setpm;
2694 linenr_T lnum;
2695 int forceit;
2696{
2697 int other;
2698 int retval;
2699 char_u *free_me = NULL;
2700
2701#ifdef FEAT_CMDWIN
2702 if (cmdwin_type != 0)
2703 return 1;
2704#endif
2705
2706 if (fnum == 0)
2707 {
2708 /* make ffname full path, set sfname */
2709 fname_expand(curbuf, &ffname, &sfname);
2710 other = otherfile(ffname);
2711 free_me = ffname; /* has been allocated, free() later */
2712 }
2713 else
2714 other = (fnum != curbuf->b_fnum);
2715
2716 if (other)
2717 ++no_wait_return; /* don't wait for autowrite message */
2718 if (other && !forceit && curbuf->b_nwindows == 1 && !P_HID(curbuf)
2719 && curbufIsChanged() && autowrite(curbuf, forceit) == FAIL)
2720 {
2721#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2722 if (p_confirm && p_write)
2723 dialog_changed(curbuf, FALSE);
2724 if (curbufIsChanged())
2725#endif
2726 {
2727 if (other)
2728 --no_wait_return;
2729 EMSG(_(e_nowrtmsg));
2730 retval = 2; /* file has been changed */
2731 goto theend;
2732 }
2733 }
2734 if (other)
2735 --no_wait_return;
2736 if (setpm)
2737 setpcmark();
2738 if (!other)
2739 {
2740 if (lnum != 0)
2741 curwin->w_cursor.lnum = lnum;
2742 check_cursor_lnum();
2743 beginline(BL_SOL | BL_FIX);
2744 retval = 0; /* it's in the same file */
2745 }
2746 else if (do_ecmd(fnum, ffname, sfname, NULL, lnum,
2747 (P_HID(curbuf) ? ECMD_HIDE : 0) + (forceit ? ECMD_FORCEIT : 0)) == OK)
2748 retval = -1; /* opened another file */
2749 else
2750 retval = 1; /* error encountered */
2751
2752theend:
2753 vim_free(free_me);
2754 return retval;
2755}
2756
2757/*
2758 * start editing a new file
2759 *
2760 * fnum: file number; if zero use ffname/sfname
2761 * ffname: the file name
2762 * - full path if sfname used,
2763 * - any file name if sfname is NULL
2764 * - empty string to re-edit with the same file name (but may be
2765 * in a different directory)
2766 * - NULL to start an empty buffer
2767 * sfname: the short file name (or NULL)
2768 * eap: contains the command to be executed after loading the file and
2769 * forced 'ff' and 'fenc'
2770 * newlnum: if > 0: put cursor on this line number (if possible)
2771 * if ECMD_LASTL: use last position in loaded file
2772 * if ECMD_LAST: use last position in all files
2773 * if ECMD_ONE: use first line
2774 * flags:
2775 * ECMD_HIDE: if TRUE don't free the current buffer
2776 * ECMD_SET_HELP: set b_help flag of (new) buffer before opening file
2777 * ECMD_OLDBUF: use existing buffer if it exists
2778 * ECMD_FORCEIT: ! used for Ex command
2779 * ECMD_ADDBUF: don't edit, just add to buffer list
2780 *
2781 * return FAIL for failure, OK otherwise
2782 */
2783 int
2784do_ecmd(fnum, ffname, sfname, eap, newlnum, flags)
2785 int fnum;
2786 char_u *ffname;
2787 char_u *sfname;
2788 exarg_T *eap; /* can be NULL! */
2789 linenr_T newlnum;
2790 int flags;
2791{
2792 int other_file; /* TRUE if editing another file */
2793 int oldbuf; /* TRUE if using existing buffer */
2794#ifdef FEAT_AUTOCMD
2795 int auto_buf = FALSE; /* TRUE if autocommands brought us
2796 into the buffer unexpectedly */
2797 char_u *new_name = NULL;
2798#endif
2799 buf_T *buf;
2800#if defined(FEAT_AUTOCMD) || defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2801 buf_T *old_curbuf = curbuf;
2802#endif
2803 char_u *free_fname = NULL;
2804#ifdef FEAT_BROWSE
2805 char_u *browse_file = NULL;
2806#endif
2807 int retval = FAIL;
2808 long n;
2809 linenr_T lnum;
2810 linenr_T topline = 0;
2811 int newcol = -1;
2812 int solcol = -1;
2813 pos_T *pos;
2814#ifdef FEAT_SUN_WORKSHOP
2815 char_u *cp;
2816#endif
2817 char_u *command = NULL;
2818
2819 if (eap != NULL)
2820 command = eap->do_ecmd_cmd;
2821
2822 if (fnum != 0)
2823 {
2824 if (fnum == curbuf->b_fnum) /* file is already being edited */
2825 return OK; /* nothing to do */
2826 other_file = TRUE;
2827 }
2828 else
2829 {
2830#ifdef FEAT_BROWSE
2831 if (cmdmod.browse)
2832 {
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002833 browse_file = do_browse(0, (char_u *)_("Edit File"), ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 NULL, NULL, NULL, curbuf);
2835 if (browse_file == NULL)
2836 goto theend;
2837 ffname = browse_file;
2838 }
2839#endif
2840 /* if no short name given, use ffname for short name */
2841 if (sfname == NULL)
2842 sfname = ffname;
2843#ifdef USE_FNAME_CASE
2844# ifdef USE_LONG_FNAME
2845 if (USE_LONG_FNAME)
2846# endif
2847 fname_case(sfname, 0); /* set correct case for short file name */
2848#endif
2849
2850#ifdef FEAT_LISTCMDS
2851 if ((flags & ECMD_ADDBUF) && (ffname == NULL || *ffname == NUL))
2852 goto theend;
2853#endif
2854
2855 if (ffname == NULL)
2856 other_file = TRUE;
2857 /* there is no file name */
2858 else if (*ffname == NUL && curbuf->b_ffname == NULL)
2859 other_file = FALSE;
2860 else
2861 {
2862 if (*ffname == NUL) /* re-edit with same file name */
2863 {
2864 ffname = curbuf->b_ffname;
2865 sfname = curbuf->b_fname;
2866 }
2867 free_fname = fix_fname(ffname); /* may expand to full path name */
2868 if (free_fname != NULL)
2869 ffname = free_fname;
2870 other_file = otherfile(ffname);
2871#ifdef FEAT_SUN_WORKSHOP
2872 if (usingSunWorkShop && p_acd
2873 && (cp = vim_strrchr(sfname, '/')) != NULL)
2874 sfname = ++cp;
2875#endif
2876 }
2877 }
2878
2879 /*
2880 * if the file was changed we may not be allowed to abandon it
2881 * - if we are going to re-edit the same file
2882 * - or if we are the only window on this file and if ECMD_HIDE is FALSE
2883 */
2884 if ( ((!other_file && !(flags & ECMD_OLDBUF))
2885 || (curbuf->b_nwindows == 1
2886 && !(flags & (ECMD_HIDE | ECMD_ADDBUF))))
2887 && check_changed(curbuf, p_awa, !other_file,
2888 (flags & ECMD_FORCEIT), FALSE))
2889 {
2890 if (fnum == 0 && other_file && ffname != NULL)
2891 (void)setaltfname(ffname, sfname, newlnum < 0 ? 0 : newlnum);
2892 goto theend;
2893 }
2894
2895#ifdef FEAT_VISUAL
2896 /*
2897 * End Visual mode before switching to another buffer, so the text can be
2898 * copied into the GUI selection buffer.
2899 */
2900 reset_VIsual();
2901#endif
2902
2903 /*
2904 * If we are starting to edit another file, open a (new) buffer.
2905 * Otherwise we re-use the current buffer.
2906 */
2907 if (other_file)
2908 {
2909#ifdef FEAT_LISTCMDS
2910 if (!(flags & ECMD_ADDBUF))
2911#endif
2912 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002913 if (!cmdmod.keepalt)
2914 curwin->w_alt_fnum = curbuf->b_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 buflist_altfpos();
2916 }
2917
2918 if (fnum)
2919 buf = buflist_findnr(fnum);
2920 else
2921 {
2922#ifdef FEAT_LISTCMDS
2923 if (flags & ECMD_ADDBUF)
2924 {
2925 linenr_T tlnum = 1L;
2926
2927 if (command != NULL)
2928 {
2929 tlnum = atol((char *)command);
2930 if (tlnum <= 0)
2931 tlnum = 1L;
2932 }
2933 (void)buflist_new(ffname, sfname, tlnum, BLN_LISTED);
2934 goto theend;
2935 }
2936#endif
2937 buf = buflist_new(ffname, sfname, 0L,
2938 BLN_CURBUF | ((flags & ECMD_SET_HELP) ? 0 : BLN_LISTED));
2939 }
2940 if (buf == NULL)
2941 goto theend;
2942 if (buf->b_ml.ml_mfp == NULL) /* no memfile yet */
2943 {
2944 oldbuf = FALSE;
2945 buf->b_nwindows = 0;
2946 }
2947 else /* existing memfile */
2948 {
2949 oldbuf = TRUE;
2950 (void)buf_check_timestamp(buf, FALSE);
2951 /* Check if autocommands made buffer invalid or changed the current
2952 * buffer. */
2953 if (!buf_valid(buf)
2954#ifdef FEAT_AUTOCMD
2955 || curbuf != old_curbuf
2956#endif
2957 )
2958 goto theend;
2959#ifdef FEAT_EVAL
2960 if (aborting()) /* autocmds may abort script processing */
2961 goto theend;
2962#endif
2963 }
2964
2965 /* May jump to last used line number for a loaded buffer or when asked
2966 * for explicitly */
2967 if ((oldbuf && newlnum == ECMD_LASTL) || newlnum == ECMD_LAST)
2968 {
2969 pos = buflist_findfpos(buf);
2970 newlnum = pos->lnum;
2971 solcol = pos->col;
2972 }
2973
2974 /*
2975 * Make the (new) buffer the one used by the current window.
2976 * If the old buffer becomes unused, free it if ECMD_HIDE is FALSE.
2977 * If the current buffer was empty and has no file name, curbuf
2978 * is returned by buflist_new().
2979 */
2980 if (buf != curbuf)
2981 {
2982#ifdef FEAT_AUTOCMD
2983 /*
2984 * Be careful: The autocommands may delete any buffer and change
2985 * the current buffer.
2986 * - If the buffer we are going to edit is deleted, give up.
2987 * - If the current buffer is deleted, prefer to load the new
2988 * buffer when loading a buffer is required. This avoids
2989 * loading another buffer which then must be closed again.
2990 * - If we ended up in the new buffer already, need to skip a few
2991 * things, set auto_buf.
2992 */
2993 if (buf->b_fname != NULL)
2994 new_name = vim_strsave(buf->b_fname);
2995 au_new_curbuf = buf;
2996 apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
2997 if (!buf_valid(buf)) /* new buffer has been deleted */
2998 {
2999 delbuf_msg(new_name); /* frees new_name */
3000 goto theend;
3001 }
3002# ifdef FEAT_EVAL
3003 if (aborting()) /* autocmds may abort script processing */
3004 {
3005 vim_free(new_name);
3006 goto theend;
3007 }
3008# endif
3009 if (buf == curbuf) /* already in new buffer */
3010 auto_buf = TRUE;
3011 else
3012 {
3013 if (curbuf == old_curbuf)
3014#endif
3015 buf_copy_options(buf, BCO_ENTER);
3016
3017 /* close the link to the current buffer */
3018 close_buffer(curwin, curbuf,
3019 (flags & ECMD_HIDE) ? 0 : DOBUF_UNLOAD);
3020
3021#ifdef FEAT_AUTOCMD
3022# ifdef FEAT_EVAL
3023 if (aborting()) /* autocmds may abort script processing */
3024 {
3025 vim_free(new_name);
3026 goto theend;
3027 }
3028# endif
3029 /* Be careful again, like above. */
3030 if (!buf_valid(buf)) /* new buffer has been deleted */
3031 {
3032 delbuf_msg(new_name); /* frees new_name */
3033 goto theend;
3034 }
3035 if (buf == curbuf) /* already in new buffer */
3036 auto_buf = TRUE;
3037 else
3038#endif
3039 {
3040 curwin->w_buffer = buf;
3041 curbuf = buf;
3042 ++curbuf->b_nwindows;
3043 /* set 'fileformat' */
3044 if (*p_ffs && !oldbuf)
3045 set_fileformat(default_fileformat(), OPT_LOCAL);
3046 }
3047
3048 /* May get the window options from the last time this buffer
3049 * was in this window (or another window). If not used
3050 * before, reset the local window options to the global
3051 * values. Also restores old folding stuff. */
3052 get_winopts(buf);
3053
3054#ifdef FEAT_AUTOCMD
3055 }
3056 vim_free(new_name);
3057 au_new_curbuf = NULL;
3058#endif
3059 }
3060 else
3061 ++curbuf->b_nwindows;
3062
3063 curwin->w_pcmark.lnum = 1;
3064 curwin->w_pcmark.col = 0;
3065 }
3066 else /* !other_file */
3067 {
3068 if (
3069#ifdef FEAT_LISTCMDS
3070 (flags & ECMD_ADDBUF) ||
3071#endif
3072 check_fname() == FAIL)
3073 goto theend;
3074 oldbuf = (flags & ECMD_OLDBUF);
3075 }
3076
3077 if ((flags & ECMD_SET_HELP) || keep_help_flag)
3078 {
3079 char_u *p;
3080
3081 curbuf->b_help = TRUE;
3082#ifdef FEAT_QUICKFIX
3083 set_string_option_direct((char_u *)"buftype", -1,
3084 (char_u *)"help", OPT_FREE|OPT_LOCAL);
3085#endif
3086
3087 /*
3088 * Always set these options after jumping to a help tag, because the
3089 * user may have an autocommand that gets in the way.
3090 * Accept all ASCII chars for keywords, except ' ', '*', '"', '|', and
3091 * latin1 word characters (for translated help files).
3092 * Only set it when needed, buf_init_chartab() is some work.
3093 */
3094 p =
3095#ifdef EBCDIC
3096 (char_u *)"65-255,^*,^|,^\"";
3097#else
3098 (char_u *)"!-~,^*,^|,^\",192-255";
3099#endif
3100 if (STRCMP(curbuf->b_p_isk, p) != 0)
3101 {
3102 set_string_option_direct((char_u *)"isk", -1, p,
3103 OPT_FREE|OPT_LOCAL);
3104 check_buf_options(curbuf);
3105 (void)buf_init_chartab(curbuf, FALSE);
3106 }
3107
3108 curbuf->b_p_ts = 8; /* 'tabstop' is 8 */
3109 curwin->w_p_list = FALSE; /* no list mode */
3110
3111 curbuf->b_p_ma = FALSE; /* not modifiable */
3112 curbuf->b_p_bin = FALSE; /* reset 'bin' before reading file */
3113 curwin->w_p_nu = 0; /* no line numbers */
3114#ifdef FEAT_SCROLLBIND
3115 curwin->w_p_scb = FALSE; /* no scroll binding */
3116#endif
3117#ifdef FEAT_ARABIC
3118 curwin->w_p_arab = FALSE; /* no arabic mode */
3119#endif
3120#ifdef FEAT_RIGHTLEFT
3121 curwin->w_p_rl = FALSE; /* help window is left-to-right */
3122#endif
3123#ifdef FEAT_FOLDING
3124 curwin->w_p_fen = FALSE; /* No folding in the help window */
3125#endif
3126#ifdef FEAT_DIFF
3127 curwin->w_p_diff = FALSE; /* No 'diff' */
3128#endif
3129
3130#ifdef FEAT_AUTOCMD
3131 buf = curbuf;
3132#endif
3133 set_buflisted(FALSE);
3134 }
3135 else
3136 {
3137#ifdef FEAT_AUTOCMD
3138 buf = curbuf;
3139#endif
3140 /* Don't make a buffer listed if it's a help buffer. Useful when
3141 * using CTRL-O to go back to a help file. */
3142 if (!curbuf->b_help)
3143 set_buflisted(TRUE);
3144 }
3145
3146#ifdef FEAT_AUTOCMD
3147 /* If autocommands change buffers under our fingers, forget about
3148 * editing the file. */
3149 if (buf != curbuf)
3150 goto theend;
3151# ifdef FEAT_EVAL
3152 if (aborting()) /* autocmds may abort script processing */
3153 goto theend;
3154# endif
3155
3156 /* Since we are starting to edit a file, consider the filetype to be
3157 * unset. Helps for when an autocommand changes files and expects syntax
3158 * highlighting to work in the other file. */
3159 did_filetype = FALSE;
3160#endif
3161
3162/*
3163 * other_file oldbuf
3164 * FALSE FALSE re-edit same file, buffer is re-used
3165 * FALSE TRUE re-edit same file, nothing changes
3166 * TRUE FALSE start editing new file, new buffer
3167 * TRUE TRUE start editing in existing buffer (nothing to do)
3168 */
3169 if (!other_file && !oldbuf) /* re-use the buffer */
3170 {
3171 set_last_cursor(curwin); /* may set b_last_cursor */
3172 if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL)
3173 {
3174 newlnum = curwin->w_cursor.lnum;
3175 solcol = curwin->w_cursor.col;
3176 }
3177#ifdef FEAT_AUTOCMD
3178 buf = curbuf;
3179 if (buf->b_fname != NULL)
3180 new_name = vim_strsave(buf->b_fname);
3181 else
3182 new_name = NULL;
3183#endif
3184 buf_freeall(curbuf, FALSE, FALSE); /* free all things for buffer */
3185#ifdef FEAT_AUTOCMD
3186 /* If autocommands deleted the buffer we were going to re-edit, give
3187 * up and jump to the end. */
3188 if (!buf_valid(buf))
3189 {
3190 delbuf_msg(new_name); /* frees new_name */
3191 goto theend;
3192 }
3193 vim_free(new_name);
3194
3195 /* If autocommands change buffers under our fingers, forget about
3196 * re-editing the file. Should do the buf_clear_file(), but perhaps
3197 * the autocommands changed the buffer... */
3198 if (buf != curbuf)
3199 goto theend;
3200# ifdef FEAT_EVAL
3201 if (aborting()) /* autocmds may abort script processing */
3202 goto theend;
3203# endif
3204#endif
3205 buf_clear_file(curbuf);
3206 curbuf->b_op_start.lnum = 0; /* clear '[ and '] marks */
3207 curbuf->b_op_end.lnum = 0;
3208 }
3209
3210/*
3211 * If we get here we are sure to start editing
3212 */
3213 /* don't redraw until the cursor is in the right line */
3214 ++RedrawingDisabled;
3215
3216 /* Assume success now */
3217 retval = OK;
3218
3219 /*
3220 * Reset cursor position, could be used by autocommands.
3221 */
3222 check_cursor();
3223
3224 /*
3225 * Check if we are editing the w_arg_idx file in the argument list.
3226 */
3227 check_arg_idx(curwin);
3228
3229#ifdef FEAT_AUTOCMD
3230 if (!auto_buf)
3231#endif
3232 {
3233 /*
3234 * Set cursor and init window before reading the file and executing
3235 * autocommands. This allows for the autocommands to position the
3236 * cursor.
3237 */
3238 win_init(curwin);
3239
3240#ifdef FEAT_FOLDING
3241 /* It's like all lines in the buffer changed. Need to update
3242 * automatic folding. */
3243 foldUpdateAll(curwin);
3244#endif
3245
3246#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
3247 if (p_acd && curbuf->b_ffname != NULL
3248 && vim_chdirfile(curbuf->b_ffname) == OK)
3249 shorten_fnames(TRUE);
3250#endif
3251 /*
3252 * Careful: open_buffer() and apply_autocmds() may change the current
3253 * buffer and window.
3254 */
3255 lnum = curwin->w_cursor.lnum;
3256 topline = curwin->w_topline;
3257 if (!oldbuf) /* need to read the file */
3258 {
3259#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
3260 swap_exists_action = SEA_DIALOG;
3261#endif
3262 curbuf->b_flags |= BF_CHECK_RO; /* set/reset 'ro' flag */
3263
3264 /*
3265 * Open the buffer and read the file.
3266 */
3267#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
3268 if (should_abort(open_buffer(FALSE, eap)))
3269 retval = FAIL;
3270#else
3271 (void)open_buffer(FALSE, eap);
3272#endif
3273
3274#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
3275 if (swap_exists_action == SEA_QUIT)
3276 retval = FAIL;
3277 handle_swap_exists(old_curbuf);
3278#endif
3279 }
3280#ifdef FEAT_AUTOCMD
3281 else
3282 {
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00003283 /* Read the modelines, but only to set window-local options. Any
3284 * buffer-local options have already been set and may have been
3285 * changed by the user. */
3286 do_modelines(TRUE);
3287
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288 apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf,
3289 &retval);
3290 apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf,
3291 &retval);
3292 }
3293 check_arg_idx(curwin);
3294#endif
3295
3296 /*
3297 * If autocommands change the cursor position or topline, we should
3298 * keep it.
3299 */
3300 if (curwin->w_cursor.lnum != lnum)
3301 {
3302 newlnum = curwin->w_cursor.lnum;
3303 newcol = curwin->w_cursor.col;
3304 }
3305 if (curwin->w_topline == topline)
3306 topline = 0;
3307
3308 /* Even when cursor didn't move we need to recompute topline. */
3309 changed_line_abv_curs();
3310
3311#ifdef FEAT_TITLE
3312 maketitle();
3313#endif
3314 }
3315
3316#ifdef FEAT_DIFF
3317 /* Tell the diff stuff that this buffer is new and/or needs updating.
3318 * Also needed when re-editing the same buffer, because unloading will
3319 * have removed it as a diff buffer. */
3320 diff_new_buffer();
3321 diff_invalidate();
3322#endif
3323
3324 if (command == NULL)
3325 {
3326 if (newcol >= 0) /* position set by autocommands */
3327 {
3328 curwin->w_cursor.lnum = newlnum;
3329 curwin->w_cursor.col = newcol;
3330 check_cursor();
3331 }
3332 else if (newlnum > 0) /* line number from caller or old position */
3333 {
3334 curwin->w_cursor.lnum = newlnum;
3335 check_cursor_lnum();
3336 if (solcol >= 0 && !p_sol)
3337 {
3338 /* 'sol' is off: Use last known column. */
3339 curwin->w_cursor.col = solcol;
3340 check_cursor_col();
3341#ifdef FEAT_VIRTUALEDIT
3342 curwin->w_cursor.coladd = 0;
3343#endif
3344 curwin->w_set_curswant = TRUE;
3345 }
3346 else
3347 beginline(BL_SOL | BL_FIX);
3348 }
3349 else /* no line number, go to last line in Ex mode */
3350 {
3351 if (exmode_active)
3352 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3353 beginline(BL_WHITE | BL_FIX);
3354 }
3355 }
3356
3357#ifdef FEAT_WINDOWS
3358 /* Check if cursors in other windows on the same buffer are still valid */
3359 check_lnums(FALSE);
3360#endif
3361
3362 /*
3363 * Did not read the file, need to show some info about the file.
3364 * Do this after setting the cursor.
3365 */
3366 if (oldbuf
3367#ifdef FEAT_AUTOCMD
3368 && !auto_buf
3369#endif
3370 )
3371 {
3372 int msg_scroll_save = msg_scroll;
3373
3374 /* Obey the 'O' flag in 'cpoptions': overwrite any previous file
3375 * message. */
3376 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
3377 msg_scroll = FALSE;
3378 if (!msg_scroll) /* wait a bit when overwriting an error msg */
3379 check_for_delay(FALSE);
3380 msg_start();
3381 msg_scroll = msg_scroll_save;
3382 msg_scrolled_ign = TRUE;
3383
3384 fileinfo(FALSE, TRUE, FALSE);
3385
3386 msg_scrolled_ign = FALSE;
3387 }
3388
3389 if (command != NULL)
3390 do_cmdline(command, NULL, NULL, DOCMD_VERBOSE);
3391
3392#ifdef FEAT_KEYMAP
3393 if (curbuf->b_kmap_state & KEYMAP_INIT)
3394 keymap_init();
3395#endif
3396
3397 --RedrawingDisabled;
3398 if (!skip_redraw)
3399 {
3400 n = p_so;
3401 if (topline == 0 && command == NULL)
3402 p_so = 999; /* force cursor halfway the window */
3403 update_topline();
3404#ifdef FEAT_SCROLLBIND
3405 curwin->w_scbind_pos = curwin->w_topline;
3406#endif
3407 p_so = n;
3408 redraw_curbuf_later(NOT_VALID); /* redraw this buffer later */
3409 }
3410
3411 if (p_im)
3412 need_start_insertmode = TRUE;
3413
3414#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
3415 /* Change directories when the acd option is set on. */
3416 if (p_acd && curbuf->b_ffname != NULL
3417 && vim_chdirfile(curbuf->b_ffname) == OK)
3418 shorten_fnames(TRUE);
3419
3420 if (gui.in_use && curbuf->b_ffname != NULL)
3421 {
3422# ifdef FEAT_SUN_WORKSHOP
3423 if (usingSunWorkShop)
3424 workshop_file_opened((char *)curbuf->b_ffname, curbuf->b_p_ro);
3425# endif
3426# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003427 if (usingNetbeans & ((flags & ECMD_SET_HELP) != ECMD_SET_HELP))
3428 netbeans_file_opened(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429# endif
3430 }
3431#endif
3432
3433theend:
3434#ifdef FEAT_BROWSE
3435 vim_free(browse_file);
3436#endif
3437 vim_free(free_fname);
3438 return retval;
3439}
3440
3441#ifdef FEAT_AUTOCMD
3442 static void
3443delbuf_msg(name)
3444 char_u *name;
3445{
3446 EMSG2(_("E143: Autocommands unexpectedly deleted new buffer %s"),
3447 name == NULL ? (char_u *)"" : name);
3448 vim_free(name);
3449 au_new_curbuf = NULL;
3450}
3451#endif
3452
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003453static int append_indent = 0; /* autoindent for first line */
3454
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455/*
3456 * ":insert" and ":append", also used by ":change"
3457 */
3458 void
3459ex_append(eap)
3460 exarg_T *eap;
3461{
3462 char_u *theline;
3463 int did_undo = FALSE;
3464 linenr_T lnum = eap->line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003465 int indent = 0;
3466 char_u *p;
3467 int vcol;
3468 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003470 /* the ! flag toggles autoindent */
3471 if (eap->forceit)
3472 curbuf->b_p_ai = !curbuf->b_p_ai;
3473
3474 /* First autoindent comes from the line we start on */
3475 if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0)
3476 append_indent = get_indent_lnum(lnum);
3477
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478 if (eap->cmdidx != CMD_append)
3479 --lnum;
3480
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003481 /* when the buffer is empty append to line 0 and delete the dummy line */
3482 if (empty && lnum == 1)
3483 lnum = 0;
3484
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 State = INSERT; /* behave like in Insert mode */
3486 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
3487 State |= LANGMAP;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003488
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 while (1)
3490 {
3491 msg_scroll = TRUE;
3492 need_wait_return = FALSE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003493 if (curbuf->b_p_ai)
3494 {
3495 if (append_indent >= 0)
3496 {
3497 indent = append_indent;
3498 append_indent = -1;
3499 }
3500 else if (lnum > 0)
3501 indent = get_indent_lnum(lnum);
3502 }
3503 ex_keep_indent = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 if (eap->getline == NULL)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003505 {
3506 /* No getline() function, use the lines that follow. This ends
3507 * when there is no more. */
3508 if (eap->nextcmd == NULL || *eap->nextcmd == NUL)
3509 break;
3510 p = vim_strchr(eap->nextcmd, NL);
3511 if (p == NULL)
3512 p = eap->nextcmd + STRLEN(eap->nextcmd);
3513 theline = vim_strnsave(eap->nextcmd, (int)(p - eap->nextcmd));
3514 if (*p != NUL)
3515 ++p;
3516 eap->nextcmd = p;
3517 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518 else
3519 theline = eap->getline(
3520#ifdef FEAT_EVAL
Bram Moolenaar3d60ec22005-01-05 22:19:46 +00003521 eap->cstack->cs_looplevel > 0 ? -1 :
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522#endif
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003523 NUL, eap->cookie, indent);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524 lines_left = Rows - 1;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003525 if (theline == NULL)
3526 break;
3527
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003528 /* Using ^ CTRL-D in getexmodeline() makes us repeat the indent. */
3529 if (ex_keep_indent)
3530 append_indent = indent;
3531
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003532 /* Look for the "." after automatic indent. */
3533 vcol = 0;
3534 for (p = theline; indent > vcol; ++p)
3535 {
3536 if (*p == ' ')
3537 ++vcol;
3538 else if (*p == TAB)
3539 vcol += 8 - vcol % 8;
3540 else
3541 break;
3542 }
3543 if ((p[0] == '.' && p[1] == NUL)
3544 || (!did_undo && u_save(lnum, lnum + 1) == FAIL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 {
3546 vim_free(theline);
3547 break;
3548 }
3549
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003550 /* don't use autoindent if nothing was typed. */
3551 if (p[0] == NUL)
3552 theline[0] = NUL;
3553
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 did_undo = TRUE;
3555 ml_append(lnum, theline, (colnr_T)0, FALSE);
3556 appended_lines_mark(lnum, 1L);
3557
3558 vim_free(theline);
3559 ++lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003560
3561 if (empty)
3562 {
3563 ml_delete(2L, FALSE);
3564 empty = FALSE;
3565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 }
3567 State = NORMAL;
3568
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003569 if (eap->forceit)
3570 curbuf->b_p_ai = !curbuf->b_p_ai;
3571
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 /* "start" is set to eap->line2+1 unless that position is invalid (when
3573 * eap->line2 pointed to the end of the buffer and nothig was appended)
3574 * "end" is set to lnum when something has been appended, otherwise
3575 * it is the same than "start" -- Acevedo */
3576 curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
3577 eap->line2 + 1 : curbuf->b_ml.ml_line_count;
3578 if (eap->cmdidx != CMD_append)
3579 --curbuf->b_op_start.lnum;
3580 curbuf->b_op_end.lnum = (eap->line2 < lnum)
3581 ? lnum : curbuf->b_op_start.lnum;
3582 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
3583 curwin->w_cursor.lnum = lnum;
3584 check_cursor_lnum();
3585 beginline(BL_SOL | BL_FIX);
3586
3587 need_wait_return = FALSE; /* don't use wait_return() now */
3588 ex_no_reprint = TRUE;
3589}
3590
3591/*
3592 * ":change"
3593 */
3594 void
3595ex_change(eap)
3596 exarg_T *eap;
3597{
3598 linenr_T lnum;
3599
3600 if (eap->line2 >= eap->line1
3601 && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
3602 return;
3603
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003604 /* the ! flag toggles autoindent */
3605 if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai)
3606 append_indent = get_indent_lnum(eap->line1);
3607
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 for (lnum = eap->line2; lnum >= eap->line1; --lnum)
3609 {
3610 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
3611 break;
3612 ml_delete(eap->line1, FALSE);
3613 }
3614 deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum));
3615
3616 /* ":append" on the line above the deleted lines. */
3617 eap->line2 = eap->line1;
3618 ex_append(eap);
3619}
3620
3621 void
3622ex_z(eap)
3623 exarg_T *eap;
3624{
3625 char_u *x;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003626 int bigness;
3627 char_u *kind;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 int minus = 0;
3629 linenr_T start, end, curs, i;
3630 int j;
3631 linenr_T lnum = eap->line2;
3632
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003633 /* Vi compatible: ":z!" uses display height, without a count uses
3634 * 'scroll' */
3635 if (eap->forceit)
3636 bigness = curwin->w_height;
3637 else if (firstwin == lastwin)
3638 bigness = curwin->w_p_scr * 2;
3639 else
3640 bigness = curwin->w_height - 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641 if (bigness < 1)
3642 bigness = 1;
3643
3644 x = eap->arg;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003645 kind = x;
3646 if (*kind == '-' || *kind == '+' || *kind == '='
3647 || *kind == '^' || *kind == '.')
3648 ++x;
3649 while (*x == '-' || *x == '+')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650 ++x;
3651
3652 if (*x != 0)
3653 {
3654 if (!VIM_ISDIGIT(*x))
3655 {
3656 EMSG(_("E144: non-numeric argument to :z"));
3657 return;
3658 }
3659 else
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003660 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661 bigness = atoi((char *)x);
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003662 p_window = bigness;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003663 if (*kind == '=')
3664 bigness += 2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666 }
3667
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003668 /* the number of '-' and '+' multiplies the distance */
3669 if (*kind == '-' || *kind == '+')
3670 for (x = kind + 1; *x == *kind; ++x)
3671 ;
3672
3673 switch (*kind)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 {
3675 case '-':
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003676 start = lnum - bigness * (x - kind);
3677 end = start + bigness;
3678 curs = end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679 break;
3680
3681 case '=':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003682 start = lnum - (bigness + 1) / 2 + 1;
3683 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 curs = lnum;
3685 minus = 1;
3686 break;
3687
3688 case '^':
3689 start = lnum - bigness * 2;
3690 end = lnum - bigness;
3691 curs = lnum - bigness;
3692 break;
3693
3694 case '.':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003695 start = lnum - (bigness + 1) / 2 + 1;
3696 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697 curs = end;
3698 break;
3699
3700 default: /* '+' */
3701 start = lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003702 if (*kind == '+')
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003703 start += bigness * (x - kind - 1) + 1;
3704 else if (eap->addr_count == 0)
3705 ++start;
3706 end = start + bigness - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707 curs = end;
3708 break;
3709 }
3710
3711 if (start < 1)
3712 start = 1;
3713
3714 if (end > curbuf->b_ml.ml_line_count)
3715 end = curbuf->b_ml.ml_line_count;
3716
3717 if (curs > curbuf->b_ml.ml_line_count)
3718 curs = curbuf->b_ml.ml_line_count;
3719
3720 for (i = start; i <= end; i++)
3721 {
3722 if (minus && i == lnum)
3723 {
3724 msg_putchar('\n');
3725
3726 for (j = 1; j < Columns; j++)
3727 msg_putchar('-');
3728 }
3729
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003730 print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731
3732 if (minus && i == lnum)
3733 {
3734 msg_putchar('\n');
3735
3736 for (j = 1; j < Columns; j++)
3737 msg_putchar('-');
3738 }
3739 }
3740
3741 curwin->w_cursor.lnum = curs;
3742 ex_no_reprint = TRUE;
3743}
3744
3745/*
3746 * Check if the restricted flag is set.
3747 * If so, give an error message and return TRUE.
3748 * Otherwise, return FALSE.
3749 */
3750 int
3751check_restricted()
3752{
3753 if (restricted)
3754 {
3755 EMSG(_("E145: Shell commands not allowed in rvim"));
3756 return TRUE;
3757 }
3758 return FALSE;
3759}
3760
3761/*
3762 * Check if the secure flag is set (.exrc or .vimrc in current directory).
3763 * If so, give an error message and return TRUE.
3764 * Otherwise, return FALSE.
3765 */
3766 int
3767check_secure()
3768{
3769 if (secure)
3770 {
3771 secure = 2;
3772 EMSG(_(e_curdir));
3773 return TRUE;
3774 }
3775#ifdef HAVE_SANDBOX
3776 /*
3777 * In the sandbox more things are not allowed, including the things
3778 * disallowed in secure mode.
3779 */
3780 if (sandbox != 0)
3781 {
3782 EMSG(_(e_sandbox));
3783 return TRUE;
3784 }
3785#endif
3786 return FALSE;
3787}
3788
3789static char_u *old_sub = NULL; /* previous substitute pattern */
3790static int global_need_beginline; /* call beginline() after ":g" */
3791
3792/*
3793 * When ":global" is used to number of substitutions and changed lines is
3794 * accumulated until it's finished.
3795 */
3796static long sub_nsubs; /* total number of substitutions */
3797static linenr_T sub_nlines; /* total number of lines changed */
3798
3799/* do_sub()
3800 *
3801 * Perform a substitution from line eap->line1 to line eap->line2 using the
3802 * command pointed to by eap->arg which should be of the form:
3803 *
3804 * /pattern/substitution/{flags}
3805 *
3806 * The usual escapes are supported as described in the regexp docs.
3807 */
3808 void
3809do_sub(eap)
3810 exarg_T *eap;
3811{
3812 linenr_T lnum;
3813 long i = 0;
3814 regmmatch_T regmatch;
3815 static int do_all = FALSE; /* do multiple substitutions per line */
3816 static int do_ask = FALSE; /* ask for confirmation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00003817 static int do_count = FALSE; /* count only */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 static int do_error = TRUE; /* if false, ignore errors */
3819 static int do_print = FALSE; /* print last line with subs. */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003820 static int do_list = FALSE; /* list last line with subs. */
3821 static int do_number = FALSE; /* list last line with line nr*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 static int do_ic = 0; /* ignore case flag */
3823 char_u *pat = NULL, *sub = NULL; /* init for GCC */
3824 int delimiter;
3825 int sublen;
3826 int got_quit = FALSE;
3827 int got_match = FALSE;
3828 int temp;
3829 int which_pat;
3830 char_u *cmd;
3831 int save_State;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003832 linenr_T first_line = 0; /* first changed line */
3833 linenr_T last_line= 0; /* below last changed line AFTER the
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 * change */
3835 linenr_T old_line_count = curbuf->b_ml.ml_line_count;
3836 linenr_T line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003837 long nmatch; /* number of lines in match */
3838 linenr_T sub_firstlnum; /* nr of first sub line */
3839 char_u *sub_firstline; /* allocated copy of first sub line */
3840 int endcolumn = FALSE; /* cursor in last column when done */
Bram Moolenaar05159a02005-02-26 23:04:13 +00003841 pos_T old_cursor = curwin->w_cursor;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842
3843 cmd = eap->arg;
3844 if (!global_busy)
3845 {
3846 sub_nsubs = 0;
3847 sub_nlines = 0;
3848 }
3849
3850#ifdef FEAT_FKMAP /* reverse the flow of the Farsi characters */
3851 if (p_altkeymap && curwin->w_p_rl)
3852 lrF_sub(cmd);
3853#endif
3854
3855 if (eap->cmdidx == CMD_tilde)
3856 which_pat = RE_LAST; /* use last used regexp */
3857 else
3858 which_pat = RE_SUBST; /* use last substitute regexp */
3859
3860 /* new pattern and substitution */
3861 if (eap->cmd[0] == 's' && *cmd != NUL && !vim_iswhite(*cmd)
3862 && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
3863 {
3864 /* don't accept alphanumeric for separator */
3865 if (isalpha(*cmd))
3866 {
3867 EMSG(_("E146: Regular expressions can't be delimited by letters"));
3868 return;
3869 }
3870 /*
3871 * undocumented vi feature:
3872 * "\/sub/" and "\?sub?" use last used search pattern (almost like
3873 * //sub/r). "\&sub&" use last substitute pattern (like //sub/).
3874 */
3875 if (*cmd == '\\')
3876 {
3877 ++cmd;
3878 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
3879 {
3880 EMSG(_(e_backslash));
3881 return;
3882 }
3883 if (*cmd != '&')
3884 which_pat = RE_SEARCH; /* use last '/' pattern */
3885 pat = (char_u *)""; /* empty search pattern */
3886 delimiter = *cmd++; /* remember delimiter character */
3887 }
3888 else /* find the end of the regexp */
3889 {
3890 which_pat = RE_LAST; /* use last used regexp */
3891 delimiter = *cmd++; /* remember delimiter character */
3892 pat = cmd; /* remember start of search pat */
3893 cmd = skip_regexp(cmd, delimiter, p_magic, &eap->arg);
3894 if (cmd[0] == delimiter) /* end delimiter found */
3895 *cmd++ = NUL; /* replace it with a NUL */
3896 }
3897
3898 /*
3899 * Small incompatibility: vi sees '\n' as end of the command, but in
3900 * Vim we want to use '\n' to find/substitute a NUL.
3901 */
3902 sub = cmd; /* remember the start of the substitution */
3903
3904 while (cmd[0])
3905 {
3906 if (cmd[0] == delimiter) /* end delimiter found */
3907 {
3908 *cmd++ = NUL; /* replace it with a NUL */
3909 break;
3910 }
3911 if (cmd[0] == '\\' && cmd[1] != 0) /* skip escaped characters */
3912 ++cmd;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003913 mb_ptr_adv(cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 }
3915
3916 if (!eap->skip)
3917 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003918 /* In POSIX vi ":s/pat/%/" uses the previous subst. string. */
3919 if (STRCMP(sub, "%") == 0
3920 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
3921 {
3922 if (old_sub == NULL) /* there is no previous command */
3923 {
3924 EMSG(_(e_nopresub));
3925 return;
3926 }
3927 sub = old_sub;
3928 }
3929 else
3930 {
3931 vim_free(old_sub);
3932 old_sub = vim_strsave(sub);
3933 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 }
3935 }
3936 else if (!eap->skip) /* use previous pattern and substitution */
3937 {
3938 if (old_sub == NULL) /* there is no previous command */
3939 {
3940 EMSG(_(e_nopresub));
3941 return;
3942 }
3943 pat = NULL; /* search_regcomp() will use previous pattern */
3944 sub = old_sub;
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00003945
3946 /* Vi compatibility quirk: repeating with ":s" keeps the cursor in the
3947 * last column after using "$". */
3948 endcolumn = (curwin->w_curswant == MAXCOL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949 }
3950
3951 /*
3952 * Find trailing options. When '&' is used, keep old options.
3953 */
3954 if (*cmd == '&')
3955 ++cmd;
3956 else
3957 {
3958 if (!p_ed)
3959 {
3960 if (p_gd) /* default is global on */
3961 do_all = TRUE;
3962 else
3963 do_all = FALSE;
3964 do_ask = FALSE;
3965 }
3966 do_error = TRUE;
3967 do_print = FALSE;
3968 do_ic = 0;
3969 }
3970 while (*cmd)
3971 {
3972 /*
3973 * Note that 'g' and 'c' are always inverted, also when p_ed is off.
3974 * 'r' is never inverted.
3975 */
3976 if (*cmd == 'g')
3977 do_all = !do_all;
3978 else if (*cmd == 'c')
3979 do_ask = !do_ask;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003980 else if (*cmd == 'n')
3981 do_count = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982 else if (*cmd == 'e')
3983 do_error = !do_error;
3984 else if (*cmd == 'r') /* use last used regexp */
3985 which_pat = RE_LAST;
3986 else if (*cmd == 'p')
3987 do_print = TRUE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003988 else if (*cmd == '#')
3989 {
3990 do_print = TRUE;
3991 do_number = TRUE;
3992 }
3993 else if (*cmd == 'l')
3994 {
3995 do_print = TRUE;
3996 do_list = TRUE;
3997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998 else if (*cmd == 'i') /* ignore case */
3999 do_ic = 'i';
4000 else if (*cmd == 'I') /* don't ignore case */
4001 do_ic = 'I';
4002 else
4003 break;
4004 ++cmd;
4005 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00004006 if (do_count)
4007 do_ask = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008
4009 /*
4010 * check for a trailing count
4011 */
4012 cmd = skipwhite(cmd);
4013 if (VIM_ISDIGIT(*cmd))
4014 {
4015 i = getdigits(&cmd);
4016 if (i <= 0 && !eap->skip && do_error)
4017 {
4018 EMSG(_(e_zerocount));
4019 return;
4020 }
4021 eap->line1 = eap->line2;
4022 eap->line2 += i - 1;
4023 if (eap->line2 > curbuf->b_ml.ml_line_count)
4024 eap->line2 = curbuf->b_ml.ml_line_count;
4025 }
4026
4027 /*
4028 * check for trailing command or garbage
4029 */
4030 cmd = skipwhite(cmd);
4031 if (*cmd && *cmd != '"') /* if not end-of-line or comment */
4032 {
4033 eap->nextcmd = check_nextcmd(cmd);
4034 if (eap->nextcmd == NULL)
4035 {
4036 EMSG(_(e_trailing));
4037 return;
4038 }
4039 }
4040
4041 if (eap->skip) /* not executing commands, only parsing */
4042 return;
4043
4044 if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4045 {
4046 if (do_error)
4047 EMSG(_(e_invcmd));
4048 return;
4049 }
4050
4051 /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
4052 if (do_ic == 'i')
4053 regmatch.rmm_ic = TRUE;
4054 else if (do_ic == 'I')
4055 regmatch.rmm_ic = FALSE;
4056
4057 sub_firstline = NULL;
4058
4059 /*
4060 * ~ in the substitute pattern is replaced with the old pattern.
4061 * We do it here once to avoid it to be replaced over and over again.
4062 * But don't do it when it starts with "\=", then it's an expression.
4063 */
4064 if (!(sub[0] == '\\' && sub[1] == '='))
4065 sub = regtilde(sub, p_magic);
4066
4067 /*
4068 * Check for a match on each line.
4069 */
4070 line2 = eap->line2;
4071 for (lnum = eap->line1; lnum <= line2 && !(got_quit
4072#if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
4073 || aborting()
4074#endif
4075 ); ++lnum)
4076 {
4077 sub_firstlnum = lnum;
4078 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
4079 if (nmatch)
4080 {
4081 colnr_T copycol;
4082 colnr_T matchcol;
4083 colnr_T prev_matchcol = MAXCOL;
4084 char_u *new_end, *new_start = NULL;
4085 unsigned new_start_len = 0;
4086 char_u *p1;
4087 int did_sub = FALSE;
4088 int lastone;
4089 unsigned len, needed_len;
4090 long nmatch_tl = 0; /* nr of lines matched below lnum */
4091 int do_again; /* do it again after joining lines */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004092 int skip_match = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093
4094 /*
4095 * The new text is build up step by step, to avoid too much
4096 * copying. There are these pieces:
4097 * sub_firstline The old text, unmodifed.
4098 * copycol Column in the old text where we started
4099 * looking for a match; from here old text still
4100 * needs to be copied to the new text.
4101 * matchcol Column number of the old text where to look
4102 * for the next match. It's just after the
4103 * previous match or one further.
4104 * prev_matchcol Column just after the previous match (if any).
4105 * Mostly equal to matchcol, except for the first
4106 * match and after skipping an empty match.
4107 * regmatch.*pos Where the pattern matched in the old text.
4108 * new_start The new text, all that has been produced so
4109 * far.
4110 * new_end The new text, where to append new text.
4111 *
4112 * lnum The line number where we were looking for the
4113 * first match in the old line.
4114 * sub_firstlnum The line number in the buffer where to look
4115 * for a match. Can be different from "lnum"
4116 * when the pattern or substitute string contains
4117 * line breaks.
4118 *
4119 * Special situations:
4120 * - When the substitute string contains a line break, the part up
4121 * to the line break is inserted in the text, but the copy of
4122 * the original line is kept. "sub_firstlnum" is adjusted for
4123 * the inserted lines.
4124 * - When the matched pattern contains a line break, the old line
4125 * is taken from the line at the end of the pattern. The lines
4126 * in the match are deleted later, "sub_firstlnum" is adjusted
4127 * accordingly.
4128 *
4129 * The new text is built up in new_start[]. It has some extra
4130 * room to avoid using alloc()/free() too often. new_start_len is
4131 * the lenght of the allocated memory at new_start.
4132 *
4133 * Make a copy of the old line, so it won't be taken away when
4134 * updating the screen or handling a multi-line match. The "old_"
4135 * pointers point into this copy.
4136 */
4137 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4138 if (sub_firstline == NULL)
4139 {
4140 vim_free(new_start);
4141 goto outofmem;
4142 }
4143 copycol = 0;
4144 matchcol = 0;
4145
4146 /* At first match, remember current cursor position. */
4147 if (!got_match)
4148 {
4149 setpcmark();
4150 got_match = TRUE;
4151 }
4152
4153 /*
4154 * Loop until nothing more to replace in this line.
4155 * 1. Handle match with empty string.
4156 * 2. If do_ask is set, ask for confirmation.
4157 * 3. substitute the string.
4158 * 4. if do_all is set, find next match
4159 * 5. break if there isn't another match in this line
4160 */
4161 for (;;)
4162 {
4163 /* Save the line number of the last change for the final
4164 * cursor position (just like Vi). */
4165 curwin->w_cursor.lnum = lnum;
4166 do_again = FALSE;
4167
4168 /*
4169 * 1. Match empty string does not count, except for first
4170 * match. This reproduces the strange vi behaviour.
4171 * This also catches endless loops.
4172 */
4173 if (matchcol == prev_matchcol
4174 && regmatch.endpos[0].lnum == 0
4175 && matchcol == regmatch.endpos[0].col)
4176 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00004177 if (sub_firstline[matchcol] == NUL)
4178 /* We already were at the end of the line. Don't look
4179 * for a match in this line again. */
4180 skip_match = TRUE;
4181 else
4182 ++matchcol; /* search for a match at next column */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 goto skip;
4184 }
4185
4186 /* Normally we continue searching for a match just after the
4187 * previous match. */
4188 matchcol = regmatch.endpos[0].col;
4189 prev_matchcol = matchcol;
4190
4191 /*
Bram Moolenaar05159a02005-02-26 23:04:13 +00004192 * 2. If do_count is set only increase the counter.
4193 * If do_ask is set, ask for confirmation.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004195 if (do_count)
4196 {
4197 /* For a multi-line match, put matchcol at the NUL at
4198 * the end of the line and set nmatch to one, so that
4199 * we continue looking for a match on the next line.
4200 * Avoids that ":s/\nB\@=//gc" get stuck. */
4201 if (nmatch > 1)
4202 {
4203 matchcol = STRLEN(sub_firstline);
4204 nmatch = 1;
4205 }
4206 sub_nsubs++;
4207 did_sub = TRUE;
4208 goto skip;
4209 }
4210
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 if (do_ask)
4212 {
4213 /* change State to CONFIRM, so that the mouse works
4214 * properly */
4215 save_State = State;
4216 State = CONFIRM;
4217#ifdef FEAT_MOUSE
4218 setmouse(); /* disable mouse in xterm */
4219#endif
4220 curwin->w_cursor.col = regmatch.startpos[0].col;
4221
4222 /* When 'cpoptions' contains "u" don't sync undo when
4223 * asking for confirmation. */
4224 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4225 ++no_u_sync;
4226
4227 /*
4228 * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
4229 */
4230 while (do_ask)
4231 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004232 if (exmode_active)
4233 {
4234 char_u *resp;
4235 colnr_T sc, ec;
4236
4237 print_line_no_prefix(lnum, FALSE, FALSE);
4238
4239 getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
4240 curwin->w_cursor.col = regmatch.endpos[0].col - 1;
4241 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
4242 msg_start();
Bram Moolenaar05159a02005-02-26 23:04:13 +00004243 for (i = 0; i < (long)sc; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004244 msg_putchar(' ');
Bram Moolenaar05159a02005-02-26 23:04:13 +00004245 for ( ; i <= (long)ec; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004246 msg_putchar('^');
4247
4248 resp = getexmodeline('?', NULL, 0);
4249 if (resp != NULL)
4250 {
4251 i = *resp;
4252 vim_free(resp);
4253 }
4254 }
4255 else
4256 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004258 int save_p_fen = curwin->w_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004260 curwin->w_p_fen = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004262 /* Invert the matched string.
4263 * Remove the inversion afterwards. */
4264 temp = RedrawingDisabled;
4265 RedrawingDisabled = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004267 search_match_lines = regmatch.endpos[0].lnum;
4268 search_match_endcol = regmatch.endpos[0].col;
4269 highlight_match = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004271 update_topline();
4272 validate_cursor();
4273 update_screen(NOT_VALID);
4274 highlight_match = FALSE;
4275 redraw_later(NOT_VALID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276
4277#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004278 curwin->w_p_fen = save_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004280 if (msg_row == Rows - 1)
4281 msg_didout = FALSE; /* avoid a scroll-up */
4282 msg_starthere();
4283 i = msg_scroll;
4284 msg_scroll = 0; /* truncate msg when
4285 needed */
4286 msg_no_more = TRUE;
4287 /* write message same highlighting as for
4288 * wait_return */
4289 smsg_attr(hl_attr(HLF_R),
4290 (char_u *)_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
4291 msg_no_more = FALSE;
4292 msg_scroll = i;
4293 showruler(TRUE);
4294 windgoto(msg_row, msg_col);
4295 RedrawingDisabled = temp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296
4297#ifdef USE_ON_FLY_SCROLL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004298 dont_scroll = FALSE; /* allow scrolling here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004300 ++no_mapping; /* don't map this key */
4301 ++allow_keys; /* allow special keys */
4302 i = safe_vgetc();
4303 --allow_keys;
4304 --no_mapping;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004306 /* clear the question */
4307 msg_didout = FALSE; /* don't scroll up */
4308 msg_col = 0;
4309 gotocmdline(TRUE);
4310 }
4311
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 need_wait_return = FALSE; /* no hit-return prompt */
4313 if (i == 'q' || i == ESC || i == Ctrl_C
4314#ifdef UNIX
4315 || i == intr_char
4316#endif
4317 )
4318 {
4319 got_quit = TRUE;
4320 break;
4321 }
4322 if (i == 'n')
4323 break;
4324 if (i == 'y')
4325 break;
4326 if (i == 'l')
4327 {
4328 /* last: replace and then stop */
4329 do_all = FALSE;
4330 line2 = lnum;
4331 break;
4332 }
4333 if (i == 'a')
4334 {
4335 do_ask = FALSE;
4336 break;
4337 }
4338#ifdef FEAT_INS_EXPAND
4339 if (i == Ctrl_E)
4340 scrollup_clamp();
4341 else if (i == Ctrl_Y)
4342 scrolldown_clamp();
4343#endif
4344 }
4345 State = save_State;
4346#ifdef FEAT_MOUSE
4347 setmouse();
4348#endif
4349 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4350 --no_u_sync;
4351
4352 if (i == 'n')
4353 {
4354 /* For a multi-line match, put matchcol at the NUL at
4355 * the end of the line and set nmatch to one, so that
4356 * we continue looking for a match on the next line.
4357 * Avoids that ":s/\nB\@=//gc" get stuck. */
4358 if (nmatch > 1)
4359 {
4360 matchcol = STRLEN(sub_firstline);
4361 nmatch = 1;
4362 }
4363 goto skip;
4364 }
4365 if (got_quit)
4366 break;
4367 }
4368
4369 /* Move the cursor to the start of the match, so that we can
4370 * use "\=col("."). */
4371 curwin->w_cursor.col = regmatch.startpos[0].col;
4372
4373 /*
4374 * 3. substitute the string.
4375 */
4376 /* get length of substitution part */
4377 sublen = vim_regsub_multi(&regmatch, sub_firstlnum,
4378 sub, sub_firstline, FALSE, p_magic, TRUE);
4379
4380 /* Need room for:
4381 * - result so far in new_start (not for first sub in line)
4382 * - original text up to match
4383 * - length of substituted part
4384 * - original text after match
4385 */
4386 if (nmatch == 1)
4387 p1 = sub_firstline;
4388 else
4389 {
4390 p1 = ml_get(sub_firstlnum + nmatch - 1);
4391 nmatch_tl += nmatch - 1;
4392 }
4393 i = regmatch.startpos[0].col - copycol;
4394 needed_len = i + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col)
4395 + sublen + 1;
4396 if (new_start == NULL)
4397 {
4398 /*
4399 * Get some space for a temporary buffer to do the
4400 * substitution into (and some extra space to avoid
4401 * too many calls to alloc()/free()).
4402 */
4403 new_start_len = needed_len + 50;
4404 if ((new_start = alloc_check(new_start_len)) == NULL)
4405 goto outofmem;
4406 *new_start = NUL;
4407 new_end = new_start;
4408 }
4409 else
4410 {
4411 /*
4412 * Check if the temporary buffer is long enough to do the
4413 * substitution into. If not, make it larger (with a bit
4414 * extra to avoid too many calls to alloc()/free()).
4415 */
4416 len = (unsigned)STRLEN(new_start);
4417 needed_len += len;
4418 if (needed_len > new_start_len)
4419 {
4420 new_start_len = needed_len + 50;
4421 if ((p1 = alloc_check(new_start_len)) == NULL)
4422 {
4423 vim_free(new_start);
4424 goto outofmem;
4425 }
4426 mch_memmove(p1, new_start, (size_t)(len + 1));
4427 vim_free(new_start);
4428 new_start = p1;
4429 }
4430 new_end = new_start + len;
4431 }
4432
4433 /*
4434 * copy the text up to the part that matched
4435 */
4436 mch_memmove(new_end, sub_firstline + copycol, (size_t)i);
4437 new_end += i;
4438
4439 (void)vim_regsub_multi(&regmatch, sub_firstlnum,
4440 sub, new_end, TRUE, p_magic, TRUE);
4441 sub_nsubs++;
4442 did_sub = TRUE;
4443
4444 /* Move the cursor to the start of the line, to avoid that it
4445 * is beyond the end of the line after the substitution. */
4446 curwin->w_cursor.col = 0;
4447
4448 /* For a multi-line match, make a copy of the last matched
4449 * line and continue in that one. */
4450 if (nmatch > 1)
4451 {
4452 sub_firstlnum += nmatch - 1;
4453 vim_free(sub_firstline);
4454 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4455 /* When going beyond the last line, stop substituting. */
4456 if (sub_firstlnum <= line2)
4457 do_again = TRUE;
4458 else
4459 do_all = FALSE;
4460 }
4461
4462 /* Remember next character to be copied. */
4463 copycol = regmatch.endpos[0].col;
4464
4465 /*
4466 * Now the trick is to replace CTRL-M chars with a real line
4467 * break. This would make it impossible to insert a CTRL-M in
4468 * the text. The line break can be avoided by preceding the
4469 * CTRL-M with a backslash. To be able to insert a backslash,
4470 * they must be doubled in the string and are halved here.
4471 * That is Vi compatible.
4472 */
4473 for (p1 = new_end; *p1; ++p1)
4474 {
4475 if (p1[0] == '\\' && p1[1] != NUL) /* remove backslash */
4476 mch_memmove(p1, p1 + 1, STRLEN(p1));
4477 else if (*p1 == CAR)
4478 {
4479 if (u_inssub(lnum) == OK) /* prepare for undo */
4480 {
4481 *p1 = NUL; /* truncate up to the CR */
4482 ml_append(lnum - 1, new_start,
4483 (colnr_T)(p1 - new_start + 1), FALSE);
4484 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
4485 if (do_ask)
4486 appended_lines(lnum - 1, 1L);
4487 else
4488 {
4489 if (first_line == 0)
4490 first_line = lnum;
4491 last_line = lnum + 1;
4492 }
4493 /* All line numbers increase. */
4494 ++sub_firstlnum;
4495 ++lnum;
4496 ++line2;
4497 /* move the cursor to the new line, like Vi */
4498 ++curwin->w_cursor.lnum;
4499 STRCPY(new_start, p1 + 1); /* copy the rest */
4500 p1 = new_start - 1;
4501 }
4502 }
4503#ifdef FEAT_MBYTE
4504 else if (has_mbyte)
4505 p1 += (*mb_ptr2len_check)(p1) - 1;
4506#endif
4507 }
4508
4509 /*
4510 * 4. If do_all is set, find next match.
4511 * Prevent endless loop with patterns that match empty
4512 * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
4513 * But ":s/\n/#/" is OK.
4514 */
4515skip:
4516 /* We already know that we did the last subst when we are at
4517 * the end of the line, except that a pattern like
4518 * "bar\|\nfoo" may match at the NUL. */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004519 lastone = (skip_match
4520 || got_int
4521 || got_quit
4522 || !(do_all || do_again)
4523 || (sub_firstline[matchcol] == NUL && nmatch <= 1
4524 && !re_multiline(regmatch.regprog)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525 nmatch = -1;
4526
4527 /*
4528 * Replace the line in the buffer when needed. This is
4529 * skipped when there are more matches.
4530 * The check for nmatch_tl is needed for when multi-line
4531 * matching must replace the lines before trying to do another
4532 * match, otherwise "\@<=" won't work.
4533 * When asking the user we like to show the already replaced
4534 * text, but don't do it when "\<@=" or "\<@!" is used, it
4535 * changes what matches.
4536 */
4537 if (lastone
4538 || (do_ask && !re_lookbehind(regmatch.regprog))
4539 || nmatch_tl > 0
4540 || (nmatch = vim_regexec_multi(&regmatch, curwin,
4541 curbuf, sub_firstlnum, matchcol)) == 0)
4542 {
4543 if (new_start != NULL)
4544 {
4545 /*
4546 * Copy the rest of the line, that didn't match.
4547 * "matchcol" has to be adjusted, we use the end of
4548 * the line as reference, because the substitute may
4549 * have changed the number of characters. Same for
4550 * "prev_matchcol".
4551 */
4552 STRCAT(new_start, sub_firstline + copycol);
4553 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4554 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4555 - prev_matchcol;
4556
4557 if (u_savesub(lnum) != OK)
4558 break;
4559 ml_replace(lnum, new_start, TRUE);
4560
4561 if (nmatch_tl > 0)
4562 {
4563 /*
4564 * Matched lines have now been substituted and are
4565 * useless, delete them. The part after the match
4566 * has been appended to new_start, we don't need
4567 * it in the buffer.
4568 */
4569 ++lnum;
4570 if (u_savedel(lnum, nmatch_tl) != OK)
4571 break;
4572 for (i = 0; i < nmatch_tl; ++i)
4573 ml_delete(lnum, (int)FALSE);
4574 mark_adjust(lnum, lnum + nmatch_tl - 1,
4575 (long)MAXLNUM, -nmatch_tl);
4576 if (do_ask)
4577 deleted_lines(lnum, nmatch_tl);
4578 --lnum;
4579 line2 -= nmatch_tl; /* nr of lines decreases */
4580 nmatch_tl = 0;
4581 }
4582
4583 /* When asking, undo is saved each time, must also set
4584 * changed flag each time. */
4585 if (do_ask)
4586 changed_bytes(lnum, 0);
4587 else
4588 {
4589 if (first_line == 0)
4590 first_line = lnum;
4591 last_line = lnum + 1;
4592 }
4593
4594 sub_firstlnum = lnum;
4595 vim_free(sub_firstline); /* free the temp buffer */
4596 sub_firstline = new_start;
4597 new_start = NULL;
4598 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4599 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4600 - prev_matchcol;
4601 copycol = 0;
4602 }
4603 if (nmatch == -1 && !lastone)
4604 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf,
4605 sub_firstlnum, matchcol);
4606
4607 /*
4608 * 5. break if there isn't another match in this line
4609 */
4610 if (nmatch <= 0)
4611 break;
4612 }
4613
4614 line_breakcheck();
4615 }
4616
4617 if (did_sub)
4618 ++sub_nlines;
4619 vim_free(sub_firstline); /* free the copy of the original line */
4620 sub_firstline = NULL;
4621 }
4622
4623 line_breakcheck();
4624 }
4625
4626 if (first_line != 0)
4627 {
4628 /* Need to subtract the number of added lines from "last_line" to get
4629 * the line number before the change (same as adding the number of
4630 * deleted lines). */
4631 i = curbuf->b_ml.ml_line_count - old_line_count;
4632 changed_lines(first_line, 0, last_line - i, i);
4633 }
4634
4635outofmem:
4636 vim_free(sub_firstline); /* may have to free allocated copy of the line */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004637
4638 /* ":s/pat//n" doesn't move the cursor */
4639 if (do_count)
4640 curwin->w_cursor = old_cursor;
4641
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642 if (sub_nsubs)
4643 {
4644 /* Set the '[ and '] marks. */
4645 curbuf->b_op_start.lnum = eap->line1;
4646 curbuf->b_op_end.lnum = line2;
4647 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
4648
4649 if (!global_busy)
4650 {
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004651 if (endcolumn)
4652 coladvance((colnr_T)MAXCOL);
4653 else
4654 beginline(BL_WHITE | BL_FIX);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004655 if (!do_sub_msg(do_count) && do_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 MSG("");
4657 }
4658 else
4659 global_need_beginline = TRUE;
4660 if (do_print)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004661 print_line(curwin->w_cursor.lnum, do_number, do_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662 }
4663 else if (!global_busy)
4664 {
4665 if (got_int) /* interrupted */
4666 EMSG(_(e_interr));
4667 else if (got_match) /* did find something but nothing substituted */
4668 MSG("");
4669 else if (do_error) /* nothing found */
4670 EMSG2(_(e_patnotf2), get_search_pat());
4671 }
4672
4673 vim_free(regmatch.regprog);
4674}
4675
4676/*
4677 * Give message for number of substitutions.
4678 * Can also be used after a ":global" command.
4679 * Return TRUE if a message was given.
4680 */
4681 static int
Bram Moolenaar05159a02005-02-26 23:04:13 +00004682do_sub_msg(count_only)
4683 int count_only; /* used 'n' flag for ":s" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004684{
Bram Moolenaar555b2802005-05-19 21:08:39 +00004685 int len = 0;
4686
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 /*
4688 * Only report substitutions when:
4689 * - more than 'report' substitutions
4690 * - command was typed by user, or number of changed lines > 'report'
4691 * - giving messages is not disabled by 'lazyredraw'
4692 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004693 if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
4694 || count_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695 && messaging())
4696 {
4697 if (got_int)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004698 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699 STRCPY(msg_buf, _("(Interrupted) "));
Bram Moolenaar555b2802005-05-19 21:08:39 +00004700 len = STRLEN(msg_buf);
4701 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 if (sub_nsubs == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004703 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4704 "%s", count_only ? _("1 match") : _("1 substitution"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004706 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
Bram Moolenaar05159a02005-02-26 23:04:13 +00004707 count_only ? _("%ld matches") : _("%ld substitutions"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708 sub_nsubs);
Bram Moolenaar555b2802005-05-19 21:08:39 +00004709 len = STRLEN(msg_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 if (sub_nlines == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004711 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4712 "%s", _(" on 1 line"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004714 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4715 _(" on %ld lines"), (long)sub_nlines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 if (msg(msg_buf))
4717 {
4718 /* save message to display it after redraw */
4719 set_keep_msg(msg_buf);
4720 keep_msg_attr = 0;
4721 }
4722 return TRUE;
4723 }
4724 if (got_int)
4725 {
4726 EMSG(_(e_interr));
4727 return TRUE;
4728 }
4729 return FALSE;
4730}
4731
4732/*
4733 * Execute a global command of the form:
4734 *
4735 * g/pattern/X : execute X on all lines where pattern matches
4736 * v/pattern/X : execute X on all lines where pattern does not match
4737 *
4738 * where 'X' is an EX command
4739 *
4740 * The command character (as well as the trailing slash) is optional, and
4741 * is assumed to be 'p' if missing.
4742 *
4743 * This is implemented in two passes: first we scan the file for the pattern and
4744 * set a mark for each line that (not) matches. secondly we execute the command
4745 * for each line that has a mark. This is required because after deleting
4746 * lines we do not know where to search for the next match.
4747 */
4748 void
4749ex_global(eap)
4750 exarg_T *eap;
4751{
4752 linenr_T lnum; /* line number according to old situation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004753 int ndone = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 int type; /* first char of cmd: 'v' or 'g' */
4755 char_u *cmd; /* command argument */
4756
4757 char_u delim; /* delimiter, normally '/' */
4758 char_u *pat;
4759 regmmatch_T regmatch;
4760 int match;
4761 int which_pat;
4762
4763 if (global_busy)
4764 {
4765 EMSG(_("E147: Cannot do :global recursive")); /* will increment global_busy */
4766 return;
4767 }
4768
4769 if (eap->forceit) /* ":global!" is like ":vglobal" */
4770 type = 'v';
4771 else
4772 type = *eap->cmd;
4773 cmd = eap->arg;
4774 which_pat = RE_LAST; /* default: use last used regexp */
4775 sub_nsubs = 0;
4776 sub_nlines = 0;
4777
4778 /*
4779 * undocumented vi feature:
4780 * "\/" and "\?": use previous search pattern.
4781 * "\&": use previous substitute pattern.
4782 */
4783 if (*cmd == '\\')
4784 {
4785 ++cmd;
4786 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
4787 {
4788 EMSG(_(e_backslash));
4789 return;
4790 }
4791 if (*cmd == '&')
4792 which_pat = RE_SUBST; /* use previous substitute pattern */
4793 else
4794 which_pat = RE_SEARCH; /* use previous search pattern */
4795 ++cmd;
4796 pat = (char_u *)"";
4797 }
4798 else if (*cmd == NUL)
4799 {
4800 EMSG(_("E148: Regular expression missing from global"));
4801 return;
4802 }
4803 else
4804 {
4805 delim = *cmd; /* get the delimiter */
4806 if (delim)
4807 ++cmd; /* skip delimiter if there is one */
4808 pat = cmd; /* remember start of pattern */
4809 cmd = skip_regexp(cmd, delim, p_magic, &eap->arg);
4810 if (cmd[0] == delim) /* end delimiter found */
4811 *cmd++ = NUL; /* replace it with a NUL */
4812 }
4813
4814#ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */
4815 if (p_altkeymap && curwin->w_p_rl)
4816 lrFswap(pat,0);
4817#endif
4818
4819 if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4820 {
4821 EMSG(_(e_invcmd));
4822 return;
4823 }
4824
4825 /*
4826 * pass 1: set marks for each (not) matching line
4827 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 for (lnum = eap->line1; lnum <= eap->line2 && !got_int; ++lnum)
4829 {
4830 /* a match on this line? */
4831 match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
4832 if ((type == 'g' && match) || (type == 'v' && !match))
4833 {
4834 ml_setmarked(lnum);
4835 ndone++;
4836 }
4837 line_breakcheck();
4838 }
4839
4840 /*
4841 * pass 2: execute the command for each line that has been marked
4842 */
4843 if (got_int)
4844 MSG(_(e_interr));
4845 else if (ndone == 0)
4846 {
4847 if (type == 'v')
Bram Moolenaar555b2802005-05-19 21:08:39 +00004848 smsg((char_u *)_("Pattern found in every line: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004850 smsg((char_u *)_(e_patnotf2), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 }
4852 else
4853 global_exe(cmd);
4854
4855 ml_clearmarked(); /* clear rest of the marks */
4856 vim_free(regmatch.regprog);
4857}
4858
4859/*
4860 * Execute "cmd" on lines marked with ml_setmarked().
4861 */
4862 void
4863global_exe(cmd)
4864 char_u *cmd;
4865{
4866 linenr_T old_lcount; /* b_ml.ml_line_count before the command */
4867 linenr_T lnum; /* line number according to old situation */
4868
4869 /*
4870 * Set current position only once for a global command.
4871 * If global_busy is set, setpcmark() will not do anything.
4872 * If there is an error, global_busy will be incremented.
4873 */
4874 setpcmark();
4875
4876 /* When the command writes a message, don't overwrite the command. */
4877 msg_didout = TRUE;
4878
4879 global_need_beginline = FALSE;
4880 global_busy = 1;
4881 old_lcount = curbuf->b_ml.ml_line_count;
4882 while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1)
4883 {
4884 curwin->w_cursor.lnum = lnum;
4885 curwin->w_cursor.col = 0;
4886 if (*cmd == NUL || *cmd == '\n')
4887 do_cmdline((char_u *)"p", NULL, NULL, DOCMD_NOWAIT);
4888 else
4889 do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
4890 ui_breakcheck();
4891 }
4892
4893 global_busy = 0;
4894 if (global_need_beginline)
4895 beginline(BL_WHITE | BL_FIX);
4896 else
4897 check_cursor(); /* cursor may be beyond the end of the line */
4898
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004899 /* the cursor may not have moved in the text but a change in a previous
4900 * line may move it on the screen */
4901 changed_line_abv_curs();
4902
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 /* If it looks like no message was written, allow overwriting the
4904 * command with the report for number of changes. */
4905 if (msg_col == 0 && msg_scrolled == 0)
4906 msg_didout = FALSE;
4907
4908 /* If subsitutes done, report number of substitues, otherwise report
4909 * number of extra or deleted lines. */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004910 if (!do_sub_msg(FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 msgmore(curbuf->b_ml.ml_line_count - old_lcount);
4912}
4913
4914#ifdef FEAT_VIMINFO
4915 int
4916read_viminfo_sub_string(virp, force)
4917 vir_T *virp;
4918 int force;
4919{
4920 if (old_sub != NULL && force)
4921 vim_free(old_sub);
4922 if (force || old_sub == NULL)
4923 old_sub = viminfo_readstring(virp, 1, TRUE);
4924 return viminfo_readline(virp);
4925}
4926
4927 void
4928write_viminfo_sub_string(fp)
4929 FILE *fp;
4930{
4931 if (get_viminfo_parameter('/') != 0 && old_sub != NULL)
4932 {
4933 fprintf(fp, _("\n# Last Substitute String:\n$"));
4934 viminfo_writestring(fp, old_sub);
4935 }
4936}
4937#endif /* FEAT_VIMINFO */
4938
4939#if (defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)) || defined(PROTO)
4940/*
4941 * Set up for a tagpreview.
4942 */
4943 void
4944prepare_tagpreview()
4945{
4946 win_T *wp;
4947
4948# ifdef FEAT_GUI
4949 need_mouse_correct = TRUE;
4950# endif
4951
4952 /*
4953 * If there is already a preview window open, use that one.
4954 */
4955 if (!curwin->w_p_pvw)
4956 {
4957 for (wp = firstwin; wp != NULL; wp = wp->w_next)
4958 if (wp->w_p_pvw)
4959 break;
4960 if (wp != NULL)
4961 win_enter(wp, TRUE);
4962 else
4963 {
4964 /*
4965 * There is no preview window open yet. Create one.
4966 */
4967 if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0)
4968 == FAIL)
4969 return;
4970 curwin->w_p_pvw = TRUE;
4971 curwin->w_p_wfh = TRUE;
4972# ifdef FEAT_SCROLLBIND
4973 curwin->w_p_scb = FALSE; /* don't take over 'scrollbind' */
4974# endif
4975# ifdef FEAT_DIFF
4976 curwin->w_p_diff = FALSE; /* no 'diff' */
4977# endif
4978# ifdef FEAT_FOLDING
4979 curwin->w_p_fdc = 0; /* no 'foldcolumn' */
4980# endif
4981 }
4982 }
4983}
4984
4985#endif
4986
4987
4988/*
4989 * ":help": open a read-only window on a help file
4990 */
4991 void
4992ex_help(eap)
4993 exarg_T *eap;
4994{
4995 char_u *arg;
4996 char_u *tag;
4997 FILE *helpfd; /* file descriptor of help file */
4998 int n;
4999 int i;
5000#ifdef FEAT_WINDOWS
5001 win_T *wp;
5002#endif
5003 int num_matches;
5004 char_u **matches;
5005 char_u *p;
5006 int empty_fnum = 0;
5007 int alt_fnum = 0;
5008 buf_T *buf;
5009#ifdef FEAT_MULTI_LANG
5010 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005011 char_u *lang;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012#endif
5013
5014 if (eap != NULL)
5015 {
5016 /*
5017 * A ":help" command ends at the first LF, or at a '|' that is
5018 * followed by some text. Set nextcmd to the following command.
5019 */
5020 for (arg = eap->arg; *arg; ++arg)
5021 {
5022 if (*arg == '\n' || *arg == '\r'
5023 || (*arg == '|' && arg[1] != NUL && arg[1] != '|'))
5024 {
5025 *arg++ = NUL;
5026 eap->nextcmd = arg;
5027 break;
5028 }
5029 }
5030 arg = eap->arg;
5031
5032 if (eap->forceit && *arg == NUL)
5033 {
5034 EMSG(_("E478: Don't panic!"));
5035 return;
5036 }
5037
5038 if (eap->skip) /* not executing commands */
5039 return;
5040 }
5041 else
5042 arg = (char_u *)"";
5043
5044 /* remove trailing blanks */
5045 p = arg + STRLEN(arg) - 1;
5046 while (p > arg && vim_iswhite(*p) && p[-1] != '\\')
5047 *p-- = NUL;
5048
5049#ifdef FEAT_MULTI_LANG
5050 /* Check for a specified language */
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005051 lang = check_help_lang(arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052#endif
5053
5054 /* When no argument given go to the index. */
5055 if (*arg == NUL)
5056 arg = (char_u *)"help.txt";
5057
5058 /*
5059 * Check if there is a match for the argument.
5060 */
5061 n = find_help_tags(arg, &num_matches, &matches,
5062 eap != NULL && eap->forceit);
5063
5064 i = 0;
5065#ifdef FEAT_MULTI_LANG
5066 if (n != FAIL && lang != NULL)
5067 /* Find first item with the requested language. */
5068 for (i = 0; i < num_matches; ++i)
5069 {
5070 len = STRLEN(matches[i]);
5071 if (len > 3 && matches[i][len - 3] == '@'
5072 && STRICMP(matches[i] + len - 2, lang) == 0)
5073 break;
5074 }
5075#endif
5076 if (i >= num_matches || n == FAIL)
5077 {
5078#ifdef FEAT_MULTI_LANG
5079 if (lang != NULL)
5080 EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg);
5081 else
5082#endif
5083 EMSG2(_("E149: Sorry, no help for %s"), arg);
5084 if (n != FAIL)
5085 FreeWild(num_matches, matches);
5086 return;
5087 }
5088
5089 /* The first match (in the requested language) is the best match. */
5090 tag = vim_strsave(matches[i]);
5091 FreeWild(num_matches, matches);
5092
5093#ifdef FEAT_GUI
5094 need_mouse_correct = TRUE;
5095#endif
5096
5097 /*
5098 * Re-use an existing help window or open a new one.
5099 */
5100 if (!curwin->w_buffer->b_help)
5101 {
5102#ifdef FEAT_WINDOWS
5103 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5104 if (wp->w_buffer != NULL && wp->w_buffer->b_help)
5105 break;
5106 if (wp != NULL && wp->w_buffer->b_nwindows > 0)
5107 win_enter(wp, TRUE);
5108 else
5109#endif
5110 {
5111 /*
5112 * There is no help window yet.
5113 * Try to open the file specified by the "helpfile" option.
5114 */
5115 if ((helpfd = mch_fopen((char *)p_hf, READBIN)) == NULL)
5116 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00005117 smsg((char_u *)_("Sorry, help file \"%s\" not found"), p_hf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005118 goto erret;
5119 }
5120 fclose(helpfd);
5121
5122#ifdef FEAT_WINDOWS
5123 /* Split off help window; put it at far top if no position
5124 * specified, the current window is vertically split and narrow. */
5125 n = WSP_HELP;
5126# ifdef FEAT_VERTSPLIT
5127 if (cmdmod.split == 0 && curwin->w_width != Columns
5128 && curwin->w_width < 80)
5129 n |= WSP_TOP;
5130# endif
5131 if (win_split(0, n) == FAIL)
5132#else
5133 /* use current window */
5134 if (!can_abandon(curbuf, FALSE))
5135#endif
5136 goto erret;
5137
5138#ifdef FEAT_WINDOWS
5139 if (curwin->w_height < p_hh)
5140 win_setheight((int)p_hh);
5141#endif
5142
5143 /*
5144 * Open help file (do_ecmd() will set b_help flag, readfile() will
5145 * set b_p_ro flag).
5146 * Set the alternate file to the previously edited file.
5147 */
5148 alt_fnum = curbuf->b_fnum;
5149 (void)do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL,
5150 ECMD_HIDE + ECMD_SET_HELP);
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005151 if (!cmdmod.keepalt)
5152 curwin->w_alt_fnum = alt_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005153 empty_fnum = curbuf->b_fnum;
5154 }
5155 }
5156
5157 if (!p_im)
5158 restart_edit = 0; /* don't want insert mode in help file */
5159
5160 if (tag != NULL)
5161 do_tag(tag, DT_HELP, 1, FALSE, TRUE);
5162
5163 /* Delete the empty buffer if we're not using it. */
5164 if (empty_fnum != 0 && curbuf->b_fnum != empty_fnum)
5165 {
5166 buf = buflist_findnr(empty_fnum);
5167 if (buf != NULL)
5168 wipe_buffer(buf, TRUE);
5169 }
5170
5171 /* keep the previous alternate file */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005172 if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 curwin->w_alt_fnum = alt_fnum;
5174
5175erret:
5176 vim_free(tag);
5177}
5178
5179
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005180#if defined(FEAT_MULTI_LANG) || defined(PROTO)
5181/*
5182 * In an argument search for a language specifiers in the form "@xx".
5183 * Changes the "@" to NUL if found, and returns a pointer to "xx".
5184 * Returns NULL if not found.
5185 */
5186 char_u *
5187check_help_lang(arg)
5188 char_u *arg;
5189{
5190 int len = STRLEN(arg);
5191
5192 if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2])
5193 && ASCII_ISALPHA(arg[len - 1]))
5194 {
5195 arg[len - 3] = NUL; /* remove the '@' */
5196 return arg + len - 2;
5197 }
5198 return NULL;
5199}
5200#endif
5201
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202/*
5203 * Return a heuristic indicating how well the given string matches. The
5204 * smaller the number, the better the match. This is the order of priorities,
5205 * from best match to worst match:
5206 * - Match with least alpha-numeric characters is better.
5207 * - Match with least total characters is better.
5208 * - Match towards the start is better.
5209 * - Match starting with "+" is worse (feature instead of command)
5210 * Assumption is made that the matched_string passed has already been found to
5211 * match some string for which help is requested. webb.
5212 */
5213 int
5214help_heuristic(matched_string, offset, wrong_case)
5215 char_u *matched_string;
5216 int offset; /* offset for match */
5217 int wrong_case; /* no matching case */
5218{
5219 int num_letters;
5220 char_u *p;
5221
5222 num_letters = 0;
5223 for (p = matched_string; *p; p++)
5224 if (ASCII_ISALNUM(*p))
5225 num_letters++;
5226
5227 /*
5228 * Multiply the number of letters by 100 to give it a much bigger
5229 * weighting than the number of characters.
5230 * If there only is a match while ignoring case, add 5000.
5231 * If the match starts in the middle of a word, add 10000 to put it
5232 * somewhere in the last half.
5233 * If the match is more than 2 chars from the start, multiply by 200 to
5234 * put it after matches at the start.
5235 */
5236 if (ASCII_ISALNUM(matched_string[offset]) && offset > 0
5237 && ASCII_ISALNUM(matched_string[offset - 1]))
5238 offset += 10000;
5239 else if (offset > 2)
5240 offset *= 200;
5241 if (wrong_case)
5242 offset += 5000;
5243 /* Features are less interesting than the subjects themselves, but "+"
5244 * alone is not a feature. */
5245 if (matched_string[0] == '+' && matched_string[1] != NUL)
5246 offset += 100;
5247 return (int)(100 * num_letters + STRLEN(matched_string) + offset);
5248}
5249
5250/*
5251 * Compare functions for qsort() below, that checks the help heuristics number
5252 * that has been put after the tagname by find_tags().
5253 */
5254 static int
5255#ifdef __BORLANDC__
5256_RTLENTRYF
5257#endif
5258help_compare(s1, s2)
5259 const void *s1;
5260 const void *s2;
5261{
5262 char *p1;
5263 char *p2;
5264
5265 p1 = *(char **)s1 + strlen(*(char **)s1) + 1;
5266 p2 = *(char **)s2 + strlen(*(char **)s2) + 1;
5267 return strcmp(p1, p2);
5268}
5269
5270/*
5271 * Find all help tags matching "arg", sort them and return in matches[], with
5272 * the number of matches in num_matches.
5273 * The matches will be sorted with a "best" match algorithm.
5274 * When "keep_lang" is TRUE try keeping the language of the current buffer.
5275 */
5276 int
5277find_help_tags(arg, num_matches, matches, keep_lang)
5278 char_u *arg;
5279 int *num_matches;
5280 char_u ***matches;
5281 int keep_lang;
5282{
5283 char_u *s, *d;
5284 int i;
5285 static char *(mtable[]) = {"*", "g*", "[*", "]*", ":*",
5286 "/*", "/\\*", "\"*", "/\\(\\)",
5287 "?", ":?", "?<CR>", "g?", "g?g?", "g??",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005288 "/\\?", "/\\z(\\)", "\\=", ":s\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005289 "[count]", "[quotex]", "[range]",
5290 "[pattern]", "\\|", "\\%$"};
5291 static char *(rtable[]) = {"star", "gstar", "[star", "]star", ":star",
5292 "/star", "/\\\\star", "quotestar", "/\\\\(\\\\)",
5293 "?", ":?", "?<CR>", "g?", "g?g?", "g??",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005294 "/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295 "\\[count]", "\\[quotex]", "\\[range]",
5296 "\\[pattern]", "\\\\bar", "/\\\\%\\$"};
5297 int flags;
5298
5299 d = IObuff; /* assume IObuff is long enough! */
5300
5301 /*
5302 * Recognize a few exceptions to the rule. Some strings that contain '*'
5303 * with "star". Otherwise '*' is recognized as a wildcard.
5304 */
5305 for (i = sizeof(mtable) / sizeof(char *); --i >= 0; )
5306 if (STRCMP(arg, mtable[i]) == 0)
5307 {
5308 STRCPY(d, rtable[i]);
5309 break;
5310 }
5311
5312 if (i < 0) /* no match in table */
5313 {
5314 /* Replace "\S" with "/\\S", etc. Otherwise every tag is matched.
5315 * Also replace "\%^" and "\%(", they match every tag too.
5316 * Also "\zs", "\z1", etc.
5317 * Also "\@<", "\@=", "\@<=", etc.
5318 * And also "\_$" and "\_^". */
5319 if (arg[0] == '\\'
5320 && ((arg[1] != NUL && arg[2] == NUL)
5321 || (vim_strchr((char_u *)"%_z@", arg[1]) != NULL
5322 && arg[2] != NUL)))
5323 {
5324 STRCPY(d, "/\\\\");
5325 STRCPY(d + 3, arg + 1);
5326 /* Check for "/\\_$", should be "/\\_\$" */
5327 if (d[3] == '_' && d[4] == '$')
5328 STRCPY(d + 4, "\\$");
5329 }
5330 else
5331 {
5332 /* replace "[:...:]" with "\[:...:]"; "[+...]" with "\[++...]" */
5333 if (arg[0] == '[' && (arg[1] == ':'
5334 || (arg[1] == '+' && arg[2] == '+')))
5335 *d++ = '\\';
5336
5337 for (s = arg; *s; ++s)
5338 {
5339 /*
5340 * Replace "|" with "bar" and '"' with "quote" to match the name of
5341 * the tags for these commands.
5342 * Replace "*" with ".*" and "?" with "." to match command line
5343 * completion.
5344 * Insert a backslash before '~', '$' and '.' to avoid their
5345 * special meaning.
5346 */
5347 if (d - IObuff > IOSIZE - 10) /* getting too long!? */
5348 break;
5349 switch (*s)
5350 {
5351 case '|': STRCPY(d, "bar");
5352 d += 3;
5353 continue;
5354 case '"': STRCPY(d, "quote");
5355 d += 5;
5356 continue;
5357 case '*': *d++ = '.';
5358 break;
5359 case '?': *d++ = '.';
5360 continue;
5361 case '$':
5362 case '.':
5363 case '~': *d++ = '\\';
5364 break;
5365 }
5366
5367 /*
5368 * Replace "^x" by "CTRL-X". Don't do this for "^_" to make
5369 * ":help i_^_CTRL-D" work.
5370 * Insert '-' before and after "CTRL-X" when applicable.
5371 */
5372 if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1])
5373 || vim_strchr((char_u *)"?@[\\]^", s[1]) != NULL)))
5374 {
5375 if (d > IObuff && d[-1] != '_')
5376 *d++ = '_'; /* prepend a '_' */
5377 STRCPY(d, "CTRL-");
5378 d += 5;
5379 if (*s < ' ')
5380 {
5381#ifdef EBCDIC
5382 *d++ = CtrlChar(*s);
5383#else
5384 *d++ = *s + '@';
5385#endif
5386 if (d[-1] == '\\')
5387 *d++ = '\\'; /* double a backslash */
5388 }
5389 else
5390 *d++ = *++s;
5391 if (s[1] != NUL && s[1] != '_')
5392 *d++ = '_'; /* append a '_' */
5393 continue;
5394 }
5395 else if (*s == '^') /* "^" or "CTRL-^" or "^_" */
5396 *d++ = '\\';
5397
5398 /*
5399 * Insert a backslash before a backslash after a slash, for search
5400 * pattern tags: "/\|" --> "/\\|".
5401 */
5402 else if (s[0] == '\\' && s[1] != '\\'
5403 && *arg == '/' && s == arg + 1)
5404 *d++ = '\\';
5405
5406 /* "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in
5407 * "CTRL-\_CTRL-N" */
5408 if (STRNICMP(s, "CTRL-\\_", 7) == 0)
5409 {
5410 STRCPY(d, "CTRL-\\\\");
5411 d += 7;
5412 s += 6;
5413 }
5414
5415 *d++ = *s;
5416
5417 /*
5418 * If tag starts with ', toss everything after a second '. Fixes
5419 * CTRL-] on 'option'. (would include the trailing '.').
5420 */
5421 if (*s == '\'' && s > arg && *arg == '\'')
5422 break;
5423 }
5424 *d = NUL;
5425 }
5426 }
5427
5428 *matches = (char_u **)"";
5429 *num_matches = 0;
5430 flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE;
5431 if (keep_lang)
5432 flags |= TAG_KEEP_LANG;
5433 if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK
5434 && *num_matches > 0)
5435 /* Sort the matches found on the heuristic number that is after the
5436 * tag name. */
5437 qsort((void *)*matches, (size_t)*num_matches,
5438 sizeof(char_u *), help_compare);
5439 return OK;
5440}
5441
5442/*
5443 * After reading a help file: May cleanup a help buffer when syntax
5444 * highlighting is not used.
5445 */
5446 void
5447fix_help_buffer()
5448{
5449 linenr_T lnum;
5450 char_u *line;
5451 int in_example = FALSE;
5452 int len;
5453 char_u *p;
5454 char_u *rt;
5455 int mustfree;
5456
5457 /* set filetype to "help". */
5458 set_option_value((char_u *)"ft", 0L, (char_u *)"help", OPT_LOCAL);
5459
5460#ifdef FEAT_SYN_HL
5461 if (!syntax_present(curbuf))
5462#endif
5463 {
5464 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
5465 {
5466 line = ml_get_buf(curbuf, lnum, FALSE);
5467 len = (int)STRLEN(line);
5468 if (in_example && len > 0 && !vim_iswhite(line[0]))
5469 {
5470 /* End of example: non-white or '<' in first column. */
5471 if (line[0] == '<')
5472 {
5473 /* blank-out a '<' in the first column */
5474 line = ml_get_buf(curbuf, lnum, TRUE);
5475 line[0] = ' ';
5476 }
5477 in_example = FALSE;
5478 }
5479 if (!in_example && len > 0)
5480 {
5481 if (line[len - 1] == '>' && (len == 1 || line[len - 2] == ' '))
5482 {
5483 /* blank-out a '>' in the last column (start of example) */
5484 line = ml_get_buf(curbuf, lnum, TRUE);
5485 line[len - 1] = ' ';
5486 in_example = TRUE;
5487 }
5488 else if (line[len - 1] == '~')
5489 {
5490 /* blank-out a '~' at the end of line (header marker) */
5491 line = ml_get_buf(curbuf, lnum, TRUE);
5492 line[len - 1] = ' ';
5493 }
5494 }
5495 }
5496 }
5497
5498 /*
5499 * In the "help.txt" file, add the locally added help files.
5500 * This uses the very first line in the help file.
5501 */
5502 if (fnamecmp(gettail(curbuf->b_fname), "help.txt") == 0)
5503 {
5504 for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; ++lnum)
5505 {
5506 line = ml_get_buf(curbuf, lnum, FALSE);
5507 if (strstr((char *)line, "*local-additions*") != NULL)
5508 {
5509 /* Go through all directories in 'runtimepath', skipping
5510 * $VIMRUNTIME. */
5511 p = p_rtp;
5512 while (*p != NUL)
5513 {
5514 copy_option_part(&p, NameBuff, MAXPATHL, ",");
5515 mustfree = FALSE;
5516 rt = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
5517 if (fullpathcmp(rt, NameBuff, FALSE) != FPC_SAME)
5518 {
5519 int fcount;
5520 char_u **fnames;
5521 FILE *fd;
5522 char_u *s;
5523 int fi;
5524#ifdef FEAT_MBYTE
5525 vimconv_T vc;
5526 char_u *cp;
5527#endif
5528
5529 /* Find all "doc/ *.txt" files in this directory. */
5530 add_pathsep(NameBuff);
5531 STRCAT(NameBuff, "doc/*.txt");
5532 if (gen_expand_wildcards(1, &NameBuff, &fcount,
5533 &fnames, EW_FILE|EW_SILENT) == OK
5534 && fcount > 0)
5535 {
5536 for (fi = 0; fi < fcount; ++fi)
5537 {
5538 fd = fopen((char *)fnames[fi], "r");
5539 if (fd != NULL)
5540 {
5541 vim_fgets(IObuff, IOSIZE, fd);
5542 if (IObuff[0] == '*'
5543 && (s = vim_strchr(IObuff + 1, '*'))
5544 != NULL)
5545 {
5546#ifdef FEAT_MBYTE
5547 int this_utf = MAYBE;
5548#endif
5549 /* Change tag definition to a
5550 * reference and remove <CR>/<NL>. */
5551 IObuff[0] = '|';
5552 *s = '|';
5553 while (*s != NUL)
5554 {
5555 if (*s == '\r' || *s == '\n')
5556 *s = NUL;
5557#ifdef FEAT_MBYTE
5558 /* The text is utf-8 when a byte
5559 * above 127 is found and no
5560 * illegal byte sequence is found.
5561 */
5562 if (*s >= 0x80 && this_utf != FALSE)
5563 {
5564 int l;
5565
5566 this_utf = TRUE;
5567 l = utf_ptr2len_check(s);
5568 if (l == 1)
5569 this_utf = FALSE;
5570 s += l - 1;
5571 }
5572#endif
5573 ++s;
5574 }
5575#ifdef FEAT_MBYTE
5576 /* The help file is latin1 or utf-8;
5577 * conversion to the current
5578 * 'encoding' may be required. */
5579 vc.vc_type = CONV_NONE;
5580 convert_setup(&vc, (char_u *)(
5581 this_utf == TRUE ? "utf-8"
5582 : "latin1"), p_enc);
5583 if (vc.vc_type == CONV_NONE)
5584 /* No conversion needed. */
5585 cp = IObuff;
5586 else
5587 {
5588 /* Do the conversion. If it fails
5589 * use the unconverted text. */
5590 cp = string_convert(&vc, IObuff,
5591 NULL);
5592 if (cp == NULL)
5593 cp = IObuff;
5594 }
5595 convert_setup(&vc, NULL, NULL);
5596
5597 ml_append(lnum, cp, (colnr_T)0, FALSE);
5598 if (cp != IObuff)
5599 vim_free(cp);
5600#else
5601 ml_append(lnum, IObuff, (colnr_T)0,
5602 FALSE);
5603#endif
5604 ++lnum;
5605 }
5606 fclose(fd);
5607 }
5608 }
5609 FreeWild(fcount, fnames);
5610 }
5611 }
5612 if (mustfree)
5613 vim_free(rt);
5614 }
5615 break;
5616 }
5617 }
5618 }
5619}
5620
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00005621/*
5622 * ":exusage"
5623 */
5624/*ARGSUSED*/
5625 void
5626ex_exusage(eap)
5627 exarg_T *eap;
5628{
5629 do_cmdline_cmd((char_u *)"help ex-cmd-index");
5630}
5631
5632/*
5633 * ":viusage"
5634 */
5635/*ARGSUSED*/
5636 void
5637ex_viusage(eap)
5638 exarg_T *eap;
5639{
5640 do_cmdline_cmd((char_u *)"help normal-index");
5641}
5642
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643#if defined(FEAT_EX_EXTRA) || defined(PROTO)
5644static void helptags_one __ARGS((char_u *dir, char_u *ext, char_u *lang));
5645
5646/*
5647 * ":helptags"
5648 */
5649 void
5650ex_helptags(eap)
5651 exarg_T *eap;
5652{
5653 garray_T ga;
5654 int i, j;
5655 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005656#ifdef FEAT_MULTI_LANG
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 char_u lang[2];
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005658#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659 char_u ext[5];
5660 char_u fname[8];
5661 int filecount;
5662 char_u **files;
5663
5664 if (!mch_isdir(eap->arg))
5665 {
5666 EMSG2(_("E150: Not a directory: %s"), eap->arg);
5667 return;
5668 }
5669
5670#ifdef FEAT_MULTI_LANG
5671 /* Get a list of all files in the directory. */
5672 STRCPY(NameBuff, eap->arg);
5673 add_pathsep(NameBuff);
5674 STRCAT(NameBuff, "*");
5675 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
5676 EW_FILE|EW_SILENT) == FAIL
5677 || filecount == 0)
5678 {
5679 EMSG2("E151: No match: %s", NameBuff);
5680 return;
5681 }
5682
5683 /* Go over all files in the directory to find out what languages are
5684 * present. */
5685 ga_init2(&ga, 1, 10);
5686 for (i = 0; i < filecount; ++i)
5687 {
5688 len = STRLEN(files[i]);
5689 if (len > 4)
5690 {
5691 if (STRICMP(files[i] + len - 4, ".txt") == 0)
5692 {
5693 /* ".txt" -> language "en" */
5694 lang[0] = 'e';
5695 lang[1] = 'n';
5696 }
5697 else if (files[i][len - 4] == '.'
5698 && ASCII_ISALPHA(files[i][len - 3])
5699 && ASCII_ISALPHA(files[i][len - 2])
5700 && TOLOWER_ASC(files[i][len - 1]) == 'x')
5701 {
5702 /* ".abx" -> language "ab" */
5703 lang[0] = TOLOWER_ASC(files[i][len - 3]);
5704 lang[1] = TOLOWER_ASC(files[i][len - 2]);
5705 }
5706 else
5707 continue;
5708
5709 /* Did we find this language already? */
5710 for (j = 0; j < ga.ga_len; j += 2)
5711 if (STRNCMP(lang, ((char_u *)ga.ga_data) + j, 2) == 0)
5712 break;
5713 if (j == ga.ga_len)
5714 {
5715 /* New language, add it. */
5716 if (ga_grow(&ga, 2) == FAIL)
5717 break;
5718 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[0];
5719 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 }
5721 }
5722 }
5723
5724 /*
5725 * Loop over the found languages to generate a tags file for each one.
5726 */
5727 for (j = 0; j < ga.ga_len; j += 2)
5728 {
5729 STRCPY(fname, "tags-xx");
5730 fname[5] = ((char_u *)ga.ga_data)[j];
5731 fname[6] = ((char_u *)ga.ga_data)[j + 1];
5732 if (fname[5] == 'e' && fname[6] == 'n')
5733 {
5734 /* English is an exception: use ".txt" and "tags". */
5735 fname[4] = NUL;
5736 STRCPY(ext, ".txt");
5737 }
5738 else
5739 {
5740 /* Language "ab" uses ".abx" and "tags-ab". */
5741 STRCPY(ext, ".xxx");
5742 ext[1] = fname[5];
5743 ext[2] = fname[6];
5744 }
5745 helptags_one(eap->arg, ext, fname);
5746 }
5747
5748 ga_clear(&ga);
5749 FreeWild(filecount, files);
5750
5751#else
5752 /* No language support, just use "*.txt" and "tags". */
5753 helptags_one(eap->arg, (char_u *)".txt", (char_u *)"tags");
5754#endif
5755}
5756
5757 static void
5758helptags_one(dir, ext, tagfname)
5759 char_u *dir; /* doc directory */
5760 char_u *ext; /* suffix, ".txt", ".itx", ".frx", etc. */
5761 char_u *tagfname; /* "tags" for English, "tags-it" for Italian. */
5762{
5763 FILE *fd_tags;
5764 FILE *fd;
5765 garray_T ga;
5766 int filecount;
5767 char_u **files;
5768 char_u *p1, *p2;
5769 int fi;
5770 char_u *s;
5771 int i;
5772 char_u *fname;
5773# ifdef FEAT_MBYTE
5774 int utf8 = MAYBE;
5775 int this_utf8;
5776 int firstline;
5777 int mix = FALSE; /* detected mixed encodings */
5778# endif
5779
5780 /*
5781 * Find all *.txt files.
5782 */
5783 STRCPY(NameBuff, dir);
5784 add_pathsep(NameBuff);
5785 STRCAT(NameBuff, "*");
5786 STRCAT(NameBuff, ext);
5787 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
5788 EW_FILE|EW_SILENT) == FAIL
5789 || filecount == 0)
5790 {
5791 if (!got_int)
5792 EMSG2("E151: No match: %s", NameBuff);
5793 return;
5794 }
5795
5796 /*
5797 * Open the tags file for writing.
5798 * Do this before scanning through all the files.
5799 */
5800 STRCPY(NameBuff, dir);
5801 add_pathsep(NameBuff);
5802 STRCAT(NameBuff, tagfname);
5803 fd_tags = fopen((char *)NameBuff, "w");
5804 if (fd_tags == NULL)
5805 {
5806 EMSG2(_("E152: Cannot open %s for writing"), NameBuff);
5807 FreeWild(filecount, files);
5808 return;
5809 }
5810
5811 /*
5812 * If generating tags for "$VIMRUNTIME/doc" add the "help-tags" tag.
5813 */
5814 ga_init2(&ga, (int)sizeof(char_u *), 100);
5815 if (fullpathcmp((char_u *)"$VIMRUNTIME/doc", dir, FALSE) == FPC_SAME)
5816 {
5817 if (ga_grow(&ga, 1) == FAIL)
5818 got_int = TRUE;
5819 else
5820 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00005821 s = alloc(18 + STRLEN(tagfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822 if (s == NULL)
5823 got_int = TRUE;
5824 else
5825 {
5826 sprintf((char *)s, "help-tags\t%s\t1\n", tagfname);
5827 ((char_u **)ga.ga_data)[ga.ga_len] = s;
5828 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 }
5830 }
5831 }
5832
5833 /*
5834 * Go over all the files and extract the tags.
5835 */
5836 for (fi = 0; fi < filecount && !got_int; ++fi)
5837 {
5838 fd = fopen((char *)files[fi], "r");
5839 if (fd == NULL)
5840 {
5841 EMSG2(_("E153: Unable to open %s for reading"), files[fi]);
5842 continue;
5843 }
5844 fname = gettail(files[fi]);
5845
5846# ifdef FEAT_MBYTE
5847 firstline = TRUE;
5848# endif
5849 while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int)
5850 {
5851# ifdef FEAT_MBYTE
5852 if (firstline)
5853 {
5854 /* Detect utf-8 file by a non-ASCII char in the first line. */
5855 this_utf8 = MAYBE;
5856 for (s = IObuff; *s != NUL; ++s)
5857 if (*s >= 0x80)
5858 {
5859 int l;
5860
5861 this_utf8 = TRUE;
5862 l = utf_ptr2len_check(s);
5863 if (l == 1)
5864 {
5865 /* Illegal UTF-8 byte sequence. */
5866 this_utf8 = FALSE;
5867 break;
5868 }
5869 s += l - 1;
5870 }
5871 if (this_utf8 == MAYBE) /* only ASCII characters found */
5872 this_utf8 = FALSE;
5873 if (utf8 == MAYBE) /* first file */
5874 utf8 = this_utf8;
5875 else if (utf8 != this_utf8)
5876 {
5877 EMSG2(_("E670: Mix of help file encodings within a language: %s"), files[fi]);
5878 mix = !got_int;
5879 got_int = TRUE;
5880 }
5881 firstline = FALSE;
5882 }
5883# endif
5884 p1 = vim_strchr(IObuff, '*'); /* find first '*' */
5885 while (p1 != NULL)
5886 {
5887 p2 = vim_strchr(p1 + 1, '*'); /* find second '*' */
5888 if (p2 != NULL && p2 > p1 + 1) /* skip "*" and "**" */
5889 {
5890 for (s = p1 + 1; s < p2; ++s)
5891 if (*s == ' ' || *s == '\t' || *s == '|')
5892 break;
5893
5894 /*
5895 * Only accept a *tag* when it consists of valid
5896 * characters, there is white space before it and is
5897 * followed by a white character or end-of-line.
5898 */
5899 if (s == p2
5900 && (p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
5901 && (vim_strchr((char_u *)" \t\n\r", s[1]) != NULL
5902 || s[1] == '\0'))
5903 {
5904 *p2 = '\0';
5905 ++p1;
5906 if (ga_grow(&ga, 1) == FAIL)
5907 {
5908 got_int = TRUE;
5909 break;
5910 }
5911 s = alloc((unsigned)(p2 - p1 + STRLEN(fname) + 2));
5912 if (s == NULL)
5913 {
5914 got_int = TRUE;
5915 break;
5916 }
5917 ((char_u **)ga.ga_data)[ga.ga_len] = s;
5918 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919 sprintf((char *)s, "%s\t%s", p1, fname);
5920
5921 /* find next '*' */
5922 p2 = vim_strchr(p2 + 1, '*');
5923 }
5924 }
5925 p1 = p2;
5926 }
5927 line_breakcheck();
5928 }
5929
5930 fclose(fd);
5931 }
5932
5933 FreeWild(filecount, files);
5934
5935 if (!got_int)
5936 {
5937 /*
5938 * Sort the tags.
5939 */
5940 sort_strings((char_u **)ga.ga_data, ga.ga_len);
5941
5942 /*
5943 * Check for duplicates.
5944 */
5945 for (i = 1; i < ga.ga_len; ++i)
5946 {
5947 p1 = ((char_u **)ga.ga_data)[i - 1];
5948 p2 = ((char_u **)ga.ga_data)[i];
5949 while (*p1 == *p2)
5950 {
5951 if (*p2 == '\t')
5952 {
5953 *p2 = NUL;
Bram Moolenaar555b2802005-05-19 21:08:39 +00005954 vim_snprintf((char *)NameBuff, MAXPATHL,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 _("E154: Duplicate tag \"%s\" in file %s/%s"),
5956 ((char_u **)ga.ga_data)[i], dir, p2 + 1);
5957 EMSG(NameBuff);
5958 *p2 = '\t';
5959 break;
5960 }
5961 ++p1;
5962 ++p2;
5963 }
5964 }
5965
5966# ifdef FEAT_MBYTE
5967 if (utf8 == TRUE)
5968 fprintf(fd_tags, "!_TAG_FILE_ENCODING\tutf-8\t//\n");
5969# endif
5970
5971 /*
5972 * Write the tags into the file.
5973 */
5974 for (i = 0; i < ga.ga_len; ++i)
5975 {
5976 s = ((char_u **)ga.ga_data)[i];
5977 if (STRNCMP(s, "help-tags", 9) == 0)
5978 /* help-tags entry was added in formatted form */
5979 fprintf(fd_tags, (char *)s);
5980 else
5981 {
5982 fprintf(fd_tags, "%s\t/*", s);
5983 for (p1 = s; *p1 != '\t'; ++p1)
5984 {
5985 /* insert backslash before '\\' and '/' */
5986 if (*p1 == '\\' || *p1 == '/')
5987 putc('\\', fd_tags);
5988 putc(*p1, fd_tags);
5989 }
5990 fprintf(fd_tags, "*\n");
5991 }
5992 }
5993 }
5994#ifdef FEAT_MBYTE
5995 if (mix)
5996 got_int = FALSE; /* continue with other languages */
5997#endif
5998
5999 for (i = 0; i < ga.ga_len; ++i)
6000 vim_free(((char_u **)ga.ga_data)[i]);
6001 ga_clear(&ga);
6002 fclose(fd_tags); /* there is no check for an error... */
6003}
6004#endif
6005
6006#if defined(FEAT_SIGNS) || defined(PROTO)
6007
6008/*
6009 * Struct to hold the sign properties.
6010 */
6011typedef struct sign sign_T;
6012
6013struct sign
6014{
6015 sign_T *sn_next; /* next sign in list */
6016 int sn_typenr; /* type number of sign (negative if not equal
6017 to name) */
6018 char_u *sn_name; /* name of sign */
6019 char_u *sn_icon; /* name of pixmap */
6020#ifdef FEAT_SIGN_ICONS
6021 void *sn_image; /* icon image */
6022#endif
6023 char_u *sn_text; /* text used instead of pixmap */
6024 int sn_line_hl; /* highlight ID for line */
6025 int sn_text_hl; /* highlight ID for text */
6026};
6027
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028static sign_T *first_sign = NULL;
6029static int last_sign_typenr = MAX_TYPENR; /* is decremented */
6030
6031static void sign_list_defined __ARGS((sign_T *sp));
6032
6033/*
6034 * ":sign" command
6035 */
6036 void
6037ex_sign(eap)
6038 exarg_T *eap;
6039{
6040 char_u *arg = eap->arg;
6041 char_u *p;
6042 int idx;
6043 sign_T *sp;
6044 sign_T *sp_prev;
6045 buf_T *buf;
6046 static char *cmds[] = {
6047 "define",
6048#define SIGNCMD_DEFINE 0
6049 "undefine",
6050#define SIGNCMD_UNDEFINE 1
6051 "list",
6052#define SIGNCMD_LIST 2
6053 "place",
6054#define SIGNCMD_PLACE 3
6055 "unplace",
6056#define SIGNCMD_UNPLACE 4
6057 "jump",
6058#define SIGNCMD_JUMP 5
6059#define SIGNCMD_LAST 6
6060 };
6061
6062 /* Parse the subcommand. */
6063 p = skiptowhite(arg);
6064 if (*p != NUL)
6065 *p++ = NUL;
6066 for (idx = 0; ; ++idx)
6067 {
6068 if (idx == SIGNCMD_LAST)
6069 {
6070 EMSG2(_("E160: Unknown sign command: %s"), arg);
6071 return;
6072 }
6073 if (STRCMP(arg, cmds[idx]) == 0)
6074 break;
6075 }
6076 arg = skipwhite(p);
6077
6078 if (idx <= SIGNCMD_LIST)
6079 {
6080 /*
6081 * Define, undefine or list signs.
6082 */
6083 if (idx == SIGNCMD_LIST && *arg == NUL)
6084 {
6085 /* ":sign list": list all defined signs */
6086 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6087 sign_list_defined(sp);
6088 }
6089 else if (*arg == NUL)
6090 EMSG(_("E156: Missing sign name"));
6091 else
6092 {
6093 p = skiptowhite(arg);
6094 if (*p != NUL)
6095 *p++ = NUL;
6096 sp_prev = NULL;
6097 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6098 {
6099 if (STRCMP(sp->sn_name, arg) == 0)
6100 break;
6101 sp_prev = sp;
6102 }
6103 if (idx == SIGNCMD_DEFINE)
6104 {
6105 /* ":sign define {name} ...": define a sign */
6106 if (sp == NULL)
6107 {
6108 /* Allocate a new sign. */
6109 sp = (sign_T *)alloc_clear((unsigned)sizeof(sign_T));
6110 if (sp == NULL)
6111 return;
6112 if (sp_prev == NULL)
6113 first_sign = sp;
6114 else
6115 sp_prev->sn_next = sp;
6116 sp->sn_name = vim_strnsave(arg, (int)(p - arg));
6117
6118 /* If the name is a number use that for the typenr,
6119 * otherwise use a negative number. */
6120 if (VIM_ISDIGIT(*arg))
6121 sp->sn_typenr = atoi((char *)arg);
6122 else
6123 {
6124 sign_T *lp;
6125 int start = last_sign_typenr;
6126
6127 for (lp = first_sign; lp != NULL; lp = lp->sn_next)
6128 {
6129 if (lp->sn_typenr == last_sign_typenr)
6130 {
6131 --last_sign_typenr;
6132 if (last_sign_typenr == 0)
6133 last_sign_typenr = MAX_TYPENR;
6134 if (last_sign_typenr == start)
6135 {
6136 EMSG(_("E612: Too many signs defined"));
6137 return;
6138 }
6139 lp = first_sign;
6140 continue;
6141 }
6142 }
6143
6144 sp->sn_typenr = last_sign_typenr--;
6145 if (last_sign_typenr == 0)
6146 last_sign_typenr = MAX_TYPENR; /* wrap around */
6147 }
6148 }
6149
6150 /* set values for a defined sign. */
6151 for (;;)
6152 {
6153 arg = skipwhite(p);
6154 if (*arg == NUL)
6155 break;
6156 p = skiptowhite_esc(arg);
6157 if (STRNCMP(arg, "icon=", 5) == 0)
6158 {
6159 arg += 5;
6160 vim_free(sp->sn_icon);
6161 sp->sn_icon = vim_strnsave(arg, (int)(p - arg));
6162 backslash_halve(sp->sn_icon);
6163#ifdef FEAT_SIGN_ICONS
6164 if (gui.in_use)
6165 {
6166 out_flush();
6167 if (sp->sn_image != NULL)
6168 gui_mch_destroy_sign(sp->sn_image);
6169 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6170 }
6171#endif
6172 }
6173 else if (STRNCMP(arg, "text=", 5) == 0)
6174 {
6175 char_u *s;
6176 int cells;
6177 int len;
6178
6179 arg += 5;
6180#ifdef FEAT_MBYTE
6181 /* Count cells and check for non-printable chars */
6182 if (has_mbyte)
6183 {
6184 cells = 0;
6185 for (s = arg; s < p; s += (*mb_ptr2len_check)(s))
6186 {
6187 if (!vim_isprintc((*mb_ptr2char)(s)))
6188 break;
6189 cells += (*mb_ptr2cells)(s);
6190 }
6191 }
6192 else
6193#endif
6194 {
6195 for (s = arg; s < p; ++s)
6196 if (!vim_isprintc(*s))
6197 break;
6198 cells = s - arg;
6199 }
6200 /* Currently must be one or two display cells */
6201 if (s != p || cells < 1 || cells > 2)
6202 {
6203 *p = NUL;
6204 EMSG2(_("E239: Invalid sign text: %s"), arg);
6205 return;
6206 }
6207
6208 vim_free(sp->sn_text);
6209 /* Allocate one byte more if we need to pad up
6210 * with a space. */
6211 len = p - arg + ((cells == 1) ? 1 : 0);
6212 sp->sn_text = vim_strnsave(arg, len);
6213
6214 if (sp->sn_text != NULL && cells == 1)
6215 STRCPY(sp->sn_text + len - 1, " ");
6216 }
6217 else if (STRNCMP(arg, "linehl=", 7) == 0)
6218 {
6219 arg += 7;
6220 sp->sn_line_hl = syn_check_group(arg, (int)(p - arg));
6221 }
6222 else if (STRNCMP(arg, "texthl=", 7) == 0)
6223 {
6224 arg += 7;
6225 sp->sn_text_hl = syn_check_group(arg, (int)(p - arg));
6226 }
6227 else
6228 {
6229 EMSG2(_(e_invarg2), arg);
6230 return;
6231 }
6232 }
6233 }
6234 else if (sp == NULL)
6235 EMSG2(_("E155: Unknown sign: %s"), arg);
6236 else if (idx == SIGNCMD_LIST)
6237 /* ":sign list {name}" */
6238 sign_list_defined(sp);
6239 else
6240 {
6241 /* ":sign undefine {name}" */
6242 vim_free(sp->sn_name);
6243 vim_free(sp->sn_icon);
6244#ifdef FEAT_SIGN_ICONS
6245 if (sp->sn_image != NULL)
6246 {
6247 out_flush();
6248 gui_mch_destroy_sign(sp->sn_image);
6249 }
6250#endif
6251 vim_free(sp->sn_text);
6252 if (sp_prev == NULL)
6253 first_sign = sp->sn_next;
6254 else
6255 sp_prev->sn_next = sp->sn_next;
6256 vim_free(sp);
6257 }
6258 }
6259 }
6260 else
6261 {
6262 int id = -1;
6263 linenr_T lnum = -1;
6264 char_u *sign_name = NULL;
6265 char_u *arg1;
6266
6267 if (*arg == NUL)
6268 {
6269 if (idx == SIGNCMD_PLACE)
6270 {
6271 /* ":sign place": list placed signs in all buffers */
6272 sign_list_placed(NULL);
6273 }
6274 else if (idx == SIGNCMD_UNPLACE)
6275 {
6276 /* ":sign unplace": remove placed sign at cursor */
6277 id = buf_findsign_id(curwin->w_buffer, curwin->w_cursor.lnum);
6278 if (id > 0)
6279 {
6280 buf_delsign(curwin->w_buffer, id);
6281 update_debug_sign(curwin->w_buffer, curwin->w_cursor.lnum);
6282 }
6283 else
6284 EMSG(_("E159: Missing sign number"));
6285 }
6286 else
6287 EMSG(_(e_argreq));
6288 return;
6289 }
6290
6291 if (idx == SIGNCMD_UNPLACE && arg[0] == '*' && arg[1] == NUL)
6292 {
6293 /* ":sign unplace *": remove all placed signs */
6294 buf_delete_all_signs();
6295 return;
6296 }
6297
6298 /* first arg could be placed sign id */
6299 arg1 = arg;
6300 if (VIM_ISDIGIT(*arg))
6301 {
6302 id = getdigits(&arg);
6303 if (!vim_iswhite(*arg) && *arg != NUL)
6304 {
6305 id = -1;
6306 arg = arg1;
6307 }
6308 else
6309 {
6310 arg = skipwhite(arg);
6311 if (idx == SIGNCMD_UNPLACE && *arg == NUL)
6312 {
6313 /* ":sign unplace {id}": remove placed sign by number */
6314 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6315 if ((lnum = buf_delsign(buf, id)) != 0)
6316 update_debug_sign(buf, lnum);
6317 return;
6318 }
6319 }
6320 }
6321
6322 /*
6323 * Check for line={lnum} name={name} and file={fname} or buffer={nr}.
6324 * Leave "arg" pointing to {fname}.
6325 */
6326 for (;;)
6327 {
6328 if (STRNCMP(arg, "line=", 5) == 0)
6329 {
6330 arg += 5;
6331 lnum = atoi((char *)arg);
6332 arg = skiptowhite(arg);
6333 }
6334 else if (STRNCMP(arg, "name=", 5) == 0)
6335 {
6336 arg += 5;
6337 sign_name = arg;
6338 arg = skiptowhite(arg);
6339 if (*arg != NUL)
6340 *arg++ = NUL;
6341 }
6342 else if (STRNCMP(arg, "file=", 5) == 0)
6343 {
6344 arg += 5;
6345 buf = buflist_findname(arg);
6346 break;
6347 }
6348 else if (STRNCMP(arg, "buffer=", 7) == 0)
6349 {
6350 arg += 7;
6351 buf = buflist_findnr((int)getdigits(&arg));
6352 if (*skipwhite(arg) != NUL)
6353 EMSG(_(e_trailing));
6354 break;
6355 }
6356 else
6357 {
6358 EMSG(_(e_invarg));
6359 return;
6360 }
6361 arg = skipwhite(arg);
6362 }
6363
6364 if (buf == NULL)
6365 {
6366 EMSG2(_("E158: Invalid buffer name: %s"), arg);
6367 }
6368 else if (id <= 0)
6369 {
6370 if (lnum >= 0 || sign_name != NULL)
6371 EMSG(_(e_invarg));
6372 else
6373 /* ":sign place file={fname}": list placed signs in one file */
6374 sign_list_placed(buf);
6375 }
6376 else if (idx == SIGNCMD_JUMP)
6377 {
6378 /* ":sign jump {id} file={fname}" */
6379 if (lnum >= 0 || sign_name != NULL)
6380 EMSG(_(e_invarg));
6381 else if ((lnum = buf_findsign(buf, id)) > 0)
6382 { /* goto a sign ... */
6383 if (buf_jump_open_win(buf) != NULL)
6384 { /* ... in a current window */
6385 curwin->w_cursor.lnum = lnum;
6386 check_cursor_lnum();
6387 beginline(BL_WHITE);
6388 }
6389 else
6390 { /* ... not currently in a window */
6391 char_u *cmd;
6392
6393 cmd = alloc((unsigned)STRLEN(buf->b_fname) + 25);
6394 if (cmd == NULL)
6395 return;
6396 sprintf((char *)cmd, "e +%ld %s", (long)lnum, buf->b_fname);
6397 do_cmdline_cmd(cmd);
6398 vim_free(cmd);
6399 }
6400#ifdef FEAT_FOLDING
6401 foldOpenCursor();
6402#endif
6403 }
6404 else
6405 EMSGN(_("E157: Invalid sign ID: %ld"), id);
6406 }
6407 else if (idx == SIGNCMD_UNPLACE)
6408 {
6409 /* ":sign unplace {id} file={fname}" */
6410 if (lnum >= 0 || sign_name != NULL)
6411 EMSG(_(e_invarg));
6412 else
6413 {
6414 lnum = buf_delsign(buf, id);
6415 update_debug_sign(buf, lnum);
6416 }
6417 }
6418 /* idx == SIGNCMD_PLACE */
6419 else if (sign_name != NULL)
6420 {
6421 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6422 if (STRCMP(sp->sn_name, sign_name) == 0)
6423 break;
6424 if (sp == NULL)
6425 {
6426 EMSG2(_("E155: Unknown sign: %s"), sign_name);
6427 return;
6428 }
6429 if (lnum > 0)
6430 /* ":sign place {id} line={lnum} name={name} file={fname}":
6431 * place a sign */
6432 buf_addsign(buf, id, lnum, sp->sn_typenr);
6433 else
6434 /* ":sign place {id} file={fname}": change sign type */
6435 lnum = buf_change_sign_type(buf, id, sp->sn_typenr);
6436 update_debug_sign(buf, lnum);
6437 }
6438 else
6439 EMSG(_(e_invarg));
6440 }
6441}
6442
6443#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6444/*
6445 * Allocate the icons. Called when the GUI has started. Allows defining
6446 * signs before it starts.
6447 */
6448 void
6449sign_gui_started()
6450{
6451 sign_T *sp;
6452
6453 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6454 if (sp->sn_icon != NULL)
6455 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6456}
6457#endif
6458
6459/*
6460 * List one sign.
6461 */
6462 static void
6463sign_list_defined(sp)
6464 sign_T *sp;
6465{
6466 char_u *p;
6467
Bram Moolenaar555b2802005-05-19 21:08:39 +00006468 smsg((char_u *)"sign %s", sp->sn_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 if (sp->sn_icon != NULL)
6470 {
6471 MSG_PUTS(" icon=");
6472 msg_outtrans(sp->sn_icon);
6473#ifdef FEAT_SIGN_ICONS
6474 if (sp->sn_image == NULL)
6475 MSG_PUTS(_(" (NOT FOUND)"));
6476#else
6477 MSG_PUTS(_(" (not supported)"));
6478#endif
6479 }
6480 if (sp->sn_text != NULL)
6481 {
6482 MSG_PUTS(" text=");
6483 msg_outtrans(sp->sn_text);
6484 }
6485 if (sp->sn_line_hl > 0)
6486 {
6487 MSG_PUTS(" linehl=");
6488 p = get_highlight_name(NULL, sp->sn_line_hl - 1);
6489 if (p == NULL)
6490 MSG_PUTS("NONE");
6491 else
6492 msg_puts(p);
6493 }
6494 if (sp->sn_text_hl > 0)
6495 {
6496 MSG_PUTS(" texthl=");
6497 p = get_highlight_name(NULL, sp->sn_text_hl - 1);
6498 if (p == NULL)
6499 MSG_PUTS("NONE");
6500 else
6501 msg_puts(p);
6502 }
6503}
6504
6505/*
6506 * Get highlighting attribute for sign "typenr".
6507 * If "line" is TRUE: line highl, if FALSE: text highl.
6508 */
6509 int
6510sign_get_attr(typenr, line)
6511 int typenr;
6512 int line;
6513{
6514 sign_T *sp;
6515
6516 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6517 if (sp->sn_typenr == typenr)
6518 {
6519 if (line)
6520 {
6521 if (sp->sn_line_hl > 0)
6522 return syn_id2attr(sp->sn_line_hl);
6523 }
6524 else
6525 {
6526 if (sp->sn_text_hl > 0)
6527 return syn_id2attr(sp->sn_text_hl);
6528 }
6529 break;
6530 }
6531 return 0;
6532}
6533
6534/*
6535 * Get text mark for sign "typenr".
6536 * Returns NULL if there isn't one.
6537 */
6538 char_u *
6539sign_get_text(typenr)
6540 int typenr;
6541{
6542 sign_T *sp;
6543
6544 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6545 if (sp->sn_typenr == typenr)
6546 return sp->sn_text;
6547 return NULL;
6548}
6549
6550#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6551 void *
6552sign_get_image(typenr)
6553 int typenr; /* the attribute which may have a sign */
6554{
6555 sign_T *sp;
6556
6557 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6558 if (sp->sn_typenr == typenr)
6559 return sp->sn_image;
6560 return NULL;
6561}
6562#endif
6563
6564/*
6565 * Get the name of a sign by its typenr.
6566 */
6567 char_u *
6568sign_typenr2name(typenr)
6569 int typenr;
6570{
6571 sign_T *sp;
6572
6573 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6574 if (sp->sn_typenr == typenr)
6575 return sp->sn_name;
6576 return (char_u *)_("[Deleted]");
6577}
6578
6579#endif
6580
6581#if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
6582/*
6583 * ":drop"
6584 * Opens the first argument in a window. When there are two or more arguments
6585 * the argument list is redefined.
6586 */
6587 void
6588ex_drop(eap)
6589 exarg_T *eap;
6590{
6591 int split = FALSE;
6592 int incurwin = FALSE;
6593 char_u *arg;
6594 char_u *first = NULL;
6595 win_T *wp;
6596 buf_T *buf;
6597
6598 /*
6599 * Check if the first argument is already being edited in a window. If
6600 * so, jump to that window.
6601 * We would actually need to check all arguments, but that's complicated
6602 * and mostly only one file is dropped.
6603 * This also ignores wildcards, since it is very unlikely the user is
6604 * editing a file name with a wildcard character.
6605 */
6606 arg = vim_strsave(eap->arg);
6607 if (arg != NULL)
6608 {
6609 /* Get the first argument, remove quotes, make it a full path. */
6610 first = fix_fname(arg);
6611 if (first != NULL)
6612 {
6613 buf = buflist_findname(first);
6614 FOR_ALL_WINDOWS(wp)
6615 {
6616 if (wp->w_buffer == buf)
6617 {
6618 incurwin = TRUE;
6619# ifdef FEAT_WINDOWS
6620 win_enter(wp, TRUE);
6621 break;
6622# endif
6623 }
6624 }
6625 vim_free(first);
6626
6627 if (incurwin)
6628 {
6629 /* Already editing the file. Redefine the argument list. */
6630 set_arglist(eap->arg);
6631 curwin->w_arg_idx = 0;
6632 vim_free(arg);
6633 return;
6634 }
6635 }
6636 vim_free(arg);
6637 }
6638
6639 /*
6640 * Check whether the current buffer is changed. If so, we will need
6641 * to split the current window or data could be lost.
6642 * Skip the check if the 'hidden' option is set, as in this case the
6643 * buffer won't be lost.
6644 */
6645 if (!P_HID(curbuf))
6646 {
6647# ifdef FEAT_WINDOWS
6648 ++emsg_off;
6649# endif
6650 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6651# ifdef FEAT_WINDOWS
6652 --emsg_off;
6653# else
6654 if (split)
6655 return;
6656# endif
6657 }
6658
6659 /* Fake a ":snext" or ":next" command, redefine the arglist. */
6660 if (split)
6661 {
6662 eap->cmdidx = CMD_snext;
6663 eap->cmd[0] = 's';
6664 }
6665 else
6666 eap->cmdidx = CMD_next;
6667 ex_next(eap);
6668}
6669#endif