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