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