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