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