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