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