blob: 9bef62db4e13fb4ebea8928fa9072993d58aca48 [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!"),
Bram Moolenaar75c50c42005-06-04 22:06:24 +00001816 (fp_in == NULL || tempname == NULL) ? fname : tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 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. */
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002436 EMSG(_(e_bufloaded));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 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
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002594 dialog_msg(buff, _("Overwrite existing file \"%s\"?"), fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 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
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002724 dialog_msg(buff, _("'readonly' option is set for \"%s\".\nDo you wish to write anyway?"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 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)
Bram Moolenaareaa48e72005-06-08 22:07:37 +00003608 || (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0))
3609 == FAIL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610 {
3611 vim_free(theline);
3612 break;
3613 }
3614
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003615 /* don't use autoindent if nothing was typed. */
3616 if (p[0] == NUL)
3617 theline[0] = NUL;
3618
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619 did_undo = TRUE;
3620 ml_append(lnum, theline, (colnr_T)0, FALSE);
3621 appended_lines_mark(lnum, 1L);
3622
3623 vim_free(theline);
3624 ++lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003625
3626 if (empty)
3627 {
3628 ml_delete(2L, FALSE);
3629 empty = FALSE;
3630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631 }
3632 State = NORMAL;
3633
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003634 if (eap->forceit)
3635 curbuf->b_p_ai = !curbuf->b_p_ai;
3636
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637 /* "start" is set to eap->line2+1 unless that position is invalid (when
3638 * eap->line2 pointed to the end of the buffer and nothig was appended)
3639 * "end" is set to lnum when something has been appended, otherwise
3640 * it is the same than "start" -- Acevedo */
3641 curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
3642 eap->line2 + 1 : curbuf->b_ml.ml_line_count;
3643 if (eap->cmdidx != CMD_append)
3644 --curbuf->b_op_start.lnum;
3645 curbuf->b_op_end.lnum = (eap->line2 < lnum)
3646 ? lnum : curbuf->b_op_start.lnum;
3647 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
3648 curwin->w_cursor.lnum = lnum;
3649 check_cursor_lnum();
3650 beginline(BL_SOL | BL_FIX);
3651
3652 need_wait_return = FALSE; /* don't use wait_return() now */
3653 ex_no_reprint = TRUE;
3654}
3655
3656/*
3657 * ":change"
3658 */
3659 void
3660ex_change(eap)
3661 exarg_T *eap;
3662{
3663 linenr_T lnum;
3664
3665 if (eap->line2 >= eap->line1
3666 && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
3667 return;
3668
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003669 /* the ! flag toggles autoindent */
3670 if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai)
3671 append_indent = get_indent_lnum(eap->line1);
3672
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673 for (lnum = eap->line2; lnum >= eap->line1; --lnum)
3674 {
3675 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
3676 break;
3677 ml_delete(eap->line1, FALSE);
3678 }
3679 deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum));
3680
3681 /* ":append" on the line above the deleted lines. */
3682 eap->line2 = eap->line1;
3683 ex_append(eap);
3684}
3685
3686 void
3687ex_z(eap)
3688 exarg_T *eap;
3689{
3690 char_u *x;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003691 int bigness;
3692 char_u *kind;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 int minus = 0;
3694 linenr_T start, end, curs, i;
3695 int j;
3696 linenr_T lnum = eap->line2;
3697
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003698 /* Vi compatible: ":z!" uses display height, without a count uses
3699 * 'scroll' */
3700 if (eap->forceit)
3701 bigness = curwin->w_height;
3702 else if (firstwin == lastwin)
3703 bigness = curwin->w_p_scr * 2;
3704 else
3705 bigness = curwin->w_height - 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 if (bigness < 1)
3707 bigness = 1;
3708
3709 x = eap->arg;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003710 kind = x;
3711 if (*kind == '-' || *kind == '+' || *kind == '='
3712 || *kind == '^' || *kind == '.')
3713 ++x;
3714 while (*x == '-' || *x == '+')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 ++x;
3716
3717 if (*x != 0)
3718 {
3719 if (!VIM_ISDIGIT(*x))
3720 {
3721 EMSG(_("E144: non-numeric argument to :z"));
3722 return;
3723 }
3724 else
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003725 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 bigness = atoi((char *)x);
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003727 p_window = bigness;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003728 if (*kind == '=')
3729 bigness += 2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003730 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 }
3732
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003733 /* the number of '-' and '+' multiplies the distance */
3734 if (*kind == '-' || *kind == '+')
3735 for (x = kind + 1; *x == *kind; ++x)
3736 ;
3737
3738 switch (*kind)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 {
3740 case '-':
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003741 start = lnum - bigness * (x - kind);
3742 end = start + bigness;
3743 curs = end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 break;
3745
3746 case '=':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003747 start = lnum - (bigness + 1) / 2 + 1;
3748 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 curs = lnum;
3750 minus = 1;
3751 break;
3752
3753 case '^':
3754 start = lnum - bigness * 2;
3755 end = lnum - bigness;
3756 curs = lnum - bigness;
3757 break;
3758
3759 case '.':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003760 start = lnum - (bigness + 1) / 2 + 1;
3761 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 curs = end;
3763 break;
3764
3765 default: /* '+' */
3766 start = lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003767 if (*kind == '+')
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003768 start += bigness * (x - kind - 1) + 1;
3769 else if (eap->addr_count == 0)
3770 ++start;
3771 end = start + bigness - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 curs = end;
3773 break;
3774 }
3775
3776 if (start < 1)
3777 start = 1;
3778
3779 if (end > curbuf->b_ml.ml_line_count)
3780 end = curbuf->b_ml.ml_line_count;
3781
3782 if (curs > curbuf->b_ml.ml_line_count)
3783 curs = curbuf->b_ml.ml_line_count;
3784
3785 for (i = start; i <= end; i++)
3786 {
3787 if (minus && i == lnum)
3788 {
3789 msg_putchar('\n');
3790
3791 for (j = 1; j < Columns; j++)
3792 msg_putchar('-');
3793 }
3794
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003795 print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796
3797 if (minus && i == lnum)
3798 {
3799 msg_putchar('\n');
3800
3801 for (j = 1; j < Columns; j++)
3802 msg_putchar('-');
3803 }
3804 }
3805
3806 curwin->w_cursor.lnum = curs;
3807 ex_no_reprint = TRUE;
3808}
3809
3810/*
3811 * Check if the restricted flag is set.
3812 * If so, give an error message and return TRUE.
3813 * Otherwise, return FALSE.
3814 */
3815 int
3816check_restricted()
3817{
3818 if (restricted)
3819 {
3820 EMSG(_("E145: Shell commands not allowed in rvim"));
3821 return TRUE;
3822 }
3823 return FALSE;
3824}
3825
3826/*
3827 * Check if the secure flag is set (.exrc or .vimrc in current directory).
3828 * If so, give an error message and return TRUE.
3829 * Otherwise, return FALSE.
3830 */
3831 int
3832check_secure()
3833{
3834 if (secure)
3835 {
3836 secure = 2;
3837 EMSG(_(e_curdir));
3838 return TRUE;
3839 }
3840#ifdef HAVE_SANDBOX
3841 /*
3842 * In the sandbox more things are not allowed, including the things
3843 * disallowed in secure mode.
3844 */
3845 if (sandbox != 0)
3846 {
3847 EMSG(_(e_sandbox));
3848 return TRUE;
3849 }
3850#endif
3851 return FALSE;
3852}
3853
3854static char_u *old_sub = NULL; /* previous substitute pattern */
3855static int global_need_beginline; /* call beginline() after ":g" */
3856
3857/*
3858 * When ":global" is used to number of substitutions and changed lines is
3859 * accumulated until it's finished.
3860 */
3861static long sub_nsubs; /* total number of substitutions */
3862static linenr_T sub_nlines; /* total number of lines changed */
3863
3864/* do_sub()
3865 *
3866 * Perform a substitution from line eap->line1 to line eap->line2 using the
3867 * command pointed to by eap->arg which should be of the form:
3868 *
3869 * /pattern/substitution/{flags}
3870 *
3871 * The usual escapes are supported as described in the regexp docs.
3872 */
3873 void
3874do_sub(eap)
3875 exarg_T *eap;
3876{
3877 linenr_T lnum;
3878 long i = 0;
3879 regmmatch_T regmatch;
3880 static int do_all = FALSE; /* do multiple substitutions per line */
3881 static int do_ask = FALSE; /* ask for confirmation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00003882 static int do_count = FALSE; /* count only */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 static int do_error = TRUE; /* if false, ignore errors */
3884 static int do_print = FALSE; /* print last line with subs. */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003885 static int do_list = FALSE; /* list last line with subs. */
3886 static int do_number = FALSE; /* list last line with line nr*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887 static int do_ic = 0; /* ignore case flag */
3888 char_u *pat = NULL, *sub = NULL; /* init for GCC */
3889 int delimiter;
3890 int sublen;
3891 int got_quit = FALSE;
3892 int got_match = FALSE;
3893 int temp;
3894 int which_pat;
3895 char_u *cmd;
3896 int save_State;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003897 linenr_T first_line = 0; /* first changed line */
3898 linenr_T last_line= 0; /* below last changed line AFTER the
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899 * change */
3900 linenr_T old_line_count = curbuf->b_ml.ml_line_count;
3901 linenr_T line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003902 long nmatch; /* number of lines in match */
3903 linenr_T sub_firstlnum; /* nr of first sub line */
3904 char_u *sub_firstline; /* allocated copy of first sub line */
3905 int endcolumn = FALSE; /* cursor in last column when done */
Bram Moolenaar05159a02005-02-26 23:04:13 +00003906 pos_T old_cursor = curwin->w_cursor;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907
3908 cmd = eap->arg;
3909 if (!global_busy)
3910 {
3911 sub_nsubs = 0;
3912 sub_nlines = 0;
3913 }
3914
3915#ifdef FEAT_FKMAP /* reverse the flow of the Farsi characters */
3916 if (p_altkeymap && curwin->w_p_rl)
3917 lrF_sub(cmd);
3918#endif
3919
3920 if (eap->cmdidx == CMD_tilde)
3921 which_pat = RE_LAST; /* use last used regexp */
3922 else
3923 which_pat = RE_SUBST; /* use last substitute regexp */
3924
3925 /* new pattern and substitution */
3926 if (eap->cmd[0] == 's' && *cmd != NUL && !vim_iswhite(*cmd)
3927 && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
3928 {
3929 /* don't accept alphanumeric for separator */
3930 if (isalpha(*cmd))
3931 {
3932 EMSG(_("E146: Regular expressions can't be delimited by letters"));
3933 return;
3934 }
3935 /*
3936 * undocumented vi feature:
3937 * "\/sub/" and "\?sub?" use last used search pattern (almost like
3938 * //sub/r). "\&sub&" use last substitute pattern (like //sub/).
3939 */
3940 if (*cmd == '\\')
3941 {
3942 ++cmd;
3943 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
3944 {
3945 EMSG(_(e_backslash));
3946 return;
3947 }
3948 if (*cmd != '&')
3949 which_pat = RE_SEARCH; /* use last '/' pattern */
3950 pat = (char_u *)""; /* empty search pattern */
3951 delimiter = *cmd++; /* remember delimiter character */
3952 }
3953 else /* find the end of the regexp */
3954 {
3955 which_pat = RE_LAST; /* use last used regexp */
3956 delimiter = *cmd++; /* remember delimiter character */
3957 pat = cmd; /* remember start of search pat */
3958 cmd = skip_regexp(cmd, delimiter, p_magic, &eap->arg);
3959 if (cmd[0] == delimiter) /* end delimiter found */
3960 *cmd++ = NUL; /* replace it with a NUL */
3961 }
3962
3963 /*
3964 * Small incompatibility: vi sees '\n' as end of the command, but in
3965 * Vim we want to use '\n' to find/substitute a NUL.
3966 */
3967 sub = cmd; /* remember the start of the substitution */
3968
3969 while (cmd[0])
3970 {
3971 if (cmd[0] == delimiter) /* end delimiter found */
3972 {
3973 *cmd++ = NUL; /* replace it with a NUL */
3974 break;
3975 }
3976 if (cmd[0] == '\\' && cmd[1] != 0) /* skip escaped characters */
3977 ++cmd;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003978 mb_ptr_adv(cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979 }
3980
3981 if (!eap->skip)
3982 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003983 /* In POSIX vi ":s/pat/%/" uses the previous subst. string. */
3984 if (STRCMP(sub, "%") == 0
3985 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
3986 {
3987 if (old_sub == NULL) /* there is no previous command */
3988 {
3989 EMSG(_(e_nopresub));
3990 return;
3991 }
3992 sub = old_sub;
3993 }
3994 else
3995 {
3996 vim_free(old_sub);
3997 old_sub = vim_strsave(sub);
3998 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999 }
4000 }
4001 else if (!eap->skip) /* use previous pattern and substitution */
4002 {
4003 if (old_sub == NULL) /* there is no previous command */
4004 {
4005 EMSG(_(e_nopresub));
4006 return;
4007 }
4008 pat = NULL; /* search_regcomp() will use previous pattern */
4009 sub = old_sub;
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004010
4011 /* Vi compatibility quirk: repeating with ":s" keeps the cursor in the
4012 * last column after using "$". */
4013 endcolumn = (curwin->w_curswant == MAXCOL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004014 }
4015
4016 /*
4017 * Find trailing options. When '&' is used, keep old options.
4018 */
4019 if (*cmd == '&')
4020 ++cmd;
4021 else
4022 {
4023 if (!p_ed)
4024 {
4025 if (p_gd) /* default is global on */
4026 do_all = TRUE;
4027 else
4028 do_all = FALSE;
4029 do_ask = FALSE;
4030 }
4031 do_error = TRUE;
4032 do_print = FALSE;
4033 do_ic = 0;
4034 }
4035 while (*cmd)
4036 {
4037 /*
4038 * Note that 'g' and 'c' are always inverted, also when p_ed is off.
4039 * 'r' is never inverted.
4040 */
4041 if (*cmd == 'g')
4042 do_all = !do_all;
4043 else if (*cmd == 'c')
4044 do_ask = !do_ask;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004045 else if (*cmd == 'n')
4046 do_count = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047 else if (*cmd == 'e')
4048 do_error = !do_error;
4049 else if (*cmd == 'r') /* use last used regexp */
4050 which_pat = RE_LAST;
4051 else if (*cmd == 'p')
4052 do_print = TRUE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004053 else if (*cmd == '#')
4054 {
4055 do_print = TRUE;
4056 do_number = TRUE;
4057 }
4058 else if (*cmd == 'l')
4059 {
4060 do_print = TRUE;
4061 do_list = TRUE;
4062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063 else if (*cmd == 'i') /* ignore case */
4064 do_ic = 'i';
4065 else if (*cmd == 'I') /* don't ignore case */
4066 do_ic = 'I';
4067 else
4068 break;
4069 ++cmd;
4070 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00004071 if (do_count)
4072 do_ask = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073
4074 /*
4075 * check for a trailing count
4076 */
4077 cmd = skipwhite(cmd);
4078 if (VIM_ISDIGIT(*cmd))
4079 {
4080 i = getdigits(&cmd);
4081 if (i <= 0 && !eap->skip && do_error)
4082 {
4083 EMSG(_(e_zerocount));
4084 return;
4085 }
4086 eap->line1 = eap->line2;
4087 eap->line2 += i - 1;
4088 if (eap->line2 > curbuf->b_ml.ml_line_count)
4089 eap->line2 = curbuf->b_ml.ml_line_count;
4090 }
4091
4092 /*
4093 * check for trailing command or garbage
4094 */
4095 cmd = skipwhite(cmd);
4096 if (*cmd && *cmd != '"') /* if not end-of-line or comment */
4097 {
4098 eap->nextcmd = check_nextcmd(cmd);
4099 if (eap->nextcmd == NULL)
4100 {
4101 EMSG(_(e_trailing));
4102 return;
4103 }
4104 }
4105
4106 if (eap->skip) /* not executing commands, only parsing */
4107 return;
4108
4109 if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4110 {
4111 if (do_error)
4112 EMSG(_(e_invcmd));
4113 return;
4114 }
4115
4116 /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
4117 if (do_ic == 'i')
4118 regmatch.rmm_ic = TRUE;
4119 else if (do_ic == 'I')
4120 regmatch.rmm_ic = FALSE;
4121
4122 sub_firstline = NULL;
4123
4124 /*
4125 * ~ in the substitute pattern is replaced with the old pattern.
4126 * We do it here once to avoid it to be replaced over and over again.
4127 * But don't do it when it starts with "\=", then it's an expression.
4128 */
4129 if (!(sub[0] == '\\' && sub[1] == '='))
4130 sub = regtilde(sub, p_magic);
4131
4132 /*
4133 * Check for a match on each line.
4134 */
4135 line2 = eap->line2;
4136 for (lnum = eap->line1; lnum <= line2 && !(got_quit
4137#if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
4138 || aborting()
4139#endif
4140 ); ++lnum)
4141 {
4142 sub_firstlnum = lnum;
4143 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
4144 if (nmatch)
4145 {
4146 colnr_T copycol;
4147 colnr_T matchcol;
4148 colnr_T prev_matchcol = MAXCOL;
4149 char_u *new_end, *new_start = NULL;
4150 unsigned new_start_len = 0;
4151 char_u *p1;
4152 int did_sub = FALSE;
4153 int lastone;
4154 unsigned len, needed_len;
4155 long nmatch_tl = 0; /* nr of lines matched below lnum */
4156 int do_again; /* do it again after joining lines */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004157 int skip_match = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158
4159 /*
4160 * The new text is build up step by step, to avoid too much
4161 * copying. There are these pieces:
4162 * sub_firstline The old text, unmodifed.
4163 * copycol Column in the old text where we started
4164 * looking for a match; from here old text still
4165 * needs to be copied to the new text.
4166 * matchcol Column number of the old text where to look
4167 * for the next match. It's just after the
4168 * previous match or one further.
4169 * prev_matchcol Column just after the previous match (if any).
4170 * Mostly equal to matchcol, except for the first
4171 * match and after skipping an empty match.
4172 * regmatch.*pos Where the pattern matched in the old text.
4173 * new_start The new text, all that has been produced so
4174 * far.
4175 * new_end The new text, where to append new text.
4176 *
4177 * lnum The line number where we were looking for the
4178 * first match in the old line.
4179 * sub_firstlnum The line number in the buffer where to look
4180 * for a match. Can be different from "lnum"
4181 * when the pattern or substitute string contains
4182 * line breaks.
4183 *
4184 * Special situations:
4185 * - When the substitute string contains a line break, the part up
4186 * to the line break is inserted in the text, but the copy of
4187 * the original line is kept. "sub_firstlnum" is adjusted for
4188 * the inserted lines.
4189 * - When the matched pattern contains a line break, the old line
4190 * is taken from the line at the end of the pattern. The lines
4191 * in the match are deleted later, "sub_firstlnum" is adjusted
4192 * accordingly.
4193 *
4194 * The new text is built up in new_start[]. It has some extra
4195 * room to avoid using alloc()/free() too often. new_start_len is
4196 * the lenght of the allocated memory at new_start.
4197 *
4198 * Make a copy of the old line, so it won't be taken away when
4199 * updating the screen or handling a multi-line match. The "old_"
4200 * pointers point into this copy.
4201 */
4202 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4203 if (sub_firstline == NULL)
4204 {
4205 vim_free(new_start);
4206 goto outofmem;
4207 }
4208 copycol = 0;
4209 matchcol = 0;
4210
4211 /* At first match, remember current cursor position. */
4212 if (!got_match)
4213 {
4214 setpcmark();
4215 got_match = TRUE;
4216 }
4217
4218 /*
4219 * Loop until nothing more to replace in this line.
4220 * 1. Handle match with empty string.
4221 * 2. If do_ask is set, ask for confirmation.
4222 * 3. substitute the string.
4223 * 4. if do_all is set, find next match
4224 * 5. break if there isn't another match in this line
4225 */
4226 for (;;)
4227 {
4228 /* Save the line number of the last change for the final
4229 * cursor position (just like Vi). */
4230 curwin->w_cursor.lnum = lnum;
4231 do_again = FALSE;
4232
4233 /*
4234 * 1. Match empty string does not count, except for first
4235 * match. This reproduces the strange vi behaviour.
4236 * This also catches endless loops.
4237 */
4238 if (matchcol == prev_matchcol
4239 && regmatch.endpos[0].lnum == 0
4240 && matchcol == regmatch.endpos[0].col)
4241 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00004242 if (sub_firstline[matchcol] == NUL)
4243 /* We already were at the end of the line. Don't look
4244 * for a match in this line again. */
4245 skip_match = TRUE;
4246 else
4247 ++matchcol; /* search for a match at next column */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004248 goto skip;
4249 }
4250
4251 /* Normally we continue searching for a match just after the
4252 * previous match. */
4253 matchcol = regmatch.endpos[0].col;
4254 prev_matchcol = matchcol;
4255
4256 /*
Bram Moolenaar05159a02005-02-26 23:04:13 +00004257 * 2. If do_count is set only increase the counter.
4258 * If do_ask is set, ask for confirmation.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004260 if (do_count)
4261 {
4262 /* For a multi-line match, put matchcol at the NUL at
4263 * the end of the line and set nmatch to one, so that
4264 * we continue looking for a match on the next line.
4265 * Avoids that ":s/\nB\@=//gc" get stuck. */
4266 if (nmatch > 1)
4267 {
4268 matchcol = STRLEN(sub_firstline);
4269 nmatch = 1;
4270 }
4271 sub_nsubs++;
4272 did_sub = TRUE;
4273 goto skip;
4274 }
4275
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 if (do_ask)
4277 {
4278 /* change State to CONFIRM, so that the mouse works
4279 * properly */
4280 save_State = State;
4281 State = CONFIRM;
4282#ifdef FEAT_MOUSE
4283 setmouse(); /* disable mouse in xterm */
4284#endif
4285 curwin->w_cursor.col = regmatch.startpos[0].col;
4286
4287 /* When 'cpoptions' contains "u" don't sync undo when
4288 * asking for confirmation. */
4289 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4290 ++no_u_sync;
4291
4292 /*
4293 * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
4294 */
4295 while (do_ask)
4296 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004297 if (exmode_active)
4298 {
4299 char_u *resp;
4300 colnr_T sc, ec;
4301
4302 print_line_no_prefix(lnum, FALSE, FALSE);
4303
4304 getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
4305 curwin->w_cursor.col = regmatch.endpos[0].col - 1;
4306 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
4307 msg_start();
Bram Moolenaar05159a02005-02-26 23:04:13 +00004308 for (i = 0; i < (long)sc; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004309 msg_putchar(' ');
Bram Moolenaar05159a02005-02-26 23:04:13 +00004310 for ( ; i <= (long)ec; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004311 msg_putchar('^');
4312
4313 resp = getexmodeline('?', NULL, 0);
4314 if (resp != NULL)
4315 {
4316 i = *resp;
4317 vim_free(resp);
4318 }
4319 }
4320 else
4321 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004323 int save_p_fen = curwin->w_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004325 curwin->w_p_fen = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004327 /* Invert the matched string.
4328 * Remove the inversion afterwards. */
4329 temp = RedrawingDisabled;
4330 RedrawingDisabled = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004332 search_match_lines = regmatch.endpos[0].lnum;
4333 search_match_endcol = regmatch.endpos[0].col;
4334 highlight_match = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004336 update_topline();
4337 validate_cursor();
4338 update_screen(NOT_VALID);
4339 highlight_match = FALSE;
4340 redraw_later(NOT_VALID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004341
4342#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004343 curwin->w_p_fen = save_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004345 if (msg_row == Rows - 1)
4346 msg_didout = FALSE; /* avoid a scroll-up */
4347 msg_starthere();
4348 i = msg_scroll;
4349 msg_scroll = 0; /* truncate msg when
4350 needed */
4351 msg_no_more = TRUE;
4352 /* write message same highlighting as for
4353 * wait_return */
4354 smsg_attr(hl_attr(HLF_R),
4355 (char_u *)_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
4356 msg_no_more = FALSE;
4357 msg_scroll = i;
4358 showruler(TRUE);
4359 windgoto(msg_row, msg_col);
4360 RedrawingDisabled = temp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361
4362#ifdef USE_ON_FLY_SCROLL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004363 dont_scroll = FALSE; /* allow scrolling here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004364#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004365 ++no_mapping; /* don't map this key */
4366 ++allow_keys; /* allow special keys */
4367 i = safe_vgetc();
4368 --allow_keys;
4369 --no_mapping;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004371 /* clear the question */
4372 msg_didout = FALSE; /* don't scroll up */
4373 msg_col = 0;
4374 gotocmdline(TRUE);
4375 }
4376
Bram Moolenaar071d4272004-06-13 20:20:40 +00004377 need_wait_return = FALSE; /* no hit-return prompt */
4378 if (i == 'q' || i == ESC || i == Ctrl_C
4379#ifdef UNIX
4380 || i == intr_char
4381#endif
4382 )
4383 {
4384 got_quit = TRUE;
4385 break;
4386 }
4387 if (i == 'n')
4388 break;
4389 if (i == 'y')
4390 break;
4391 if (i == 'l')
4392 {
4393 /* last: replace and then stop */
4394 do_all = FALSE;
4395 line2 = lnum;
4396 break;
4397 }
4398 if (i == 'a')
4399 {
4400 do_ask = FALSE;
4401 break;
4402 }
4403#ifdef FEAT_INS_EXPAND
4404 if (i == Ctrl_E)
4405 scrollup_clamp();
4406 else if (i == Ctrl_Y)
4407 scrolldown_clamp();
4408#endif
4409 }
4410 State = save_State;
4411#ifdef FEAT_MOUSE
4412 setmouse();
4413#endif
4414 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4415 --no_u_sync;
4416
4417 if (i == 'n')
4418 {
4419 /* For a multi-line match, put matchcol at the NUL at
4420 * the end of the line and set nmatch to one, so that
4421 * we continue looking for a match on the next line.
4422 * Avoids that ":s/\nB\@=//gc" get stuck. */
4423 if (nmatch > 1)
4424 {
4425 matchcol = STRLEN(sub_firstline);
4426 nmatch = 1;
4427 }
4428 goto skip;
4429 }
4430 if (got_quit)
4431 break;
4432 }
4433
4434 /* Move the cursor to the start of the match, so that we can
4435 * use "\=col("."). */
4436 curwin->w_cursor.col = regmatch.startpos[0].col;
4437
4438 /*
4439 * 3. substitute the string.
4440 */
4441 /* get length of substitution part */
4442 sublen = vim_regsub_multi(&regmatch, sub_firstlnum,
4443 sub, sub_firstline, FALSE, p_magic, TRUE);
4444
4445 /* Need room for:
4446 * - result so far in new_start (not for first sub in line)
4447 * - original text up to match
4448 * - length of substituted part
4449 * - original text after match
4450 */
4451 if (nmatch == 1)
4452 p1 = sub_firstline;
4453 else
4454 {
4455 p1 = ml_get(sub_firstlnum + nmatch - 1);
4456 nmatch_tl += nmatch - 1;
4457 }
4458 i = regmatch.startpos[0].col - copycol;
4459 needed_len = i + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col)
4460 + sublen + 1;
4461 if (new_start == NULL)
4462 {
4463 /*
4464 * Get some space for a temporary buffer to do the
4465 * substitution into (and some extra space to avoid
4466 * too many calls to alloc()/free()).
4467 */
4468 new_start_len = needed_len + 50;
4469 if ((new_start = alloc_check(new_start_len)) == NULL)
4470 goto outofmem;
4471 *new_start = NUL;
4472 new_end = new_start;
4473 }
4474 else
4475 {
4476 /*
4477 * Check if the temporary buffer is long enough to do the
4478 * substitution into. If not, make it larger (with a bit
4479 * extra to avoid too many calls to alloc()/free()).
4480 */
4481 len = (unsigned)STRLEN(new_start);
4482 needed_len += len;
4483 if (needed_len > new_start_len)
4484 {
4485 new_start_len = needed_len + 50;
4486 if ((p1 = alloc_check(new_start_len)) == NULL)
4487 {
4488 vim_free(new_start);
4489 goto outofmem;
4490 }
4491 mch_memmove(p1, new_start, (size_t)(len + 1));
4492 vim_free(new_start);
4493 new_start = p1;
4494 }
4495 new_end = new_start + len;
4496 }
4497
4498 /*
4499 * copy the text up to the part that matched
4500 */
4501 mch_memmove(new_end, sub_firstline + copycol, (size_t)i);
4502 new_end += i;
4503
4504 (void)vim_regsub_multi(&regmatch, sub_firstlnum,
4505 sub, new_end, TRUE, p_magic, TRUE);
4506 sub_nsubs++;
4507 did_sub = TRUE;
4508
4509 /* Move the cursor to the start of the line, to avoid that it
4510 * is beyond the end of the line after the substitution. */
4511 curwin->w_cursor.col = 0;
4512
4513 /* For a multi-line match, make a copy of the last matched
4514 * line and continue in that one. */
4515 if (nmatch > 1)
4516 {
4517 sub_firstlnum += nmatch - 1;
4518 vim_free(sub_firstline);
4519 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4520 /* When going beyond the last line, stop substituting. */
4521 if (sub_firstlnum <= line2)
4522 do_again = TRUE;
4523 else
4524 do_all = FALSE;
4525 }
4526
4527 /* Remember next character to be copied. */
4528 copycol = regmatch.endpos[0].col;
4529
4530 /*
4531 * Now the trick is to replace CTRL-M chars with a real line
4532 * break. This would make it impossible to insert a CTRL-M in
4533 * the text. The line break can be avoided by preceding the
4534 * CTRL-M with a backslash. To be able to insert a backslash,
4535 * they must be doubled in the string and are halved here.
4536 * That is Vi compatible.
4537 */
4538 for (p1 = new_end; *p1; ++p1)
4539 {
4540 if (p1[0] == '\\' && p1[1] != NUL) /* remove backslash */
4541 mch_memmove(p1, p1 + 1, STRLEN(p1));
4542 else if (*p1 == CAR)
4543 {
4544 if (u_inssub(lnum) == OK) /* prepare for undo */
4545 {
4546 *p1 = NUL; /* truncate up to the CR */
4547 ml_append(lnum - 1, new_start,
4548 (colnr_T)(p1 - new_start + 1), FALSE);
4549 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
4550 if (do_ask)
4551 appended_lines(lnum - 1, 1L);
4552 else
4553 {
4554 if (first_line == 0)
4555 first_line = lnum;
4556 last_line = lnum + 1;
4557 }
4558 /* All line numbers increase. */
4559 ++sub_firstlnum;
4560 ++lnum;
4561 ++line2;
4562 /* move the cursor to the new line, like Vi */
4563 ++curwin->w_cursor.lnum;
4564 STRCPY(new_start, p1 + 1); /* copy the rest */
4565 p1 = new_start - 1;
4566 }
4567 }
4568#ifdef FEAT_MBYTE
4569 else if (has_mbyte)
4570 p1 += (*mb_ptr2len_check)(p1) - 1;
4571#endif
4572 }
4573
4574 /*
4575 * 4. If do_all is set, find next match.
4576 * Prevent endless loop with patterns that match empty
4577 * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
4578 * But ":s/\n/#/" is OK.
4579 */
4580skip:
4581 /* We already know that we did the last subst when we are at
4582 * the end of the line, except that a pattern like
4583 * "bar\|\nfoo" may match at the NUL. */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004584 lastone = (skip_match
4585 || got_int
4586 || got_quit
4587 || !(do_all || do_again)
4588 || (sub_firstline[matchcol] == NUL && nmatch <= 1
4589 && !re_multiline(regmatch.regprog)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590 nmatch = -1;
4591
4592 /*
4593 * Replace the line in the buffer when needed. This is
4594 * skipped when there are more matches.
4595 * The check for nmatch_tl is needed for when multi-line
4596 * matching must replace the lines before trying to do another
4597 * match, otherwise "\@<=" won't work.
4598 * When asking the user we like to show the already replaced
4599 * text, but don't do it when "\<@=" or "\<@!" is used, it
4600 * changes what matches.
4601 */
4602 if (lastone
4603 || (do_ask && !re_lookbehind(regmatch.regprog))
4604 || nmatch_tl > 0
4605 || (nmatch = vim_regexec_multi(&regmatch, curwin,
4606 curbuf, sub_firstlnum, matchcol)) == 0)
4607 {
4608 if (new_start != NULL)
4609 {
4610 /*
4611 * Copy the rest of the line, that didn't match.
4612 * "matchcol" has to be adjusted, we use the end of
4613 * the line as reference, because the substitute may
4614 * have changed the number of characters. Same for
4615 * "prev_matchcol".
4616 */
4617 STRCAT(new_start, sub_firstline + copycol);
4618 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4619 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4620 - prev_matchcol;
4621
4622 if (u_savesub(lnum) != OK)
4623 break;
4624 ml_replace(lnum, new_start, TRUE);
4625
4626 if (nmatch_tl > 0)
4627 {
4628 /*
4629 * Matched lines have now been substituted and are
4630 * useless, delete them. The part after the match
4631 * has been appended to new_start, we don't need
4632 * it in the buffer.
4633 */
4634 ++lnum;
4635 if (u_savedel(lnum, nmatch_tl) != OK)
4636 break;
4637 for (i = 0; i < nmatch_tl; ++i)
4638 ml_delete(lnum, (int)FALSE);
4639 mark_adjust(lnum, lnum + nmatch_tl - 1,
4640 (long)MAXLNUM, -nmatch_tl);
4641 if (do_ask)
4642 deleted_lines(lnum, nmatch_tl);
4643 --lnum;
4644 line2 -= nmatch_tl; /* nr of lines decreases */
4645 nmatch_tl = 0;
4646 }
4647
4648 /* When asking, undo is saved each time, must also set
4649 * changed flag each time. */
4650 if (do_ask)
4651 changed_bytes(lnum, 0);
4652 else
4653 {
4654 if (first_line == 0)
4655 first_line = lnum;
4656 last_line = lnum + 1;
4657 }
4658
4659 sub_firstlnum = lnum;
4660 vim_free(sub_firstline); /* free the temp buffer */
4661 sub_firstline = new_start;
4662 new_start = NULL;
4663 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4664 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4665 - prev_matchcol;
4666 copycol = 0;
4667 }
4668 if (nmatch == -1 && !lastone)
4669 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf,
4670 sub_firstlnum, matchcol);
4671
4672 /*
4673 * 5. break if there isn't another match in this line
4674 */
4675 if (nmatch <= 0)
4676 break;
4677 }
4678
4679 line_breakcheck();
4680 }
4681
4682 if (did_sub)
4683 ++sub_nlines;
4684 vim_free(sub_firstline); /* free the copy of the original line */
4685 sub_firstline = NULL;
4686 }
4687
4688 line_breakcheck();
4689 }
4690
4691 if (first_line != 0)
4692 {
4693 /* Need to subtract the number of added lines from "last_line" to get
4694 * the line number before the change (same as adding the number of
4695 * deleted lines). */
4696 i = curbuf->b_ml.ml_line_count - old_line_count;
4697 changed_lines(first_line, 0, last_line - i, i);
4698 }
4699
4700outofmem:
4701 vim_free(sub_firstline); /* may have to free allocated copy of the line */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004702
4703 /* ":s/pat//n" doesn't move the cursor */
4704 if (do_count)
4705 curwin->w_cursor = old_cursor;
4706
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707 if (sub_nsubs)
4708 {
4709 /* Set the '[ and '] marks. */
4710 curbuf->b_op_start.lnum = eap->line1;
4711 curbuf->b_op_end.lnum = line2;
4712 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
4713
4714 if (!global_busy)
4715 {
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004716 if (endcolumn)
4717 coladvance((colnr_T)MAXCOL);
4718 else
4719 beginline(BL_WHITE | BL_FIX);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004720 if (!do_sub_msg(do_count) && do_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 MSG("");
4722 }
4723 else
4724 global_need_beginline = TRUE;
4725 if (do_print)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004726 print_line(curwin->w_cursor.lnum, do_number, do_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 }
4728 else if (!global_busy)
4729 {
4730 if (got_int) /* interrupted */
4731 EMSG(_(e_interr));
4732 else if (got_match) /* did find something but nothing substituted */
4733 MSG("");
4734 else if (do_error) /* nothing found */
4735 EMSG2(_(e_patnotf2), get_search_pat());
4736 }
4737
4738 vim_free(regmatch.regprog);
4739}
4740
4741/*
4742 * Give message for number of substitutions.
4743 * Can also be used after a ":global" command.
4744 * Return TRUE if a message was given.
4745 */
4746 static int
Bram Moolenaar05159a02005-02-26 23:04:13 +00004747do_sub_msg(count_only)
4748 int count_only; /* used 'n' flag for ":s" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749{
Bram Moolenaar555b2802005-05-19 21:08:39 +00004750 int len = 0;
4751
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752 /*
4753 * Only report substitutions when:
4754 * - more than 'report' substitutions
4755 * - command was typed by user, or number of changed lines > 'report'
4756 * - giving messages is not disabled by 'lazyredraw'
4757 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004758 if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
4759 || count_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760 && messaging())
4761 {
4762 if (got_int)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004763 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 STRCPY(msg_buf, _("(Interrupted) "));
Bram Moolenaar555b2802005-05-19 21:08:39 +00004765 len = STRLEN(msg_buf);
4766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767 if (sub_nsubs == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004768 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4769 "%s", count_only ? _("1 match") : _("1 substitution"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004771 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
Bram Moolenaar05159a02005-02-26 23:04:13 +00004772 count_only ? _("%ld matches") : _("%ld substitutions"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 sub_nsubs);
Bram Moolenaar555b2802005-05-19 21:08:39 +00004774 len = STRLEN(msg_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775 if (sub_nlines == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004776 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4777 "%s", _(" on 1 line"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004779 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4780 _(" on %ld lines"), (long)sub_nlines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 if (msg(msg_buf))
4782 {
4783 /* save message to display it after redraw */
4784 set_keep_msg(msg_buf);
4785 keep_msg_attr = 0;
4786 }
4787 return TRUE;
4788 }
4789 if (got_int)
4790 {
4791 EMSG(_(e_interr));
4792 return TRUE;
4793 }
4794 return FALSE;
4795}
4796
4797/*
4798 * Execute a global command of the form:
4799 *
4800 * g/pattern/X : execute X on all lines where pattern matches
4801 * v/pattern/X : execute X on all lines where pattern does not match
4802 *
4803 * where 'X' is an EX command
4804 *
4805 * The command character (as well as the trailing slash) is optional, and
4806 * is assumed to be 'p' if missing.
4807 *
4808 * This is implemented in two passes: first we scan the file for the pattern and
4809 * set a mark for each line that (not) matches. secondly we execute the command
4810 * for each line that has a mark. This is required because after deleting
4811 * lines we do not know where to search for the next match.
4812 */
4813 void
4814ex_global(eap)
4815 exarg_T *eap;
4816{
4817 linenr_T lnum; /* line number according to old situation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004818 int ndone = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 int type; /* first char of cmd: 'v' or 'g' */
4820 char_u *cmd; /* command argument */
4821
4822 char_u delim; /* delimiter, normally '/' */
4823 char_u *pat;
4824 regmmatch_T regmatch;
4825 int match;
4826 int which_pat;
4827
4828 if (global_busy)
4829 {
4830 EMSG(_("E147: Cannot do :global recursive")); /* will increment global_busy */
4831 return;
4832 }
4833
4834 if (eap->forceit) /* ":global!" is like ":vglobal" */
4835 type = 'v';
4836 else
4837 type = *eap->cmd;
4838 cmd = eap->arg;
4839 which_pat = RE_LAST; /* default: use last used regexp */
4840 sub_nsubs = 0;
4841 sub_nlines = 0;
4842
4843 /*
4844 * undocumented vi feature:
4845 * "\/" and "\?": use previous search pattern.
4846 * "\&": use previous substitute pattern.
4847 */
4848 if (*cmd == '\\')
4849 {
4850 ++cmd;
4851 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
4852 {
4853 EMSG(_(e_backslash));
4854 return;
4855 }
4856 if (*cmd == '&')
4857 which_pat = RE_SUBST; /* use previous substitute pattern */
4858 else
4859 which_pat = RE_SEARCH; /* use previous search pattern */
4860 ++cmd;
4861 pat = (char_u *)"";
4862 }
4863 else if (*cmd == NUL)
4864 {
4865 EMSG(_("E148: Regular expression missing from global"));
4866 return;
4867 }
4868 else
4869 {
4870 delim = *cmd; /* get the delimiter */
4871 if (delim)
4872 ++cmd; /* skip delimiter if there is one */
4873 pat = cmd; /* remember start of pattern */
4874 cmd = skip_regexp(cmd, delim, p_magic, &eap->arg);
4875 if (cmd[0] == delim) /* end delimiter found */
4876 *cmd++ = NUL; /* replace it with a NUL */
4877 }
4878
4879#ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */
4880 if (p_altkeymap && curwin->w_p_rl)
4881 lrFswap(pat,0);
4882#endif
4883
4884 if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4885 {
4886 EMSG(_(e_invcmd));
4887 return;
4888 }
4889
4890 /*
4891 * pass 1: set marks for each (not) matching line
4892 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 for (lnum = eap->line1; lnum <= eap->line2 && !got_int; ++lnum)
4894 {
4895 /* a match on this line? */
4896 match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
4897 if ((type == 'g' && match) || (type == 'v' && !match))
4898 {
4899 ml_setmarked(lnum);
4900 ndone++;
4901 }
4902 line_breakcheck();
4903 }
4904
4905 /*
4906 * pass 2: execute the command for each line that has been marked
4907 */
4908 if (got_int)
4909 MSG(_(e_interr));
4910 else if (ndone == 0)
4911 {
4912 if (type == 'v')
Bram Moolenaar555b2802005-05-19 21:08:39 +00004913 smsg((char_u *)_("Pattern found in every line: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004915 smsg((char_u *)_(e_patnotf2), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 }
4917 else
4918 global_exe(cmd);
4919
4920 ml_clearmarked(); /* clear rest of the marks */
4921 vim_free(regmatch.regprog);
4922}
4923
4924/*
4925 * Execute "cmd" on lines marked with ml_setmarked().
4926 */
4927 void
4928global_exe(cmd)
4929 char_u *cmd;
4930{
4931 linenr_T old_lcount; /* b_ml.ml_line_count before the command */
4932 linenr_T lnum; /* line number according to old situation */
4933
4934 /*
4935 * Set current position only once for a global command.
4936 * If global_busy is set, setpcmark() will not do anything.
4937 * If there is an error, global_busy will be incremented.
4938 */
4939 setpcmark();
4940
4941 /* When the command writes a message, don't overwrite the command. */
4942 msg_didout = TRUE;
4943
4944 global_need_beginline = FALSE;
4945 global_busy = 1;
4946 old_lcount = curbuf->b_ml.ml_line_count;
4947 while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1)
4948 {
4949 curwin->w_cursor.lnum = lnum;
4950 curwin->w_cursor.col = 0;
4951 if (*cmd == NUL || *cmd == '\n')
4952 do_cmdline((char_u *)"p", NULL, NULL, DOCMD_NOWAIT);
4953 else
4954 do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
4955 ui_breakcheck();
4956 }
4957
4958 global_busy = 0;
4959 if (global_need_beginline)
4960 beginline(BL_WHITE | BL_FIX);
4961 else
4962 check_cursor(); /* cursor may be beyond the end of the line */
4963
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004964 /* the cursor may not have moved in the text but a change in a previous
4965 * line may move it on the screen */
4966 changed_line_abv_curs();
4967
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968 /* If it looks like no message was written, allow overwriting the
4969 * command with the report for number of changes. */
4970 if (msg_col == 0 && msg_scrolled == 0)
4971 msg_didout = FALSE;
4972
4973 /* If subsitutes done, report number of substitues, otherwise report
4974 * number of extra or deleted lines. */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004975 if (!do_sub_msg(FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976 msgmore(curbuf->b_ml.ml_line_count - old_lcount);
4977}
4978
4979#ifdef FEAT_VIMINFO
4980 int
4981read_viminfo_sub_string(virp, force)
4982 vir_T *virp;
4983 int force;
4984{
4985 if (old_sub != NULL && force)
4986 vim_free(old_sub);
4987 if (force || old_sub == NULL)
4988 old_sub = viminfo_readstring(virp, 1, TRUE);
4989 return viminfo_readline(virp);
4990}
4991
4992 void
4993write_viminfo_sub_string(fp)
4994 FILE *fp;
4995{
4996 if (get_viminfo_parameter('/') != 0 && old_sub != NULL)
4997 {
4998 fprintf(fp, _("\n# Last Substitute String:\n$"));
4999 viminfo_writestring(fp, old_sub);
5000 }
5001}
5002#endif /* FEAT_VIMINFO */
5003
5004#if (defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)) || defined(PROTO)
5005/*
5006 * Set up for a tagpreview.
5007 */
5008 void
5009prepare_tagpreview()
5010{
5011 win_T *wp;
5012
5013# ifdef FEAT_GUI
5014 need_mouse_correct = TRUE;
5015# endif
5016
5017 /*
5018 * If there is already a preview window open, use that one.
5019 */
5020 if (!curwin->w_p_pvw)
5021 {
5022 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5023 if (wp->w_p_pvw)
5024 break;
5025 if (wp != NULL)
5026 win_enter(wp, TRUE);
5027 else
5028 {
5029 /*
5030 * There is no preview window open yet. Create one.
5031 */
5032 if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0)
5033 == FAIL)
5034 return;
5035 curwin->w_p_pvw = TRUE;
5036 curwin->w_p_wfh = TRUE;
5037# ifdef FEAT_SCROLLBIND
5038 curwin->w_p_scb = FALSE; /* don't take over 'scrollbind' */
5039# endif
5040# ifdef FEAT_DIFF
5041 curwin->w_p_diff = FALSE; /* no 'diff' */
5042# endif
5043# ifdef FEAT_FOLDING
5044 curwin->w_p_fdc = 0; /* no 'foldcolumn' */
5045# endif
5046 }
5047 }
5048}
5049
5050#endif
5051
5052
5053/*
5054 * ":help": open a read-only window on a help file
5055 */
5056 void
5057ex_help(eap)
5058 exarg_T *eap;
5059{
5060 char_u *arg;
5061 char_u *tag;
5062 FILE *helpfd; /* file descriptor of help file */
5063 int n;
5064 int i;
5065#ifdef FEAT_WINDOWS
5066 win_T *wp;
5067#endif
5068 int num_matches;
5069 char_u **matches;
5070 char_u *p;
5071 int empty_fnum = 0;
5072 int alt_fnum = 0;
5073 buf_T *buf;
5074#ifdef FEAT_MULTI_LANG
5075 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005076 char_u *lang;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077#endif
5078
5079 if (eap != NULL)
5080 {
5081 /*
5082 * A ":help" command ends at the first LF, or at a '|' that is
5083 * followed by some text. Set nextcmd to the following command.
5084 */
5085 for (arg = eap->arg; *arg; ++arg)
5086 {
5087 if (*arg == '\n' || *arg == '\r'
5088 || (*arg == '|' && arg[1] != NUL && arg[1] != '|'))
5089 {
5090 *arg++ = NUL;
5091 eap->nextcmd = arg;
5092 break;
5093 }
5094 }
5095 arg = eap->arg;
5096
5097 if (eap->forceit && *arg == NUL)
5098 {
5099 EMSG(_("E478: Don't panic!"));
5100 return;
5101 }
5102
5103 if (eap->skip) /* not executing commands */
5104 return;
5105 }
5106 else
5107 arg = (char_u *)"";
5108
5109 /* remove trailing blanks */
5110 p = arg + STRLEN(arg) - 1;
5111 while (p > arg && vim_iswhite(*p) && p[-1] != '\\')
5112 *p-- = NUL;
5113
5114#ifdef FEAT_MULTI_LANG
5115 /* Check for a specified language */
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005116 lang = check_help_lang(arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005117#endif
5118
5119 /* When no argument given go to the index. */
5120 if (*arg == NUL)
5121 arg = (char_u *)"help.txt";
5122
5123 /*
5124 * Check if there is a match for the argument.
5125 */
5126 n = find_help_tags(arg, &num_matches, &matches,
5127 eap != NULL && eap->forceit);
5128
5129 i = 0;
5130#ifdef FEAT_MULTI_LANG
5131 if (n != FAIL && lang != NULL)
5132 /* Find first item with the requested language. */
5133 for (i = 0; i < num_matches; ++i)
5134 {
5135 len = STRLEN(matches[i]);
5136 if (len > 3 && matches[i][len - 3] == '@'
5137 && STRICMP(matches[i] + len - 2, lang) == 0)
5138 break;
5139 }
5140#endif
5141 if (i >= num_matches || n == FAIL)
5142 {
5143#ifdef FEAT_MULTI_LANG
5144 if (lang != NULL)
5145 EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg);
5146 else
5147#endif
5148 EMSG2(_("E149: Sorry, no help for %s"), arg);
5149 if (n != FAIL)
5150 FreeWild(num_matches, matches);
5151 return;
5152 }
5153
5154 /* The first match (in the requested language) is the best match. */
5155 tag = vim_strsave(matches[i]);
5156 FreeWild(num_matches, matches);
5157
5158#ifdef FEAT_GUI
5159 need_mouse_correct = TRUE;
5160#endif
5161
5162 /*
5163 * Re-use an existing help window or open a new one.
5164 */
5165 if (!curwin->w_buffer->b_help)
5166 {
5167#ifdef FEAT_WINDOWS
5168 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5169 if (wp->w_buffer != NULL && wp->w_buffer->b_help)
5170 break;
5171 if (wp != NULL && wp->w_buffer->b_nwindows > 0)
5172 win_enter(wp, TRUE);
5173 else
5174#endif
5175 {
5176 /*
5177 * There is no help window yet.
5178 * Try to open the file specified by the "helpfile" option.
5179 */
5180 if ((helpfd = mch_fopen((char *)p_hf, READBIN)) == NULL)
5181 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00005182 smsg((char_u *)_("Sorry, help file \"%s\" not found"), p_hf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183 goto erret;
5184 }
5185 fclose(helpfd);
5186
5187#ifdef FEAT_WINDOWS
5188 /* Split off help window; put it at far top if no position
5189 * specified, the current window is vertically split and narrow. */
5190 n = WSP_HELP;
5191# ifdef FEAT_VERTSPLIT
5192 if (cmdmod.split == 0 && curwin->w_width != Columns
5193 && curwin->w_width < 80)
5194 n |= WSP_TOP;
5195# endif
5196 if (win_split(0, n) == FAIL)
5197#else
5198 /* use current window */
5199 if (!can_abandon(curbuf, FALSE))
5200#endif
5201 goto erret;
5202
5203#ifdef FEAT_WINDOWS
5204 if (curwin->w_height < p_hh)
5205 win_setheight((int)p_hh);
5206#endif
5207
5208 /*
5209 * Open help file (do_ecmd() will set b_help flag, readfile() will
5210 * set b_p_ro flag).
5211 * Set the alternate file to the previously edited file.
5212 */
5213 alt_fnum = curbuf->b_fnum;
5214 (void)do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL,
5215 ECMD_HIDE + ECMD_SET_HELP);
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005216 if (!cmdmod.keepalt)
5217 curwin->w_alt_fnum = alt_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 empty_fnum = curbuf->b_fnum;
5219 }
5220 }
5221
5222 if (!p_im)
5223 restart_edit = 0; /* don't want insert mode in help file */
5224
5225 if (tag != NULL)
5226 do_tag(tag, DT_HELP, 1, FALSE, TRUE);
5227
5228 /* Delete the empty buffer if we're not using it. */
5229 if (empty_fnum != 0 && curbuf->b_fnum != empty_fnum)
5230 {
5231 buf = buflist_findnr(empty_fnum);
5232 if (buf != NULL)
5233 wipe_buffer(buf, TRUE);
5234 }
5235
5236 /* keep the previous alternate file */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005237 if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 curwin->w_alt_fnum = alt_fnum;
5239
5240erret:
5241 vim_free(tag);
5242}
5243
5244
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005245#if defined(FEAT_MULTI_LANG) || defined(PROTO)
5246/*
5247 * In an argument search for a language specifiers in the form "@xx".
5248 * Changes the "@" to NUL if found, and returns a pointer to "xx".
5249 * Returns NULL if not found.
5250 */
5251 char_u *
5252check_help_lang(arg)
5253 char_u *arg;
5254{
5255 int len = STRLEN(arg);
5256
5257 if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2])
5258 && ASCII_ISALPHA(arg[len - 1]))
5259 {
5260 arg[len - 3] = NUL; /* remove the '@' */
5261 return arg + len - 2;
5262 }
5263 return NULL;
5264}
5265#endif
5266
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267/*
5268 * Return a heuristic indicating how well the given string matches. The
5269 * smaller the number, the better the match. This is the order of priorities,
5270 * from best match to worst match:
5271 * - Match with least alpha-numeric characters is better.
5272 * - Match with least total characters is better.
5273 * - Match towards the start is better.
5274 * - Match starting with "+" is worse (feature instead of command)
5275 * Assumption is made that the matched_string passed has already been found to
5276 * match some string for which help is requested. webb.
5277 */
5278 int
5279help_heuristic(matched_string, offset, wrong_case)
5280 char_u *matched_string;
5281 int offset; /* offset for match */
5282 int wrong_case; /* no matching case */
5283{
5284 int num_letters;
5285 char_u *p;
5286
5287 num_letters = 0;
5288 for (p = matched_string; *p; p++)
5289 if (ASCII_ISALNUM(*p))
5290 num_letters++;
5291
5292 /*
5293 * Multiply the number of letters by 100 to give it a much bigger
5294 * weighting than the number of characters.
5295 * If there only is a match while ignoring case, add 5000.
5296 * If the match starts in the middle of a word, add 10000 to put it
5297 * somewhere in the last half.
5298 * If the match is more than 2 chars from the start, multiply by 200 to
5299 * put it after matches at the start.
5300 */
5301 if (ASCII_ISALNUM(matched_string[offset]) && offset > 0
5302 && ASCII_ISALNUM(matched_string[offset - 1]))
5303 offset += 10000;
5304 else if (offset > 2)
5305 offset *= 200;
5306 if (wrong_case)
5307 offset += 5000;
5308 /* Features are less interesting than the subjects themselves, but "+"
5309 * alone is not a feature. */
5310 if (matched_string[0] == '+' && matched_string[1] != NUL)
5311 offset += 100;
5312 return (int)(100 * num_letters + STRLEN(matched_string) + offset);
5313}
5314
5315/*
5316 * Compare functions for qsort() below, that checks the help heuristics number
5317 * that has been put after the tagname by find_tags().
5318 */
5319 static int
5320#ifdef __BORLANDC__
5321_RTLENTRYF
5322#endif
5323help_compare(s1, s2)
5324 const void *s1;
5325 const void *s2;
5326{
5327 char *p1;
5328 char *p2;
5329
5330 p1 = *(char **)s1 + strlen(*(char **)s1) + 1;
5331 p2 = *(char **)s2 + strlen(*(char **)s2) + 1;
5332 return strcmp(p1, p2);
5333}
5334
5335/*
5336 * Find all help tags matching "arg", sort them and return in matches[], with
5337 * the number of matches in num_matches.
5338 * The matches will be sorted with a "best" match algorithm.
5339 * When "keep_lang" is TRUE try keeping the language of the current buffer.
5340 */
5341 int
5342find_help_tags(arg, num_matches, matches, keep_lang)
5343 char_u *arg;
5344 int *num_matches;
5345 char_u ***matches;
5346 int keep_lang;
5347{
5348 char_u *s, *d;
5349 int i;
5350 static char *(mtable[]) = {"*", "g*", "[*", "]*", ":*",
5351 "/*", "/\\*", "\"*", "/\\(\\)",
5352 "?", ":?", "?<CR>", "g?", "g?g?", "g??",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005353 "/\\?", "/\\z(\\)", "\\=", ":s\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005354 "[count]", "[quotex]", "[range]",
5355 "[pattern]", "\\|", "\\%$"};
5356 static char *(rtable[]) = {"star", "gstar", "[star", "]star", ":star",
5357 "/star", "/\\\\star", "quotestar", "/\\\\(\\\\)",
5358 "?", ":?", "?<CR>", "g?", "g?g?", "g??",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005359 "/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360 "\\[count]", "\\[quotex]", "\\[range]",
5361 "\\[pattern]", "\\\\bar", "/\\\\%\\$"};
5362 int flags;
5363
5364 d = IObuff; /* assume IObuff is long enough! */
5365
5366 /*
5367 * Recognize a few exceptions to the rule. Some strings that contain '*'
5368 * with "star". Otherwise '*' is recognized as a wildcard.
5369 */
5370 for (i = sizeof(mtable) / sizeof(char *); --i >= 0; )
5371 if (STRCMP(arg, mtable[i]) == 0)
5372 {
5373 STRCPY(d, rtable[i]);
5374 break;
5375 }
5376
5377 if (i < 0) /* no match in table */
5378 {
5379 /* Replace "\S" with "/\\S", etc. Otherwise every tag is matched.
5380 * Also replace "\%^" and "\%(", they match every tag too.
5381 * Also "\zs", "\z1", etc.
5382 * Also "\@<", "\@=", "\@<=", etc.
5383 * And also "\_$" and "\_^". */
5384 if (arg[0] == '\\'
5385 && ((arg[1] != NUL && arg[2] == NUL)
5386 || (vim_strchr((char_u *)"%_z@", arg[1]) != NULL
5387 && arg[2] != NUL)))
5388 {
5389 STRCPY(d, "/\\\\");
5390 STRCPY(d + 3, arg + 1);
5391 /* Check for "/\\_$", should be "/\\_\$" */
5392 if (d[3] == '_' && d[4] == '$')
5393 STRCPY(d + 4, "\\$");
5394 }
5395 else
5396 {
5397 /* replace "[:...:]" with "\[:...:]"; "[+...]" with "\[++...]" */
5398 if (arg[0] == '[' && (arg[1] == ':'
5399 || (arg[1] == '+' && arg[2] == '+')))
5400 *d++ = '\\';
5401
5402 for (s = arg; *s; ++s)
5403 {
5404 /*
5405 * Replace "|" with "bar" and '"' with "quote" to match the name of
5406 * the tags for these commands.
5407 * Replace "*" with ".*" and "?" with "." to match command line
5408 * completion.
5409 * Insert a backslash before '~', '$' and '.' to avoid their
5410 * special meaning.
5411 */
5412 if (d - IObuff > IOSIZE - 10) /* getting too long!? */
5413 break;
5414 switch (*s)
5415 {
5416 case '|': STRCPY(d, "bar");
5417 d += 3;
5418 continue;
5419 case '"': STRCPY(d, "quote");
5420 d += 5;
5421 continue;
5422 case '*': *d++ = '.';
5423 break;
5424 case '?': *d++ = '.';
5425 continue;
5426 case '$':
5427 case '.':
5428 case '~': *d++ = '\\';
5429 break;
5430 }
5431
5432 /*
5433 * Replace "^x" by "CTRL-X". Don't do this for "^_" to make
5434 * ":help i_^_CTRL-D" work.
5435 * Insert '-' before and after "CTRL-X" when applicable.
5436 */
5437 if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1])
5438 || vim_strchr((char_u *)"?@[\\]^", s[1]) != NULL)))
5439 {
5440 if (d > IObuff && d[-1] != '_')
5441 *d++ = '_'; /* prepend a '_' */
5442 STRCPY(d, "CTRL-");
5443 d += 5;
5444 if (*s < ' ')
5445 {
5446#ifdef EBCDIC
5447 *d++ = CtrlChar(*s);
5448#else
5449 *d++ = *s + '@';
5450#endif
5451 if (d[-1] == '\\')
5452 *d++ = '\\'; /* double a backslash */
5453 }
5454 else
5455 *d++ = *++s;
5456 if (s[1] != NUL && s[1] != '_')
5457 *d++ = '_'; /* append a '_' */
5458 continue;
5459 }
5460 else if (*s == '^') /* "^" or "CTRL-^" or "^_" */
5461 *d++ = '\\';
5462
5463 /*
5464 * Insert a backslash before a backslash after a slash, for search
5465 * pattern tags: "/\|" --> "/\\|".
5466 */
5467 else if (s[0] == '\\' && s[1] != '\\'
5468 && *arg == '/' && s == arg + 1)
5469 *d++ = '\\';
5470
5471 /* "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in
5472 * "CTRL-\_CTRL-N" */
5473 if (STRNICMP(s, "CTRL-\\_", 7) == 0)
5474 {
5475 STRCPY(d, "CTRL-\\\\");
5476 d += 7;
5477 s += 6;
5478 }
5479
5480 *d++ = *s;
5481
5482 /*
5483 * If tag starts with ', toss everything after a second '. Fixes
5484 * CTRL-] on 'option'. (would include the trailing '.').
5485 */
5486 if (*s == '\'' && s > arg && *arg == '\'')
5487 break;
5488 }
5489 *d = NUL;
5490 }
5491 }
5492
5493 *matches = (char_u **)"";
5494 *num_matches = 0;
5495 flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE;
5496 if (keep_lang)
5497 flags |= TAG_KEEP_LANG;
5498 if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK
5499 && *num_matches > 0)
5500 /* Sort the matches found on the heuristic number that is after the
5501 * tag name. */
5502 qsort((void *)*matches, (size_t)*num_matches,
5503 sizeof(char_u *), help_compare);
5504 return OK;
5505}
5506
5507/*
5508 * After reading a help file: May cleanup a help buffer when syntax
5509 * highlighting is not used.
5510 */
5511 void
5512fix_help_buffer()
5513{
5514 linenr_T lnum;
5515 char_u *line;
5516 int in_example = FALSE;
5517 int len;
5518 char_u *p;
5519 char_u *rt;
5520 int mustfree;
5521
5522 /* set filetype to "help". */
5523 set_option_value((char_u *)"ft", 0L, (char_u *)"help", OPT_LOCAL);
5524
5525#ifdef FEAT_SYN_HL
5526 if (!syntax_present(curbuf))
5527#endif
5528 {
5529 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
5530 {
5531 line = ml_get_buf(curbuf, lnum, FALSE);
5532 len = (int)STRLEN(line);
5533 if (in_example && len > 0 && !vim_iswhite(line[0]))
5534 {
5535 /* End of example: non-white or '<' in first column. */
5536 if (line[0] == '<')
5537 {
5538 /* blank-out a '<' in the first column */
5539 line = ml_get_buf(curbuf, lnum, TRUE);
5540 line[0] = ' ';
5541 }
5542 in_example = FALSE;
5543 }
5544 if (!in_example && len > 0)
5545 {
5546 if (line[len - 1] == '>' && (len == 1 || line[len - 2] == ' '))
5547 {
5548 /* blank-out a '>' in the last column (start of example) */
5549 line = ml_get_buf(curbuf, lnum, TRUE);
5550 line[len - 1] = ' ';
5551 in_example = TRUE;
5552 }
5553 else if (line[len - 1] == '~')
5554 {
5555 /* blank-out a '~' at the end of line (header marker) */
5556 line = ml_get_buf(curbuf, lnum, TRUE);
5557 line[len - 1] = ' ';
5558 }
5559 }
5560 }
5561 }
5562
5563 /*
5564 * In the "help.txt" file, add the locally added help files.
5565 * This uses the very first line in the help file.
5566 */
5567 if (fnamecmp(gettail(curbuf->b_fname), "help.txt") == 0)
5568 {
5569 for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; ++lnum)
5570 {
5571 line = ml_get_buf(curbuf, lnum, FALSE);
5572 if (strstr((char *)line, "*local-additions*") != NULL)
5573 {
5574 /* Go through all directories in 'runtimepath', skipping
5575 * $VIMRUNTIME. */
5576 p = p_rtp;
5577 while (*p != NUL)
5578 {
5579 copy_option_part(&p, NameBuff, MAXPATHL, ",");
5580 mustfree = FALSE;
5581 rt = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
5582 if (fullpathcmp(rt, NameBuff, FALSE) != FPC_SAME)
5583 {
5584 int fcount;
5585 char_u **fnames;
5586 FILE *fd;
5587 char_u *s;
5588 int fi;
5589#ifdef FEAT_MBYTE
5590 vimconv_T vc;
5591 char_u *cp;
5592#endif
5593
5594 /* Find all "doc/ *.txt" files in this directory. */
5595 add_pathsep(NameBuff);
5596 STRCAT(NameBuff, "doc/*.txt");
5597 if (gen_expand_wildcards(1, &NameBuff, &fcount,
5598 &fnames, EW_FILE|EW_SILENT) == OK
5599 && fcount > 0)
5600 {
5601 for (fi = 0; fi < fcount; ++fi)
5602 {
5603 fd = fopen((char *)fnames[fi], "r");
5604 if (fd != NULL)
5605 {
5606 vim_fgets(IObuff, IOSIZE, fd);
5607 if (IObuff[0] == '*'
5608 && (s = vim_strchr(IObuff + 1, '*'))
5609 != NULL)
5610 {
5611#ifdef FEAT_MBYTE
5612 int this_utf = MAYBE;
5613#endif
5614 /* Change tag definition to a
5615 * reference and remove <CR>/<NL>. */
5616 IObuff[0] = '|';
5617 *s = '|';
5618 while (*s != NUL)
5619 {
5620 if (*s == '\r' || *s == '\n')
5621 *s = NUL;
5622#ifdef FEAT_MBYTE
5623 /* The text is utf-8 when a byte
5624 * above 127 is found and no
5625 * illegal byte sequence is found.
5626 */
5627 if (*s >= 0x80 && this_utf != FALSE)
5628 {
5629 int l;
5630
5631 this_utf = TRUE;
5632 l = utf_ptr2len_check(s);
5633 if (l == 1)
5634 this_utf = FALSE;
5635 s += l - 1;
5636 }
5637#endif
5638 ++s;
5639 }
5640#ifdef FEAT_MBYTE
5641 /* The help file is latin1 or utf-8;
5642 * conversion to the current
5643 * 'encoding' may be required. */
5644 vc.vc_type = CONV_NONE;
5645 convert_setup(&vc, (char_u *)(
5646 this_utf == TRUE ? "utf-8"
5647 : "latin1"), p_enc);
5648 if (vc.vc_type == CONV_NONE)
5649 /* No conversion needed. */
5650 cp = IObuff;
5651 else
5652 {
5653 /* Do the conversion. If it fails
5654 * use the unconverted text. */
5655 cp = string_convert(&vc, IObuff,
5656 NULL);
5657 if (cp == NULL)
5658 cp = IObuff;
5659 }
5660 convert_setup(&vc, NULL, NULL);
5661
5662 ml_append(lnum, cp, (colnr_T)0, FALSE);
5663 if (cp != IObuff)
5664 vim_free(cp);
5665#else
5666 ml_append(lnum, IObuff, (colnr_T)0,
5667 FALSE);
5668#endif
5669 ++lnum;
5670 }
5671 fclose(fd);
5672 }
5673 }
5674 FreeWild(fcount, fnames);
5675 }
5676 }
5677 if (mustfree)
5678 vim_free(rt);
5679 }
5680 break;
5681 }
5682 }
5683 }
5684}
5685
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00005686/*
5687 * ":exusage"
5688 */
5689/*ARGSUSED*/
5690 void
5691ex_exusage(eap)
5692 exarg_T *eap;
5693{
5694 do_cmdline_cmd((char_u *)"help ex-cmd-index");
5695}
5696
5697/*
5698 * ":viusage"
5699 */
5700/*ARGSUSED*/
5701 void
5702ex_viusage(eap)
5703 exarg_T *eap;
5704{
5705 do_cmdline_cmd((char_u *)"help normal-index");
5706}
5707
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708#if defined(FEAT_EX_EXTRA) || defined(PROTO)
5709static void helptags_one __ARGS((char_u *dir, char_u *ext, char_u *lang));
5710
5711/*
5712 * ":helptags"
5713 */
5714 void
5715ex_helptags(eap)
5716 exarg_T *eap;
5717{
5718 garray_T ga;
5719 int i, j;
5720 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005721#ifdef FEAT_MULTI_LANG
Bram Moolenaar071d4272004-06-13 20:20:40 +00005722 char_u lang[2];
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005723#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 char_u ext[5];
5725 char_u fname[8];
5726 int filecount;
5727 char_u **files;
5728
5729 if (!mch_isdir(eap->arg))
5730 {
5731 EMSG2(_("E150: Not a directory: %s"), eap->arg);
5732 return;
5733 }
5734
5735#ifdef FEAT_MULTI_LANG
5736 /* Get a list of all files in the directory. */
5737 STRCPY(NameBuff, eap->arg);
5738 add_pathsep(NameBuff);
5739 STRCAT(NameBuff, "*");
5740 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
5741 EW_FILE|EW_SILENT) == FAIL
5742 || filecount == 0)
5743 {
5744 EMSG2("E151: No match: %s", NameBuff);
5745 return;
5746 }
5747
5748 /* Go over all files in the directory to find out what languages are
5749 * present. */
5750 ga_init2(&ga, 1, 10);
5751 for (i = 0; i < filecount; ++i)
5752 {
5753 len = STRLEN(files[i]);
5754 if (len > 4)
5755 {
5756 if (STRICMP(files[i] + len - 4, ".txt") == 0)
5757 {
5758 /* ".txt" -> language "en" */
5759 lang[0] = 'e';
5760 lang[1] = 'n';
5761 }
5762 else if (files[i][len - 4] == '.'
5763 && ASCII_ISALPHA(files[i][len - 3])
5764 && ASCII_ISALPHA(files[i][len - 2])
5765 && TOLOWER_ASC(files[i][len - 1]) == 'x')
5766 {
5767 /* ".abx" -> language "ab" */
5768 lang[0] = TOLOWER_ASC(files[i][len - 3]);
5769 lang[1] = TOLOWER_ASC(files[i][len - 2]);
5770 }
5771 else
5772 continue;
5773
5774 /* Did we find this language already? */
5775 for (j = 0; j < ga.ga_len; j += 2)
5776 if (STRNCMP(lang, ((char_u *)ga.ga_data) + j, 2) == 0)
5777 break;
5778 if (j == ga.ga_len)
5779 {
5780 /* New language, add it. */
5781 if (ga_grow(&ga, 2) == FAIL)
5782 break;
5783 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[0];
5784 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785 }
5786 }
5787 }
5788
5789 /*
5790 * Loop over the found languages to generate a tags file for each one.
5791 */
5792 for (j = 0; j < ga.ga_len; j += 2)
5793 {
5794 STRCPY(fname, "tags-xx");
5795 fname[5] = ((char_u *)ga.ga_data)[j];
5796 fname[6] = ((char_u *)ga.ga_data)[j + 1];
5797 if (fname[5] == 'e' && fname[6] == 'n')
5798 {
5799 /* English is an exception: use ".txt" and "tags". */
5800 fname[4] = NUL;
5801 STRCPY(ext, ".txt");
5802 }
5803 else
5804 {
5805 /* Language "ab" uses ".abx" and "tags-ab". */
5806 STRCPY(ext, ".xxx");
5807 ext[1] = fname[5];
5808 ext[2] = fname[6];
5809 }
5810 helptags_one(eap->arg, ext, fname);
5811 }
5812
5813 ga_clear(&ga);
5814 FreeWild(filecount, files);
5815
5816#else
5817 /* No language support, just use "*.txt" and "tags". */
5818 helptags_one(eap->arg, (char_u *)".txt", (char_u *)"tags");
5819#endif
5820}
5821
5822 static void
5823helptags_one(dir, ext, tagfname)
5824 char_u *dir; /* doc directory */
5825 char_u *ext; /* suffix, ".txt", ".itx", ".frx", etc. */
5826 char_u *tagfname; /* "tags" for English, "tags-it" for Italian. */
5827{
5828 FILE *fd_tags;
5829 FILE *fd;
5830 garray_T ga;
5831 int filecount;
5832 char_u **files;
5833 char_u *p1, *p2;
5834 int fi;
5835 char_u *s;
5836 int i;
5837 char_u *fname;
5838# ifdef FEAT_MBYTE
5839 int utf8 = MAYBE;
5840 int this_utf8;
5841 int firstline;
5842 int mix = FALSE; /* detected mixed encodings */
5843# endif
5844
5845 /*
5846 * Find all *.txt files.
5847 */
5848 STRCPY(NameBuff, dir);
5849 add_pathsep(NameBuff);
5850 STRCAT(NameBuff, "*");
5851 STRCAT(NameBuff, ext);
5852 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
5853 EW_FILE|EW_SILENT) == FAIL
5854 || filecount == 0)
5855 {
5856 if (!got_int)
5857 EMSG2("E151: No match: %s", NameBuff);
5858 return;
5859 }
5860
5861 /*
5862 * Open the tags file for writing.
5863 * Do this before scanning through all the files.
5864 */
5865 STRCPY(NameBuff, dir);
5866 add_pathsep(NameBuff);
5867 STRCAT(NameBuff, tagfname);
5868 fd_tags = fopen((char *)NameBuff, "w");
5869 if (fd_tags == NULL)
5870 {
5871 EMSG2(_("E152: Cannot open %s for writing"), NameBuff);
5872 FreeWild(filecount, files);
5873 return;
5874 }
5875
5876 /*
5877 * If generating tags for "$VIMRUNTIME/doc" add the "help-tags" tag.
5878 */
5879 ga_init2(&ga, (int)sizeof(char_u *), 100);
5880 if (fullpathcmp((char_u *)"$VIMRUNTIME/doc", dir, FALSE) == FPC_SAME)
5881 {
5882 if (ga_grow(&ga, 1) == FAIL)
5883 got_int = TRUE;
5884 else
5885 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00005886 s = alloc(18 + STRLEN(tagfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887 if (s == NULL)
5888 got_int = TRUE;
5889 else
5890 {
5891 sprintf((char *)s, "help-tags\t%s\t1\n", tagfname);
5892 ((char_u **)ga.ga_data)[ga.ga_len] = s;
5893 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894 }
5895 }
5896 }
5897
5898 /*
5899 * Go over all the files and extract the tags.
5900 */
5901 for (fi = 0; fi < filecount && !got_int; ++fi)
5902 {
5903 fd = fopen((char *)files[fi], "r");
5904 if (fd == NULL)
5905 {
5906 EMSG2(_("E153: Unable to open %s for reading"), files[fi]);
5907 continue;
5908 }
5909 fname = gettail(files[fi]);
5910
5911# ifdef FEAT_MBYTE
5912 firstline = TRUE;
5913# endif
5914 while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int)
5915 {
5916# ifdef FEAT_MBYTE
5917 if (firstline)
5918 {
5919 /* Detect utf-8 file by a non-ASCII char in the first line. */
5920 this_utf8 = MAYBE;
5921 for (s = IObuff; *s != NUL; ++s)
5922 if (*s >= 0x80)
5923 {
5924 int l;
5925
5926 this_utf8 = TRUE;
5927 l = utf_ptr2len_check(s);
5928 if (l == 1)
5929 {
5930 /* Illegal UTF-8 byte sequence. */
5931 this_utf8 = FALSE;
5932 break;
5933 }
5934 s += l - 1;
5935 }
5936 if (this_utf8 == MAYBE) /* only ASCII characters found */
5937 this_utf8 = FALSE;
5938 if (utf8 == MAYBE) /* first file */
5939 utf8 = this_utf8;
5940 else if (utf8 != this_utf8)
5941 {
5942 EMSG2(_("E670: Mix of help file encodings within a language: %s"), files[fi]);
5943 mix = !got_int;
5944 got_int = TRUE;
5945 }
5946 firstline = FALSE;
5947 }
5948# endif
5949 p1 = vim_strchr(IObuff, '*'); /* find first '*' */
5950 while (p1 != NULL)
5951 {
5952 p2 = vim_strchr(p1 + 1, '*'); /* find second '*' */
5953 if (p2 != NULL && p2 > p1 + 1) /* skip "*" and "**" */
5954 {
5955 for (s = p1 + 1; s < p2; ++s)
5956 if (*s == ' ' || *s == '\t' || *s == '|')
5957 break;
5958
5959 /*
5960 * Only accept a *tag* when it consists of valid
5961 * characters, there is white space before it and is
5962 * followed by a white character or end-of-line.
5963 */
5964 if (s == p2
5965 && (p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
5966 && (vim_strchr((char_u *)" \t\n\r", s[1]) != NULL
5967 || s[1] == '\0'))
5968 {
5969 *p2 = '\0';
5970 ++p1;
5971 if (ga_grow(&ga, 1) == FAIL)
5972 {
5973 got_int = TRUE;
5974 break;
5975 }
5976 s = alloc((unsigned)(p2 - p1 + STRLEN(fname) + 2));
5977 if (s == NULL)
5978 {
5979 got_int = TRUE;
5980 break;
5981 }
5982 ((char_u **)ga.ga_data)[ga.ga_len] = s;
5983 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984 sprintf((char *)s, "%s\t%s", p1, fname);
5985
5986 /* find next '*' */
5987 p2 = vim_strchr(p2 + 1, '*');
5988 }
5989 }
5990 p1 = p2;
5991 }
5992 line_breakcheck();
5993 }
5994
5995 fclose(fd);
5996 }
5997
5998 FreeWild(filecount, files);
5999
6000 if (!got_int)
6001 {
6002 /*
6003 * Sort the tags.
6004 */
6005 sort_strings((char_u **)ga.ga_data, ga.ga_len);
6006
6007 /*
6008 * Check for duplicates.
6009 */
6010 for (i = 1; i < ga.ga_len; ++i)
6011 {
6012 p1 = ((char_u **)ga.ga_data)[i - 1];
6013 p2 = ((char_u **)ga.ga_data)[i];
6014 while (*p1 == *p2)
6015 {
6016 if (*p2 == '\t')
6017 {
6018 *p2 = NUL;
Bram Moolenaar555b2802005-05-19 21:08:39 +00006019 vim_snprintf((char *)NameBuff, MAXPATHL,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020 _("E154: Duplicate tag \"%s\" in file %s/%s"),
6021 ((char_u **)ga.ga_data)[i], dir, p2 + 1);
6022 EMSG(NameBuff);
6023 *p2 = '\t';
6024 break;
6025 }
6026 ++p1;
6027 ++p2;
6028 }
6029 }
6030
6031# ifdef FEAT_MBYTE
6032 if (utf8 == TRUE)
6033 fprintf(fd_tags, "!_TAG_FILE_ENCODING\tutf-8\t//\n");
6034# endif
6035
6036 /*
6037 * Write the tags into the file.
6038 */
6039 for (i = 0; i < ga.ga_len; ++i)
6040 {
6041 s = ((char_u **)ga.ga_data)[i];
6042 if (STRNCMP(s, "help-tags", 9) == 0)
6043 /* help-tags entry was added in formatted form */
6044 fprintf(fd_tags, (char *)s);
6045 else
6046 {
6047 fprintf(fd_tags, "%s\t/*", s);
6048 for (p1 = s; *p1 != '\t'; ++p1)
6049 {
6050 /* insert backslash before '\\' and '/' */
6051 if (*p1 == '\\' || *p1 == '/')
6052 putc('\\', fd_tags);
6053 putc(*p1, fd_tags);
6054 }
6055 fprintf(fd_tags, "*\n");
6056 }
6057 }
6058 }
6059#ifdef FEAT_MBYTE
6060 if (mix)
6061 got_int = FALSE; /* continue with other languages */
6062#endif
6063
6064 for (i = 0; i < ga.ga_len; ++i)
6065 vim_free(((char_u **)ga.ga_data)[i]);
6066 ga_clear(&ga);
6067 fclose(fd_tags); /* there is no check for an error... */
6068}
6069#endif
6070
6071#if defined(FEAT_SIGNS) || defined(PROTO)
6072
6073/*
6074 * Struct to hold the sign properties.
6075 */
6076typedef struct sign sign_T;
6077
6078struct sign
6079{
6080 sign_T *sn_next; /* next sign in list */
6081 int sn_typenr; /* type number of sign (negative if not equal
6082 to name) */
6083 char_u *sn_name; /* name of sign */
6084 char_u *sn_icon; /* name of pixmap */
6085#ifdef FEAT_SIGN_ICONS
6086 void *sn_image; /* icon image */
6087#endif
6088 char_u *sn_text; /* text used instead of pixmap */
6089 int sn_line_hl; /* highlight ID for line */
6090 int sn_text_hl; /* highlight ID for text */
6091};
6092
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093static sign_T *first_sign = NULL;
6094static int last_sign_typenr = MAX_TYPENR; /* is decremented */
6095
6096static void sign_list_defined __ARGS((sign_T *sp));
6097
6098/*
6099 * ":sign" command
6100 */
6101 void
6102ex_sign(eap)
6103 exarg_T *eap;
6104{
6105 char_u *arg = eap->arg;
6106 char_u *p;
6107 int idx;
6108 sign_T *sp;
6109 sign_T *sp_prev;
6110 buf_T *buf;
6111 static char *cmds[] = {
6112 "define",
6113#define SIGNCMD_DEFINE 0
6114 "undefine",
6115#define SIGNCMD_UNDEFINE 1
6116 "list",
6117#define SIGNCMD_LIST 2
6118 "place",
6119#define SIGNCMD_PLACE 3
6120 "unplace",
6121#define SIGNCMD_UNPLACE 4
6122 "jump",
6123#define SIGNCMD_JUMP 5
6124#define SIGNCMD_LAST 6
6125 };
6126
6127 /* Parse the subcommand. */
6128 p = skiptowhite(arg);
6129 if (*p != NUL)
6130 *p++ = NUL;
6131 for (idx = 0; ; ++idx)
6132 {
6133 if (idx == SIGNCMD_LAST)
6134 {
6135 EMSG2(_("E160: Unknown sign command: %s"), arg);
6136 return;
6137 }
6138 if (STRCMP(arg, cmds[idx]) == 0)
6139 break;
6140 }
6141 arg = skipwhite(p);
6142
6143 if (idx <= SIGNCMD_LIST)
6144 {
6145 /*
6146 * Define, undefine or list signs.
6147 */
6148 if (idx == SIGNCMD_LIST && *arg == NUL)
6149 {
6150 /* ":sign list": list all defined signs */
6151 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6152 sign_list_defined(sp);
6153 }
6154 else if (*arg == NUL)
6155 EMSG(_("E156: Missing sign name"));
6156 else
6157 {
6158 p = skiptowhite(arg);
6159 if (*p != NUL)
6160 *p++ = NUL;
6161 sp_prev = NULL;
6162 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6163 {
6164 if (STRCMP(sp->sn_name, arg) == 0)
6165 break;
6166 sp_prev = sp;
6167 }
6168 if (idx == SIGNCMD_DEFINE)
6169 {
6170 /* ":sign define {name} ...": define a sign */
6171 if (sp == NULL)
6172 {
6173 /* Allocate a new sign. */
6174 sp = (sign_T *)alloc_clear((unsigned)sizeof(sign_T));
6175 if (sp == NULL)
6176 return;
6177 if (sp_prev == NULL)
6178 first_sign = sp;
6179 else
6180 sp_prev->sn_next = sp;
6181 sp->sn_name = vim_strnsave(arg, (int)(p - arg));
6182
6183 /* If the name is a number use that for the typenr,
6184 * otherwise use a negative number. */
6185 if (VIM_ISDIGIT(*arg))
6186 sp->sn_typenr = atoi((char *)arg);
6187 else
6188 {
6189 sign_T *lp;
6190 int start = last_sign_typenr;
6191
6192 for (lp = first_sign; lp != NULL; lp = lp->sn_next)
6193 {
6194 if (lp->sn_typenr == last_sign_typenr)
6195 {
6196 --last_sign_typenr;
6197 if (last_sign_typenr == 0)
6198 last_sign_typenr = MAX_TYPENR;
6199 if (last_sign_typenr == start)
6200 {
6201 EMSG(_("E612: Too many signs defined"));
6202 return;
6203 }
6204 lp = first_sign;
6205 continue;
6206 }
6207 }
6208
6209 sp->sn_typenr = last_sign_typenr--;
6210 if (last_sign_typenr == 0)
6211 last_sign_typenr = MAX_TYPENR; /* wrap around */
6212 }
6213 }
6214
6215 /* set values for a defined sign. */
6216 for (;;)
6217 {
6218 arg = skipwhite(p);
6219 if (*arg == NUL)
6220 break;
6221 p = skiptowhite_esc(arg);
6222 if (STRNCMP(arg, "icon=", 5) == 0)
6223 {
6224 arg += 5;
6225 vim_free(sp->sn_icon);
6226 sp->sn_icon = vim_strnsave(arg, (int)(p - arg));
6227 backslash_halve(sp->sn_icon);
6228#ifdef FEAT_SIGN_ICONS
6229 if (gui.in_use)
6230 {
6231 out_flush();
6232 if (sp->sn_image != NULL)
6233 gui_mch_destroy_sign(sp->sn_image);
6234 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6235 }
6236#endif
6237 }
6238 else if (STRNCMP(arg, "text=", 5) == 0)
6239 {
6240 char_u *s;
6241 int cells;
6242 int len;
6243
6244 arg += 5;
6245#ifdef FEAT_MBYTE
6246 /* Count cells and check for non-printable chars */
6247 if (has_mbyte)
6248 {
6249 cells = 0;
6250 for (s = arg; s < p; s += (*mb_ptr2len_check)(s))
6251 {
6252 if (!vim_isprintc((*mb_ptr2char)(s)))
6253 break;
6254 cells += (*mb_ptr2cells)(s);
6255 }
6256 }
6257 else
6258#endif
6259 {
6260 for (s = arg; s < p; ++s)
6261 if (!vim_isprintc(*s))
6262 break;
6263 cells = s - arg;
6264 }
6265 /* Currently must be one or two display cells */
6266 if (s != p || cells < 1 || cells > 2)
6267 {
6268 *p = NUL;
6269 EMSG2(_("E239: Invalid sign text: %s"), arg);
6270 return;
6271 }
6272
6273 vim_free(sp->sn_text);
6274 /* Allocate one byte more if we need to pad up
6275 * with a space. */
6276 len = p - arg + ((cells == 1) ? 1 : 0);
6277 sp->sn_text = vim_strnsave(arg, len);
6278
6279 if (sp->sn_text != NULL && cells == 1)
6280 STRCPY(sp->sn_text + len - 1, " ");
6281 }
6282 else if (STRNCMP(arg, "linehl=", 7) == 0)
6283 {
6284 arg += 7;
6285 sp->sn_line_hl = syn_check_group(arg, (int)(p - arg));
6286 }
6287 else if (STRNCMP(arg, "texthl=", 7) == 0)
6288 {
6289 arg += 7;
6290 sp->sn_text_hl = syn_check_group(arg, (int)(p - arg));
6291 }
6292 else
6293 {
6294 EMSG2(_(e_invarg2), arg);
6295 return;
6296 }
6297 }
6298 }
6299 else if (sp == NULL)
6300 EMSG2(_("E155: Unknown sign: %s"), arg);
6301 else if (idx == SIGNCMD_LIST)
6302 /* ":sign list {name}" */
6303 sign_list_defined(sp);
6304 else
6305 {
6306 /* ":sign undefine {name}" */
6307 vim_free(sp->sn_name);
6308 vim_free(sp->sn_icon);
6309#ifdef FEAT_SIGN_ICONS
6310 if (sp->sn_image != NULL)
6311 {
6312 out_flush();
6313 gui_mch_destroy_sign(sp->sn_image);
6314 }
6315#endif
6316 vim_free(sp->sn_text);
6317 if (sp_prev == NULL)
6318 first_sign = sp->sn_next;
6319 else
6320 sp_prev->sn_next = sp->sn_next;
6321 vim_free(sp);
6322 }
6323 }
6324 }
6325 else
6326 {
6327 int id = -1;
6328 linenr_T lnum = -1;
6329 char_u *sign_name = NULL;
6330 char_u *arg1;
6331
6332 if (*arg == NUL)
6333 {
6334 if (idx == SIGNCMD_PLACE)
6335 {
6336 /* ":sign place": list placed signs in all buffers */
6337 sign_list_placed(NULL);
6338 }
6339 else if (idx == SIGNCMD_UNPLACE)
6340 {
6341 /* ":sign unplace": remove placed sign at cursor */
6342 id = buf_findsign_id(curwin->w_buffer, curwin->w_cursor.lnum);
6343 if (id > 0)
6344 {
6345 buf_delsign(curwin->w_buffer, id);
6346 update_debug_sign(curwin->w_buffer, curwin->w_cursor.lnum);
6347 }
6348 else
6349 EMSG(_("E159: Missing sign number"));
6350 }
6351 else
6352 EMSG(_(e_argreq));
6353 return;
6354 }
6355
6356 if (idx == SIGNCMD_UNPLACE && arg[0] == '*' && arg[1] == NUL)
6357 {
6358 /* ":sign unplace *": remove all placed signs */
6359 buf_delete_all_signs();
6360 return;
6361 }
6362
6363 /* first arg could be placed sign id */
6364 arg1 = arg;
6365 if (VIM_ISDIGIT(*arg))
6366 {
6367 id = getdigits(&arg);
6368 if (!vim_iswhite(*arg) && *arg != NUL)
6369 {
6370 id = -1;
6371 arg = arg1;
6372 }
6373 else
6374 {
6375 arg = skipwhite(arg);
6376 if (idx == SIGNCMD_UNPLACE && *arg == NUL)
6377 {
6378 /* ":sign unplace {id}": remove placed sign by number */
6379 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6380 if ((lnum = buf_delsign(buf, id)) != 0)
6381 update_debug_sign(buf, lnum);
6382 return;
6383 }
6384 }
6385 }
6386
6387 /*
6388 * Check for line={lnum} name={name} and file={fname} or buffer={nr}.
6389 * Leave "arg" pointing to {fname}.
6390 */
6391 for (;;)
6392 {
6393 if (STRNCMP(arg, "line=", 5) == 0)
6394 {
6395 arg += 5;
6396 lnum = atoi((char *)arg);
6397 arg = skiptowhite(arg);
6398 }
6399 else if (STRNCMP(arg, "name=", 5) == 0)
6400 {
6401 arg += 5;
6402 sign_name = arg;
6403 arg = skiptowhite(arg);
6404 if (*arg != NUL)
6405 *arg++ = NUL;
6406 }
6407 else if (STRNCMP(arg, "file=", 5) == 0)
6408 {
6409 arg += 5;
6410 buf = buflist_findname(arg);
6411 break;
6412 }
6413 else if (STRNCMP(arg, "buffer=", 7) == 0)
6414 {
6415 arg += 7;
6416 buf = buflist_findnr((int)getdigits(&arg));
6417 if (*skipwhite(arg) != NUL)
6418 EMSG(_(e_trailing));
6419 break;
6420 }
6421 else
6422 {
6423 EMSG(_(e_invarg));
6424 return;
6425 }
6426 arg = skipwhite(arg);
6427 }
6428
6429 if (buf == NULL)
6430 {
6431 EMSG2(_("E158: Invalid buffer name: %s"), arg);
6432 }
6433 else if (id <= 0)
6434 {
6435 if (lnum >= 0 || sign_name != NULL)
6436 EMSG(_(e_invarg));
6437 else
6438 /* ":sign place file={fname}": list placed signs in one file */
6439 sign_list_placed(buf);
6440 }
6441 else if (idx == SIGNCMD_JUMP)
6442 {
6443 /* ":sign jump {id} file={fname}" */
6444 if (lnum >= 0 || sign_name != NULL)
6445 EMSG(_(e_invarg));
6446 else if ((lnum = buf_findsign(buf, id)) > 0)
6447 { /* goto a sign ... */
6448 if (buf_jump_open_win(buf) != NULL)
6449 { /* ... in a current window */
6450 curwin->w_cursor.lnum = lnum;
6451 check_cursor_lnum();
6452 beginline(BL_WHITE);
6453 }
6454 else
6455 { /* ... not currently in a window */
6456 char_u *cmd;
6457
6458 cmd = alloc((unsigned)STRLEN(buf->b_fname) + 25);
6459 if (cmd == NULL)
6460 return;
6461 sprintf((char *)cmd, "e +%ld %s", (long)lnum, buf->b_fname);
6462 do_cmdline_cmd(cmd);
6463 vim_free(cmd);
6464 }
6465#ifdef FEAT_FOLDING
6466 foldOpenCursor();
6467#endif
6468 }
6469 else
6470 EMSGN(_("E157: Invalid sign ID: %ld"), id);
6471 }
6472 else if (idx == SIGNCMD_UNPLACE)
6473 {
6474 /* ":sign unplace {id} file={fname}" */
6475 if (lnum >= 0 || sign_name != NULL)
6476 EMSG(_(e_invarg));
6477 else
6478 {
6479 lnum = buf_delsign(buf, id);
6480 update_debug_sign(buf, lnum);
6481 }
6482 }
6483 /* idx == SIGNCMD_PLACE */
6484 else if (sign_name != NULL)
6485 {
6486 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6487 if (STRCMP(sp->sn_name, sign_name) == 0)
6488 break;
6489 if (sp == NULL)
6490 {
6491 EMSG2(_("E155: Unknown sign: %s"), sign_name);
6492 return;
6493 }
6494 if (lnum > 0)
6495 /* ":sign place {id} line={lnum} name={name} file={fname}":
6496 * place a sign */
6497 buf_addsign(buf, id, lnum, sp->sn_typenr);
6498 else
6499 /* ":sign place {id} file={fname}": change sign type */
6500 lnum = buf_change_sign_type(buf, id, sp->sn_typenr);
6501 update_debug_sign(buf, lnum);
6502 }
6503 else
6504 EMSG(_(e_invarg));
6505 }
6506}
6507
6508#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6509/*
6510 * Allocate the icons. Called when the GUI has started. Allows defining
6511 * signs before it starts.
6512 */
6513 void
6514sign_gui_started()
6515{
6516 sign_T *sp;
6517
6518 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6519 if (sp->sn_icon != NULL)
6520 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6521}
6522#endif
6523
6524/*
6525 * List one sign.
6526 */
6527 static void
6528sign_list_defined(sp)
6529 sign_T *sp;
6530{
6531 char_u *p;
6532
Bram Moolenaar555b2802005-05-19 21:08:39 +00006533 smsg((char_u *)"sign %s", sp->sn_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 if (sp->sn_icon != NULL)
6535 {
6536 MSG_PUTS(" icon=");
6537 msg_outtrans(sp->sn_icon);
6538#ifdef FEAT_SIGN_ICONS
6539 if (sp->sn_image == NULL)
6540 MSG_PUTS(_(" (NOT FOUND)"));
6541#else
6542 MSG_PUTS(_(" (not supported)"));
6543#endif
6544 }
6545 if (sp->sn_text != NULL)
6546 {
6547 MSG_PUTS(" text=");
6548 msg_outtrans(sp->sn_text);
6549 }
6550 if (sp->sn_line_hl > 0)
6551 {
6552 MSG_PUTS(" linehl=");
6553 p = get_highlight_name(NULL, sp->sn_line_hl - 1);
6554 if (p == NULL)
6555 MSG_PUTS("NONE");
6556 else
6557 msg_puts(p);
6558 }
6559 if (sp->sn_text_hl > 0)
6560 {
6561 MSG_PUTS(" texthl=");
6562 p = get_highlight_name(NULL, sp->sn_text_hl - 1);
6563 if (p == NULL)
6564 MSG_PUTS("NONE");
6565 else
6566 msg_puts(p);
6567 }
6568}
6569
6570/*
6571 * Get highlighting attribute for sign "typenr".
6572 * If "line" is TRUE: line highl, if FALSE: text highl.
6573 */
6574 int
6575sign_get_attr(typenr, line)
6576 int typenr;
6577 int line;
6578{
6579 sign_T *sp;
6580
6581 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6582 if (sp->sn_typenr == typenr)
6583 {
6584 if (line)
6585 {
6586 if (sp->sn_line_hl > 0)
6587 return syn_id2attr(sp->sn_line_hl);
6588 }
6589 else
6590 {
6591 if (sp->sn_text_hl > 0)
6592 return syn_id2attr(sp->sn_text_hl);
6593 }
6594 break;
6595 }
6596 return 0;
6597}
6598
6599/*
6600 * Get text mark for sign "typenr".
6601 * Returns NULL if there isn't one.
6602 */
6603 char_u *
6604sign_get_text(typenr)
6605 int typenr;
6606{
6607 sign_T *sp;
6608
6609 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6610 if (sp->sn_typenr == typenr)
6611 return sp->sn_text;
6612 return NULL;
6613}
6614
6615#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6616 void *
6617sign_get_image(typenr)
6618 int typenr; /* the attribute which may have a sign */
6619{
6620 sign_T *sp;
6621
6622 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6623 if (sp->sn_typenr == typenr)
6624 return sp->sn_image;
6625 return NULL;
6626}
6627#endif
6628
6629/*
6630 * Get the name of a sign by its typenr.
6631 */
6632 char_u *
6633sign_typenr2name(typenr)
6634 int typenr;
6635{
6636 sign_T *sp;
6637
6638 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6639 if (sp->sn_typenr == typenr)
6640 return sp->sn_name;
6641 return (char_u *)_("[Deleted]");
6642}
6643
6644#endif
6645
6646#if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
6647/*
6648 * ":drop"
6649 * Opens the first argument in a window. When there are two or more arguments
6650 * the argument list is redefined.
6651 */
6652 void
6653ex_drop(eap)
6654 exarg_T *eap;
6655{
6656 int split = FALSE;
6657 int incurwin = FALSE;
6658 char_u *arg;
6659 char_u *first = NULL;
6660 win_T *wp;
6661 buf_T *buf;
6662
6663 /*
6664 * Check if the first argument is already being edited in a window. If
6665 * so, jump to that window.
6666 * We would actually need to check all arguments, but that's complicated
6667 * and mostly only one file is dropped.
6668 * This also ignores wildcards, since it is very unlikely the user is
6669 * editing a file name with a wildcard character.
6670 */
6671 arg = vim_strsave(eap->arg);
6672 if (arg != NULL)
6673 {
6674 /* Get the first argument, remove quotes, make it a full path. */
6675 first = fix_fname(arg);
6676 if (first != NULL)
6677 {
6678 buf = buflist_findname(first);
6679 FOR_ALL_WINDOWS(wp)
6680 {
6681 if (wp->w_buffer == buf)
6682 {
6683 incurwin = TRUE;
6684# ifdef FEAT_WINDOWS
6685 win_enter(wp, TRUE);
6686 break;
6687# endif
6688 }
6689 }
6690 vim_free(first);
6691
6692 if (incurwin)
6693 {
6694 /* Already editing the file. Redefine the argument list. */
6695 set_arglist(eap->arg);
6696 curwin->w_arg_idx = 0;
6697 vim_free(arg);
6698 return;
6699 }
6700 }
6701 vim_free(arg);
6702 }
6703
6704 /*
6705 * Check whether the current buffer is changed. If so, we will need
6706 * to split the current window or data could be lost.
6707 * Skip the check if the 'hidden' option is set, as in this case the
6708 * buffer won't be lost.
6709 */
6710 if (!P_HID(curbuf))
6711 {
6712# ifdef FEAT_WINDOWS
6713 ++emsg_off;
6714# endif
6715 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6716# ifdef FEAT_WINDOWS
6717 --emsg_off;
6718# else
6719 if (split)
6720 return;
6721# endif
6722 }
6723
6724 /* Fake a ":snext" or ":next" command, redefine the arglist. */
6725 if (split)
6726 {
6727 eap->cmdidx = CMD_snext;
6728 eap->cmd[0] = 's';
6729 }
6730 else
6731 eap->cmdidx = CMD_next;
6732 ex_next(eap);
6733}
6734#endif