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