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