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