blob: e77d05aad5ef466babf2c6a4769a1cbe8ecd7366 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * ex_cmds.c: some functions for command line commands
12 */
13
14#include "vim.h"
Bram Moolenaara5792f52005-11-23 21:25:05 +000015#ifdef HAVE_FCNTL_H
16# include <fcntl.h>
17#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000018#include "version.h"
19
20#ifdef FEAT_EX_EXTRA
21static int linelen __ARGS((int *has_tab));
22#endif
23static void do_filter __ARGS((linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, int do_in, int do_out));
24#ifdef FEAT_VIMINFO
25static char_u *viminfo_filename __ARGS((char_u *));
26static void do_viminfo __ARGS((FILE *fp_in, FILE *fp_out, int want_info, int want_marks, int force_read));
27static int viminfo_encoding __ARGS((vir_T *virp));
28static int read_viminfo_up_to_marks __ARGS((vir_T *virp, int forceit, int writing));
29#endif
30
31static int check_overwrite __ARGS((exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int other));
32static int check_readonly __ARGS((int *forceit, buf_T *buf));
33#ifdef FEAT_AUTOCMD
34static void delbuf_msg __ARGS((char_u *name));
35#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000036static int
37#ifdef __BORLANDC__
38 _RTLENTRYF
39#endif
40 help_compare __ARGS((const void *s1, const void *s2));
41
42/*
43 * ":ascii" and "ga".
44 */
45/*ARGSUSED*/
46 void
47do_ascii(eap)
48 exarg_T *eap;
49{
50 int c;
51 char buf1[20];
52 char buf2[20];
53 char_u buf3[7];
54#ifdef FEAT_MBYTE
Bram Moolenaar362e1a32006-03-06 23:29:24 +000055 int cc[MAX_MCO];
56 int ci = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000057 int len;
58
59 if (enc_utf8)
Bram Moolenaar362e1a32006-03-06 23:29:24 +000060 c = utfc_ptr2char(ml_get_cursor(), cc);
Bram Moolenaar071d4272004-06-13 20:20:40 +000061 else
62#endif
63 c = gchar_cursor();
64 if (c == NUL)
65 {
66 MSG("NUL");
67 return;
68 }
69
70#ifdef FEAT_MBYTE
71 IObuff[0] = NUL;
72 if (!has_mbyte || (enc_dbcs != 0 && c < 0x100) || c < 0x80)
73#endif
74 {
75 if (c == NL) /* NUL is stored as NL */
76 c = NUL;
77 if (vim_isprintc_strict(c) && (c < ' '
78#ifndef EBCDIC
79 || c > '~'
80#endif
81 ))
82 {
83 transchar_nonprint(buf3, c);
84 sprintf(buf1, " <%s>", (char *)buf3);
85 }
86 else
87 buf1[0] = NUL;
88#ifndef EBCDIC
89 if (c >= 0x80)
90 sprintf(buf2, " <M-%s>", transchar(c & 0x7f));
91 else
92#endif
93 buf2[0] = NUL;
Bram Moolenaar555b2802005-05-19 21:08:39 +000094 vim_snprintf((char *)IObuff, IOSIZE,
95 _("<%s>%s%s %d, Hex %02x, Octal %03o"),
96 transchar(c), buf1, buf2, c, c, c);
Bram Moolenaar071d4272004-06-13 20:20:40 +000097#ifdef FEAT_MBYTE
Bram Moolenaar362e1a32006-03-06 23:29:24 +000098 c = cc[ci++];
Bram Moolenaar071d4272004-06-13 20:20:40 +000099#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)
Bram Moolenaar4770d092006-01-12 23:22:24 +0000112# ifdef USE_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +0000113 && !gui.in_use
Bram Moolenaar4770d092006-01-12 23:22:24 +0000114# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115 )
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);
Bram Moolenaar362e1a32006-03-06 23:29:24 +0000121 if (ci == MAX_MCO)
122 break;
123 c = cc[ci++];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124 }
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 Moolenaarae5bce12005-08-15 21:41:48 +0000428
429 if (regmatch.regprog != NULL)
430 fast_breakcheck();
431 if (got_int)
432 goto theend;
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000433 }
434
Bram Moolenaar54ee7752005-05-31 22:22:17 +0000435 /* Allocate a buffer that can hold the longest line. */
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000436 sortbuf = alloc((unsigned)maxlen + 1);
437 if (sortbuf == NULL)
438 goto theend;
439
Bram Moolenaarae5bce12005-08-15 21:41:48 +0000440 /* Sort the array of line numbers. Note: can't be interrupted! */
Bram Moolenaar54ee7752005-05-31 22:22:17 +0000441 qsort((void *)nrs, count, sizeof(sorti_T), sort_compare);
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000442
443 /* Insert the lines in the sorted order below the last one. */
444 lnum = eap->line2;
445 for (i = 0; i < count; ++i)
446 {
447 s = ml_get(nrs[eap->forceit ? count - i - 1 : i].lnum);
448 if (!unique || i == 0
449 || (sort_ic ? STRICMP(s, sortbuf) : STRCMP(s, sortbuf)) != 0)
450 {
451 if (ml_append(lnum++, s, (colnr_T)0, FALSE) == FAIL)
452 break;
Bram Moolenaar54ee7752005-05-31 22:22:17 +0000453 if (unique)
454 STRCPY(sortbuf, s);
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000455 }
Bram Moolenaarae5bce12005-08-15 21:41:48 +0000456 fast_breakcheck();
457 if (got_int)
458 goto theend;
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000459 }
460
461 /* delete the original lines if appending worked */
462 if (i == count)
463 for (i = 0; i < count; ++i)
464 ml_delete(eap->line1, FALSE);
465 else
466 count = 0;
467
Bram Moolenaar54ee7752005-05-31 22:22:17 +0000468 /* Adjust marks for deleted (or added) lines and prepare for displaying. */
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000469 deleted = count - (lnum - eap->line2);
470 if (deleted > 0)
471 mark_adjust(eap->line2 - deleted, eap->line2, (long)MAXLNUM, -deleted);
472 else if (deleted < 0)
473 mark_adjust(eap->line2, MAXLNUM, -deleted, 0L);
474 changed_lines(eap->line1, 0, eap->line2 + 1, -deleted);
Bram Moolenaar54ee7752005-05-31 22:22:17 +0000475
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000476 curwin->w_cursor.lnum = eap->line1;
477 beginline(BL_WHITE | BL_FIX);
478
479theend:
480 vim_free(nrs);
481 vim_free(sortbuf);
482 vim_free(regmatch.regprog);
Bram Moolenaarae5bce12005-08-15 21:41:48 +0000483 if (got_int)
484 EMSG(_(e_interr));
Bram Moolenaar67fe1a12005-05-22 22:12:58 +0000485}
486
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487/*
488 * ":retab".
489 */
490 void
491ex_retab(eap)
492 exarg_T *eap;
493{
494 linenr_T lnum;
495 int got_tab = FALSE;
496 long num_spaces = 0;
497 long num_tabs;
498 long len;
499 long col;
500 long vcol;
501 long start_col = 0; /* For start of white-space string */
502 long start_vcol = 0; /* For start of white-space string */
503 int temp;
504 long old_len;
505 char_u *ptr;
506 char_u *new_line = (char_u *)1; /* init to non-NULL */
507 int did_undo; /* called u_save for current line */
508 int new_ts;
509 int save_list;
510 linenr_T first_line = 0; /* first changed line */
511 linenr_T last_line = 0; /* last changed line */
512
513 save_list = curwin->w_p_list;
514 curwin->w_p_list = 0; /* don't want list mode here */
515
516 new_ts = getdigits(&(eap->arg));
517 if (new_ts < 0)
518 {
519 EMSG(_(e_positive));
520 return;
521 }
522 if (new_ts == 0)
523 new_ts = curbuf->b_p_ts;
524 for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)
525 {
526 ptr = ml_get(lnum);
527 col = 0;
528 vcol = 0;
529 did_undo = FALSE;
530 for (;;)
531 {
532 if (vim_iswhite(ptr[col]))
533 {
534 if (!got_tab && num_spaces == 0)
535 {
536 /* First consecutive white-space */
537 start_vcol = vcol;
538 start_col = col;
539 }
540 if (ptr[col] == ' ')
541 num_spaces++;
542 else
543 got_tab = TRUE;
544 }
545 else
546 {
547 if (got_tab || (eap->forceit && num_spaces > 1))
548 {
549 /* Retabulate this string of white-space */
550
551 /* len is virtual length of white string */
552 len = num_spaces = vcol - start_vcol;
553 num_tabs = 0;
554 if (!curbuf->b_p_et)
555 {
556 temp = new_ts - (start_vcol % new_ts);
557 if (num_spaces >= temp)
558 {
559 num_spaces -= temp;
560 num_tabs++;
561 }
562 num_tabs += num_spaces / new_ts;
563 num_spaces -= (num_spaces / new_ts) * new_ts;
564 }
565 if (curbuf->b_p_et || got_tab ||
566 (num_spaces + num_tabs < len))
567 {
568 if (did_undo == FALSE)
569 {
570 did_undo = TRUE;
571 if (u_save((linenr_T)(lnum - 1),
572 (linenr_T)(lnum + 1)) == FAIL)
573 {
574 new_line = NULL; /* flag out-of-memory */
575 break;
576 }
577 }
578
579 /* len is actual number of white characters used */
580 len = num_spaces + num_tabs;
581 old_len = (long)STRLEN(ptr);
582 new_line = lalloc(old_len - col + start_col + len + 1,
583 TRUE);
584 if (new_line == NULL)
585 break;
586 if (start_col > 0)
587 mch_memmove(new_line, ptr, (size_t)start_col);
588 mch_memmove(new_line + start_col + len,
589 ptr + col, (size_t)(old_len - col + 1));
590 ptr = new_line + start_col;
591 for (col = 0; col < len; col++)
592 ptr[col] = (col < num_tabs) ? '\t' : ' ';
593 ml_replace(lnum, new_line, FALSE);
594 if (first_line == 0)
595 first_line = lnum;
596 last_line = lnum;
597 ptr = new_line;
598 col = start_col + len;
599 }
600 }
601 got_tab = FALSE;
602 num_spaces = 0;
603 }
604 if (ptr[col] == NUL)
605 break;
606 vcol += chartabsize(ptr + col, (colnr_T)vcol);
607#ifdef FEAT_MBYTE
608 if (has_mbyte)
Bram Moolenaar0fa313a2005-08-10 21:07:57 +0000609 col += (*mb_ptr2len)(ptr + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 else
611#endif
612 ++col;
613 }
614 if (new_line == NULL) /* out of memory */
615 break;
616 line_breakcheck();
617 }
618 if (got_int)
619 EMSG(_(e_interr));
620
621 if (curbuf->b_p_ts != new_ts)
622 redraw_curbuf_later(NOT_VALID);
623 if (first_line != 0)
624 changed_lines(first_line, 0, last_line + 1, 0L);
625
626 curwin->w_p_list = save_list; /* restore 'list' */
627
628 curbuf->b_p_ts = new_ts;
629 coladvance(curwin->w_curswant);
630
631 u_clearline();
632}
633#endif
634
635/*
636 * :move command - move lines line1-line2 to line dest
637 *
638 * return FAIL for failure, OK otherwise
639 */
640 int
641do_move(line1, line2, dest)
642 linenr_T line1;
643 linenr_T line2;
644 linenr_T dest;
645{
646 char_u *str;
647 linenr_T l;
648 linenr_T extra; /* Num lines added before line1 */
649 linenr_T num_lines; /* Num lines moved */
650 linenr_T last_line; /* Last line in file after adding new text */
651
652 if (dest >= line1 && dest < line2)
653 {
654 EMSG(_("E134: Move lines into themselves"));
655 return FAIL;
656 }
657
658 num_lines = line2 - line1 + 1;
659
660 /*
661 * First we copy the old text to its new location -- webb
662 * Also copy the flag that ":global" command uses.
663 */
664 if (u_save(dest, dest + 1) == FAIL)
665 return FAIL;
666 for (extra = 0, l = line1; l <= line2; l++)
667 {
668 str = vim_strsave(ml_get(l + extra));
669 if (str != NULL)
670 {
671 ml_append(dest + l - line1, str, (colnr_T)0, FALSE);
672 vim_free(str);
673 if (dest < line1)
674 extra++;
675 }
676 }
677
678 /*
679 * Now we must be careful adjusting our marks so that we don't overlap our
680 * mark_adjust() calls.
681 *
682 * We adjust the marks within the old text so that they refer to the
683 * last lines of the file (temporarily), because we know no other marks
684 * will be set there since these line numbers did not exist until we added
685 * our new lines.
686 *
687 * Then we adjust the marks on lines between the old and new text positions
688 * (either forwards or backwards).
689 *
690 * And Finally we adjust the marks we put at the end of the file back to
691 * their final destination at the new text position -- webb
692 */
693 last_line = curbuf->b_ml.ml_line_count;
694 mark_adjust(line1, line2, last_line - line2, 0L);
695 if (dest >= line2)
696 {
697 mark_adjust(line2 + 1, dest, -num_lines, 0L);
698 curbuf->b_op_start.lnum = dest - num_lines + 1;
699 curbuf->b_op_end.lnum = dest;
700 }
701 else
702 {
703 mark_adjust(dest + 1, line1 - 1, num_lines, 0L);
704 curbuf->b_op_start.lnum = dest + 1;
705 curbuf->b_op_end.lnum = dest + num_lines;
706 }
707 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
708 mark_adjust(last_line - num_lines + 1, last_line,
709 -(last_line - dest - extra), 0L);
710
711 /*
712 * Now we delete the original text -- webb
713 */
714 if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL)
715 return FAIL;
716
717 for (l = line1; l <= line2; l++)
718 ml_delete(line1 + extra, TRUE);
719
720 if (!global_busy && num_lines > p_report)
721 {
722 if (num_lines == 1)
723 MSG(_("1 line moved"));
724 else
725 smsg((char_u *)_("%ld lines moved"), num_lines);
726 }
727
728 /*
729 * Leave the cursor on the last of the moved lines.
730 */
731 if (dest >= line1)
732 curwin->w_cursor.lnum = dest;
733 else
734 curwin->w_cursor.lnum = dest + (line2 - line1) + 1;
735
736 if (line1 < dest)
737 changed_lines(line1, 0, dest + num_lines + 1, 0L);
738 else
739 changed_lines(dest + 1, 0, line1 + num_lines, 0L);
740
741 return OK;
742}
743
744/*
745 * ":copy"
746 */
747 void
748ex_copy(line1, line2, n)
749 linenr_T line1;
750 linenr_T line2;
751 linenr_T n;
752{
753 linenr_T count;
754 char_u *p;
755
756 count = line2 - line1 + 1;
757 curbuf->b_op_start.lnum = n + 1;
758 curbuf->b_op_end.lnum = n + count;
759 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
760
761 /*
762 * there are three situations:
763 * 1. destination is above line1
764 * 2. destination is between line1 and line2
765 * 3. destination is below line2
766 *
767 * n = destination (when starting)
768 * curwin->w_cursor.lnum = destination (while copying)
769 * line1 = start of source (while copying)
770 * line2 = end of source (while copying)
771 */
772 if (u_save(n, n + 1) == FAIL)
773 return;
774
775 curwin->w_cursor.lnum = n;
776 while (line1 <= line2)
777 {
778 /* need to use vim_strsave() because the line will be unlocked within
779 * ml_append() */
780 p = vim_strsave(ml_get(line1));
781 if (p != NULL)
782 {
783 ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);
784 vim_free(p);
785 }
786 /* situation 2: skip already copied lines */
787 if (line1 == n)
788 line1 = curwin->w_cursor.lnum;
789 ++line1;
790 if (curwin->w_cursor.lnum < line1)
791 ++line1;
792 if (curwin->w_cursor.lnum < line2)
793 ++line2;
794 ++curwin->w_cursor.lnum;
795 }
796
797 appended_lines_mark(n, count);
798
799 msgmore((long)count);
800}
801
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000802static char_u *prevcmd = NULL; /* the previous command */
803
804#if defined(EXITFREE) || defined(PROTO)
805 void
806free_prev_shellcmd()
807{
808 vim_free(prevcmd);
809}
810#endif
811
Bram Moolenaar071d4272004-06-13 20:20:40 +0000812/*
813 * Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd"
814 * Bangs in the argument are replaced with the previously entered command.
815 * Remember the argument.
816 *
817 * RISCOS: Bangs only replaced when followed by a space, since many
818 * pathnames contain one.
819 */
820 void
821do_bang(addr_count, eap, forceit, do_in, do_out)
822 int addr_count;
823 exarg_T *eap;
824 int forceit;
825 int do_in, do_out;
826{
827 char_u *arg = eap->arg; /* command */
828 linenr_T line1 = eap->line1; /* start of range */
829 linenr_T line2 = eap->line2; /* end of range */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830 char_u *newcmd = NULL; /* the new command */
831 int free_newcmd = FALSE; /* need to free() newcmd */
832 int ins_prevcmd;
833 char_u *t;
834 char_u *p;
835 char_u *trailarg;
836 int len;
837 int scroll_save = msg_scroll;
838
839 /*
840 * Disallow shell commands for "rvim".
841 * Disallow shell commands from .exrc and .vimrc in current directory for
842 * security reasons.
843 */
844 if (check_restricted() || check_secure())
845 return;
846
847 if (addr_count == 0) /* :! */
848 {
849 msg_scroll = FALSE; /* don't scroll here */
850 autowrite_all();
851 msg_scroll = scroll_save;
852 }
853
854 /*
855 * Try to find an embedded bang, like in :!<cmd> ! [args]
856 * (:!! is indicated by the 'forceit' variable)
857 */
858 ins_prevcmd = forceit;
859 trailarg = arg;
860 do
861 {
862 len = (int)STRLEN(trailarg) + 1;
863 if (newcmd != NULL)
864 len += (int)STRLEN(newcmd);
865 if (ins_prevcmd)
866 {
867 if (prevcmd == NULL)
868 {
869 EMSG(_(e_noprev));
870 vim_free(newcmd);
871 return;
872 }
873 len += (int)STRLEN(prevcmd);
874 }
875 if ((t = alloc(len)) == NULL)
876 {
877 vim_free(newcmd);
878 return;
879 }
880 *t = NUL;
881 if (newcmd != NULL)
882 STRCAT(t, newcmd);
883 if (ins_prevcmd)
884 STRCAT(t, prevcmd);
885 p = t + STRLEN(t);
886 STRCAT(t, trailarg);
887 vim_free(newcmd);
888 newcmd = t;
889
890 /*
891 * Scan the rest of the argument for '!', which is replaced by the
892 * previous command. "\!" is replaced by "!" (this is vi compatible).
893 */
894 trailarg = NULL;
895 while (*p)
896 {
897 if (*p == '!'
898#ifdef RISCOS
899 && (p[1] == ' ' || p[1] == NUL)
900#endif
901 )
902 {
903 if (p > newcmd && p[-1] == '\\')
904 mch_memmove(p - 1, p, (size_t)(STRLEN(p) + 1));
905 else
906 {
907 trailarg = p;
908 *trailarg++ = NUL;
909 ins_prevcmd = TRUE;
910 break;
911 }
912 }
913 ++p;
914 }
915 } while (trailarg != NULL);
916
917 vim_free(prevcmd);
918 prevcmd = newcmd;
919
920 if (bangredo) /* put cmd in redo buffer for ! command */
921 {
Bram Moolenaarebefac62005-12-28 22:39:57 +0000922 AppendToRedobuffLit(prevcmd, -1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 AppendToRedobuff((char_u *)"\n");
924 bangredo = FALSE;
925 }
926 /*
927 * Add quotes around the command, for shells that need them.
928 */
929 if (*p_shq != NUL)
930 {
931 newcmd = alloc((unsigned)(STRLEN(prevcmd) + 2 * STRLEN(p_shq) + 1));
932 if (newcmd == NULL)
933 return;
934 STRCPY(newcmd, p_shq);
935 STRCAT(newcmd, prevcmd);
936 STRCAT(newcmd, p_shq);
937 free_newcmd = TRUE;
938 }
939 if (addr_count == 0) /* :! */
940 {
941 /* echo the command */
942 msg_start();
943 msg_putchar(':');
944 msg_putchar('!');
945 msg_outtrans(newcmd);
946 msg_clr_eos();
947 windgoto(msg_row, msg_col);
948
949 do_shell(newcmd, 0);
950 }
951 else /* :range! */
Bram Moolenaarade00832006-03-10 21:46:58 +0000952 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 /* Careful: This may recursively call do_bang() again! (because of
954 * autocommands) */
955 do_filter(line1, line2, eap, newcmd, do_in, do_out);
Bram Moolenaarade00832006-03-10 21:46:58 +0000956#ifdef FEAT_AUTOCMD
957 apply_autocmds(EVENT_SHELLFILTERPOST, NULL, NULL, FALSE, curbuf);
958#endif
959 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 if (free_newcmd)
961 vim_free(newcmd);
962}
963
964/*
965 * do_filter: filter lines through a command given by the user
966 *
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000967 * We mostly use temp files and the call_shell() routine here. This would
968 * normally be done using pipes on a UNIX machine, but this is more portable
969 * to non-unix machines. The call_shell() routine needs to be able
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970 * to deal with redirection somehow, and should handle things like looking
971 * at the PATH env. variable, and adding reasonable extensions to the
972 * command name given by the user. All reasonable versions of call_shell()
973 * do this.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000974 * Alternatively, if on Unix and redirecting input or output, but not both,
975 * and the 'shelltemp' option isn't set, use pipes.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976 * We use input redirection if do_in is TRUE.
977 * We use output redirection if do_out is TRUE.
978 */
979 static void
980do_filter(line1, line2, eap, cmd, do_in, do_out)
981 linenr_T line1, line2;
982 exarg_T *eap; /* for forced 'ff' and 'fenc' */
983 char_u *cmd;
984 int do_in, do_out;
985{
986 char_u *itmp = NULL;
987 char_u *otmp = NULL;
988 linenr_T linecount;
989 linenr_T read_linecount;
990 pos_T cursor_save;
991 char_u *cmd_buf;
992#ifdef FEAT_AUTOCMD
993 buf_T *old_curbuf = curbuf;
994#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000995 int shell_flags = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996
997 if (*cmd == NUL) /* no filter command */
998 return;
999
1000#ifdef WIN3264
1001 /*
1002 * Check if external commands are allowed now.
1003 */
1004 if (can_end_termcap_mode(TRUE) == FALSE)
1005 return;
1006#endif
1007
1008 cursor_save = curwin->w_cursor;
1009 linecount = line2 - line1 + 1;
1010 curwin->w_cursor.lnum = line1;
1011 curwin->w_cursor.col = 0;
1012 changed_line_abv_curs();
1013 invalidate_botline();
1014
1015 /*
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001016 * When using temp files:
1017 * 1. * Form temp file names
1018 * 2. * Write the lines to a temp file
1019 * 3. Run the filter command on the temp file
1020 * 4. * Read the output of the command into the buffer
1021 * 5. * Delete the original lines to be filtered
1022 * 6. * Remove the temp files
1023 *
1024 * When writing the input with a pipe or when catching the output with a
1025 * pipe only need to do 3.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 */
1027
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001028 if (do_out)
1029 shell_flags |= SHELL_DOOUT;
1030
1031#if !defined(USE_SYSTEM) && defined(UNIX)
1032 if (!do_in && do_out && !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001034 /* Use a pipe to fetch stdout of the command, do not use a temp file. */
1035 shell_flags |= SHELL_READ;
1036 curwin->w_cursor.lnum = line2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001038 else if (do_in && !do_out && !p_stmp)
1039 {
1040 /* Use a pipe to write stdin of the command, do not use a temp file. */
1041 shell_flags |= SHELL_WRITE;
1042 curbuf->b_op_start.lnum = line1;
1043 curbuf->b_op_end.lnum = line2;
1044 }
1045 else if (do_in && do_out && !p_stmp)
1046 {
1047 /* Use a pipe to write stdin and fetch stdout of the command, do not
1048 * use a temp file. */
1049 shell_flags |= SHELL_READ|SHELL_WRITE;
1050 curbuf->b_op_start.lnum = line1;
1051 curbuf->b_op_end.lnum = line2;
1052 curwin->w_cursor.lnum = line2;
1053 }
1054 else
1055#endif
1056 if ((do_in && (itmp = vim_tempname('i')) == NULL)
1057 || (do_out && (otmp = vim_tempname('o')) == NULL))
1058 {
1059 EMSG(_(e_notmp));
1060 goto filterend;
1061 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062
1063/*
1064 * The writing and reading of temp files will not be shown.
1065 * Vi also doesn't do this and the messages are not very informative.
1066 */
1067 ++no_wait_return; /* don't call wait_return() while busy */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001068 if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069 FALSE, FALSE, FALSE, TRUE) == FAIL)
1070 {
1071 msg_putchar('\n'); /* keep message from buf_write() */
1072 --no_wait_return;
1073#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1074 if (!aborting())
1075#endif
1076 (void)EMSG2(_(e_notcreate), itmp); /* will call wait_return */
1077 goto filterend;
1078 }
1079#ifdef FEAT_AUTOCMD
1080 if (curbuf != old_curbuf)
1081 goto filterend;
1082#endif
1083
1084 if (!do_out)
1085 msg_putchar('\n');
1086
1087 cmd_buf = make_filter_cmd(cmd, itmp, otmp);
1088 if (cmd_buf == NULL)
1089 goto filterend;
1090
1091 windgoto((int)Rows - 1, 0);
1092 cursor_on();
1093
1094 /*
1095 * When not redirecting the output the command can write anything to the
1096 * screen. If 'shellredir' is equal to ">", screen may be messed up by
1097 * stderr output of external command. Clear the screen later.
1098 * If do_in is FALSE, this could be something like ":r !cat", which may
1099 * also mess up the screen, clear it later.
1100 */
1101 if (!do_out || STRCMP(p_srr, ">") == 0 || !do_in)
1102 redraw_later_clear();
1103
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001104 if (do_out)
1105 {
1106 if (u_save((linenr_T)(line2), (linenr_T)(line2 + 1)) == FAIL)
1107 goto error;
1108 redraw_curbuf_later(VALID);
1109 }
1110 read_linecount = curbuf->b_ml.ml_line_count;
1111
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 /*
1113 * When call_shell() fails wait_return() is called to give the user a
1114 * chance to read the error messages. Otherwise errors are ignored, so you
1115 * can see the error messages from the command that appear on stdout; use
1116 * 'u' to fix the text
1117 * Switch to cooked mode when not redirecting stdin, avoids that something
1118 * like ":r !cat" hangs.
1119 * Pass on the SHELL_DOOUT flag when the output is being redirected.
1120 */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001121 if (call_shell(cmd_buf, SHELL_FILTER | SHELL_COOKED | shell_flags))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 {
1123 redraw_later_clear();
1124 wait_return(FALSE);
1125 }
1126 vim_free(cmd_buf);
1127
1128 did_check_timestamps = FALSE;
1129 need_check_timestamps = TRUE;
1130
1131 /* When interrupting the shell command, it may still have produced some
1132 * useful output. Reset got_int here, so that readfile() won't cancel
1133 * reading. */
1134 ui_breakcheck();
1135 got_int = FALSE;
1136
1137 if (do_out)
1138 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001139 if (otmp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001141 if (readfile(otmp, NULL, line2, (linenr_T)0, (linenr_T)MAXLNUM,
1142 eap, READ_FILTER) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001144#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1145 if (!aborting())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001147 {
1148 msg_putchar('\n');
1149 EMSG2(_(e_notread), otmp);
1150 }
1151 goto error;
1152 }
1153#ifdef FEAT_AUTOCMD
1154 if (curbuf != old_curbuf)
1155 goto filterend;
1156#endif
1157 }
1158
1159 read_linecount = curbuf->b_ml.ml_line_count - read_linecount;
1160
1161 if (shell_flags & SHELL_READ)
1162 {
1163 curbuf->b_op_start.lnum = line2 + 1;
1164 curbuf->b_op_end.lnum = curwin->w_cursor.lnum;
1165 appended_lines_mark(line2, read_linecount);
1166 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167
1168 if (do_in)
1169 {
1170 if (cmdmod.keepmarks || vim_strchr(p_cpo, CPO_REMMARK) == NULL)
1171 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172 if (read_linecount >= linecount)
1173 /* move all marks from old lines to new lines */
1174 mark_adjust(line1, line2, linecount, 0L);
1175 else
1176 {
1177 /* move marks from old lines to new lines, delete marks
1178 * that are in deleted lines */
1179 mark_adjust(line1, line1 + read_linecount - 1,
1180 linecount, 0L);
1181 mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0L);
1182 }
1183 }
1184
1185 /*
1186 * Put cursor on first filtered line for ":range!cmd".
1187 * Adjust '[ and '] (set by buf_write()).
1188 */
1189 curwin->w_cursor.lnum = line1;
1190 del_lines(linecount, TRUE);
1191 curbuf->b_op_start.lnum -= linecount; /* adjust '[ */
1192 curbuf->b_op_end.lnum -= linecount; /* adjust '] */
1193 write_lnum_adjust(-linecount); /* adjust last line
1194 for next write */
Bram Moolenaar8c711452005-01-14 21:53:12 +00001195#ifdef FEAT_FOLDING
1196 foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum);
1197#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 }
1199 else
1200 {
1201 /*
1202 * Put cursor on last new line for ":r !cmd".
1203 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204 linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001205 curwin->w_cursor.lnum = curbuf->b_op_end.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206 }
Bram Moolenaar8c711452005-01-14 21:53:12 +00001207
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 beginline(BL_WHITE | BL_FIX); /* cursor on first non-blank */
1209 --no_wait_return;
1210
1211 if (linecount > p_report)
1212 {
1213 if (do_in)
1214 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00001215 vim_snprintf((char *)msg_buf, sizeof(msg_buf),
1216 _("%ld lines filtered"), (long)linecount);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001217 if (msg(msg_buf) && !msg_scroll)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218 /* save message to display it after redraw */
Bram Moolenaar238a5642006-02-21 22:12:05 +00001219 set_keep_msg(msg_buf, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 }
1221 else
1222 msgmore((long)linecount);
1223 }
1224 }
1225 else
1226 {
1227error:
1228 /* put cursor back in same position for ":w !cmd" */
1229 curwin->w_cursor = cursor_save;
1230 --no_wait_return;
1231 wait_return(FALSE);
1232 }
1233
1234filterend:
1235
1236#ifdef FEAT_AUTOCMD
1237 if (curbuf != old_curbuf)
1238 {
1239 --no_wait_return;
1240 EMSG(_("E135: *Filter* Autocommands must not change current buffer"));
1241 }
1242#endif
1243 if (itmp != NULL)
1244 mch_remove(itmp);
1245 if (otmp != NULL)
1246 mch_remove(otmp);
1247 vim_free(itmp);
1248 vim_free(otmp);
1249}
1250
1251/*
1252 * Call a shell to execute a command.
1253 * When "cmd" is NULL start an interactive shell.
1254 */
1255 void
1256do_shell(cmd, flags)
1257 char_u *cmd;
1258 int flags; /* may be SHELL_DOOUT when output is redirected */
1259{
1260 buf_T *buf;
1261#ifndef FEAT_GUI_MSWIN
1262 int save_nwr;
1263#endif
1264#ifdef MSWIN
1265 int winstart = FALSE;
1266#endif
1267
1268 /*
1269 * Disallow shell commands for "rvim".
1270 * Disallow shell commands from .exrc and .vimrc in current directory for
1271 * security reasons.
1272 */
1273 if (check_restricted() || check_secure())
1274 {
1275 msg_end();
1276 return;
1277 }
1278
1279#ifdef MSWIN
1280 /*
1281 * Check if external commands are allowed now.
1282 */
1283 if (can_end_termcap_mode(TRUE) == FALSE)
1284 return;
1285
1286 /*
1287 * Check if ":!start" is used.
1288 */
1289 if (cmd != NULL)
1290 winstart = (STRNICMP(cmd, "start ", 6) == 0);
1291#endif
1292
1293 /*
1294 * For autocommands we want to get the output on the current screen, to
1295 * avoid having to type return below.
1296 */
1297 msg_putchar('\r'); /* put cursor at start of line */
1298#ifdef FEAT_AUTOCMD
1299 if (!autocmd_busy)
1300#endif
1301 {
1302#ifdef MSWIN
1303 if (!winstart)
1304#endif
1305 stoptermcap();
1306 }
1307#ifdef MSWIN
1308 if (!winstart)
1309#endif
1310 msg_putchar('\n'); /* may shift screen one line up */
1311
1312 /* warning message before calling the shell */
1313 if (p_warn
1314#ifdef FEAT_AUTOCMD
1315 && !autocmd_busy
1316#endif
1317 && msg_silent == 0)
1318 for (buf = firstbuf; buf; buf = buf->b_next)
1319 if (bufIsChanged(buf))
1320 {
1321#ifdef FEAT_GUI_MSWIN
1322 if (!winstart)
1323 starttermcap(); /* don't want a message box here */
1324#endif
1325 MSG_PUTS(_("[No write since last change]\n"));
1326#ifdef FEAT_GUI_MSWIN
1327 if (!winstart)
1328 stoptermcap();
1329#endif
1330 break;
1331 }
1332
1333 /* This windgoto is required for when the '\n' resulted in a "delete line
1334 * 1" command to the terminal. */
1335 if (!swapping_screen())
1336 windgoto(msg_row, msg_col);
1337 cursor_on();
1338 (void)call_shell(cmd, SHELL_COOKED | flags);
1339 did_check_timestamps = FALSE;
1340 need_check_timestamps = TRUE;
1341
1342 /*
1343 * put the message cursor at the end of the screen, avoids wait_return()
1344 * to overwrite the text that the external command showed
1345 */
1346 if (!swapping_screen())
1347 {
1348 msg_row = Rows - 1;
1349 msg_col = 0;
1350 }
1351
1352#ifdef FEAT_AUTOCMD
1353 if (autocmd_busy)
1354 {
1355 if (msg_silent == 0)
1356 redraw_later_clear();
1357 }
1358 else
1359#endif
1360 {
1361 /*
1362 * For ":sh" there is no need to call wait_return(), just redraw.
1363 * Also for the Win32 GUI (the output is in a console window).
1364 * Otherwise there is probably text on the screen that the user wants
1365 * to read before redrawing, so call wait_return().
1366 */
1367#ifndef FEAT_GUI_MSWIN
1368 if (cmd == NULL
1369# ifdef WIN3264
1370 || (winstart && !need_wait_return)
1371# endif
1372 )
1373 {
1374 if (msg_silent == 0)
1375 redraw_later_clear();
1376 need_wait_return = FALSE;
1377 }
1378 else
1379 {
1380 /*
1381 * If we switch screens when starttermcap() is called, we really
1382 * want to wait for "hit return to continue".
1383 */
1384 save_nwr = no_wait_return;
1385 if (swapping_screen())
1386 no_wait_return = FALSE;
1387# ifdef AMIGA
1388 wait_return(term_console ? -1 : msg_silent == 0); /* see below */
1389# else
1390 wait_return(msg_silent == 0);
1391# endif
1392 no_wait_return = save_nwr;
1393 }
1394#endif /* FEAT_GUI_W32 */
1395
1396#ifdef MSWIN
1397 if (!winstart) /* if winstart==TRUE, never stopped termcap! */
1398#endif
1399 starttermcap(); /* start termcap if not done by wait_return() */
1400
1401 /*
1402 * In an Amiga window redrawing is caused by asking the window size.
1403 * If we got an interrupt this will not work. The chance that the
1404 * window size is wrong is very small, but we need to redraw the
1405 * screen. Don't do this if ':' hit in wait_return(). THIS IS UGLY
1406 * but it saves an extra redraw.
1407 */
1408#ifdef AMIGA
1409 if (skip_redraw) /* ':' hit in wait_return() */
1410 {
1411 if (msg_silent == 0)
1412 redraw_later_clear();
1413 }
1414 else if (term_console)
1415 {
1416 OUT_STR(IF_EB("\033[0 q", ESC_STR "[0 q")); /* get window size */
1417 if (got_int && msg_silent == 0)
1418 redraw_later_clear(); /* if got_int is TRUE, redraw needed */
1419 else
1420 must_redraw = 0; /* no extra redraw needed */
1421 }
1422#endif
1423 }
1424
1425 /* display any error messages now */
1426 display_errors();
Bram Moolenaarade00832006-03-10 21:46:58 +00001427
1428#ifdef FEAT_AUTOCMD
1429 apply_autocmds(EVENT_SHELLCMDPOST, NULL, NULL, FALSE, curbuf);
1430#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431}
1432
1433/*
1434 * Create a shell command from a command string, input redirection file and
1435 * output redirection file.
1436 * Returns an allocated string with the shell command, or NULL for failure.
1437 */
1438 char_u *
1439make_filter_cmd(cmd, itmp, otmp)
1440 char_u *cmd; /* command */
1441 char_u *itmp; /* NULL or name of input file */
1442 char_u *otmp; /* NULL or name of output file */
1443{
1444 char_u *buf;
1445 long_u len;
1446
1447 len = (long_u)STRLEN(cmd) + 3; /* "()" + NUL */
1448 if (itmp != NULL)
1449 len += (long_u)STRLEN(itmp) + 9; /* " { < " + " } " */
1450 if (otmp != NULL)
1451 len += (long_u)STRLEN(otmp) + (long_u)STRLEN(p_srr) + 2; /* " " */
1452 buf = lalloc(len, TRUE);
1453 if (buf == NULL)
1454 return NULL;
1455
1456#if (defined(UNIX) && !defined(ARCHIE)) || defined(OS2)
1457 /*
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001458 * Put braces around the command (for concatenated commands) when
1459 * redirecting input and/or output.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001461 if (itmp != NULL || otmp != NULL)
1462 sprintf((char *)buf, "(%s)", (char *)cmd);
1463 else
1464 STRCPY(buf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 if (itmp != NULL)
1466 {
1467 STRCAT(buf, " < ");
1468 STRCAT(buf, itmp);
1469 }
1470#else
1471 /*
1472 * for shells that don't understand braces around commands, at least allow
1473 * the use of commands in a pipe.
1474 */
1475 STRCPY(buf, cmd);
1476 if (itmp != NULL)
1477 {
1478 char_u *p;
1479
1480 /*
1481 * If there is a pipe, we have to put the '<' in front of it.
1482 * Don't do this when 'shellquote' is not empty, otherwise the
1483 * redirection would be inside the quotes.
1484 */
1485 if (*p_shq == NUL)
1486 {
1487 p = vim_strchr(buf, '|');
1488 if (p != NULL)
1489 *p = NUL;
1490 }
1491# ifdef RISCOS
1492 STRCAT(buf, " { < "); /* Use RISC OS notation for input. */
1493 STRCAT(buf, itmp);
1494 STRCAT(buf, " } ");
1495# else
1496 STRCAT(buf, " <"); /* " < " causes problems on Amiga */
1497 STRCAT(buf, itmp);
1498# endif
1499 if (*p_shq == NUL)
1500 {
1501 p = vim_strchr(cmd, '|');
1502 if (p != NULL)
1503 {
1504 STRCAT(buf, " "); /* insert a space before the '|' for DOS */
1505 STRCAT(buf, p);
1506 }
1507 }
1508 }
1509#endif
1510 if (otmp != NULL)
1511 append_redir(buf, p_srr, otmp);
1512
1513 return buf;
1514}
1515
1516/*
1517 * Append output redirection for file "fname" to the end of string buffer "buf"
1518 * Works with the 'shellredir' and 'shellpipe' options.
1519 * The caller should make sure that there is enough room:
1520 * STRLEN(opt) + STRLEN(fname) + 3
1521 */
1522 void
1523append_redir(buf, opt, fname)
1524 char_u *buf;
1525 char_u *opt;
1526 char_u *fname;
1527{
1528 char_u *p;
1529
1530 buf += STRLEN(buf);
1531 /* find "%s", skipping "%%" */
1532 for (p = opt; (p = vim_strchr(p, '%')) != NULL; ++p)
1533 if (p[1] == 's')
1534 break;
1535 if (p != NULL)
1536 {
1537 *buf = ' '; /* not really needed? Not with sh, ksh or bash */
1538 sprintf((char *)buf + 1, (char *)opt, (char *)fname);
1539 }
1540 else
1541 sprintf((char *)buf,
1542#ifdef FEAT_QUICKFIX
1543# ifndef RISCOS
1544 opt != p_sp ? " %s%s" :
1545# endif
1546 " %s %s",
1547#else
1548# ifndef RISCOS
1549 " %s%s", /* " > %s" causes problems on Amiga */
1550# else
1551 " %s %s", /* But is needed for 'shellpipe' and RISC OS */
1552# endif
1553#endif
1554 (char *)opt, (char *)fname);
1555}
1556
1557#ifdef FEAT_VIMINFO
1558
1559static int no_viminfo __ARGS((void));
1560static int viminfo_errcnt;
1561
1562 static int
1563no_viminfo()
1564{
1565 /* "vim -i NONE" does not read or write a viminfo file */
1566 return (use_viminfo != NULL && STRCMP(use_viminfo, "NONE") == 0);
1567}
1568
1569/*
1570 * Report an error for reading a viminfo file.
1571 * Count the number of errors. When there are more than 10, return TRUE.
1572 */
1573 int
1574viminfo_error(errnum, message, line)
1575 char *errnum;
1576 char *message;
1577 char_u *line;
1578{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001579 vim_snprintf((char *)IObuff, IOSIZE, _("%sviminfo: %s in line: "),
1580 errnum, message);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 STRNCAT(IObuff, line, IOSIZE - STRLEN(IObuff));
Bram Moolenaar758711c2005-02-02 23:11:38 +00001582 if (IObuff[STRLEN(IObuff) - 1] == '\n')
1583 IObuff[STRLEN(IObuff) - 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 emsg(IObuff);
1585 if (++viminfo_errcnt >= 10)
1586 {
1587 EMSG(_("E136: viminfo: Too many errors, skipping rest of file"));
1588 return TRUE;
1589 }
1590 return FALSE;
1591}
1592
1593/*
1594 * read_viminfo() -- Read the viminfo file. Registers etc. which are already
1595 * set are not over-written unless force is TRUE. -- webb
1596 */
1597 int
1598read_viminfo(file, want_info, want_marks, forceit)
1599 char_u *file;
1600 int want_info;
1601 int want_marks;
1602 int forceit;
1603{
1604 FILE *fp;
1605 char_u *fname;
1606
1607 if (no_viminfo())
1608 return FAIL;
1609
1610 fname = viminfo_filename(file); /* may set to default if NULL */
1611 if (fname == NULL)
1612 return FAIL;
1613 fp = mch_fopen((char *)fname, READBIN);
1614
1615 if (p_verbose > 0)
Bram Moolenaar54ee7752005-05-31 22:22:17 +00001616 {
1617 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00001618 smsg((char_u *)_("Reading viminfo file \"%s\"%s%s%s"),
1619 fname,
1620 want_info ? _(" info") : "",
1621 want_marks ? _(" marks") : "",
1622 fp == NULL ? _(" FAILED") : "");
Bram Moolenaar54ee7752005-05-31 22:22:17 +00001623 verbose_leave();
1624 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625
1626 vim_free(fname);
1627 if (fp == NULL)
1628 return FAIL;
1629
1630 viminfo_errcnt = 0;
1631 do_viminfo(fp, NULL, want_info, want_marks, forceit);
1632
1633 fclose(fp);
1634
1635 return OK;
1636}
1637
1638/*
1639 * write_viminfo() -- Write the viminfo file. The old one is read in first so
1640 * that effectively a merge of current info and old info is done. This allows
1641 * multiple vims to run simultaneously, without losing any marks etc. If
1642 * forceit is TRUE, then the old file is not read in, and only internal info is
1643 * written to the file. -- webb
1644 */
1645 void
1646write_viminfo(file, forceit)
1647 char_u *file;
1648 int forceit;
1649{
1650 char_u *fname;
1651 FILE *fp_in = NULL; /* input viminfo file, if any */
1652 FILE *fp_out = NULL; /* output viminfo file */
1653 char_u *tempname = NULL; /* name of temp viminfo file */
1654 struct stat st_new; /* mch_stat() of potential new file */
1655 char_u *wp;
1656#if defined(UNIX) || defined(VMS)
1657 mode_t umask_save;
1658#endif
1659#ifdef UNIX
1660 int shortname = FALSE; /* use 8.3 file name */
1661 struct stat st_old; /* mch_stat() of existing viminfo file */
1662#endif
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001663#ifdef WIN3264
1664 long perm = -1;
1665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666
1667 if (no_viminfo())
1668 return;
1669
1670 fname = viminfo_filename(file); /* may set to default if NULL */
1671 if (fname == NULL)
1672 return;
1673
1674 fp_in = mch_fopen((char *)fname, READBIN);
1675 if (fp_in == NULL)
1676 {
1677 /* if it does exist, but we can't read it, don't try writing */
1678 if (mch_stat((char *)fname, &st_new) == 0)
1679 goto end;
1680#if defined(UNIX) || defined(VMS)
1681 /*
1682 * For Unix we create the .viminfo non-accessible for others,
1683 * because it may contain text from non-accessible documents.
1684 */
1685 umask_save = umask(077);
1686#endif
1687 fp_out = mch_fopen((char *)fname, WRITEBIN);
1688#if defined(UNIX) || defined(VMS)
1689 (void)umask(umask_save);
1690#endif
1691 }
1692 else
1693 {
1694 /*
1695 * There is an existing viminfo file. Create a temporary file to
1696 * write the new viminfo into, in the same directory as the
1697 * existing viminfo file, which will be renamed later.
1698 */
1699#ifdef UNIX
1700 /*
1701 * For Unix we check the owner of the file. It's not very nice to
1702 * overwrite a user's viminfo file after a "su root", with a
1703 * viminfo file that the user can't read.
1704 */
1705 st_old.st_dev = st_old.st_ino = 0;
1706 st_old.st_mode = 0600;
Bram Moolenaar12625ca2005-11-25 19:58:47 +00001707 if (mch_stat((char *)fname, &st_old) == 0 && getuid()
1708 && !(st_old.st_uid == getuid()
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 ? (st_old.st_mode & 0200)
1710 : (st_old.st_gid == getgid()
1711 ? (st_old.st_mode & 0020)
1712 : (st_old.st_mode & 0002))))
1713 {
1714 int tt;
1715
1716 /* avoid a wait_return for this message, it's annoying */
1717 tt = msg_didany;
1718 EMSG2(_("E137: Viminfo file is not writable: %s"), fname);
1719 msg_didany = tt;
1720 goto end;
1721 }
1722#endif
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001723#ifdef WIN3264
1724 /* Get the file attributes of the existing viminfo file. */
1725 perm = mch_getperm(fname);
1726#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727
1728 /*
1729 * Make tempname.
1730 * May try twice: Once normal and once with shortname set, just in
1731 * case somebody puts his viminfo file in an 8.3 filesystem.
1732 */
1733 for (;;)
1734 {
1735 tempname = buf_modname(
1736#ifdef UNIX
1737 shortname,
1738#else
1739# ifdef SHORT_FNAME
1740 TRUE,
1741# else
1742# ifdef FEAT_GUI_W32
1743 gui_is_win32s(),
1744# else
1745 FALSE,
1746# endif
1747# endif
1748#endif
1749 fname,
1750#ifdef VMS
1751 (char_u *)"-tmp",
1752#else
1753# ifdef RISCOS
1754 (char_u *)"/tmp",
1755# else
1756 (char_u *)".tmp",
1757# endif
1758#endif
1759 FALSE);
1760 if (tempname == NULL) /* out of memory */
1761 break;
1762
1763 /*
1764 * Check if tempfile already exists. Never overwrite an
1765 * existing file!
1766 */
1767 if (mch_stat((char *)tempname, &st_new) == 0)
1768 {
1769#ifdef UNIX
1770 /*
1771 * Check if tempfile is same as original file. May happen
1772 * when modname() gave the same file back. E.g. silly
1773 * link, or file name-length reached. Try again with
1774 * shortname set.
1775 */
Bram Moolenaar12625ca2005-11-25 19:58:47 +00001776 if (!shortname && st_new.st_dev == st_old.st_dev
1777 && st_new.st_ino == st_old.st_ino)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779 vim_free(tempname);
1780 tempname = NULL;
1781 shortname = TRUE;
1782 continue;
1783 }
1784#endif
1785 /*
1786 * Try another name. Change one character, just before
1787 * the extension. This should also work for an 8.3
1788 * file name, when after adding the extension it still is
1789 * the same file as the original.
1790 */
1791 wp = tempname + STRLEN(tempname) - 5;
1792 if (wp < gettail(tempname)) /* empty file name? */
1793 wp = gettail(tempname);
1794 for (*wp = 'z'; mch_stat((char *)tempname, &st_new) == 0;
1795 --*wp)
1796 {
1797 /*
1798 * They all exist? Must be something wrong! Don't
1799 * write the viminfo file then.
1800 */
1801 if (*wp == 'a')
1802 {
1803 vim_free(tempname);
1804 tempname = NULL;
1805 break;
1806 }
1807 }
1808 }
1809 break;
1810 }
1811
1812 if (tempname != NULL)
1813 {
Bram Moolenaar114216c2006-03-14 23:08:30 +00001814#ifdef VMS
1815 /* fdopen() fails for some reason */
1816 if (fp_out == NULL)
1817 {
1818 umask_save = umask(077);
1819 fp_out = mch_fopen((char *)tempname, WRITEBIN);
1820 (void)umask(umask_save);
1821 }
1822#else
Bram Moolenaara5792f52005-11-23 21:25:05 +00001823 int fd;
1824
1825 /* Use mch_open() to be able to use O_NOFOLLOW and set file
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001826 * protection:
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001827 * Unix: same as original file, but strip s-bit. Reset umask to
1828 * avoid it getting in the way.
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001829 * Others: r&w for user only. */
Bram Moolenaar114216c2006-03-14 23:08:30 +00001830# ifdef UNIX
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001831 umask_save = umask(0);
Bram Moolenaara5792f52005-11-23 21:25:05 +00001832 fd = mch_open((char *)tempname,
1833 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW,
Bram Moolenaarbba577a2005-11-28 23:05:55 +00001834 (int)((st_old.st_mode & 0777) | 0600));
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001835 (void)umask(umask_save);
Bram Moolenaar114216c2006-03-14 23:08:30 +00001836# else
Bram Moolenaarbba577a2005-11-28 23:05:55 +00001837 fd = mch_open((char *)tempname,
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001838 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW, 0600);
Bram Moolenaar114216c2006-03-14 23:08:30 +00001839# endif
Bram Moolenaara5792f52005-11-23 21:25:05 +00001840 if (fd < 0)
1841 fp_out = NULL;
1842 else
1843 fp_out = fdopen(fd, WRITEBIN);
Bram Moolenaar114216c2006-03-14 23:08:30 +00001844#endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845
1846 /*
1847 * If we can't create in the same directory, try creating a
1848 * "normal" temp file.
1849 */
1850 if (fp_out == NULL)
1851 {
1852 vim_free(tempname);
1853 if ((tempname = vim_tempname('o')) != NULL)
1854 fp_out = mch_fopen((char *)tempname, WRITEBIN);
1855 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00001856
1857#if defined(UNIX) && defined(HAVE_FCHOWN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 /*
Bram Moolenaara5792f52005-11-23 21:25:05 +00001859 * Make sure the owner can read/write it. This only works for
1860 * root.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 */
1862 if (fp_out != NULL)
Bram Moolenaara5792f52005-11-23 21:25:05 +00001863 (void)fchown(fileno(fp_out), st_old.st_uid, st_old.st_gid);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864#endif
1865 }
1866 }
1867
1868 /*
1869 * Check if the new viminfo file can be written to.
1870 */
1871 if (fp_out == NULL)
1872 {
1873 EMSG2(_("E138: Can't write viminfo file %s!"),
Bram Moolenaar75c50c42005-06-04 22:06:24 +00001874 (fp_in == NULL || tempname == NULL) ? fname : tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 if (fp_in != NULL)
1876 fclose(fp_in);
1877 goto end;
1878 }
1879
1880 if (p_verbose > 0)
Bram Moolenaar54ee7752005-05-31 22:22:17 +00001881 {
1882 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00001883 smsg((char_u *)_("Writing viminfo file \"%s\""), fname);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00001884 verbose_leave();
1885 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886
1887 viminfo_errcnt = 0;
1888 do_viminfo(fp_in, fp_out, !forceit, !forceit, FALSE);
1889
1890 fclose(fp_out); /* errors are ignored !? */
1891 if (fp_in != NULL)
1892 {
1893 fclose(fp_in);
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001894
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895 /*
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001896 * In case of an error keep the original viminfo file.
1897 * Otherwise rename the newly written file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898 */
1899 if (viminfo_errcnt || vim_rename(tempname, fname) == -1)
1900 mch_remove(tempname);
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001901
1902#ifdef WIN3264
1903 /* If the viminfo file was hidden then also hide the new file. */
1904 if (perm > 0 && (perm & FILE_ATTRIBUTE_HIDDEN))
1905 mch_hide(fname);
1906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 }
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001908
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909end:
1910 vim_free(fname);
1911 vim_free(tempname);
1912}
1913
1914/*
1915 * Get the viminfo file name to use.
1916 * If "file" is given and not empty, use it (has already been expanded by
1917 * cmdline functions).
1918 * Otherwise use "-i file_name", value from 'viminfo' or the default, and
1919 * expand environment variables.
1920 * Returns an allocated string. NULL when out of memory.
1921 */
1922 static char_u *
1923viminfo_filename(file)
1924 char_u *file;
1925{
1926 if (file == NULL || *file == NUL)
1927 {
1928 if (use_viminfo != NULL)
1929 file = use_viminfo;
1930 else if ((file = find_viminfo_parameter('n')) == NULL || *file == NUL)
1931 {
1932#ifdef VIMINFO_FILE2
1933 /* don't use $HOME when not defined (turned into "c:/"!). */
1934# ifdef VMS
1935 if (mch_getenv((char_u *)"SYS$LOGIN") == NULL)
1936# else
1937 if (mch_getenv((char_u *)"HOME") == NULL)
1938# endif
1939 {
1940 /* don't use $VIM when not available. */
1941 expand_env((char_u *)"$VIM", NameBuff, MAXPATHL);
1942 if (STRCMP("$VIM", NameBuff) != 0) /* $VIM was expanded */
1943 file = (char_u *)VIMINFO_FILE2;
1944 else
1945 file = (char_u *)VIMINFO_FILE;
1946 }
1947 else
1948#endif
1949 file = (char_u *)VIMINFO_FILE;
1950 }
1951 expand_env(file, NameBuff, MAXPATHL);
1952 file = NameBuff;
1953 }
1954 return vim_strsave(file);
1955}
1956
1957/*
1958 * do_viminfo() -- Should only be called from read_viminfo() & write_viminfo().
1959 */
1960 static void
1961do_viminfo(fp_in, fp_out, want_info, want_marks, force_read)
1962 FILE *fp_in;
1963 FILE *fp_out;
1964 int want_info;
1965 int want_marks;
1966 int force_read;
1967{
1968 int count = 0;
1969 int eof = FALSE;
1970 vir_T vir;
1971
1972 if ((vir.vir_line = alloc(LSIZE)) == NULL)
1973 return;
1974 vir.vir_fd = fp_in;
1975#ifdef FEAT_MBYTE
1976 vir.vir_conv.vc_type = CONV_NONE;
1977#endif
1978
1979 if (fp_in != NULL)
1980 {
1981 if (want_info)
1982 eof = read_viminfo_up_to_marks(&vir, force_read, fp_out != NULL);
1983 else
1984 /* Skip info, find start of marks */
1985 while (!(eof = viminfo_readline(&vir))
1986 && vir.vir_line[0] != '>')
1987 ;
1988 }
1989 if (fp_out != NULL)
1990 {
1991 /* Write the info: */
1992 fprintf(fp_out, _("# This viminfo file was generated by Vim %s.\n"),
1993 VIM_VERSION_MEDIUM);
1994 fprintf(fp_out, _("# You may edit it if you're careful!\n\n"));
1995#ifdef FEAT_MBYTE
1996 fprintf(fp_out, _("# Value of 'encoding' when this file was written\n"));
1997 fprintf(fp_out, "*encoding=%s\n\n", p_enc);
1998#endif
1999 write_viminfo_search_pattern(fp_out);
2000 write_viminfo_sub_string(fp_out);
2001#ifdef FEAT_CMDHIST
2002 write_viminfo_history(fp_out);
2003#endif
2004 write_viminfo_registers(fp_out);
2005#ifdef FEAT_EVAL
2006 write_viminfo_varlist(fp_out);
2007#endif
2008 write_viminfo_filemarks(fp_out);
2009 write_viminfo_bufferlist(fp_out);
2010 count = write_viminfo_marks(fp_out);
2011 }
2012 if (fp_in != NULL && want_marks)
2013 copy_viminfo_marks(&vir, fp_out, count, eof);
2014
2015 vim_free(vir.vir_line);
2016#ifdef FEAT_MBYTE
2017 if (vir.vir_conv.vc_type != CONV_NONE)
2018 convert_setup(&vir.vir_conv, NULL, NULL);
2019#endif
2020}
2021
2022/*
2023 * read_viminfo_up_to_marks() -- Only called from do_viminfo(). Reads in the
2024 * first part of the viminfo file which contains everything but the marks that
2025 * are local to a file. Returns TRUE when end-of-file is reached. -- webb
2026 */
2027 static int
2028read_viminfo_up_to_marks(virp, forceit, writing)
2029 vir_T *virp;
2030 int forceit;
2031 int writing;
2032{
2033 int eof;
2034 buf_T *buf;
2035
2036#ifdef FEAT_CMDHIST
2037 prepare_viminfo_history(forceit ? 9999 : 0);
2038#endif
2039 eof = viminfo_readline(virp);
2040 while (!eof && virp->vir_line[0] != '>')
2041 {
2042 switch (virp->vir_line[0])
2043 {
2044 /* Characters reserved for future expansion, ignored now */
2045 case '+': /* "+40 /path/dir file", for running vim without args */
2046 case '|': /* to be defined */
2047 case '^': /* to be defined */
2048 case '<': /* long line - ignored */
2049 /* A comment or empty line. */
2050 case NUL:
2051 case '\r':
2052 case '\n':
2053 case '#':
2054 eof = viminfo_readline(virp);
2055 break;
2056 case '*': /* "*encoding=value" */
2057 eof = viminfo_encoding(virp);
2058 break;
2059 case '!': /* global variable */
2060#ifdef FEAT_EVAL
2061 eof = read_viminfo_varlist(virp, writing);
2062#else
2063 eof = viminfo_readline(virp);
2064#endif
2065 break;
2066 case '%': /* entry for buffer list */
2067 eof = read_viminfo_bufferlist(virp, writing);
2068 break;
2069 case '"':
2070 eof = read_viminfo_register(virp, forceit);
2071 break;
2072 case '/': /* Search string */
2073 case '&': /* Substitute search string */
2074 case '~': /* Last search string, followed by '/' or '&' */
2075 eof = read_viminfo_search_pattern(virp, forceit);
2076 break;
2077 case '$':
2078 eof = read_viminfo_sub_string(virp, forceit);
2079 break;
2080 case ':':
2081 case '?':
2082 case '=':
2083 case '@':
2084#ifdef FEAT_CMDHIST
2085 eof = read_viminfo_history(virp);
2086#else
2087 eof = viminfo_readline(virp);
2088#endif
2089 break;
2090 case '-':
2091 case '\'':
2092 eof = read_viminfo_filemark(virp, forceit);
2093 break;
2094 default:
2095 if (viminfo_error("E575: ", _("Illegal starting char"),
2096 virp->vir_line))
2097 eof = TRUE;
2098 else
2099 eof = viminfo_readline(virp);
2100 break;
2101 }
2102 }
2103
2104#ifdef FEAT_CMDHIST
2105 /* Finish reading history items. */
2106 finish_viminfo_history();
2107#endif
2108
2109 /* Change file names to buffer numbers for fmarks. */
2110 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2111 fmarks_check_names(buf);
2112
2113 return eof;
2114}
2115
2116/*
2117 * Compare the 'encoding' value in the viminfo file with the current value of
2118 * 'encoding'. If different and the 'c' flag is in 'viminfo', setup for
2119 * conversion of text with iconv() in viminfo_readstring().
2120 */
2121 static int
2122viminfo_encoding(virp)
2123 vir_T *virp;
2124{
2125#ifdef FEAT_MBYTE
2126 char_u *p;
2127 int i;
2128
2129 if (get_viminfo_parameter('c') != 0)
2130 {
2131 p = vim_strchr(virp->vir_line, '=');
2132 if (p != NULL)
2133 {
2134 /* remove trailing newline */
2135 ++p;
2136 for (i = 0; vim_isprintc(p[i]); ++i)
2137 ;
2138 p[i] = NUL;
2139
2140 convert_setup(&virp->vir_conv, p, p_enc);
2141 }
2142 }
2143#endif
2144 return viminfo_readline(virp);
2145}
2146
2147/*
2148 * Read a line from the viminfo file.
2149 * Returns TRUE for end-of-file;
2150 */
2151 int
2152viminfo_readline(virp)
2153 vir_T *virp;
2154{
2155 return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
2156}
2157
2158/*
2159 * check string read from viminfo file
2160 * remove '\n' at the end of the line
2161 * - replace CTRL-V CTRL-V with CTRL-V
2162 * - replace CTRL-V 'n' with '\n'
2163 *
2164 * Check for a long line as written by viminfo_writestring().
2165 *
2166 * Return the string in allocated memory (NULL when out of memory).
2167 */
2168/*ARGSUSED*/
2169 char_u *
2170viminfo_readstring(virp, off, convert)
2171 vir_T *virp;
2172 int off; /* offset for virp->vir_line */
2173 int convert; /* convert the string */
2174{
2175 char_u *retval;
2176 char_u *s, *d;
2177 long len;
2178
2179 if (virp->vir_line[off] == Ctrl_V && vim_isdigit(virp->vir_line[off + 1]))
2180 {
2181 len = atol((char *)virp->vir_line + off + 1);
2182 retval = lalloc(len, TRUE);
2183 if (retval == NULL)
2184 {
2185 /* Line too long? File messed up? Skip next line. */
2186 (void)vim_fgets(virp->vir_line, 10, virp->vir_fd);
2187 return NULL;
2188 }
2189 (void)vim_fgets(retval, (int)len, virp->vir_fd);
2190 s = retval + 1; /* Skip the leading '<' */
2191 }
2192 else
2193 {
2194 retval = vim_strsave(virp->vir_line + off);
2195 if (retval == NULL)
2196 return NULL;
2197 s = retval;
2198 }
2199
2200 /* Change CTRL-V CTRL-V to CTRL-V and CTRL-V n to \n in-place. */
2201 d = retval;
2202 while (*s != NUL && *s != '\n')
2203 {
2204 if (s[0] == Ctrl_V && s[1] != NUL)
2205 {
2206 if (s[1] == 'n')
2207 *d++ = '\n';
2208 else
2209 *d++ = Ctrl_V;
2210 s += 2;
2211 }
2212 else
2213 *d++ = *s++;
2214 }
2215 *d = NUL;
2216
2217#ifdef FEAT_MBYTE
2218 if (convert && virp->vir_conv.vc_type != CONV_NONE && *retval != NUL)
2219 {
2220 d = string_convert(&virp->vir_conv, retval, NULL);
2221 if (d != NULL)
2222 {
2223 vim_free(retval);
2224 retval = d;
2225 }
2226 }
2227#endif
2228
2229 return retval;
2230}
2231
2232/*
2233 * write string to viminfo file
2234 * - replace CTRL-V with CTRL-V CTRL-V
2235 * - replace '\n' with CTRL-V 'n'
2236 * - add a '\n' at the end
2237 *
2238 * For a long line:
2239 * - write " CTRL-V <length> \n " in first line
2240 * - write " < <string> \n " in second line
2241 */
2242 void
2243viminfo_writestring(fd, p)
2244 FILE *fd;
2245 char_u *p;
2246{
2247 int c;
2248 char_u *s;
2249 int len = 0;
2250
2251 for (s = p; *s != NUL; ++s)
2252 {
2253 if (*s == Ctrl_V || *s == '\n')
2254 ++len;
2255 ++len;
2256 }
2257
2258 /* If the string will be too long, write its length and put it in the next
2259 * line. Take into account that some room is needed for what comes before
2260 * the string (e.g., variable name). Add something to the length for the
2261 * '<', NL and trailing NUL. */
2262 if (len > LSIZE / 2)
2263 fprintf(fd, IF_EB("\026%d\n<", CTRL_V_STR "%d\n<"), len + 3);
2264
2265 while ((c = *p++) != NUL)
2266 {
2267 if (c == Ctrl_V || c == '\n')
2268 {
2269 putc(Ctrl_V, fd);
2270 if (c == '\n')
2271 c = 'n';
2272 }
2273 putc(c, fd);
2274 }
2275 putc('\n', fd);
2276}
2277#endif /* FEAT_VIMINFO */
2278
2279/*
2280 * Implementation of ":fixdel", also used by get_stty().
2281 * <BS> resulting <Del>
2282 * ^? ^H
2283 * not ^? ^?
2284 */
2285/*ARGSUSED*/
2286 void
2287do_fixdel(eap)
2288 exarg_T *eap;
2289{
2290 char_u *p;
2291
2292 p = find_termcode((char_u *)"kb");
2293 add_termcode((char_u *)"kD", p != NULL
2294 && *p == DEL ? (char_u *)CTRL_H_STR : DEL_STR, FALSE);
2295}
2296
2297 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002298print_line_no_prefix(lnum, use_number, list)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 linenr_T lnum;
2300 int use_number;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002301 int list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302{
Bram Moolenaar592e0a22004-07-03 16:05:59 +00002303 char_u numbuf[30];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304
2305 if (curwin->w_p_nu || use_number)
2306 {
Bram Moolenaar592e0a22004-07-03 16:05:59 +00002307 sprintf((char *)numbuf, "%*ld ", number_width(curwin), (long)lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 msg_puts_attr(numbuf, hl_attr(HLF_N)); /* Highlight line nrs */
2309 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002310 msg_prt_line(ml_get(lnum), list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311}
2312
2313/*
2314 * Print a text line. Also in silent mode ("ex -s").
2315 */
2316 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002317print_line(lnum, use_number, list)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 linenr_T lnum;
2319 int use_number;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002320 int list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321{
2322 int save_silent = silent_mode;
2323
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 msg_start();
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002325 silent_mode = FALSE;
2326 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
2327 print_line_no_prefix(lnum, use_number, list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 if (save_silent)
2329 {
2330 msg_putchar('\n');
2331 cursor_on(); /* msg_start() switches it off */
2332 out_flush();
2333 silent_mode = save_silent;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002334 info_message = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 }
2336}
2337
2338/*
2339 * ":file[!] [fname]".
2340 */
2341 void
2342ex_file(eap)
2343 exarg_T *eap;
2344{
2345 char_u *fname, *sfname, *xfname;
2346 buf_T *buf;
2347
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002348 /* ":0file" removes the file name. Check for illegal uses ":3file",
2349 * "0file name", etc. */
2350 if (eap->addr_count > 0
2351 && (*eap->arg != NUL
2352 || eap->line2 > 0
2353 || eap->addr_count > 1))
2354 {
2355 EMSG(_(e_invarg));
2356 return;
2357 }
2358
2359 if (*eap->arg != NUL || eap->addr_count == 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 {
2361#ifdef FEAT_AUTOCMD
2362 buf = curbuf;
2363 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
2364 /* buffer changed, don't change name now */
2365 if (buf != curbuf)
2366 return;
2367# ifdef FEAT_EVAL
2368 if (aborting()) /* autocmds may abort script processing */
2369 return;
2370# endif
2371#endif
2372 /*
2373 * The name of the current buffer will be changed.
2374 * A new (unlisted) buffer entry needs to be made to hold the old file
2375 * name, which will become the alternate file name.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002376 * But don't set the alternate file name if the buffer didn't have a
2377 * name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 */
2379 fname = curbuf->b_ffname;
2380 sfname = curbuf->b_sfname;
2381 xfname = curbuf->b_fname;
2382 curbuf->b_ffname = NULL;
2383 curbuf->b_sfname = NULL;
2384 if (setfname(curbuf, eap->arg, NULL, TRUE) == FAIL)
2385 {
2386 curbuf->b_ffname = fname;
2387 curbuf->b_sfname = sfname;
2388 return;
2389 }
2390 curbuf->b_flags |= BF_NOTEDITED;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002391 if (xfname != NULL && *xfname != NUL)
2392 {
2393 buf = buflist_new(fname, xfname, curwin->w_cursor.lnum, 0);
2394 if (buf != NULL && !cmdmod.keepalt)
2395 curwin->w_alt_fnum = buf->b_fnum;
2396 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 vim_free(fname);
2398 vim_free(sfname);
2399#ifdef FEAT_AUTOCMD
2400 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
2401#endif
2402 }
2403 /* print full file name if :cd used */
2404 fileinfo(FALSE, FALSE, eap->forceit);
2405}
2406
2407/*
2408 * ":update".
2409 */
2410 void
2411ex_update(eap)
2412 exarg_T *eap;
2413{
2414 if (curbufIsChanged())
2415 (void)do_write(eap);
2416}
2417
2418/*
2419 * ":write" and ":saveas".
2420 */
2421 void
2422ex_write(eap)
2423 exarg_T *eap;
2424{
2425 if (eap->usefilter) /* input lines to shell command */
2426 do_bang(1, eap, FALSE, TRUE, FALSE);
2427 else
2428 (void)do_write(eap);
2429}
2430
2431/*
2432 * write current buffer to file 'eap->arg'
2433 * if 'eap->append' is TRUE, append to the file
2434 *
2435 * if *eap->arg == NUL write to current file
2436 *
2437 * return FAIL for failure, OK otherwise
2438 */
2439 int
2440do_write(eap)
2441 exarg_T *eap;
2442{
2443 int other;
2444 char_u *fname = NULL; /* init to shut up gcc */
2445 char_u *ffname;
2446 int retval = FAIL;
2447 char_u *free_fname = NULL;
2448#ifdef FEAT_BROWSE
2449 char_u *browse_file = NULL;
2450#endif
2451 buf_T *alt_buf = NULL;
2452
2453 if (not_writing()) /* check 'write' option */
2454 return FAIL;
2455
2456 ffname = eap->arg;
2457#ifdef FEAT_BROWSE
2458 if (cmdmod.browse)
2459 {
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002460 browse_file = do_browse(BROWSE_SAVE, (char_u *)_("Save As"), ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 NULL, NULL, NULL, curbuf);
2462 if (browse_file == NULL)
2463 goto theend;
2464 ffname = browse_file;
2465 }
2466#endif
2467 if (*ffname == NUL)
2468 {
2469 if (eap->cmdidx == CMD_saveas)
2470 {
2471 EMSG(_(e_argreq));
2472 goto theend;
2473 }
2474 other = FALSE;
2475 }
2476 else
2477 {
2478 fname = ffname;
2479 free_fname = fix_fname(ffname);
2480 /*
2481 * When out-of-memory, keep unexpanded file name, because we MUST be
2482 * able to write the file in this situation.
2483 */
2484 if (free_fname != NULL)
2485 ffname = free_fname;
2486 other = otherfile(ffname);
2487 }
2488
2489 /*
2490 * If we have a new file, put its name in the list of alternate file names.
2491 */
2492 if (other)
2493 {
2494 if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL
2495 || eap->cmdidx == CMD_saveas)
2496 alt_buf = setaltfname(ffname, fname, (linenr_T)1);
2497 else
2498 alt_buf = buflist_findname(ffname);
2499 if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL)
2500 {
2501 /* Overwriting a file that is loaded in another buffer is not a
2502 * good idea. */
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002503 EMSG(_(e_bufloaded));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 goto theend;
2505 }
2506 }
2507
2508 /*
2509 * Writing to the current file is not allowed in readonly mode
2510 * and a file name is required.
2511 * "nofile" and "nowrite" buffers cannot be written implicitly either.
2512 */
2513 if (!other && (
2514#ifdef FEAT_QUICKFIX
2515 bt_dontwrite_msg(curbuf) ||
2516#endif
2517 check_fname() == FAIL || check_readonly(&eap->forceit, curbuf)))
2518 goto theend;
2519
2520 if (!other)
2521 {
2522 ffname = curbuf->b_ffname;
2523 fname = curbuf->b_fname;
2524 /*
2525 * Not writing the whole file is only allowed with '!'.
2526 */
2527 if ( (eap->line1 != 1
2528 || eap->line2 != curbuf->b_ml.ml_line_count)
2529 && !eap->forceit
2530 && !eap->append
2531 && !p_wa)
2532 {
2533#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2534 if (p_confirm || cmdmod.confirm)
2535 {
2536 if (vim_dialog_yesno(VIM_QUESTION, NULL,
2537 (char_u *)_("Write partial file?"), 2) != VIM_YES)
2538 goto theend;
2539 eap->forceit = TRUE;
2540 }
2541 else
2542#endif
2543 {
2544 EMSG(_("E140: Use ! to write partial buffer"));
2545 goto theend;
2546 }
2547 }
2548 }
2549
2550 if (check_overwrite(eap, curbuf, fname, ffname, other) == OK)
2551 {
2552 if (eap->cmdidx == CMD_saveas && alt_buf != NULL)
2553 {
2554#ifdef FEAT_AUTOCMD
2555 buf_T *was_curbuf = curbuf;
2556
2557 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
Bram Moolenaar269ec652004-07-29 08:43:53 +00002558 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559# ifdef FEAT_EVAL
2560 if (curbuf != was_curbuf || aborting())
2561# else
2562 if (curbuf != was_curbuf)
2563# endif
2564 {
2565 /* buffer changed, don't change name now */
2566 retval = FAIL;
2567 goto theend;
2568 }
2569#endif
2570 /* Exchange the file names for the current and the alternate
2571 * buffer. This makes it look like we are now editing the buffer
2572 * under the new name. Must be done before buf_write(), because
2573 * if there is no file name and 'cpo' contains 'F', it will set
2574 * the file name. */
2575 fname = alt_buf->b_fname;
2576 alt_buf->b_fname = curbuf->b_fname;
2577 curbuf->b_fname = fname;
2578 fname = alt_buf->b_ffname;
2579 alt_buf->b_ffname = curbuf->b_ffname;
2580 curbuf->b_ffname = fname;
2581 fname = alt_buf->b_sfname;
2582 alt_buf->b_sfname = curbuf->b_sfname;
2583 curbuf->b_sfname = fname;
2584 buf_name_changed(curbuf);
2585#ifdef FEAT_AUTOCMD
2586 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
Bram Moolenaar269ec652004-07-29 08:43:53 +00002587 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, alt_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 if (!alt_buf->b_p_bl)
2589 {
2590 alt_buf->b_p_bl = TRUE;
2591 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, alt_buf);
2592 }
2593# ifdef FEAT_EVAL
2594 if (curbuf != was_curbuf || aborting())
2595# else
2596 if (curbuf != was_curbuf)
2597# endif
2598 {
2599 /* buffer changed, don't write the file */
2600 retval = FAIL;
2601 goto theend;
2602 }
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002603
2604 /* If 'filetype' was empty try detecting it now. */
2605 if (*curbuf->b_p_ft == NUL)
2606 {
2607 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00002608 do_modelines(0);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002609 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610#endif
2611 }
2612
2613 retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2,
2614 eap, eap->append, eap->forceit, TRUE, FALSE);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002615
Bram Moolenaar071d4272004-06-13 20:20:40 +00002616 }
2617
2618theend:
2619#ifdef FEAT_BROWSE
2620 vim_free(browse_file);
2621#endif
2622 vim_free(free_fname);
2623 return retval;
2624}
2625
2626/*
2627 * Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED,
2628 * BF_NEW or BF_READERR, check for overwriting current file.
2629 * May set eap->forceit if a dialog says it's OK to overwrite.
2630 * Return OK if it's OK, FAIL if it is not.
2631 */
2632/*ARGSUSED*/
2633 static int
2634check_overwrite(eap, buf, fname, ffname, other)
2635 exarg_T *eap;
2636 buf_T *buf;
2637 char_u *fname; /* file name to be used (can differ from
2638 buf->ffname) */
2639 char_u *ffname; /* full path version of fname */
2640 int other; /* writing under other name */
2641{
2642 /*
2643 * write to other file or b_flags set or not writing the whole file:
2644 * overwriting only allowed with '!'
2645 */
2646 if ( (other
2647 || (buf->b_flags & BF_NOTEDITED)
2648 || ((buf->b_flags & BF_NEW)
2649 && vim_strchr(p_cpo, CPO_OVERNEW) == NULL)
2650 || (buf->b_flags & BF_READERR))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 && !p_wa
2652 && vim_fexists(ffname))
2653 {
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002654 if (!eap->forceit && !eap->append)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002655 {
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002656#ifdef UNIX
Bram Moolenaar0ac93792006-01-21 22:16:51 +00002657 /* with UNIX it is possible to open a directory */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002658 if (mch_isdir(ffname))
2659 {
2660 EMSG2(_(e_isadir2), ffname);
2661 return FAIL;
2662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663#endif
2664#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002665 if (p_confirm || cmdmod.confirm)
2666 {
2667 char_u buff[IOSIZE];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002669 dialog_msg(buff, _("Overwrite existing file \"%s\"?"), fname);
2670 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES)
2671 return FAIL;
2672 eap->forceit = TRUE;
2673 }
2674 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675#endif
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002676 {
2677 EMSG(_(e_exists));
2678 return FAIL;
2679 }
2680 }
2681
2682 /* For ":w! filename" check that no swap file exists for "filename". */
2683 if (other && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 {
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002685 char_u dir[MAXPATHL];
2686 char_u *p;
2687 int r;
2688 char_u *swapname;
2689
2690 /* We only try the first entry in 'directory', without checking if
2691 * it's writable. If the "." directory is not writable the write
2692 * will probably fail anyway.
2693 * Use 'shortname' of the current buffer, since there is no buffer
2694 * for the written file. */
2695 if (*p_dir == NUL)
2696 STRCPY(dir, ".");
2697 else
2698 {
2699 p = p_dir;
2700 copy_option_part(&p, dir, MAXPATHL, ",");
2701 }
2702 swapname = makeswapname(fname, ffname, curbuf, dir);
2703 r = vim_fexists(swapname);
2704 vim_free(swapname);
2705 if (r)
2706 {
2707#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2708 if (p_confirm || cmdmod.confirm)
2709 {
2710 char_u buff[IOSIZE];
2711
2712 dialog_msg(buff,
2713 _("Swap file \"%s\" exists, overwrite anyway?"),
2714 swapname);
2715 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2)
2716 != VIM_YES)
2717 return FAIL;
2718 eap->forceit = TRUE;
2719 }
2720 else
2721#endif
2722 {
2723 EMSG2(_("E768: Swap file exists: %s (:silent! overrides)"),
2724 swapname);
2725 return FAIL;
2726 }
2727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 }
2729 }
2730 return OK;
2731}
2732
2733/*
2734 * Handle ":wnext", ":wNext" and ":wprevious" commands.
2735 */
2736 void
2737ex_wnext(eap)
2738 exarg_T *eap;
2739{
2740 int i;
2741
2742 if (eap->cmd[1] == 'n')
2743 i = curwin->w_arg_idx + (int)eap->line2;
2744 else
2745 i = curwin->w_arg_idx - (int)eap->line2;
2746 eap->line1 = 1;
2747 eap->line2 = curbuf->b_ml.ml_line_count;
2748 if (do_write(eap) != FAIL)
2749 do_argfile(eap, i);
2750}
2751
2752/*
2753 * ":wall", ":wqall" and ":xall": Write all changed files (and exit).
2754 */
2755 void
2756do_wqall(eap)
2757 exarg_T *eap;
2758{
2759 buf_T *buf;
2760 int error = 0;
2761 int save_forceit = eap->forceit;
2762
2763 if (eap->cmdidx == CMD_xall || eap->cmdidx == CMD_wqall)
2764 exiting = TRUE;
2765
2766 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2767 {
2768 if (bufIsChanged(buf))
2769 {
2770 /*
2771 * Check if there is a reason the buffer cannot be written:
2772 * 1. if the 'write' option is set
2773 * 2. if there is no file name (even after browsing)
2774 * 3. if the 'readonly' is set (even after a dialog)
2775 * 4. if overwriting is allowed (even after a dialog)
2776 */
2777 if (not_writing())
2778 {
2779 ++error;
2780 break;
2781 }
2782#ifdef FEAT_BROWSE
2783 /* ":browse wall": ask for file name if there isn't one */
2784 if (buf->b_ffname == NULL && cmdmod.browse)
2785 browse_save_fname(buf);
2786#endif
2787 if (buf->b_ffname == NULL)
2788 {
2789 EMSGN(_("E141: No file name for buffer %ld"), (long)buf->b_fnum);
2790 ++error;
2791 }
2792 else if (check_readonly(&eap->forceit, buf)
2793 || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname,
2794 FALSE) == FAIL)
2795 {
2796 ++error;
2797 }
2798 else
2799 {
2800 if (buf_write_all(buf, eap->forceit) == FAIL)
2801 ++error;
2802#ifdef FEAT_AUTOCMD
2803 /* an autocommand may have deleted the buffer */
2804 if (!buf_valid(buf))
2805 buf = firstbuf;
2806#endif
2807 }
2808 eap->forceit = save_forceit; /* check_overwrite() may set it */
2809 }
2810 }
2811 if (exiting)
2812 {
2813 if (!error)
2814 getout(0); /* exit Vim */
2815 not_exiting();
2816 }
2817}
2818
2819/*
2820 * Check the 'write' option.
2821 * Return TRUE and give a message when it's not st.
2822 */
2823 int
2824not_writing()
2825{
2826 if (p_write)
2827 return FALSE;
2828 EMSG(_("E142: File not written: Writing is disabled by 'write' option"));
2829 return TRUE;
2830}
2831
2832/*
2833 * Check if a buffer is read-only. Ask for overruling in a dialog.
2834 * Return TRUE and give an error message when the buffer is readonly.
2835 */
2836 static int
2837check_readonly(forceit, buf)
2838 int *forceit;
2839 buf_T *buf;
2840{
2841 if (!*forceit && buf->b_p_ro)
2842 {
2843#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2844 if ((p_confirm || cmdmod.confirm) && buf->b_fname != NULL)
2845 {
2846 char_u buff[IOSIZE];
2847
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002848 dialog_msg(buff, _("'readonly' option is set for \"%s\".\nDo you wish to write anyway?"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 buf->b_fname);
2850
2851 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES)
2852 {
2853 /* Set forceit, to force the writing of a readonly file */
2854 *forceit = TRUE;
2855 return FALSE;
2856 }
2857 else
2858 return TRUE;
2859 }
2860 else
2861#endif
2862 EMSG(_(e_readonly));
2863 return TRUE;
2864 }
2865 return FALSE;
2866}
2867
2868/*
Bram Moolenaar8ada17c2006-01-19 22:16:24 +00002869 * Try to abandon current file and edit a new or existing file.
2870 * 'fnum' is the number of the file, if zero use ffname/sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 *
Bram Moolenaar8ada17c2006-01-19 22:16:24 +00002872 * Return 1 for "normal" error, 2 for "not written" error, 0 for success
2873 * -1 for succesfully opening another file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874 * 'lnum' is the line number for the cursor in the new file (if non-zero).
2875 */
2876 int
2877getfile(fnum, ffname, sfname, setpm, lnum, forceit)
2878 int fnum;
2879 char_u *ffname;
2880 char_u *sfname;
2881 int setpm;
2882 linenr_T lnum;
2883 int forceit;
2884{
2885 int other;
2886 int retval;
2887 char_u *free_me = NULL;
2888
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002889 if (text_locked())
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 return 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891
2892 if (fnum == 0)
2893 {
2894 /* make ffname full path, set sfname */
2895 fname_expand(curbuf, &ffname, &sfname);
2896 other = otherfile(ffname);
2897 free_me = ffname; /* has been allocated, free() later */
2898 }
2899 else
2900 other = (fnum != curbuf->b_fnum);
2901
2902 if (other)
2903 ++no_wait_return; /* don't wait for autowrite message */
2904 if (other && !forceit && curbuf->b_nwindows == 1 && !P_HID(curbuf)
2905 && curbufIsChanged() && autowrite(curbuf, forceit) == FAIL)
2906 {
2907#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2908 if (p_confirm && p_write)
2909 dialog_changed(curbuf, FALSE);
2910 if (curbufIsChanged())
2911#endif
2912 {
2913 if (other)
2914 --no_wait_return;
2915 EMSG(_(e_nowrtmsg));
2916 retval = 2; /* file has been changed */
2917 goto theend;
2918 }
2919 }
2920 if (other)
2921 --no_wait_return;
2922 if (setpm)
2923 setpcmark();
2924 if (!other)
2925 {
2926 if (lnum != 0)
2927 curwin->w_cursor.lnum = lnum;
2928 check_cursor_lnum();
2929 beginline(BL_SOL | BL_FIX);
2930 retval = 0; /* it's in the same file */
2931 }
2932 else if (do_ecmd(fnum, ffname, sfname, NULL, lnum,
2933 (P_HID(curbuf) ? ECMD_HIDE : 0) + (forceit ? ECMD_FORCEIT : 0)) == OK)
2934 retval = -1; /* opened another file */
2935 else
2936 retval = 1; /* error encountered */
2937
2938theend:
2939 vim_free(free_me);
2940 return retval;
2941}
2942
2943/*
2944 * start editing a new file
2945 *
2946 * fnum: file number; if zero use ffname/sfname
2947 * ffname: the file name
2948 * - full path if sfname used,
2949 * - any file name if sfname is NULL
2950 * - empty string to re-edit with the same file name (but may be
2951 * in a different directory)
2952 * - NULL to start an empty buffer
2953 * sfname: the short file name (or NULL)
2954 * eap: contains the command to be executed after loading the file and
2955 * forced 'ff' and 'fenc'
2956 * newlnum: if > 0: put cursor on this line number (if possible)
2957 * if ECMD_LASTL: use last position in loaded file
2958 * if ECMD_LAST: use last position in all files
2959 * if ECMD_ONE: use first line
2960 * flags:
2961 * ECMD_HIDE: if TRUE don't free the current buffer
2962 * ECMD_SET_HELP: set b_help flag of (new) buffer before opening file
2963 * ECMD_OLDBUF: use existing buffer if it exists
2964 * ECMD_FORCEIT: ! used for Ex command
2965 * ECMD_ADDBUF: don't edit, just add to buffer list
2966 *
2967 * return FAIL for failure, OK otherwise
2968 */
2969 int
2970do_ecmd(fnum, ffname, sfname, eap, newlnum, flags)
2971 int fnum;
2972 char_u *ffname;
2973 char_u *sfname;
2974 exarg_T *eap; /* can be NULL! */
2975 linenr_T newlnum;
2976 int flags;
2977{
2978 int other_file; /* TRUE if editing another file */
2979 int oldbuf; /* TRUE if using existing buffer */
2980#ifdef FEAT_AUTOCMD
2981 int auto_buf = FALSE; /* TRUE if autocommands brought us
2982 into the buffer unexpectedly */
2983 char_u *new_name = NULL;
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00002984 int did_set_swapcommand = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985#endif
2986 buf_T *buf;
2987#if defined(FEAT_AUTOCMD) || defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2988 buf_T *old_curbuf = curbuf;
2989#endif
2990 char_u *free_fname = NULL;
2991#ifdef FEAT_BROWSE
2992 char_u *browse_file = NULL;
2993#endif
2994 int retval = FAIL;
2995 long n;
2996 linenr_T lnum;
2997 linenr_T topline = 0;
2998 int newcol = -1;
2999 int solcol = -1;
3000 pos_T *pos;
3001#ifdef FEAT_SUN_WORKSHOP
3002 char_u *cp;
3003#endif
3004 char_u *command = NULL;
3005
3006 if (eap != NULL)
3007 command = eap->do_ecmd_cmd;
3008
3009 if (fnum != 0)
3010 {
3011 if (fnum == curbuf->b_fnum) /* file is already being edited */
3012 return OK; /* nothing to do */
3013 other_file = TRUE;
3014 }
3015 else
3016 {
3017#ifdef FEAT_BROWSE
3018 if (cmdmod.browse)
3019 {
Bram Moolenaar0be6e642005-08-04 21:32:22 +00003020 if (
3021# ifdef FEAT_GUI
3022 !gui.in_use &&
3023# endif
3024 au_has_group((char_u *)"FileExplorer"))
3025 {
3026 /* No browsing supported but we do have the file explorer:
3027 * Edit the directory. */
3028 if (ffname == NULL || !mch_isdir(ffname))
3029 ffname = (char_u *)".";
3030 }
3031 else
3032 {
3033 browse_file = do_browse(0, (char_u *)_("Edit File"), ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 NULL, NULL, NULL, curbuf);
Bram Moolenaar0be6e642005-08-04 21:32:22 +00003035 if (browse_file == NULL)
3036 goto theend;
3037 ffname = browse_file;
3038 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039 }
3040#endif
3041 /* if no short name given, use ffname for short name */
3042 if (sfname == NULL)
3043 sfname = ffname;
3044#ifdef USE_FNAME_CASE
3045# ifdef USE_LONG_FNAME
3046 if (USE_LONG_FNAME)
3047# endif
Bram Moolenaar342337a2005-07-21 21:11:17 +00003048 if (sfname != NULL)
3049 fname_case(sfname, 0); /* set correct case for sfname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050#endif
3051
3052#ifdef FEAT_LISTCMDS
3053 if ((flags & ECMD_ADDBUF) && (ffname == NULL || *ffname == NUL))
3054 goto theend;
3055#endif
3056
3057 if (ffname == NULL)
3058 other_file = TRUE;
3059 /* there is no file name */
3060 else if (*ffname == NUL && curbuf->b_ffname == NULL)
3061 other_file = FALSE;
3062 else
3063 {
3064 if (*ffname == NUL) /* re-edit with same file name */
3065 {
3066 ffname = curbuf->b_ffname;
3067 sfname = curbuf->b_fname;
3068 }
3069 free_fname = fix_fname(ffname); /* may expand to full path name */
3070 if (free_fname != NULL)
3071 ffname = free_fname;
3072 other_file = otherfile(ffname);
3073#ifdef FEAT_SUN_WORKSHOP
3074 if (usingSunWorkShop && p_acd
3075 && (cp = vim_strrchr(sfname, '/')) != NULL)
3076 sfname = ++cp;
3077#endif
3078 }
3079 }
3080
3081 /*
3082 * if the file was changed we may not be allowed to abandon it
3083 * - if we are going to re-edit the same file
3084 * - or if we are the only window on this file and if ECMD_HIDE is FALSE
3085 */
3086 if ( ((!other_file && !(flags & ECMD_OLDBUF))
3087 || (curbuf->b_nwindows == 1
3088 && !(flags & (ECMD_HIDE | ECMD_ADDBUF))))
3089 && check_changed(curbuf, p_awa, !other_file,
3090 (flags & ECMD_FORCEIT), FALSE))
3091 {
3092 if (fnum == 0 && other_file && ffname != NULL)
3093 (void)setaltfname(ffname, sfname, newlnum < 0 ? 0 : newlnum);
3094 goto theend;
3095 }
3096
3097#ifdef FEAT_VISUAL
3098 /*
3099 * End Visual mode before switching to another buffer, so the text can be
3100 * copied into the GUI selection buffer.
3101 */
3102 reset_VIsual();
3103#endif
3104
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00003105#ifdef FEAT_AUTOCMD
3106 if ((command != NULL || newlnum > (linenr_T)0)
3107 && *get_vim_var_str(VV_SWAPCOMMAND) == NUL)
3108 {
3109 int len;
3110 char_u *p;
3111
3112 /* Set v:swapcommand for the SwapExists autocommands. */
3113 if (command != NULL)
3114 len = STRLEN(command) + 3;
3115 else
3116 len = 30;
3117 p = alloc((unsigned)len);
3118 if (p != NULL)
3119 {
3120 if (command != NULL)
3121 vim_snprintf((char *)p, len, ":%s\r", command);
3122 else
3123 vim_snprintf((char *)p, len, "%ldG", (long)newlnum);
3124 set_vim_var_string(VV_SWAPCOMMAND, p, -1);
3125 did_set_swapcommand = TRUE;
3126 vim_free(p);
3127 }
3128 }
3129#endif
3130
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 /*
3132 * If we are starting to edit another file, open a (new) buffer.
3133 * Otherwise we re-use the current buffer.
3134 */
3135 if (other_file)
3136 {
3137#ifdef FEAT_LISTCMDS
3138 if (!(flags & ECMD_ADDBUF))
3139#endif
3140 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003141 if (!cmdmod.keepalt)
3142 curwin->w_alt_fnum = curbuf->b_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143 buflist_altfpos();
3144 }
3145
3146 if (fnum)
3147 buf = buflist_findnr(fnum);
3148 else
3149 {
3150#ifdef FEAT_LISTCMDS
3151 if (flags & ECMD_ADDBUF)
3152 {
3153 linenr_T tlnum = 1L;
3154
3155 if (command != NULL)
3156 {
3157 tlnum = atol((char *)command);
3158 if (tlnum <= 0)
3159 tlnum = 1L;
3160 }
3161 (void)buflist_new(ffname, sfname, tlnum, BLN_LISTED);
3162 goto theend;
3163 }
3164#endif
3165 buf = buflist_new(ffname, sfname, 0L,
3166 BLN_CURBUF | ((flags & ECMD_SET_HELP) ? 0 : BLN_LISTED));
3167 }
3168 if (buf == NULL)
3169 goto theend;
3170 if (buf->b_ml.ml_mfp == NULL) /* no memfile yet */
3171 {
3172 oldbuf = FALSE;
3173 buf->b_nwindows = 0;
3174 }
3175 else /* existing memfile */
3176 {
3177 oldbuf = TRUE;
3178 (void)buf_check_timestamp(buf, FALSE);
3179 /* Check if autocommands made buffer invalid or changed the current
3180 * buffer. */
3181 if (!buf_valid(buf)
3182#ifdef FEAT_AUTOCMD
3183 || curbuf != old_curbuf
3184#endif
3185 )
3186 goto theend;
3187#ifdef FEAT_EVAL
3188 if (aborting()) /* autocmds may abort script processing */
3189 goto theend;
3190#endif
3191 }
3192
3193 /* May jump to last used line number for a loaded buffer or when asked
3194 * for explicitly */
3195 if ((oldbuf && newlnum == ECMD_LASTL) || newlnum == ECMD_LAST)
3196 {
3197 pos = buflist_findfpos(buf);
3198 newlnum = pos->lnum;
3199 solcol = pos->col;
3200 }
3201
3202 /*
3203 * Make the (new) buffer the one used by the current window.
3204 * If the old buffer becomes unused, free it if ECMD_HIDE is FALSE.
3205 * If the current buffer was empty and has no file name, curbuf
3206 * is returned by buflist_new().
3207 */
3208 if (buf != curbuf)
3209 {
3210#ifdef FEAT_AUTOCMD
3211 /*
3212 * Be careful: The autocommands may delete any buffer and change
3213 * the current buffer.
3214 * - If the buffer we are going to edit is deleted, give up.
3215 * - If the current buffer is deleted, prefer to load the new
3216 * buffer when loading a buffer is required. This avoids
3217 * loading another buffer which then must be closed again.
3218 * - If we ended up in the new buffer already, need to skip a few
3219 * things, set auto_buf.
3220 */
3221 if (buf->b_fname != NULL)
3222 new_name = vim_strsave(buf->b_fname);
3223 au_new_curbuf = buf;
3224 apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
3225 if (!buf_valid(buf)) /* new buffer has been deleted */
3226 {
3227 delbuf_msg(new_name); /* frees new_name */
3228 goto theend;
3229 }
3230# ifdef FEAT_EVAL
3231 if (aborting()) /* autocmds may abort script processing */
3232 {
3233 vim_free(new_name);
3234 goto theend;
3235 }
3236# endif
3237 if (buf == curbuf) /* already in new buffer */
3238 auto_buf = TRUE;
3239 else
3240 {
3241 if (curbuf == old_curbuf)
3242#endif
3243 buf_copy_options(buf, BCO_ENTER);
3244
3245 /* close the link to the current buffer */
3246 close_buffer(curwin, curbuf,
3247 (flags & ECMD_HIDE) ? 0 : DOBUF_UNLOAD);
3248
3249#ifdef FEAT_AUTOCMD
3250# ifdef FEAT_EVAL
3251 if (aborting()) /* autocmds may abort script processing */
3252 {
3253 vim_free(new_name);
3254 goto theend;
3255 }
3256# endif
3257 /* Be careful again, like above. */
3258 if (!buf_valid(buf)) /* new buffer has been deleted */
3259 {
3260 delbuf_msg(new_name); /* frees new_name */
3261 goto theend;
3262 }
3263 if (buf == curbuf) /* already in new buffer */
3264 auto_buf = TRUE;
3265 else
3266#endif
3267 {
3268 curwin->w_buffer = buf;
3269 curbuf = buf;
3270 ++curbuf->b_nwindows;
3271 /* set 'fileformat' */
3272 if (*p_ffs && !oldbuf)
3273 set_fileformat(default_fileformat(), OPT_LOCAL);
3274 }
3275
3276 /* May get the window options from the last time this buffer
3277 * was in this window (or another window). If not used
3278 * before, reset the local window options to the global
3279 * values. Also restores old folding stuff. */
3280 get_winopts(buf);
3281
3282#ifdef FEAT_AUTOCMD
3283 }
3284 vim_free(new_name);
3285 au_new_curbuf = NULL;
3286#endif
3287 }
3288 else
3289 ++curbuf->b_nwindows;
3290
3291 curwin->w_pcmark.lnum = 1;
3292 curwin->w_pcmark.col = 0;
3293 }
3294 else /* !other_file */
3295 {
3296 if (
3297#ifdef FEAT_LISTCMDS
3298 (flags & ECMD_ADDBUF) ||
3299#endif
3300 check_fname() == FAIL)
3301 goto theend;
3302 oldbuf = (flags & ECMD_OLDBUF);
3303 }
3304
3305 if ((flags & ECMD_SET_HELP) || keep_help_flag)
3306 {
3307 char_u *p;
3308
3309 curbuf->b_help = TRUE;
3310#ifdef FEAT_QUICKFIX
3311 set_string_option_direct((char_u *)"buftype", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003312 (char_u *)"help", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313#endif
3314
3315 /*
3316 * Always set these options after jumping to a help tag, because the
3317 * user may have an autocommand that gets in the way.
3318 * Accept all ASCII chars for keywords, except ' ', '*', '"', '|', and
3319 * latin1 word characters (for translated help files).
3320 * Only set it when needed, buf_init_chartab() is some work.
3321 */
3322 p =
3323#ifdef EBCDIC
3324 (char_u *)"65-255,^*,^|,^\"";
3325#else
3326 (char_u *)"!-~,^*,^|,^\",192-255";
3327#endif
3328 if (STRCMP(curbuf->b_p_isk, p) != 0)
3329 {
3330 set_string_option_direct((char_u *)"isk", -1, p,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003331 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 check_buf_options(curbuf);
3333 (void)buf_init_chartab(curbuf, FALSE);
3334 }
3335
3336 curbuf->b_p_ts = 8; /* 'tabstop' is 8 */
3337 curwin->w_p_list = FALSE; /* no list mode */
3338
3339 curbuf->b_p_ma = FALSE; /* not modifiable */
3340 curbuf->b_p_bin = FALSE; /* reset 'bin' before reading file */
3341 curwin->w_p_nu = 0; /* no line numbers */
3342#ifdef FEAT_SCROLLBIND
3343 curwin->w_p_scb = FALSE; /* no scroll binding */
3344#endif
3345#ifdef FEAT_ARABIC
3346 curwin->w_p_arab = FALSE; /* no arabic mode */
3347#endif
3348#ifdef FEAT_RIGHTLEFT
3349 curwin->w_p_rl = FALSE; /* help window is left-to-right */
3350#endif
3351#ifdef FEAT_FOLDING
3352 curwin->w_p_fen = FALSE; /* No folding in the help window */
3353#endif
3354#ifdef FEAT_DIFF
3355 curwin->w_p_diff = FALSE; /* No 'diff' */
3356#endif
Bram Moolenaara1956f62006-03-12 22:18:00 +00003357#ifdef FEAT_SPELL
Bram Moolenaar9a50b1b2005-06-27 22:48:21 +00003358 curwin->w_p_spell = FALSE; /* No spell checking */
3359#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360
3361#ifdef FEAT_AUTOCMD
3362 buf = curbuf;
3363#endif
3364 set_buflisted(FALSE);
3365 }
3366 else
3367 {
3368#ifdef FEAT_AUTOCMD
3369 buf = curbuf;
3370#endif
3371 /* Don't make a buffer listed if it's a help buffer. Useful when
3372 * using CTRL-O to go back to a help file. */
3373 if (!curbuf->b_help)
3374 set_buflisted(TRUE);
3375 }
3376
3377#ifdef FEAT_AUTOCMD
3378 /* If autocommands change buffers under our fingers, forget about
3379 * editing the file. */
3380 if (buf != curbuf)
3381 goto theend;
3382# ifdef FEAT_EVAL
3383 if (aborting()) /* autocmds may abort script processing */
3384 goto theend;
3385# endif
3386
3387 /* Since we are starting to edit a file, consider the filetype to be
3388 * unset. Helps for when an autocommand changes files and expects syntax
3389 * highlighting to work in the other file. */
3390 did_filetype = FALSE;
3391#endif
3392
3393/*
3394 * other_file oldbuf
3395 * FALSE FALSE re-edit same file, buffer is re-used
3396 * FALSE TRUE re-edit same file, nothing changes
3397 * TRUE FALSE start editing new file, new buffer
3398 * TRUE TRUE start editing in existing buffer (nothing to do)
3399 */
3400 if (!other_file && !oldbuf) /* re-use the buffer */
3401 {
3402 set_last_cursor(curwin); /* may set b_last_cursor */
3403 if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL)
3404 {
3405 newlnum = curwin->w_cursor.lnum;
3406 solcol = curwin->w_cursor.col;
3407 }
3408#ifdef FEAT_AUTOCMD
3409 buf = curbuf;
3410 if (buf->b_fname != NULL)
3411 new_name = vim_strsave(buf->b_fname);
3412 else
3413 new_name = NULL;
3414#endif
3415 buf_freeall(curbuf, FALSE, FALSE); /* free all things for buffer */
3416#ifdef FEAT_AUTOCMD
3417 /* If autocommands deleted the buffer we were going to re-edit, give
3418 * up and jump to the end. */
3419 if (!buf_valid(buf))
3420 {
3421 delbuf_msg(new_name); /* frees new_name */
3422 goto theend;
3423 }
3424 vim_free(new_name);
3425
3426 /* If autocommands change buffers under our fingers, forget about
3427 * re-editing the file. Should do the buf_clear_file(), but perhaps
3428 * the autocommands changed the buffer... */
3429 if (buf != curbuf)
3430 goto theend;
3431# ifdef FEAT_EVAL
3432 if (aborting()) /* autocmds may abort script processing */
3433 goto theend;
3434# endif
3435#endif
3436 buf_clear_file(curbuf);
3437 curbuf->b_op_start.lnum = 0; /* clear '[ and '] marks */
3438 curbuf->b_op_end.lnum = 0;
3439 }
3440
3441/*
3442 * If we get here we are sure to start editing
3443 */
3444 /* don't redraw until the cursor is in the right line */
3445 ++RedrawingDisabled;
3446
3447 /* Assume success now */
3448 retval = OK;
3449
3450 /*
3451 * Reset cursor position, could be used by autocommands.
3452 */
3453 check_cursor();
3454
3455 /*
3456 * Check if we are editing the w_arg_idx file in the argument list.
3457 */
3458 check_arg_idx(curwin);
3459
3460#ifdef FEAT_AUTOCMD
3461 if (!auto_buf)
3462#endif
3463 {
3464 /*
3465 * Set cursor and init window before reading the file and executing
3466 * autocommands. This allows for the autocommands to position the
3467 * cursor.
3468 */
Bram Moolenaarfaa959a2006-02-20 21:37:40 +00003469 curwin_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470
3471#ifdef FEAT_FOLDING
3472 /* It's like all lines in the buffer changed. Need to update
3473 * automatic folding. */
3474 foldUpdateAll(curwin);
3475#endif
3476
3477#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
3478 if (p_acd && curbuf->b_ffname != NULL
3479 && vim_chdirfile(curbuf->b_ffname) == OK)
3480 shorten_fnames(TRUE);
3481#endif
3482 /*
3483 * Careful: open_buffer() and apply_autocmds() may change the current
3484 * buffer and window.
3485 */
3486 lnum = curwin->w_cursor.lnum;
3487 topline = curwin->w_topline;
3488 if (!oldbuf) /* need to read the file */
3489 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003490#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491 swap_exists_action = SEA_DIALOG;
3492#endif
3493 curbuf->b_flags |= BF_CHECK_RO; /* set/reset 'ro' flag */
3494
3495 /*
3496 * Open the buffer and read the file.
3497 */
3498#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
3499 if (should_abort(open_buffer(FALSE, eap)))
3500 retval = FAIL;
3501#else
3502 (void)open_buffer(FALSE, eap);
3503#endif
3504
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003505#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 if (swap_exists_action == SEA_QUIT)
3507 retval = FAIL;
3508 handle_swap_exists(old_curbuf);
3509#endif
3510 }
3511#ifdef FEAT_AUTOCMD
3512 else
3513 {
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00003514 /* Read the modelines, but only to set window-local options. Any
3515 * buffer-local options have already been set and may have been
3516 * changed by the user. */
Bram Moolenaara3227e22006-03-08 21:32:40 +00003517 do_modelines(OPT_WINONLY);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00003518
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf,
3520 &retval);
3521 apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf,
3522 &retval);
3523 }
3524 check_arg_idx(curwin);
3525#endif
3526
3527 /*
3528 * If autocommands change the cursor position or topline, we should
3529 * keep it.
3530 */
3531 if (curwin->w_cursor.lnum != lnum)
3532 {
3533 newlnum = curwin->w_cursor.lnum;
3534 newcol = curwin->w_cursor.col;
3535 }
3536 if (curwin->w_topline == topline)
3537 topline = 0;
3538
3539 /* Even when cursor didn't move we need to recompute topline. */
3540 changed_line_abv_curs();
3541
3542#ifdef FEAT_TITLE
3543 maketitle();
3544#endif
3545 }
3546
3547#ifdef FEAT_DIFF
3548 /* Tell the diff stuff that this buffer is new and/or needs updating.
3549 * Also needed when re-editing the same buffer, because unloading will
3550 * have removed it as a diff buffer. */
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003551 if (curwin->w_p_diff)
3552 {
3553 diff_buf_add(curbuf);
3554 diff_invalidate(curbuf);
3555 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556#endif
3557
3558 if (command == NULL)
3559 {
3560 if (newcol >= 0) /* position set by autocommands */
3561 {
3562 curwin->w_cursor.lnum = newlnum;
3563 curwin->w_cursor.col = newcol;
3564 check_cursor();
3565 }
3566 else if (newlnum > 0) /* line number from caller or old position */
3567 {
3568 curwin->w_cursor.lnum = newlnum;
3569 check_cursor_lnum();
3570 if (solcol >= 0 && !p_sol)
3571 {
3572 /* 'sol' is off: Use last known column. */
3573 curwin->w_cursor.col = solcol;
3574 check_cursor_col();
3575#ifdef FEAT_VIRTUALEDIT
3576 curwin->w_cursor.coladd = 0;
3577#endif
3578 curwin->w_set_curswant = TRUE;
3579 }
3580 else
3581 beginline(BL_SOL | BL_FIX);
3582 }
3583 else /* no line number, go to last line in Ex mode */
3584 {
3585 if (exmode_active)
3586 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3587 beginline(BL_WHITE | BL_FIX);
3588 }
3589 }
3590
3591#ifdef FEAT_WINDOWS
3592 /* Check if cursors in other windows on the same buffer are still valid */
3593 check_lnums(FALSE);
3594#endif
3595
3596 /*
3597 * Did not read the file, need to show some info about the file.
3598 * Do this after setting the cursor.
3599 */
3600 if (oldbuf
3601#ifdef FEAT_AUTOCMD
3602 && !auto_buf
3603#endif
3604 )
3605 {
3606 int msg_scroll_save = msg_scroll;
3607
3608 /* Obey the 'O' flag in 'cpoptions': overwrite any previous file
3609 * message. */
3610 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
3611 msg_scroll = FALSE;
3612 if (!msg_scroll) /* wait a bit when overwriting an error msg */
3613 check_for_delay(FALSE);
3614 msg_start();
3615 msg_scroll = msg_scroll_save;
3616 msg_scrolled_ign = TRUE;
3617
3618 fileinfo(FALSE, TRUE, FALSE);
3619
3620 msg_scrolled_ign = FALSE;
3621 }
3622
3623 if (command != NULL)
3624 do_cmdline(command, NULL, NULL, DOCMD_VERBOSE);
3625
3626#ifdef FEAT_KEYMAP
3627 if (curbuf->b_kmap_state & KEYMAP_INIT)
3628 keymap_init();
3629#endif
3630
3631 --RedrawingDisabled;
3632 if (!skip_redraw)
3633 {
3634 n = p_so;
3635 if (topline == 0 && command == NULL)
3636 p_so = 999; /* force cursor halfway the window */
3637 update_topline();
3638#ifdef FEAT_SCROLLBIND
3639 curwin->w_scbind_pos = curwin->w_topline;
3640#endif
3641 p_so = n;
3642 redraw_curbuf_later(NOT_VALID); /* redraw this buffer later */
3643 }
3644
3645 if (p_im)
3646 need_start_insertmode = TRUE;
3647
3648#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
3649 /* Change directories when the acd option is set on. */
3650 if (p_acd && curbuf->b_ffname != NULL
3651 && vim_chdirfile(curbuf->b_ffname) == OK)
3652 shorten_fnames(TRUE);
3653
3654 if (gui.in_use && curbuf->b_ffname != NULL)
3655 {
3656# ifdef FEAT_SUN_WORKSHOP
3657 if (usingSunWorkShop)
3658 workshop_file_opened((char *)curbuf->b_ffname, curbuf->b_p_ro);
3659# endif
3660# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003661 if (usingNetbeans & ((flags & ECMD_SET_HELP) != ECMD_SET_HELP))
3662 netbeans_file_opened(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663# endif
3664 }
3665#endif
3666
3667theend:
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00003668#ifdef FEAT_AUTOCMD
3669 if (did_set_swapcommand)
3670 set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
3671#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003672#ifdef FEAT_BROWSE
3673 vim_free(browse_file);
3674#endif
3675 vim_free(free_fname);
3676 return retval;
3677}
3678
3679#ifdef FEAT_AUTOCMD
3680 static void
3681delbuf_msg(name)
3682 char_u *name;
3683{
3684 EMSG2(_("E143: Autocommands unexpectedly deleted new buffer %s"),
3685 name == NULL ? (char_u *)"" : name);
3686 vim_free(name);
3687 au_new_curbuf = NULL;
3688}
3689#endif
3690
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003691static int append_indent = 0; /* autoindent for first line */
3692
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693/*
3694 * ":insert" and ":append", also used by ":change"
3695 */
3696 void
3697ex_append(eap)
3698 exarg_T *eap;
3699{
3700 char_u *theline;
3701 int did_undo = FALSE;
3702 linenr_T lnum = eap->line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003703 int indent = 0;
3704 char_u *p;
3705 int vcol;
3706 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003708 /* the ! flag toggles autoindent */
3709 if (eap->forceit)
3710 curbuf->b_p_ai = !curbuf->b_p_ai;
3711
3712 /* First autoindent comes from the line we start on */
3713 if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0)
3714 append_indent = get_indent_lnum(lnum);
3715
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716 if (eap->cmdidx != CMD_append)
3717 --lnum;
3718
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003719 /* when the buffer is empty append to line 0 and delete the dummy line */
3720 if (empty && lnum == 1)
3721 lnum = 0;
3722
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 State = INSERT; /* behave like in Insert mode */
3724 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
3725 State |= LANGMAP;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003726
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00003727 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728 {
3729 msg_scroll = TRUE;
3730 need_wait_return = FALSE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003731 if (curbuf->b_p_ai)
3732 {
3733 if (append_indent >= 0)
3734 {
3735 indent = append_indent;
3736 append_indent = -1;
3737 }
3738 else if (lnum > 0)
3739 indent = get_indent_lnum(lnum);
3740 }
3741 ex_keep_indent = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 if (eap->getline == NULL)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003743 {
3744 /* No getline() function, use the lines that follow. This ends
3745 * when there is no more. */
3746 if (eap->nextcmd == NULL || *eap->nextcmd == NUL)
3747 break;
3748 p = vim_strchr(eap->nextcmd, NL);
3749 if (p == NULL)
3750 p = eap->nextcmd + STRLEN(eap->nextcmd);
3751 theline = vim_strnsave(eap->nextcmd, (int)(p - eap->nextcmd));
3752 if (*p != NUL)
3753 ++p;
3754 eap->nextcmd = p;
3755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 else
3757 theline = eap->getline(
3758#ifdef FEAT_EVAL
Bram Moolenaar3d60ec22005-01-05 22:19:46 +00003759 eap->cstack->cs_looplevel > 0 ? -1 :
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760#endif
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003761 NUL, eap->cookie, indent);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 lines_left = Rows - 1;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003763 if (theline == NULL)
3764 break;
3765
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003766 /* Using ^ CTRL-D in getexmodeline() makes us repeat the indent. */
3767 if (ex_keep_indent)
3768 append_indent = indent;
3769
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003770 /* Look for the "." after automatic indent. */
3771 vcol = 0;
3772 for (p = theline; indent > vcol; ++p)
3773 {
3774 if (*p == ' ')
3775 ++vcol;
3776 else if (*p == TAB)
3777 vcol += 8 - vcol % 8;
3778 else
3779 break;
3780 }
3781 if ((p[0] == '.' && p[1] == NUL)
Bram Moolenaareaa48e72005-06-08 22:07:37 +00003782 || (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0))
3783 == FAIL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 {
3785 vim_free(theline);
3786 break;
3787 }
3788
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003789 /* don't use autoindent if nothing was typed. */
3790 if (p[0] == NUL)
3791 theline[0] = NUL;
3792
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 did_undo = TRUE;
3794 ml_append(lnum, theline, (colnr_T)0, FALSE);
3795 appended_lines_mark(lnum, 1L);
3796
3797 vim_free(theline);
3798 ++lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003799
3800 if (empty)
3801 {
3802 ml_delete(2L, FALSE);
3803 empty = FALSE;
3804 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805 }
3806 State = NORMAL;
3807
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003808 if (eap->forceit)
3809 curbuf->b_p_ai = !curbuf->b_p_ai;
3810
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 /* "start" is set to eap->line2+1 unless that position is invalid (when
3812 * eap->line2 pointed to the end of the buffer and nothig was appended)
3813 * "end" is set to lnum when something has been appended, otherwise
3814 * it is the same than "start" -- Acevedo */
3815 curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
3816 eap->line2 + 1 : curbuf->b_ml.ml_line_count;
3817 if (eap->cmdidx != CMD_append)
3818 --curbuf->b_op_start.lnum;
3819 curbuf->b_op_end.lnum = (eap->line2 < lnum)
3820 ? lnum : curbuf->b_op_start.lnum;
3821 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
3822 curwin->w_cursor.lnum = lnum;
3823 check_cursor_lnum();
3824 beginline(BL_SOL | BL_FIX);
3825
3826 need_wait_return = FALSE; /* don't use wait_return() now */
3827 ex_no_reprint = TRUE;
3828}
3829
3830/*
3831 * ":change"
3832 */
3833 void
3834ex_change(eap)
3835 exarg_T *eap;
3836{
3837 linenr_T lnum;
3838
3839 if (eap->line2 >= eap->line1
3840 && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
3841 return;
3842
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003843 /* the ! flag toggles autoindent */
3844 if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai)
3845 append_indent = get_indent_lnum(eap->line1);
3846
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 for (lnum = eap->line2; lnum >= eap->line1; --lnum)
3848 {
3849 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
3850 break;
3851 ml_delete(eap->line1, FALSE);
3852 }
3853 deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum));
3854
3855 /* ":append" on the line above the deleted lines. */
3856 eap->line2 = eap->line1;
3857 ex_append(eap);
3858}
3859
3860 void
3861ex_z(eap)
3862 exarg_T *eap;
3863{
3864 char_u *x;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003865 int bigness;
3866 char_u *kind;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 int minus = 0;
3868 linenr_T start, end, curs, i;
3869 int j;
3870 linenr_T lnum = eap->line2;
3871
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003872 /* Vi compatible: ":z!" uses display height, without a count uses
3873 * 'scroll' */
3874 if (eap->forceit)
3875 bigness = curwin->w_height;
3876 else if (firstwin == lastwin)
3877 bigness = curwin->w_p_scr * 2;
3878 else
3879 bigness = curwin->w_height - 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880 if (bigness < 1)
3881 bigness = 1;
3882
3883 x = eap->arg;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003884 kind = x;
3885 if (*kind == '-' || *kind == '+' || *kind == '='
3886 || *kind == '^' || *kind == '.')
3887 ++x;
3888 while (*x == '-' || *x == '+')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889 ++x;
3890
3891 if (*x != 0)
3892 {
3893 if (!VIM_ISDIGIT(*x))
3894 {
3895 EMSG(_("E144: non-numeric argument to :z"));
3896 return;
3897 }
3898 else
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003899 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900 bigness = atoi((char *)x);
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003901 p_window = bigness;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003902 if (*kind == '=')
3903 bigness += 2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003904 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 }
3906
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003907 /* the number of '-' and '+' multiplies the distance */
3908 if (*kind == '-' || *kind == '+')
3909 for (x = kind + 1; *x == *kind; ++x)
3910 ;
3911
3912 switch (*kind)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 {
3914 case '-':
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003915 start = lnum - bigness * (x - kind);
3916 end = start + bigness;
3917 curs = end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 break;
3919
3920 case '=':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003921 start = lnum - (bigness + 1) / 2 + 1;
3922 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 curs = lnum;
3924 minus = 1;
3925 break;
3926
3927 case '^':
3928 start = lnum - bigness * 2;
3929 end = lnum - bigness;
3930 curs = lnum - bigness;
3931 break;
3932
3933 case '.':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003934 start = lnum - (bigness + 1) / 2 + 1;
3935 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936 curs = end;
3937 break;
3938
3939 default: /* '+' */
3940 start = lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003941 if (*kind == '+')
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003942 start += bigness * (x - kind - 1) + 1;
3943 else if (eap->addr_count == 0)
3944 ++start;
3945 end = start + bigness - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 curs = end;
3947 break;
3948 }
3949
3950 if (start < 1)
3951 start = 1;
3952
3953 if (end > curbuf->b_ml.ml_line_count)
3954 end = curbuf->b_ml.ml_line_count;
3955
3956 if (curs > curbuf->b_ml.ml_line_count)
3957 curs = curbuf->b_ml.ml_line_count;
3958
3959 for (i = start; i <= end; i++)
3960 {
3961 if (minus && i == lnum)
3962 {
3963 msg_putchar('\n');
3964
3965 for (j = 1; j < Columns; j++)
3966 msg_putchar('-');
3967 }
3968
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003969 print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970
3971 if (minus && i == lnum)
3972 {
3973 msg_putchar('\n');
3974
3975 for (j = 1; j < Columns; j++)
3976 msg_putchar('-');
3977 }
3978 }
3979
3980 curwin->w_cursor.lnum = curs;
3981 ex_no_reprint = TRUE;
3982}
3983
3984/*
3985 * Check if the restricted flag is set.
3986 * If so, give an error message and return TRUE.
3987 * Otherwise, return FALSE.
3988 */
3989 int
3990check_restricted()
3991{
3992 if (restricted)
3993 {
3994 EMSG(_("E145: Shell commands not allowed in rvim"));
3995 return TRUE;
3996 }
3997 return FALSE;
3998}
3999
4000/*
4001 * Check if the secure flag is set (.exrc or .vimrc in current directory).
4002 * If so, give an error message and return TRUE.
4003 * Otherwise, return FALSE.
4004 */
4005 int
4006check_secure()
4007{
4008 if (secure)
4009 {
4010 secure = 2;
4011 EMSG(_(e_curdir));
4012 return TRUE;
4013 }
4014#ifdef HAVE_SANDBOX
4015 /*
4016 * In the sandbox more things are not allowed, including the things
4017 * disallowed in secure mode.
4018 */
4019 if (sandbox != 0)
4020 {
4021 EMSG(_(e_sandbox));
4022 return TRUE;
4023 }
4024#endif
4025 return FALSE;
4026}
4027
4028static char_u *old_sub = NULL; /* previous substitute pattern */
4029static int global_need_beginline; /* call beginline() after ":g" */
4030
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031/* do_sub()
4032 *
4033 * Perform a substitution from line eap->line1 to line eap->line2 using the
4034 * command pointed to by eap->arg which should be of the form:
4035 *
4036 * /pattern/substitution/{flags}
4037 *
4038 * The usual escapes are supported as described in the regexp docs.
4039 */
4040 void
4041do_sub(eap)
4042 exarg_T *eap;
4043{
4044 linenr_T lnum;
4045 long i = 0;
4046 regmmatch_T regmatch;
4047 static int do_all = FALSE; /* do multiple substitutions per line */
4048 static int do_ask = FALSE; /* ask for confirmation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004049 static int do_count = FALSE; /* count only */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 static int do_error = TRUE; /* if false, ignore errors */
4051 static int do_print = FALSE; /* print last line with subs. */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004052 static int do_list = FALSE; /* list last line with subs. */
4053 static int do_number = FALSE; /* list last line with line nr*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 static int do_ic = 0; /* ignore case flag */
4055 char_u *pat = NULL, *sub = NULL; /* init for GCC */
4056 int delimiter;
4057 int sublen;
4058 int got_quit = FALSE;
4059 int got_match = FALSE;
4060 int temp;
4061 int which_pat;
4062 char_u *cmd;
4063 int save_State;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00004064 linenr_T first_line = 0; /* first changed line */
4065 linenr_T last_line= 0; /* below last changed line AFTER the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004066 * change */
4067 linenr_T old_line_count = curbuf->b_ml.ml_line_count;
4068 linenr_T line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00004069 long nmatch; /* number of lines in match */
4070 linenr_T sub_firstlnum; /* nr of first sub line */
4071 char_u *sub_firstline; /* allocated copy of first sub line */
4072 int endcolumn = FALSE; /* cursor in last column when done */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004073 pos_T old_cursor = curwin->w_cursor;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074
4075 cmd = eap->arg;
4076 if (!global_busy)
4077 {
4078 sub_nsubs = 0;
4079 sub_nlines = 0;
4080 }
4081
4082#ifdef FEAT_FKMAP /* reverse the flow of the Farsi characters */
4083 if (p_altkeymap && curwin->w_p_rl)
4084 lrF_sub(cmd);
4085#endif
4086
4087 if (eap->cmdidx == CMD_tilde)
4088 which_pat = RE_LAST; /* use last used regexp */
4089 else
4090 which_pat = RE_SUBST; /* use last substitute regexp */
4091
4092 /* new pattern and substitution */
4093 if (eap->cmd[0] == 's' && *cmd != NUL && !vim_iswhite(*cmd)
4094 && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
4095 {
4096 /* don't accept alphanumeric for separator */
4097 if (isalpha(*cmd))
4098 {
4099 EMSG(_("E146: Regular expressions can't be delimited by letters"));
4100 return;
4101 }
4102 /*
4103 * undocumented vi feature:
4104 * "\/sub/" and "\?sub?" use last used search pattern (almost like
4105 * //sub/r). "\&sub&" use last substitute pattern (like //sub/).
4106 */
4107 if (*cmd == '\\')
4108 {
4109 ++cmd;
4110 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
4111 {
4112 EMSG(_(e_backslash));
4113 return;
4114 }
4115 if (*cmd != '&')
4116 which_pat = RE_SEARCH; /* use last '/' pattern */
4117 pat = (char_u *)""; /* empty search pattern */
4118 delimiter = *cmd++; /* remember delimiter character */
4119 }
4120 else /* find the end of the regexp */
4121 {
4122 which_pat = RE_LAST; /* use last used regexp */
4123 delimiter = *cmd++; /* remember delimiter character */
4124 pat = cmd; /* remember start of search pat */
4125 cmd = skip_regexp(cmd, delimiter, p_magic, &eap->arg);
4126 if (cmd[0] == delimiter) /* end delimiter found */
4127 *cmd++ = NUL; /* replace it with a NUL */
4128 }
4129
4130 /*
4131 * Small incompatibility: vi sees '\n' as end of the command, but in
4132 * Vim we want to use '\n' to find/substitute a NUL.
4133 */
4134 sub = cmd; /* remember the start of the substitution */
4135
4136 while (cmd[0])
4137 {
4138 if (cmd[0] == delimiter) /* end delimiter found */
4139 {
4140 *cmd++ = NUL; /* replace it with a NUL */
4141 break;
4142 }
4143 if (cmd[0] == '\\' && cmd[1] != 0) /* skip escaped characters */
4144 ++cmd;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004145 mb_ptr_adv(cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 }
4147
4148 if (!eap->skip)
4149 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004150 /* In POSIX vi ":s/pat/%/" uses the previous subst. string. */
4151 if (STRCMP(sub, "%") == 0
4152 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
4153 {
4154 if (old_sub == NULL) /* there is no previous command */
4155 {
4156 EMSG(_(e_nopresub));
4157 return;
4158 }
4159 sub = old_sub;
4160 }
4161 else
4162 {
4163 vim_free(old_sub);
4164 old_sub = vim_strsave(sub);
4165 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 }
4167 }
4168 else if (!eap->skip) /* use previous pattern and substitution */
4169 {
4170 if (old_sub == NULL) /* there is no previous command */
4171 {
4172 EMSG(_(e_nopresub));
4173 return;
4174 }
4175 pat = NULL; /* search_regcomp() will use previous pattern */
4176 sub = old_sub;
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004177
4178 /* Vi compatibility quirk: repeating with ":s" keeps the cursor in the
4179 * last column after using "$". */
4180 endcolumn = (curwin->w_curswant == MAXCOL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 }
4182
4183 /*
4184 * Find trailing options. When '&' is used, keep old options.
4185 */
4186 if (*cmd == '&')
4187 ++cmd;
4188 else
4189 {
4190 if (!p_ed)
4191 {
4192 if (p_gd) /* default is global on */
4193 do_all = TRUE;
4194 else
4195 do_all = FALSE;
4196 do_ask = FALSE;
4197 }
4198 do_error = TRUE;
4199 do_print = FALSE;
Bram Moolenaarcc016f52005-12-10 20:23:46 +00004200 do_count = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 do_ic = 0;
4202 }
4203 while (*cmd)
4204 {
4205 /*
4206 * Note that 'g' and 'c' are always inverted, also when p_ed is off.
4207 * 'r' is never inverted.
4208 */
4209 if (*cmd == 'g')
4210 do_all = !do_all;
4211 else if (*cmd == 'c')
4212 do_ask = !do_ask;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004213 else if (*cmd == 'n')
4214 do_count = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215 else if (*cmd == 'e')
4216 do_error = !do_error;
4217 else if (*cmd == 'r') /* use last used regexp */
4218 which_pat = RE_LAST;
4219 else if (*cmd == 'p')
4220 do_print = TRUE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004221 else if (*cmd == '#')
4222 {
4223 do_print = TRUE;
4224 do_number = TRUE;
4225 }
4226 else if (*cmd == 'l')
4227 {
4228 do_print = TRUE;
4229 do_list = TRUE;
4230 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 else if (*cmd == 'i') /* ignore case */
4232 do_ic = 'i';
4233 else if (*cmd == 'I') /* don't ignore case */
4234 do_ic = 'I';
4235 else
4236 break;
4237 ++cmd;
4238 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00004239 if (do_count)
4240 do_ask = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241
4242 /*
4243 * check for a trailing count
4244 */
4245 cmd = skipwhite(cmd);
4246 if (VIM_ISDIGIT(*cmd))
4247 {
4248 i = getdigits(&cmd);
4249 if (i <= 0 && !eap->skip && do_error)
4250 {
4251 EMSG(_(e_zerocount));
4252 return;
4253 }
4254 eap->line1 = eap->line2;
4255 eap->line2 += i - 1;
4256 if (eap->line2 > curbuf->b_ml.ml_line_count)
4257 eap->line2 = curbuf->b_ml.ml_line_count;
4258 }
4259
4260 /*
4261 * check for trailing command or garbage
4262 */
4263 cmd = skipwhite(cmd);
4264 if (*cmd && *cmd != '"') /* if not end-of-line or comment */
4265 {
4266 eap->nextcmd = check_nextcmd(cmd);
4267 if (eap->nextcmd == NULL)
4268 {
4269 EMSG(_(e_trailing));
4270 return;
4271 }
4272 }
4273
4274 if (eap->skip) /* not executing commands, only parsing */
4275 return;
4276
4277 if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4278 {
4279 if (do_error)
4280 EMSG(_(e_invcmd));
4281 return;
4282 }
4283
4284 /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
4285 if (do_ic == 'i')
4286 regmatch.rmm_ic = TRUE;
4287 else if (do_ic == 'I')
4288 regmatch.rmm_ic = FALSE;
4289
4290 sub_firstline = NULL;
4291
4292 /*
4293 * ~ in the substitute pattern is replaced with the old pattern.
4294 * We do it here once to avoid it to be replaced over and over again.
4295 * But don't do it when it starts with "\=", then it's an expression.
4296 */
4297 if (!(sub[0] == '\\' && sub[1] == '='))
4298 sub = regtilde(sub, p_magic);
4299
4300 /*
4301 * Check for a match on each line.
4302 */
4303 line2 = eap->line2;
4304 for (lnum = eap->line1; lnum <= line2 && !(got_quit
4305#if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
4306 || aborting()
4307#endif
4308 ); ++lnum)
4309 {
4310 sub_firstlnum = lnum;
4311 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
4312 if (nmatch)
4313 {
4314 colnr_T copycol;
4315 colnr_T matchcol;
4316 colnr_T prev_matchcol = MAXCOL;
4317 char_u *new_end, *new_start = NULL;
4318 unsigned new_start_len = 0;
4319 char_u *p1;
4320 int did_sub = FALSE;
4321 int lastone;
4322 unsigned len, needed_len;
4323 long nmatch_tl = 0; /* nr of lines matched below lnum */
4324 int do_again; /* do it again after joining lines */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004325 int skip_match = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326
4327 /*
4328 * The new text is build up step by step, to avoid too much
4329 * copying. There are these pieces:
4330 * sub_firstline The old text, unmodifed.
4331 * copycol Column in the old text where we started
4332 * looking for a match; from here old text still
4333 * needs to be copied to the new text.
4334 * matchcol Column number of the old text where to look
4335 * for the next match. It's just after the
4336 * previous match or one further.
4337 * prev_matchcol Column just after the previous match (if any).
4338 * Mostly equal to matchcol, except for the first
4339 * match and after skipping an empty match.
4340 * regmatch.*pos Where the pattern matched in the old text.
4341 * new_start The new text, all that has been produced so
4342 * far.
4343 * new_end The new text, where to append new text.
4344 *
4345 * lnum The line number where we were looking for the
4346 * first match in the old line.
4347 * sub_firstlnum The line number in the buffer where to look
4348 * for a match. Can be different from "lnum"
4349 * when the pattern or substitute string contains
4350 * line breaks.
4351 *
4352 * Special situations:
4353 * - When the substitute string contains a line break, the part up
4354 * to the line break is inserted in the text, but the copy of
4355 * the original line is kept. "sub_firstlnum" is adjusted for
4356 * the inserted lines.
4357 * - When the matched pattern contains a line break, the old line
4358 * is taken from the line at the end of the pattern. The lines
4359 * in the match are deleted later, "sub_firstlnum" is adjusted
4360 * accordingly.
4361 *
4362 * The new text is built up in new_start[]. It has some extra
4363 * room to avoid using alloc()/free() too often. new_start_len is
4364 * the lenght of the allocated memory at new_start.
4365 *
4366 * Make a copy of the old line, so it won't be taken away when
4367 * updating the screen or handling a multi-line match. The "old_"
4368 * pointers point into this copy.
4369 */
4370 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4371 if (sub_firstline == NULL)
4372 {
4373 vim_free(new_start);
4374 goto outofmem;
4375 }
4376 copycol = 0;
4377 matchcol = 0;
4378
4379 /* At first match, remember current cursor position. */
4380 if (!got_match)
4381 {
4382 setpcmark();
4383 got_match = TRUE;
4384 }
4385
4386 /*
4387 * Loop until nothing more to replace in this line.
4388 * 1. Handle match with empty string.
4389 * 2. If do_ask is set, ask for confirmation.
4390 * 3. substitute the string.
4391 * 4. if do_all is set, find next match
4392 * 5. break if there isn't another match in this line
4393 */
4394 for (;;)
4395 {
4396 /* Save the line number of the last change for the final
4397 * cursor position (just like Vi). */
4398 curwin->w_cursor.lnum = lnum;
4399 do_again = FALSE;
4400
4401 /*
4402 * 1. Match empty string does not count, except for first
4403 * match. This reproduces the strange vi behaviour.
4404 * This also catches endless loops.
4405 */
4406 if (matchcol == prev_matchcol
4407 && regmatch.endpos[0].lnum == 0
4408 && matchcol == regmatch.endpos[0].col)
4409 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00004410 if (sub_firstline[matchcol] == NUL)
4411 /* We already were at the end of the line. Don't look
4412 * for a match in this line again. */
4413 skip_match = TRUE;
4414 else
4415 ++matchcol; /* search for a match at next column */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 goto skip;
4417 }
4418
4419 /* Normally we continue searching for a match just after the
4420 * previous match. */
4421 matchcol = regmatch.endpos[0].col;
4422 prev_matchcol = matchcol;
4423
4424 /*
Bram Moolenaar05159a02005-02-26 23:04:13 +00004425 * 2. If do_count is set only increase the counter.
4426 * If do_ask is set, ask for confirmation.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004428 if (do_count)
4429 {
4430 /* For a multi-line match, put matchcol at the NUL at
4431 * the end of the line and set nmatch to one, so that
4432 * we continue looking for a match on the next line.
4433 * Avoids that ":s/\nB\@=//gc" get stuck. */
4434 if (nmatch > 1)
4435 {
4436 matchcol = STRLEN(sub_firstline);
4437 nmatch = 1;
4438 }
4439 sub_nsubs++;
4440 did_sub = TRUE;
4441 goto skip;
4442 }
4443
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 if (do_ask)
4445 {
4446 /* change State to CONFIRM, so that the mouse works
4447 * properly */
4448 save_State = State;
4449 State = CONFIRM;
4450#ifdef FEAT_MOUSE
4451 setmouse(); /* disable mouse in xterm */
4452#endif
4453 curwin->w_cursor.col = regmatch.startpos[0].col;
4454
4455 /* When 'cpoptions' contains "u" don't sync undo when
4456 * asking for confirmation. */
4457 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4458 ++no_u_sync;
4459
4460 /*
4461 * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
4462 */
4463 while (do_ask)
4464 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004465 if (exmode_active)
4466 {
4467 char_u *resp;
4468 colnr_T sc, ec;
4469
4470 print_line_no_prefix(lnum, FALSE, FALSE);
4471
4472 getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
4473 curwin->w_cursor.col = regmatch.endpos[0].col - 1;
4474 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
4475 msg_start();
Bram Moolenaar05159a02005-02-26 23:04:13 +00004476 for (i = 0; i < (long)sc; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004477 msg_putchar(' ');
Bram Moolenaar05159a02005-02-26 23:04:13 +00004478 for ( ; i <= (long)ec; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004479 msg_putchar('^');
4480
4481 resp = getexmodeline('?', NULL, 0);
4482 if (resp != NULL)
4483 {
4484 i = *resp;
4485 vim_free(resp);
4486 }
4487 }
4488 else
4489 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004491 int save_p_fen = curwin->w_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004493 curwin->w_p_fen = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004494#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004495 /* Invert the matched string.
4496 * Remove the inversion afterwards. */
4497 temp = RedrawingDisabled;
4498 RedrawingDisabled = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004500 search_match_lines = regmatch.endpos[0].lnum;
4501 search_match_endcol = regmatch.endpos[0].col;
4502 highlight_match = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004504 update_topline();
4505 validate_cursor();
Bram Moolenaara1956f62006-03-12 22:18:00 +00004506 update_screen(SOME_VALID);
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004507 highlight_match = FALSE;
Bram Moolenaara1956f62006-03-12 22:18:00 +00004508 redraw_later(SOME_VALID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509
4510#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004511 curwin->w_p_fen = save_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004513 if (msg_row == Rows - 1)
4514 msg_didout = FALSE; /* avoid a scroll-up */
4515 msg_starthere();
4516 i = msg_scroll;
4517 msg_scroll = 0; /* truncate msg when
4518 needed */
4519 msg_no_more = TRUE;
4520 /* write message same highlighting as for
4521 * wait_return */
4522 smsg_attr(hl_attr(HLF_R),
4523 (char_u *)_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
4524 msg_no_more = FALSE;
4525 msg_scroll = i;
4526 showruler(TRUE);
4527 windgoto(msg_row, msg_col);
4528 RedrawingDisabled = temp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529
4530#ifdef USE_ON_FLY_SCROLL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004531 dont_scroll = FALSE; /* allow scrolling here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004533 ++no_mapping; /* don't map this key */
4534 ++allow_keys; /* allow special keys */
4535 i = safe_vgetc();
4536 --allow_keys;
4537 --no_mapping;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004539 /* clear the question */
4540 msg_didout = FALSE; /* don't scroll up */
4541 msg_col = 0;
4542 gotocmdline(TRUE);
4543 }
4544
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 need_wait_return = FALSE; /* no hit-return prompt */
4546 if (i == 'q' || i == ESC || i == Ctrl_C
4547#ifdef UNIX
4548 || i == intr_char
4549#endif
4550 )
4551 {
4552 got_quit = TRUE;
4553 break;
4554 }
4555 if (i == 'n')
4556 break;
4557 if (i == 'y')
4558 break;
4559 if (i == 'l')
4560 {
4561 /* last: replace and then stop */
4562 do_all = FALSE;
4563 line2 = lnum;
4564 break;
4565 }
4566 if (i == 'a')
4567 {
4568 do_ask = FALSE;
4569 break;
4570 }
4571#ifdef FEAT_INS_EXPAND
4572 if (i == Ctrl_E)
4573 scrollup_clamp();
4574 else if (i == Ctrl_Y)
4575 scrolldown_clamp();
4576#endif
4577 }
4578 State = save_State;
4579#ifdef FEAT_MOUSE
4580 setmouse();
4581#endif
4582 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4583 --no_u_sync;
4584
4585 if (i == 'n')
4586 {
4587 /* For a multi-line match, put matchcol at the NUL at
4588 * the end of the line and set nmatch to one, so that
4589 * we continue looking for a match on the next line.
4590 * Avoids that ":s/\nB\@=//gc" get stuck. */
4591 if (nmatch > 1)
4592 {
4593 matchcol = STRLEN(sub_firstline);
4594 nmatch = 1;
4595 }
4596 goto skip;
4597 }
4598 if (got_quit)
4599 break;
4600 }
4601
4602 /* Move the cursor to the start of the match, so that we can
4603 * use "\=col("."). */
4604 curwin->w_cursor.col = regmatch.startpos[0].col;
4605
4606 /*
4607 * 3. substitute the string.
4608 */
4609 /* get length of substitution part */
4610 sublen = vim_regsub_multi(&regmatch, sub_firstlnum,
4611 sub, sub_firstline, FALSE, p_magic, TRUE);
4612
Bram Moolenaar4463f292005-09-25 22:20:24 +00004613 /* When the match included the "$" of the last line it may
4614 * include one line too much. */
4615 if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)
4616 {
4617 nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
4618 skip_match = TRUE;
4619 }
4620
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 /* Need room for:
4622 * - result so far in new_start (not for first sub in line)
4623 * - original text up to match
4624 * - length of substituted part
4625 * - original text after match
4626 */
4627 if (nmatch == 1)
4628 p1 = sub_firstline;
4629 else
4630 {
4631 p1 = ml_get(sub_firstlnum + nmatch - 1);
4632 nmatch_tl += nmatch - 1;
4633 }
4634 i = regmatch.startpos[0].col - copycol;
4635 needed_len = i + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col)
4636 + sublen + 1;
4637 if (new_start == NULL)
4638 {
4639 /*
4640 * Get some space for a temporary buffer to do the
4641 * substitution into (and some extra space to avoid
4642 * too many calls to alloc()/free()).
4643 */
4644 new_start_len = needed_len + 50;
4645 if ((new_start = alloc_check(new_start_len)) == NULL)
4646 goto outofmem;
4647 *new_start = NUL;
4648 new_end = new_start;
4649 }
4650 else
4651 {
4652 /*
4653 * Check if the temporary buffer is long enough to do the
4654 * substitution into. If not, make it larger (with a bit
4655 * extra to avoid too many calls to alloc()/free()).
4656 */
4657 len = (unsigned)STRLEN(new_start);
4658 needed_len += len;
4659 if (needed_len > new_start_len)
4660 {
4661 new_start_len = needed_len + 50;
4662 if ((p1 = alloc_check(new_start_len)) == NULL)
4663 {
4664 vim_free(new_start);
4665 goto outofmem;
4666 }
4667 mch_memmove(p1, new_start, (size_t)(len + 1));
4668 vim_free(new_start);
4669 new_start = p1;
4670 }
4671 new_end = new_start + len;
4672 }
4673
4674 /*
4675 * copy the text up to the part that matched
4676 */
4677 mch_memmove(new_end, sub_firstline + copycol, (size_t)i);
4678 new_end += i;
4679
4680 (void)vim_regsub_multi(&regmatch, sub_firstlnum,
4681 sub, new_end, TRUE, p_magic, TRUE);
4682 sub_nsubs++;
4683 did_sub = TRUE;
4684
4685 /* Move the cursor to the start of the line, to avoid that it
4686 * is beyond the end of the line after the substitution. */
4687 curwin->w_cursor.col = 0;
4688
4689 /* For a multi-line match, make a copy of the last matched
4690 * line and continue in that one. */
4691 if (nmatch > 1)
4692 {
4693 sub_firstlnum += nmatch - 1;
4694 vim_free(sub_firstline);
4695 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4696 /* When going beyond the last line, stop substituting. */
4697 if (sub_firstlnum <= line2)
4698 do_again = TRUE;
4699 else
4700 do_all = FALSE;
4701 }
4702
4703 /* Remember next character to be copied. */
4704 copycol = regmatch.endpos[0].col;
4705
4706 /*
4707 * Now the trick is to replace CTRL-M chars with a real line
4708 * break. This would make it impossible to insert a CTRL-M in
4709 * the text. The line break can be avoided by preceding the
4710 * CTRL-M with a backslash. To be able to insert a backslash,
4711 * they must be doubled in the string and are halved here.
4712 * That is Vi compatible.
4713 */
4714 for (p1 = new_end; *p1; ++p1)
4715 {
4716 if (p1[0] == '\\' && p1[1] != NUL) /* remove backslash */
4717 mch_memmove(p1, p1 + 1, STRLEN(p1));
4718 else if (*p1 == CAR)
4719 {
4720 if (u_inssub(lnum) == OK) /* prepare for undo */
4721 {
4722 *p1 = NUL; /* truncate up to the CR */
4723 ml_append(lnum - 1, new_start,
4724 (colnr_T)(p1 - new_start + 1), FALSE);
4725 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
4726 if (do_ask)
4727 appended_lines(lnum - 1, 1L);
4728 else
4729 {
4730 if (first_line == 0)
4731 first_line = lnum;
4732 last_line = lnum + 1;
4733 }
4734 /* All line numbers increase. */
4735 ++sub_firstlnum;
4736 ++lnum;
4737 ++line2;
4738 /* move the cursor to the new line, like Vi */
4739 ++curwin->w_cursor.lnum;
4740 STRCPY(new_start, p1 + 1); /* copy the rest */
4741 p1 = new_start - 1;
4742 }
4743 }
4744#ifdef FEAT_MBYTE
4745 else if (has_mbyte)
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004746 p1 += (*mb_ptr2len)(p1) - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747#endif
4748 }
4749
4750 /*
4751 * 4. If do_all is set, find next match.
4752 * Prevent endless loop with patterns that match empty
4753 * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
4754 * But ":s/\n/#/" is OK.
4755 */
4756skip:
4757 /* We already know that we did the last subst when we are at
4758 * the end of the line, except that a pattern like
4759 * "bar\|\nfoo" may match at the NUL. */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004760 lastone = (skip_match
4761 || got_int
4762 || got_quit
4763 || !(do_all || do_again)
4764 || (sub_firstline[matchcol] == NUL && nmatch <= 1
4765 && !re_multiline(regmatch.regprog)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 nmatch = -1;
4767
4768 /*
4769 * Replace the line in the buffer when needed. This is
4770 * skipped when there are more matches.
4771 * The check for nmatch_tl is needed for when multi-line
4772 * matching must replace the lines before trying to do another
4773 * match, otherwise "\@<=" won't work.
4774 * When asking the user we like to show the already replaced
4775 * text, but don't do it when "\<@=" or "\<@!" is used, it
4776 * changes what matches.
4777 */
4778 if (lastone
4779 || (do_ask && !re_lookbehind(regmatch.regprog))
4780 || nmatch_tl > 0
4781 || (nmatch = vim_regexec_multi(&regmatch, curwin,
4782 curbuf, sub_firstlnum, matchcol)) == 0)
4783 {
4784 if (new_start != NULL)
4785 {
4786 /*
4787 * Copy the rest of the line, that didn't match.
4788 * "matchcol" has to be adjusted, we use the end of
4789 * the line as reference, because the substitute may
4790 * have changed the number of characters. Same for
4791 * "prev_matchcol".
4792 */
4793 STRCAT(new_start, sub_firstline + copycol);
4794 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4795 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4796 - prev_matchcol;
4797
4798 if (u_savesub(lnum) != OK)
4799 break;
4800 ml_replace(lnum, new_start, TRUE);
4801
4802 if (nmatch_tl > 0)
4803 {
4804 /*
4805 * Matched lines have now been substituted and are
4806 * useless, delete them. The part after the match
4807 * has been appended to new_start, we don't need
4808 * it in the buffer.
4809 */
4810 ++lnum;
4811 if (u_savedel(lnum, nmatch_tl) != OK)
4812 break;
4813 for (i = 0; i < nmatch_tl; ++i)
4814 ml_delete(lnum, (int)FALSE);
4815 mark_adjust(lnum, lnum + nmatch_tl - 1,
4816 (long)MAXLNUM, -nmatch_tl);
4817 if (do_ask)
4818 deleted_lines(lnum, nmatch_tl);
4819 --lnum;
4820 line2 -= nmatch_tl; /* nr of lines decreases */
4821 nmatch_tl = 0;
4822 }
4823
4824 /* When asking, undo is saved each time, must also set
4825 * changed flag each time. */
4826 if (do_ask)
4827 changed_bytes(lnum, 0);
4828 else
4829 {
4830 if (first_line == 0)
4831 first_line = lnum;
4832 last_line = lnum + 1;
4833 }
4834
4835 sub_firstlnum = lnum;
4836 vim_free(sub_firstline); /* free the temp buffer */
4837 sub_firstline = new_start;
4838 new_start = NULL;
4839 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4840 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4841 - prev_matchcol;
4842 copycol = 0;
4843 }
4844 if (nmatch == -1 && !lastone)
4845 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf,
4846 sub_firstlnum, matchcol);
4847
4848 /*
4849 * 5. break if there isn't another match in this line
4850 */
4851 if (nmatch <= 0)
4852 break;
4853 }
4854
4855 line_breakcheck();
4856 }
4857
4858 if (did_sub)
4859 ++sub_nlines;
4860 vim_free(sub_firstline); /* free the copy of the original line */
4861 sub_firstline = NULL;
4862 }
4863
4864 line_breakcheck();
4865 }
4866
4867 if (first_line != 0)
4868 {
4869 /* Need to subtract the number of added lines from "last_line" to get
4870 * the line number before the change (same as adding the number of
4871 * deleted lines). */
4872 i = curbuf->b_ml.ml_line_count - old_line_count;
4873 changed_lines(first_line, 0, last_line - i, i);
4874 }
4875
4876outofmem:
4877 vim_free(sub_firstline); /* may have to free allocated copy of the line */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004878
4879 /* ":s/pat//n" doesn't move the cursor */
4880 if (do_count)
4881 curwin->w_cursor = old_cursor;
4882
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 if (sub_nsubs)
4884 {
4885 /* Set the '[ and '] marks. */
4886 curbuf->b_op_start.lnum = eap->line1;
4887 curbuf->b_op_end.lnum = line2;
4888 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
4889
4890 if (!global_busy)
4891 {
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004892 if (endcolumn)
4893 coladvance((colnr_T)MAXCOL);
4894 else
4895 beginline(BL_WHITE | BL_FIX);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004896 if (!do_sub_msg(do_count) && do_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 MSG("");
4898 }
4899 else
4900 global_need_beginline = TRUE;
4901 if (do_print)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004902 print_line(curwin->w_cursor.lnum, do_number, do_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 }
4904 else if (!global_busy)
4905 {
4906 if (got_int) /* interrupted */
4907 EMSG(_(e_interr));
4908 else if (got_match) /* did find something but nothing substituted */
4909 MSG("");
4910 else if (do_error) /* nothing found */
4911 EMSG2(_(e_patnotf2), get_search_pat());
4912 }
4913
4914 vim_free(regmatch.regprog);
4915}
4916
4917/*
4918 * Give message for number of substitutions.
4919 * Can also be used after a ":global" command.
4920 * Return TRUE if a message was given.
4921 */
Bram Moolenaar8aff23a2005-08-19 20:40:30 +00004922 int
Bram Moolenaar05159a02005-02-26 23:04:13 +00004923do_sub_msg(count_only)
4924 int count_only; /* used 'n' flag for ":s" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925{
Bram Moolenaar555b2802005-05-19 21:08:39 +00004926 int len = 0;
4927
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 /*
4929 * Only report substitutions when:
4930 * - more than 'report' substitutions
4931 * - command was typed by user, or number of changed lines > 'report'
4932 * - giving messages is not disabled by 'lazyredraw'
4933 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004934 if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
4935 || count_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 && messaging())
4937 {
4938 if (got_int)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004939 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 STRCPY(msg_buf, _("(Interrupted) "));
Bram Moolenaar555b2802005-05-19 21:08:39 +00004941 len = STRLEN(msg_buf);
4942 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004943 if (sub_nsubs == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004944 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4945 "%s", count_only ? _("1 match") : _("1 substitution"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004947 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
Bram Moolenaar05159a02005-02-26 23:04:13 +00004948 count_only ? _("%ld matches") : _("%ld substitutions"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949 sub_nsubs);
Bram Moolenaar555b2802005-05-19 21:08:39 +00004950 len = STRLEN(msg_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951 if (sub_nlines == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004952 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4953 "%s", _(" on 1 line"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004955 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4956 _(" on %ld lines"), (long)sub_nlines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957 if (msg(msg_buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004958 /* save message to display it after redraw */
Bram Moolenaar238a5642006-02-21 22:12:05 +00004959 set_keep_msg(msg_buf, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 return TRUE;
4961 }
4962 if (got_int)
4963 {
4964 EMSG(_(e_interr));
4965 return TRUE;
4966 }
4967 return FALSE;
4968}
4969
4970/*
4971 * Execute a global command of the form:
4972 *
4973 * g/pattern/X : execute X on all lines where pattern matches
4974 * v/pattern/X : execute X on all lines where pattern does not match
4975 *
4976 * where 'X' is an EX command
4977 *
4978 * The command character (as well as the trailing slash) is optional, and
4979 * is assumed to be 'p' if missing.
4980 *
4981 * This is implemented in two passes: first we scan the file for the pattern and
4982 * set a mark for each line that (not) matches. secondly we execute the command
4983 * for each line that has a mark. This is required because after deleting
4984 * lines we do not know where to search for the next match.
4985 */
4986 void
4987ex_global(eap)
4988 exarg_T *eap;
4989{
4990 linenr_T lnum; /* line number according to old situation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004991 int ndone = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004992 int type; /* first char of cmd: 'v' or 'g' */
4993 char_u *cmd; /* command argument */
4994
4995 char_u delim; /* delimiter, normally '/' */
4996 char_u *pat;
4997 regmmatch_T regmatch;
4998 int match;
4999 int which_pat;
5000
5001 if (global_busy)
5002 {
5003 EMSG(_("E147: Cannot do :global recursive")); /* will increment global_busy */
5004 return;
5005 }
5006
5007 if (eap->forceit) /* ":global!" is like ":vglobal" */
5008 type = 'v';
5009 else
5010 type = *eap->cmd;
5011 cmd = eap->arg;
5012 which_pat = RE_LAST; /* default: use last used regexp */
5013 sub_nsubs = 0;
5014 sub_nlines = 0;
5015
5016 /*
5017 * undocumented vi feature:
5018 * "\/" and "\?": use previous search pattern.
5019 * "\&": use previous substitute pattern.
5020 */
5021 if (*cmd == '\\')
5022 {
5023 ++cmd;
5024 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
5025 {
5026 EMSG(_(e_backslash));
5027 return;
5028 }
5029 if (*cmd == '&')
5030 which_pat = RE_SUBST; /* use previous substitute pattern */
5031 else
5032 which_pat = RE_SEARCH; /* use previous search pattern */
5033 ++cmd;
5034 pat = (char_u *)"";
5035 }
5036 else if (*cmd == NUL)
5037 {
5038 EMSG(_("E148: Regular expression missing from global"));
5039 return;
5040 }
5041 else
5042 {
5043 delim = *cmd; /* get the delimiter */
5044 if (delim)
5045 ++cmd; /* skip delimiter if there is one */
5046 pat = cmd; /* remember start of pattern */
5047 cmd = skip_regexp(cmd, delim, p_magic, &eap->arg);
5048 if (cmd[0] == delim) /* end delimiter found */
5049 *cmd++ = NUL; /* replace it with a NUL */
5050 }
5051
5052#ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */
5053 if (p_altkeymap && curwin->w_p_rl)
5054 lrFswap(pat,0);
5055#endif
5056
5057 if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, &regmatch) == FAIL)
5058 {
5059 EMSG(_(e_invcmd));
5060 return;
5061 }
5062
5063 /*
5064 * pass 1: set marks for each (not) matching line
5065 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005066 for (lnum = eap->line1; lnum <= eap->line2 && !got_int; ++lnum)
5067 {
5068 /* a match on this line? */
5069 match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
5070 if ((type == 'g' && match) || (type == 'v' && !match))
5071 {
5072 ml_setmarked(lnum);
5073 ndone++;
5074 }
5075 line_breakcheck();
5076 }
5077
5078 /*
5079 * pass 2: execute the command for each line that has been marked
5080 */
5081 if (got_int)
5082 MSG(_(e_interr));
5083 else if (ndone == 0)
5084 {
5085 if (type == 'v')
Bram Moolenaar555b2802005-05-19 21:08:39 +00005086 smsg((char_u *)_("Pattern found in every line: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00005088 smsg((char_u *)_(e_patnotf2), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089 }
5090 else
5091 global_exe(cmd);
5092
5093 ml_clearmarked(); /* clear rest of the marks */
5094 vim_free(regmatch.regprog);
5095}
5096
5097/*
5098 * Execute "cmd" on lines marked with ml_setmarked().
5099 */
5100 void
5101global_exe(cmd)
5102 char_u *cmd;
5103{
5104 linenr_T old_lcount; /* b_ml.ml_line_count before the command */
5105 linenr_T lnum; /* line number according to old situation */
5106
5107 /*
5108 * Set current position only once for a global command.
5109 * If global_busy is set, setpcmark() will not do anything.
5110 * If there is an error, global_busy will be incremented.
5111 */
5112 setpcmark();
5113
5114 /* When the command writes a message, don't overwrite the command. */
5115 msg_didout = TRUE;
5116
5117 global_need_beginline = FALSE;
5118 global_busy = 1;
5119 old_lcount = curbuf->b_ml.ml_line_count;
5120 while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1)
5121 {
5122 curwin->w_cursor.lnum = lnum;
5123 curwin->w_cursor.col = 0;
5124 if (*cmd == NUL || *cmd == '\n')
5125 do_cmdline((char_u *)"p", NULL, NULL, DOCMD_NOWAIT);
5126 else
5127 do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
5128 ui_breakcheck();
5129 }
5130
5131 global_busy = 0;
5132 if (global_need_beginline)
5133 beginline(BL_WHITE | BL_FIX);
5134 else
5135 check_cursor(); /* cursor may be beyond the end of the line */
5136
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005137 /* the cursor may not have moved in the text but a change in a previous
5138 * line may move it on the screen */
5139 changed_line_abv_curs();
5140
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141 /* If it looks like no message was written, allow overwriting the
5142 * command with the report for number of changes. */
5143 if (msg_col == 0 && msg_scrolled == 0)
5144 msg_didout = FALSE;
5145
5146 /* If subsitutes done, report number of substitues, otherwise report
5147 * number of extra or deleted lines. */
Bram Moolenaar05159a02005-02-26 23:04:13 +00005148 if (!do_sub_msg(FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149 msgmore(curbuf->b_ml.ml_line_count - old_lcount);
5150}
5151
5152#ifdef FEAT_VIMINFO
5153 int
5154read_viminfo_sub_string(virp, force)
5155 vir_T *virp;
5156 int force;
5157{
5158 if (old_sub != NULL && force)
5159 vim_free(old_sub);
5160 if (force || old_sub == NULL)
5161 old_sub = viminfo_readstring(virp, 1, TRUE);
5162 return viminfo_readline(virp);
5163}
5164
5165 void
5166write_viminfo_sub_string(fp)
5167 FILE *fp;
5168{
5169 if (get_viminfo_parameter('/') != 0 && old_sub != NULL)
5170 {
5171 fprintf(fp, _("\n# Last Substitute String:\n$"));
5172 viminfo_writestring(fp, old_sub);
5173 }
5174}
5175#endif /* FEAT_VIMINFO */
5176
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005177#if defined(EXITFREE) || defined(PROTO)
5178 void
5179free_old_sub()
5180{
5181 vim_free(old_sub);
5182}
5183#endif
5184
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185#if (defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)) || defined(PROTO)
5186/*
5187 * Set up for a tagpreview.
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005188 * Return TRUE when it was created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189 */
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005190 int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191prepare_tagpreview()
5192{
5193 win_T *wp;
5194
5195# ifdef FEAT_GUI
5196 need_mouse_correct = TRUE;
5197# endif
5198
5199 /*
5200 * If there is already a preview window open, use that one.
5201 */
5202 if (!curwin->w_p_pvw)
5203 {
5204 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5205 if (wp->w_p_pvw)
5206 break;
5207 if (wp != NULL)
5208 win_enter(wp, TRUE);
5209 else
5210 {
5211 /*
5212 * There is no preview window open yet. Create one.
5213 */
5214 if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0)
5215 == FAIL)
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005216 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217 curwin->w_p_pvw = TRUE;
5218 curwin->w_p_wfh = TRUE;
5219# ifdef FEAT_SCROLLBIND
5220 curwin->w_p_scb = FALSE; /* don't take over 'scrollbind' */
5221# endif
5222# ifdef FEAT_DIFF
5223 curwin->w_p_diff = FALSE; /* no 'diff' */
5224# endif
5225# ifdef FEAT_FOLDING
5226 curwin->w_p_fdc = 0; /* no 'foldcolumn' */
5227# endif
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005228 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229 }
5230 }
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005231 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005232}
5233
5234#endif
5235
5236
5237/*
5238 * ":help": open a read-only window on a help file
5239 */
5240 void
5241ex_help(eap)
5242 exarg_T *eap;
5243{
5244 char_u *arg;
5245 char_u *tag;
5246 FILE *helpfd; /* file descriptor of help file */
5247 int n;
5248 int i;
5249#ifdef FEAT_WINDOWS
5250 win_T *wp;
5251#endif
5252 int num_matches;
5253 char_u **matches;
5254 char_u *p;
5255 int empty_fnum = 0;
5256 int alt_fnum = 0;
5257 buf_T *buf;
5258#ifdef FEAT_MULTI_LANG
5259 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005260 char_u *lang;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261#endif
5262
5263 if (eap != NULL)
5264 {
5265 /*
5266 * A ":help" command ends at the first LF, or at a '|' that is
5267 * followed by some text. Set nextcmd to the following command.
5268 */
5269 for (arg = eap->arg; *arg; ++arg)
5270 {
5271 if (*arg == '\n' || *arg == '\r'
5272 || (*arg == '|' && arg[1] != NUL && arg[1] != '|'))
5273 {
5274 *arg++ = NUL;
5275 eap->nextcmd = arg;
5276 break;
5277 }
5278 }
5279 arg = eap->arg;
5280
5281 if (eap->forceit && *arg == NUL)
5282 {
5283 EMSG(_("E478: Don't panic!"));
5284 return;
5285 }
5286
5287 if (eap->skip) /* not executing commands */
5288 return;
5289 }
5290 else
5291 arg = (char_u *)"";
5292
5293 /* remove trailing blanks */
5294 p = arg + STRLEN(arg) - 1;
5295 while (p > arg && vim_iswhite(*p) && p[-1] != '\\')
5296 *p-- = NUL;
5297
5298#ifdef FEAT_MULTI_LANG
5299 /* Check for a specified language */
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005300 lang = check_help_lang(arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005301#endif
5302
5303 /* When no argument given go to the index. */
5304 if (*arg == NUL)
5305 arg = (char_u *)"help.txt";
5306
5307 /*
5308 * Check if there is a match for the argument.
5309 */
5310 n = find_help_tags(arg, &num_matches, &matches,
5311 eap != NULL && eap->forceit);
5312
5313 i = 0;
5314#ifdef FEAT_MULTI_LANG
5315 if (n != FAIL && lang != NULL)
5316 /* Find first item with the requested language. */
5317 for (i = 0; i < num_matches; ++i)
5318 {
5319 len = STRLEN(matches[i]);
5320 if (len > 3 && matches[i][len - 3] == '@'
5321 && STRICMP(matches[i] + len - 2, lang) == 0)
5322 break;
5323 }
5324#endif
5325 if (i >= num_matches || n == FAIL)
5326 {
5327#ifdef FEAT_MULTI_LANG
5328 if (lang != NULL)
5329 EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg);
5330 else
5331#endif
5332 EMSG2(_("E149: Sorry, no help for %s"), arg);
5333 if (n != FAIL)
5334 FreeWild(num_matches, matches);
5335 return;
5336 }
5337
5338 /* The first match (in the requested language) is the best match. */
5339 tag = vim_strsave(matches[i]);
5340 FreeWild(num_matches, matches);
5341
5342#ifdef FEAT_GUI
5343 need_mouse_correct = TRUE;
5344#endif
5345
5346 /*
5347 * Re-use an existing help window or open a new one.
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005348 * Always open a new one for ":tab help".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349 */
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005350 if (!curwin->w_buffer->b_help
5351#ifdef FEAT_WINDOWS
5352 || cmdmod.tab != 0
5353#endif
5354 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355 {
5356#ifdef FEAT_WINDOWS
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005357 if (cmdmod.tab != 0)
5358 wp = NULL;
5359 else
5360 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5361 if (wp->w_buffer != NULL && wp->w_buffer->b_help)
5362 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 if (wp != NULL && wp->w_buffer->b_nwindows > 0)
5364 win_enter(wp, TRUE);
5365 else
5366#endif
5367 {
5368 /*
5369 * There is no help window yet.
5370 * Try to open the file specified by the "helpfile" option.
5371 */
5372 if ((helpfd = mch_fopen((char *)p_hf, READBIN)) == NULL)
5373 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00005374 smsg((char_u *)_("Sorry, help file \"%s\" not found"), p_hf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 goto erret;
5376 }
5377 fclose(helpfd);
5378
5379#ifdef FEAT_WINDOWS
5380 /* Split off help window; put it at far top if no position
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005381 * specified, the current window is vertically split and
5382 * narrow. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 n = WSP_HELP;
5384# ifdef FEAT_VERTSPLIT
5385 if (cmdmod.split == 0 && curwin->w_width != Columns
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005386 && curwin->w_width < 80)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 n |= WSP_TOP;
5388# endif
5389 if (win_split(0, n) == FAIL)
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005390 goto erret;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391#else
5392 /* use current window */
5393 if (!can_abandon(curbuf, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005394 goto erret;
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005395#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005396
5397#ifdef FEAT_WINDOWS
5398 if (curwin->w_height < p_hh)
5399 win_setheight((int)p_hh);
5400#endif
5401
5402 /*
5403 * Open help file (do_ecmd() will set b_help flag, readfile() will
5404 * set b_p_ro flag).
5405 * Set the alternate file to the previously edited file.
5406 */
5407 alt_fnum = curbuf->b_fnum;
5408 (void)do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL,
5409 ECMD_HIDE + ECMD_SET_HELP);
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005410 if (!cmdmod.keepalt)
5411 curwin->w_alt_fnum = alt_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005412 empty_fnum = curbuf->b_fnum;
5413 }
5414 }
5415
5416 if (!p_im)
5417 restart_edit = 0; /* don't want insert mode in help file */
5418
5419 if (tag != NULL)
5420 do_tag(tag, DT_HELP, 1, FALSE, TRUE);
5421
5422 /* Delete the empty buffer if we're not using it. */
5423 if (empty_fnum != 0 && curbuf->b_fnum != empty_fnum)
5424 {
5425 buf = buflist_findnr(empty_fnum);
5426 if (buf != NULL)
5427 wipe_buffer(buf, TRUE);
5428 }
5429
5430 /* keep the previous alternate file */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005431 if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432 curwin->w_alt_fnum = alt_fnum;
5433
5434erret:
5435 vim_free(tag);
5436}
5437
5438
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005439#if defined(FEAT_MULTI_LANG) || defined(PROTO)
5440/*
5441 * In an argument search for a language specifiers in the form "@xx".
5442 * Changes the "@" to NUL if found, and returns a pointer to "xx".
5443 * Returns NULL if not found.
5444 */
5445 char_u *
5446check_help_lang(arg)
5447 char_u *arg;
5448{
5449 int len = STRLEN(arg);
5450
5451 if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2])
5452 && ASCII_ISALPHA(arg[len - 1]))
5453 {
5454 arg[len - 3] = NUL; /* remove the '@' */
5455 return arg + len - 2;
5456 }
5457 return NULL;
5458}
5459#endif
5460
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461/*
5462 * Return a heuristic indicating how well the given string matches. The
5463 * smaller the number, the better the match. This is the order of priorities,
5464 * from best match to worst match:
5465 * - Match with least alpha-numeric characters is better.
5466 * - Match with least total characters is better.
5467 * - Match towards the start is better.
5468 * - Match starting with "+" is worse (feature instead of command)
5469 * Assumption is made that the matched_string passed has already been found to
5470 * match some string for which help is requested. webb.
5471 */
5472 int
5473help_heuristic(matched_string, offset, wrong_case)
5474 char_u *matched_string;
5475 int offset; /* offset for match */
5476 int wrong_case; /* no matching case */
5477{
5478 int num_letters;
5479 char_u *p;
5480
5481 num_letters = 0;
5482 for (p = matched_string; *p; p++)
5483 if (ASCII_ISALNUM(*p))
5484 num_letters++;
5485
5486 /*
5487 * Multiply the number of letters by 100 to give it a much bigger
5488 * weighting than the number of characters.
5489 * If there only is a match while ignoring case, add 5000.
5490 * If the match starts in the middle of a word, add 10000 to put it
5491 * somewhere in the last half.
5492 * If the match is more than 2 chars from the start, multiply by 200 to
5493 * put it after matches at the start.
5494 */
5495 if (ASCII_ISALNUM(matched_string[offset]) && offset > 0
5496 && ASCII_ISALNUM(matched_string[offset - 1]))
5497 offset += 10000;
5498 else if (offset > 2)
5499 offset *= 200;
5500 if (wrong_case)
5501 offset += 5000;
5502 /* Features are less interesting than the subjects themselves, but "+"
5503 * alone is not a feature. */
5504 if (matched_string[0] == '+' && matched_string[1] != NUL)
5505 offset += 100;
5506 return (int)(100 * num_letters + STRLEN(matched_string) + offset);
5507}
5508
5509/*
5510 * Compare functions for qsort() below, that checks the help heuristics number
5511 * that has been put after the tagname by find_tags().
5512 */
5513 static int
5514#ifdef __BORLANDC__
5515_RTLENTRYF
5516#endif
5517help_compare(s1, s2)
5518 const void *s1;
5519 const void *s2;
5520{
5521 char *p1;
5522 char *p2;
5523
5524 p1 = *(char **)s1 + strlen(*(char **)s1) + 1;
5525 p2 = *(char **)s2 + strlen(*(char **)s2) + 1;
5526 return strcmp(p1, p2);
5527}
5528
5529/*
5530 * Find all help tags matching "arg", sort them and return in matches[], with
5531 * the number of matches in num_matches.
5532 * The matches will be sorted with a "best" match algorithm.
5533 * When "keep_lang" is TRUE try keeping the language of the current buffer.
5534 */
5535 int
5536find_help_tags(arg, num_matches, matches, keep_lang)
5537 char_u *arg;
5538 int *num_matches;
5539 char_u ***matches;
5540 int keep_lang;
5541{
5542 char_u *s, *d;
5543 int i;
5544 static char *(mtable[]) = {"*", "g*", "[*", "]*", ":*",
Bram Moolenaar231334e2005-07-25 20:46:57 +00005545 "/*", "/\\*", "\"*", "**",
5546 "/\\(\\)",
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005547 "?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005548 "/\\?", "/\\z(\\)", "\\=", ":s\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 "[count]", "[quotex]", "[range]",
5550 "[pattern]", "\\|", "\\%$"};
5551 static char *(rtable[]) = {"star", "gstar", "[star", "]star", ":star",
Bram Moolenaar231334e2005-07-25 20:46:57 +00005552 "/star", "/\\\\star", "quotestar", "starstar",
5553 "/\\\\(\\\\)",
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005554 "?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005555 "/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 "\\[count]", "\\[quotex]", "\\[range]",
5557 "\\[pattern]", "\\\\bar", "/\\\\%\\$"};
5558 int flags;
5559
5560 d = IObuff; /* assume IObuff is long enough! */
5561
5562 /*
5563 * Recognize a few exceptions to the rule. Some strings that contain '*'
5564 * with "star". Otherwise '*' is recognized as a wildcard.
5565 */
5566 for (i = sizeof(mtable) / sizeof(char *); --i >= 0; )
5567 if (STRCMP(arg, mtable[i]) == 0)
5568 {
5569 STRCPY(d, rtable[i]);
5570 break;
5571 }
5572
5573 if (i < 0) /* no match in table */
5574 {
5575 /* Replace "\S" with "/\\S", etc. Otherwise every tag is matched.
5576 * Also replace "\%^" and "\%(", they match every tag too.
5577 * Also "\zs", "\z1", etc.
5578 * Also "\@<", "\@=", "\@<=", etc.
5579 * And also "\_$" and "\_^". */
5580 if (arg[0] == '\\'
5581 && ((arg[1] != NUL && arg[2] == NUL)
5582 || (vim_strchr((char_u *)"%_z@", arg[1]) != NULL
5583 && arg[2] != NUL)))
5584 {
5585 STRCPY(d, "/\\\\");
5586 STRCPY(d + 3, arg + 1);
5587 /* Check for "/\\_$", should be "/\\_\$" */
5588 if (d[3] == '_' && d[4] == '$')
5589 STRCPY(d + 4, "\\$");
5590 }
5591 else
5592 {
5593 /* replace "[:...:]" with "\[:...:]"; "[+...]" with "\[++...]" */
5594 if (arg[0] == '[' && (arg[1] == ':'
5595 || (arg[1] == '+' && arg[2] == '+')))
5596 *d++ = '\\';
5597
5598 for (s = arg; *s; ++s)
5599 {
5600 /*
5601 * Replace "|" with "bar" and '"' with "quote" to match the name of
5602 * the tags for these commands.
5603 * Replace "*" with ".*" and "?" with "." to match command line
5604 * completion.
5605 * Insert a backslash before '~', '$' and '.' to avoid their
5606 * special meaning.
5607 */
5608 if (d - IObuff > IOSIZE - 10) /* getting too long!? */
5609 break;
5610 switch (*s)
5611 {
5612 case '|': STRCPY(d, "bar");
5613 d += 3;
5614 continue;
5615 case '"': STRCPY(d, "quote");
5616 d += 5;
5617 continue;
5618 case '*': *d++ = '.';
5619 break;
5620 case '?': *d++ = '.';
5621 continue;
5622 case '$':
5623 case '.':
5624 case '~': *d++ = '\\';
5625 break;
5626 }
5627
5628 /*
5629 * Replace "^x" by "CTRL-X". Don't do this for "^_" to make
5630 * ":help i_^_CTRL-D" work.
5631 * Insert '-' before and after "CTRL-X" when applicable.
5632 */
5633 if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1])
5634 || vim_strchr((char_u *)"?@[\\]^", s[1]) != NULL)))
5635 {
5636 if (d > IObuff && d[-1] != '_')
5637 *d++ = '_'; /* prepend a '_' */
5638 STRCPY(d, "CTRL-");
5639 d += 5;
5640 if (*s < ' ')
5641 {
5642#ifdef EBCDIC
5643 *d++ = CtrlChar(*s);
5644#else
5645 *d++ = *s + '@';
5646#endif
5647 if (d[-1] == '\\')
5648 *d++ = '\\'; /* double a backslash */
5649 }
5650 else
5651 *d++ = *++s;
5652 if (s[1] != NUL && s[1] != '_')
5653 *d++ = '_'; /* append a '_' */
5654 continue;
5655 }
5656 else if (*s == '^') /* "^" or "CTRL-^" or "^_" */
5657 *d++ = '\\';
5658
5659 /*
5660 * Insert a backslash before a backslash after a slash, for search
5661 * pattern tags: "/\|" --> "/\\|".
5662 */
5663 else if (s[0] == '\\' && s[1] != '\\'
5664 && *arg == '/' && s == arg + 1)
5665 *d++ = '\\';
5666
5667 /* "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in
5668 * "CTRL-\_CTRL-N" */
5669 if (STRNICMP(s, "CTRL-\\_", 7) == 0)
5670 {
5671 STRCPY(d, "CTRL-\\\\");
5672 d += 7;
5673 s += 6;
5674 }
5675
5676 *d++ = *s;
5677
5678 /*
5679 * If tag starts with ', toss everything after a second '. Fixes
5680 * CTRL-] on 'option'. (would include the trailing '.').
5681 */
5682 if (*s == '\'' && s > arg && *arg == '\'')
5683 break;
5684 }
5685 *d = NUL;
5686 }
5687 }
5688
5689 *matches = (char_u **)"";
5690 *num_matches = 0;
5691 flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE;
5692 if (keep_lang)
5693 flags |= TAG_KEEP_LANG;
5694 if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK
5695 && *num_matches > 0)
5696 /* Sort the matches found on the heuristic number that is after the
5697 * tag name. */
5698 qsort((void *)*matches, (size_t)*num_matches,
5699 sizeof(char_u *), help_compare);
5700 return OK;
5701}
5702
5703/*
5704 * After reading a help file: May cleanup a help buffer when syntax
5705 * highlighting is not used.
5706 */
5707 void
5708fix_help_buffer()
5709{
5710 linenr_T lnum;
5711 char_u *line;
5712 int in_example = FALSE;
5713 int len;
5714 char_u *p;
5715 char_u *rt;
5716 int mustfree;
5717
5718 /* set filetype to "help". */
5719 set_option_value((char_u *)"ft", 0L, (char_u *)"help", OPT_LOCAL);
5720
5721#ifdef FEAT_SYN_HL
5722 if (!syntax_present(curbuf))
5723#endif
5724 {
5725 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
5726 {
5727 line = ml_get_buf(curbuf, lnum, FALSE);
5728 len = (int)STRLEN(line);
5729 if (in_example && len > 0 && !vim_iswhite(line[0]))
5730 {
5731 /* End of example: non-white or '<' in first column. */
5732 if (line[0] == '<')
5733 {
5734 /* blank-out a '<' in the first column */
5735 line = ml_get_buf(curbuf, lnum, TRUE);
5736 line[0] = ' ';
5737 }
5738 in_example = FALSE;
5739 }
5740 if (!in_example && len > 0)
5741 {
5742 if (line[len - 1] == '>' && (len == 1 || line[len - 2] == ' '))
5743 {
5744 /* blank-out a '>' in the last column (start of example) */
5745 line = ml_get_buf(curbuf, lnum, TRUE);
5746 line[len - 1] = ' ';
5747 in_example = TRUE;
5748 }
5749 else if (line[len - 1] == '~')
5750 {
5751 /* blank-out a '~' at the end of line (header marker) */
5752 line = ml_get_buf(curbuf, lnum, TRUE);
5753 line[len - 1] = ' ';
5754 }
5755 }
5756 }
5757 }
5758
5759 /*
5760 * In the "help.txt" file, add the locally added help files.
5761 * This uses the very first line in the help file.
5762 */
5763 if (fnamecmp(gettail(curbuf->b_fname), "help.txt") == 0)
5764 {
5765 for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; ++lnum)
5766 {
5767 line = ml_get_buf(curbuf, lnum, FALSE);
5768 if (strstr((char *)line, "*local-additions*") != NULL)
5769 {
5770 /* Go through all directories in 'runtimepath', skipping
5771 * $VIMRUNTIME. */
5772 p = p_rtp;
5773 while (*p != NUL)
5774 {
5775 copy_option_part(&p, NameBuff, MAXPATHL, ",");
5776 mustfree = FALSE;
5777 rt = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
5778 if (fullpathcmp(rt, NameBuff, FALSE) != FPC_SAME)
5779 {
5780 int fcount;
5781 char_u **fnames;
5782 FILE *fd;
5783 char_u *s;
5784 int fi;
5785#ifdef FEAT_MBYTE
5786 vimconv_T vc;
5787 char_u *cp;
5788#endif
5789
5790 /* Find all "doc/ *.txt" files in this directory. */
5791 add_pathsep(NameBuff);
5792 STRCAT(NameBuff, "doc/*.txt");
5793 if (gen_expand_wildcards(1, &NameBuff, &fcount,
5794 &fnames, EW_FILE|EW_SILENT) == OK
5795 && fcount > 0)
5796 {
5797 for (fi = 0; fi < fcount; ++fi)
5798 {
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00005799 fd = mch_fopen((char *)fnames[fi], "r");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 if (fd != NULL)
5801 {
5802 vim_fgets(IObuff, IOSIZE, fd);
5803 if (IObuff[0] == '*'
5804 && (s = vim_strchr(IObuff + 1, '*'))
5805 != NULL)
5806 {
5807#ifdef FEAT_MBYTE
5808 int this_utf = MAYBE;
5809#endif
5810 /* Change tag definition to a
5811 * reference and remove <CR>/<NL>. */
5812 IObuff[0] = '|';
5813 *s = '|';
5814 while (*s != NUL)
5815 {
5816 if (*s == '\r' || *s == '\n')
5817 *s = NUL;
5818#ifdef FEAT_MBYTE
5819 /* The text is utf-8 when a byte
5820 * above 127 is found and no
5821 * illegal byte sequence is found.
5822 */
5823 if (*s >= 0x80 && this_utf != FALSE)
5824 {
5825 int l;
5826
5827 this_utf = TRUE;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005828 l = utf_ptr2len(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 if (l == 1)
5830 this_utf = FALSE;
5831 s += l - 1;
5832 }
5833#endif
5834 ++s;
5835 }
5836#ifdef FEAT_MBYTE
5837 /* The help file is latin1 or utf-8;
5838 * conversion to the current
5839 * 'encoding' may be required. */
5840 vc.vc_type = CONV_NONE;
5841 convert_setup(&vc, (char_u *)(
5842 this_utf == TRUE ? "utf-8"
5843 : "latin1"), p_enc);
5844 if (vc.vc_type == CONV_NONE)
5845 /* No conversion needed. */
5846 cp = IObuff;
5847 else
5848 {
5849 /* Do the conversion. If it fails
5850 * use the unconverted text. */
5851 cp = string_convert(&vc, IObuff,
5852 NULL);
5853 if (cp == NULL)
5854 cp = IObuff;
5855 }
5856 convert_setup(&vc, NULL, NULL);
5857
5858 ml_append(lnum, cp, (colnr_T)0, FALSE);
5859 if (cp != IObuff)
5860 vim_free(cp);
5861#else
5862 ml_append(lnum, IObuff, (colnr_T)0,
5863 FALSE);
5864#endif
5865 ++lnum;
5866 }
5867 fclose(fd);
5868 }
5869 }
5870 FreeWild(fcount, fnames);
5871 }
5872 }
5873 if (mustfree)
5874 vim_free(rt);
5875 }
5876 break;
5877 }
5878 }
5879 }
5880}
5881
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00005882/*
5883 * ":exusage"
5884 */
5885/*ARGSUSED*/
5886 void
5887ex_exusage(eap)
5888 exarg_T *eap;
5889{
5890 do_cmdline_cmd((char_u *)"help ex-cmd-index");
5891}
5892
5893/*
5894 * ":viusage"
5895 */
5896/*ARGSUSED*/
5897 void
5898ex_viusage(eap)
5899 exarg_T *eap;
5900{
5901 do_cmdline_cmd((char_u *)"help normal-index");
5902}
5903
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904#if defined(FEAT_EX_EXTRA) || defined(PROTO)
5905static void helptags_one __ARGS((char_u *dir, char_u *ext, char_u *lang));
5906
5907/*
5908 * ":helptags"
5909 */
5910 void
5911ex_helptags(eap)
5912 exarg_T *eap;
5913{
5914 garray_T ga;
5915 int i, j;
5916 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005917#ifdef FEAT_MULTI_LANG
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918 char_u lang[2];
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005919#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 char_u ext[5];
5921 char_u fname[8];
5922 int filecount;
5923 char_u **files;
5924
5925 if (!mch_isdir(eap->arg))
5926 {
5927 EMSG2(_("E150: Not a directory: %s"), eap->arg);
5928 return;
5929 }
5930
5931#ifdef FEAT_MULTI_LANG
5932 /* Get a list of all files in the directory. */
5933 STRCPY(NameBuff, eap->arg);
5934 add_pathsep(NameBuff);
5935 STRCAT(NameBuff, "*");
5936 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
5937 EW_FILE|EW_SILENT) == FAIL
5938 || filecount == 0)
5939 {
5940 EMSG2("E151: No match: %s", NameBuff);
5941 return;
5942 }
5943
5944 /* Go over all files in the directory to find out what languages are
5945 * present. */
5946 ga_init2(&ga, 1, 10);
5947 for (i = 0; i < filecount; ++i)
5948 {
5949 len = STRLEN(files[i]);
5950 if (len > 4)
5951 {
5952 if (STRICMP(files[i] + len - 4, ".txt") == 0)
5953 {
5954 /* ".txt" -> language "en" */
5955 lang[0] = 'e';
5956 lang[1] = 'n';
5957 }
5958 else if (files[i][len - 4] == '.'
5959 && ASCII_ISALPHA(files[i][len - 3])
5960 && ASCII_ISALPHA(files[i][len - 2])
5961 && TOLOWER_ASC(files[i][len - 1]) == 'x')
5962 {
5963 /* ".abx" -> language "ab" */
5964 lang[0] = TOLOWER_ASC(files[i][len - 3]);
5965 lang[1] = TOLOWER_ASC(files[i][len - 2]);
5966 }
5967 else
5968 continue;
5969
5970 /* Did we find this language already? */
5971 for (j = 0; j < ga.ga_len; j += 2)
5972 if (STRNCMP(lang, ((char_u *)ga.ga_data) + j, 2) == 0)
5973 break;
5974 if (j == ga.ga_len)
5975 {
5976 /* New language, add it. */
5977 if (ga_grow(&ga, 2) == FAIL)
5978 break;
5979 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[0];
5980 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005981 }
5982 }
5983 }
5984
5985 /*
5986 * Loop over the found languages to generate a tags file for each one.
5987 */
5988 for (j = 0; j < ga.ga_len; j += 2)
5989 {
5990 STRCPY(fname, "tags-xx");
5991 fname[5] = ((char_u *)ga.ga_data)[j];
5992 fname[6] = ((char_u *)ga.ga_data)[j + 1];
5993 if (fname[5] == 'e' && fname[6] == 'n')
5994 {
5995 /* English is an exception: use ".txt" and "tags". */
5996 fname[4] = NUL;
5997 STRCPY(ext, ".txt");
5998 }
5999 else
6000 {
6001 /* Language "ab" uses ".abx" and "tags-ab". */
6002 STRCPY(ext, ".xxx");
6003 ext[1] = fname[5];
6004 ext[2] = fname[6];
6005 }
6006 helptags_one(eap->arg, ext, fname);
6007 }
6008
6009 ga_clear(&ga);
6010 FreeWild(filecount, files);
6011
6012#else
6013 /* No language support, just use "*.txt" and "tags". */
6014 helptags_one(eap->arg, (char_u *)".txt", (char_u *)"tags");
6015#endif
6016}
6017
6018 static void
6019helptags_one(dir, ext, tagfname)
6020 char_u *dir; /* doc directory */
6021 char_u *ext; /* suffix, ".txt", ".itx", ".frx", etc. */
6022 char_u *tagfname; /* "tags" for English, "tags-it" for Italian. */
6023{
6024 FILE *fd_tags;
6025 FILE *fd;
6026 garray_T ga;
6027 int filecount;
6028 char_u **files;
6029 char_u *p1, *p2;
6030 int fi;
6031 char_u *s;
6032 int i;
6033 char_u *fname;
6034# ifdef FEAT_MBYTE
6035 int utf8 = MAYBE;
6036 int this_utf8;
6037 int firstline;
6038 int mix = FALSE; /* detected mixed encodings */
6039# endif
6040
6041 /*
6042 * Find all *.txt files.
6043 */
6044 STRCPY(NameBuff, dir);
6045 add_pathsep(NameBuff);
6046 STRCAT(NameBuff, "*");
6047 STRCAT(NameBuff, ext);
6048 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
6049 EW_FILE|EW_SILENT) == FAIL
6050 || filecount == 0)
6051 {
6052 if (!got_int)
6053 EMSG2("E151: No match: %s", NameBuff);
6054 return;
6055 }
6056
6057 /*
6058 * Open the tags file for writing.
6059 * Do this before scanning through all the files.
6060 */
6061 STRCPY(NameBuff, dir);
6062 add_pathsep(NameBuff);
6063 STRCAT(NameBuff, tagfname);
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00006064 fd_tags = mch_fopen((char *)NameBuff, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006065 if (fd_tags == NULL)
6066 {
6067 EMSG2(_("E152: Cannot open %s for writing"), NameBuff);
6068 FreeWild(filecount, files);
6069 return;
6070 }
6071
6072 /*
6073 * If generating tags for "$VIMRUNTIME/doc" add the "help-tags" tag.
6074 */
6075 ga_init2(&ga, (int)sizeof(char_u *), 100);
6076 if (fullpathcmp((char_u *)"$VIMRUNTIME/doc", dir, FALSE) == FPC_SAME)
6077 {
6078 if (ga_grow(&ga, 1) == FAIL)
6079 got_int = TRUE;
6080 else
6081 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00006082 s = alloc(18 + STRLEN(tagfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 if (s == NULL)
6084 got_int = TRUE;
6085 else
6086 {
6087 sprintf((char *)s, "help-tags\t%s\t1\n", tagfname);
6088 ((char_u **)ga.ga_data)[ga.ga_len] = s;
6089 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090 }
6091 }
6092 }
6093
6094 /*
6095 * Go over all the files and extract the tags.
6096 */
6097 for (fi = 0; fi < filecount && !got_int; ++fi)
6098 {
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00006099 fd = mch_fopen((char *)files[fi], "r");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 if (fd == NULL)
6101 {
6102 EMSG2(_("E153: Unable to open %s for reading"), files[fi]);
6103 continue;
6104 }
6105 fname = gettail(files[fi]);
6106
6107# ifdef FEAT_MBYTE
6108 firstline = TRUE;
6109# endif
6110 while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int)
6111 {
6112# ifdef FEAT_MBYTE
6113 if (firstline)
6114 {
6115 /* Detect utf-8 file by a non-ASCII char in the first line. */
6116 this_utf8 = MAYBE;
6117 for (s = IObuff; *s != NUL; ++s)
6118 if (*s >= 0x80)
6119 {
6120 int l;
6121
6122 this_utf8 = TRUE;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00006123 l = utf_ptr2len(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 if (l == 1)
6125 {
6126 /* Illegal UTF-8 byte sequence. */
6127 this_utf8 = FALSE;
6128 break;
6129 }
6130 s += l - 1;
6131 }
6132 if (this_utf8 == MAYBE) /* only ASCII characters found */
6133 this_utf8 = FALSE;
6134 if (utf8 == MAYBE) /* first file */
6135 utf8 = this_utf8;
6136 else if (utf8 != this_utf8)
6137 {
6138 EMSG2(_("E670: Mix of help file encodings within a language: %s"), files[fi]);
6139 mix = !got_int;
6140 got_int = TRUE;
6141 }
6142 firstline = FALSE;
6143 }
6144# endif
6145 p1 = vim_strchr(IObuff, '*'); /* find first '*' */
6146 while (p1 != NULL)
6147 {
6148 p2 = vim_strchr(p1 + 1, '*'); /* find second '*' */
6149 if (p2 != NULL && p2 > p1 + 1) /* skip "*" and "**" */
6150 {
6151 for (s = p1 + 1; s < p2; ++s)
6152 if (*s == ' ' || *s == '\t' || *s == '|')
6153 break;
6154
6155 /*
6156 * Only accept a *tag* when it consists of valid
6157 * characters, there is white space before it and is
6158 * followed by a white character or end-of-line.
6159 */
6160 if (s == p2
6161 && (p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
6162 && (vim_strchr((char_u *)" \t\n\r", s[1]) != NULL
6163 || s[1] == '\0'))
6164 {
6165 *p2 = '\0';
6166 ++p1;
6167 if (ga_grow(&ga, 1) == FAIL)
6168 {
6169 got_int = TRUE;
6170 break;
6171 }
6172 s = alloc((unsigned)(p2 - p1 + STRLEN(fname) + 2));
6173 if (s == NULL)
6174 {
6175 got_int = TRUE;
6176 break;
6177 }
6178 ((char_u **)ga.ga_data)[ga.ga_len] = s;
6179 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 sprintf((char *)s, "%s\t%s", p1, fname);
6181
6182 /* find next '*' */
6183 p2 = vim_strchr(p2 + 1, '*');
6184 }
6185 }
6186 p1 = p2;
6187 }
6188 line_breakcheck();
6189 }
6190
6191 fclose(fd);
6192 }
6193
6194 FreeWild(filecount, files);
6195
6196 if (!got_int)
6197 {
6198 /*
6199 * Sort the tags.
6200 */
6201 sort_strings((char_u **)ga.ga_data, ga.ga_len);
6202
6203 /*
6204 * Check for duplicates.
6205 */
6206 for (i = 1; i < ga.ga_len; ++i)
6207 {
6208 p1 = ((char_u **)ga.ga_data)[i - 1];
6209 p2 = ((char_u **)ga.ga_data)[i];
6210 while (*p1 == *p2)
6211 {
6212 if (*p2 == '\t')
6213 {
6214 *p2 = NUL;
Bram Moolenaar555b2802005-05-19 21:08:39 +00006215 vim_snprintf((char *)NameBuff, MAXPATHL,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 _("E154: Duplicate tag \"%s\" in file %s/%s"),
6217 ((char_u **)ga.ga_data)[i], dir, p2 + 1);
6218 EMSG(NameBuff);
6219 *p2 = '\t';
6220 break;
6221 }
6222 ++p1;
6223 ++p2;
6224 }
6225 }
6226
6227# ifdef FEAT_MBYTE
6228 if (utf8 == TRUE)
6229 fprintf(fd_tags, "!_TAG_FILE_ENCODING\tutf-8\t//\n");
6230# endif
6231
6232 /*
6233 * Write the tags into the file.
6234 */
6235 for (i = 0; i < ga.ga_len; ++i)
6236 {
6237 s = ((char_u **)ga.ga_data)[i];
6238 if (STRNCMP(s, "help-tags", 9) == 0)
6239 /* help-tags entry was added in formatted form */
6240 fprintf(fd_tags, (char *)s);
6241 else
6242 {
6243 fprintf(fd_tags, "%s\t/*", s);
6244 for (p1 = s; *p1 != '\t'; ++p1)
6245 {
6246 /* insert backslash before '\\' and '/' */
6247 if (*p1 == '\\' || *p1 == '/')
6248 putc('\\', fd_tags);
6249 putc(*p1, fd_tags);
6250 }
6251 fprintf(fd_tags, "*\n");
6252 }
6253 }
6254 }
6255#ifdef FEAT_MBYTE
6256 if (mix)
6257 got_int = FALSE; /* continue with other languages */
6258#endif
6259
6260 for (i = 0; i < ga.ga_len; ++i)
6261 vim_free(((char_u **)ga.ga_data)[i]);
6262 ga_clear(&ga);
6263 fclose(fd_tags); /* there is no check for an error... */
6264}
6265#endif
6266
6267#if defined(FEAT_SIGNS) || defined(PROTO)
6268
6269/*
6270 * Struct to hold the sign properties.
6271 */
6272typedef struct sign sign_T;
6273
6274struct sign
6275{
6276 sign_T *sn_next; /* next sign in list */
6277 int sn_typenr; /* type number of sign (negative if not equal
6278 to name) */
6279 char_u *sn_name; /* name of sign */
6280 char_u *sn_icon; /* name of pixmap */
6281#ifdef FEAT_SIGN_ICONS
6282 void *sn_image; /* icon image */
6283#endif
6284 char_u *sn_text; /* text used instead of pixmap */
6285 int sn_line_hl; /* highlight ID for line */
6286 int sn_text_hl; /* highlight ID for text */
6287};
6288
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289static sign_T *first_sign = NULL;
6290static int last_sign_typenr = MAX_TYPENR; /* is decremented */
6291
6292static void sign_list_defined __ARGS((sign_T *sp));
6293
6294/*
6295 * ":sign" command
6296 */
6297 void
6298ex_sign(eap)
6299 exarg_T *eap;
6300{
6301 char_u *arg = eap->arg;
6302 char_u *p;
6303 int idx;
6304 sign_T *sp;
6305 sign_T *sp_prev;
6306 buf_T *buf;
6307 static char *cmds[] = {
6308 "define",
6309#define SIGNCMD_DEFINE 0
6310 "undefine",
6311#define SIGNCMD_UNDEFINE 1
6312 "list",
6313#define SIGNCMD_LIST 2
6314 "place",
6315#define SIGNCMD_PLACE 3
6316 "unplace",
6317#define SIGNCMD_UNPLACE 4
6318 "jump",
6319#define SIGNCMD_JUMP 5
6320#define SIGNCMD_LAST 6
6321 };
6322
6323 /* Parse the subcommand. */
6324 p = skiptowhite(arg);
6325 if (*p != NUL)
6326 *p++ = NUL;
6327 for (idx = 0; ; ++idx)
6328 {
6329 if (idx == SIGNCMD_LAST)
6330 {
6331 EMSG2(_("E160: Unknown sign command: %s"), arg);
6332 return;
6333 }
6334 if (STRCMP(arg, cmds[idx]) == 0)
6335 break;
6336 }
6337 arg = skipwhite(p);
6338
6339 if (idx <= SIGNCMD_LIST)
6340 {
6341 /*
6342 * Define, undefine or list signs.
6343 */
6344 if (idx == SIGNCMD_LIST && *arg == NUL)
6345 {
6346 /* ":sign list": list all defined signs */
6347 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6348 sign_list_defined(sp);
6349 }
6350 else if (*arg == NUL)
6351 EMSG(_("E156: Missing sign name"));
6352 else
6353 {
6354 p = skiptowhite(arg);
6355 if (*p != NUL)
6356 *p++ = NUL;
6357 sp_prev = NULL;
6358 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6359 {
6360 if (STRCMP(sp->sn_name, arg) == 0)
6361 break;
6362 sp_prev = sp;
6363 }
6364 if (idx == SIGNCMD_DEFINE)
6365 {
6366 /* ":sign define {name} ...": define a sign */
6367 if (sp == NULL)
6368 {
6369 /* Allocate a new sign. */
6370 sp = (sign_T *)alloc_clear((unsigned)sizeof(sign_T));
6371 if (sp == NULL)
6372 return;
6373 if (sp_prev == NULL)
6374 first_sign = sp;
6375 else
6376 sp_prev->sn_next = sp;
6377 sp->sn_name = vim_strnsave(arg, (int)(p - arg));
6378
6379 /* If the name is a number use that for the typenr,
6380 * otherwise use a negative number. */
6381 if (VIM_ISDIGIT(*arg))
6382 sp->sn_typenr = atoi((char *)arg);
6383 else
6384 {
6385 sign_T *lp;
6386 int start = last_sign_typenr;
6387
6388 for (lp = first_sign; lp != NULL; lp = lp->sn_next)
6389 {
6390 if (lp->sn_typenr == last_sign_typenr)
6391 {
6392 --last_sign_typenr;
6393 if (last_sign_typenr == 0)
6394 last_sign_typenr = MAX_TYPENR;
6395 if (last_sign_typenr == start)
6396 {
6397 EMSG(_("E612: Too many signs defined"));
6398 return;
6399 }
6400 lp = first_sign;
6401 continue;
6402 }
6403 }
6404
6405 sp->sn_typenr = last_sign_typenr--;
6406 if (last_sign_typenr == 0)
6407 last_sign_typenr = MAX_TYPENR; /* wrap around */
6408 }
6409 }
6410
6411 /* set values for a defined sign. */
6412 for (;;)
6413 {
6414 arg = skipwhite(p);
6415 if (*arg == NUL)
6416 break;
6417 p = skiptowhite_esc(arg);
6418 if (STRNCMP(arg, "icon=", 5) == 0)
6419 {
6420 arg += 5;
6421 vim_free(sp->sn_icon);
6422 sp->sn_icon = vim_strnsave(arg, (int)(p - arg));
6423 backslash_halve(sp->sn_icon);
6424#ifdef FEAT_SIGN_ICONS
6425 if (gui.in_use)
6426 {
6427 out_flush();
6428 if (sp->sn_image != NULL)
6429 gui_mch_destroy_sign(sp->sn_image);
6430 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6431 }
6432#endif
6433 }
6434 else if (STRNCMP(arg, "text=", 5) == 0)
6435 {
6436 char_u *s;
6437 int cells;
6438 int len;
6439
6440 arg += 5;
6441#ifdef FEAT_MBYTE
6442 /* Count cells and check for non-printable chars */
6443 if (has_mbyte)
6444 {
6445 cells = 0;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00006446 for (s = arg; s < p; s += (*mb_ptr2len)(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447 {
6448 if (!vim_isprintc((*mb_ptr2char)(s)))
6449 break;
6450 cells += (*mb_ptr2cells)(s);
6451 }
6452 }
6453 else
6454#endif
6455 {
6456 for (s = arg; s < p; ++s)
6457 if (!vim_isprintc(*s))
6458 break;
6459 cells = s - arg;
6460 }
6461 /* Currently must be one or two display cells */
6462 if (s != p || cells < 1 || cells > 2)
6463 {
6464 *p = NUL;
6465 EMSG2(_("E239: Invalid sign text: %s"), arg);
6466 return;
6467 }
6468
6469 vim_free(sp->sn_text);
6470 /* Allocate one byte more if we need to pad up
6471 * with a space. */
6472 len = p - arg + ((cells == 1) ? 1 : 0);
6473 sp->sn_text = vim_strnsave(arg, len);
6474
6475 if (sp->sn_text != NULL && cells == 1)
6476 STRCPY(sp->sn_text + len - 1, " ");
6477 }
6478 else if (STRNCMP(arg, "linehl=", 7) == 0)
6479 {
6480 arg += 7;
6481 sp->sn_line_hl = syn_check_group(arg, (int)(p - arg));
6482 }
6483 else if (STRNCMP(arg, "texthl=", 7) == 0)
6484 {
6485 arg += 7;
6486 sp->sn_text_hl = syn_check_group(arg, (int)(p - arg));
6487 }
6488 else
6489 {
6490 EMSG2(_(e_invarg2), arg);
6491 return;
6492 }
6493 }
6494 }
6495 else if (sp == NULL)
6496 EMSG2(_("E155: Unknown sign: %s"), arg);
6497 else if (idx == SIGNCMD_LIST)
6498 /* ":sign list {name}" */
6499 sign_list_defined(sp);
6500 else
6501 {
6502 /* ":sign undefine {name}" */
6503 vim_free(sp->sn_name);
6504 vim_free(sp->sn_icon);
6505#ifdef FEAT_SIGN_ICONS
6506 if (sp->sn_image != NULL)
6507 {
6508 out_flush();
6509 gui_mch_destroy_sign(sp->sn_image);
6510 }
6511#endif
6512 vim_free(sp->sn_text);
6513 if (sp_prev == NULL)
6514 first_sign = sp->sn_next;
6515 else
6516 sp_prev->sn_next = sp->sn_next;
6517 vim_free(sp);
6518 }
6519 }
6520 }
6521 else
6522 {
6523 int id = -1;
6524 linenr_T lnum = -1;
6525 char_u *sign_name = NULL;
6526 char_u *arg1;
6527
6528 if (*arg == NUL)
6529 {
6530 if (idx == SIGNCMD_PLACE)
6531 {
6532 /* ":sign place": list placed signs in all buffers */
6533 sign_list_placed(NULL);
6534 }
6535 else if (idx == SIGNCMD_UNPLACE)
6536 {
6537 /* ":sign unplace": remove placed sign at cursor */
6538 id = buf_findsign_id(curwin->w_buffer, curwin->w_cursor.lnum);
6539 if (id > 0)
6540 {
6541 buf_delsign(curwin->w_buffer, id);
6542 update_debug_sign(curwin->w_buffer, curwin->w_cursor.lnum);
6543 }
6544 else
6545 EMSG(_("E159: Missing sign number"));
6546 }
6547 else
6548 EMSG(_(e_argreq));
6549 return;
6550 }
6551
6552 if (idx == SIGNCMD_UNPLACE && arg[0] == '*' && arg[1] == NUL)
6553 {
6554 /* ":sign unplace *": remove all placed signs */
6555 buf_delete_all_signs();
6556 return;
6557 }
6558
6559 /* first arg could be placed sign id */
6560 arg1 = arg;
6561 if (VIM_ISDIGIT(*arg))
6562 {
6563 id = getdigits(&arg);
6564 if (!vim_iswhite(*arg) && *arg != NUL)
6565 {
6566 id = -1;
6567 arg = arg1;
6568 }
6569 else
6570 {
6571 arg = skipwhite(arg);
6572 if (idx == SIGNCMD_UNPLACE && *arg == NUL)
6573 {
6574 /* ":sign unplace {id}": remove placed sign by number */
6575 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6576 if ((lnum = buf_delsign(buf, id)) != 0)
6577 update_debug_sign(buf, lnum);
6578 return;
6579 }
6580 }
6581 }
6582
6583 /*
6584 * Check for line={lnum} name={name} and file={fname} or buffer={nr}.
6585 * Leave "arg" pointing to {fname}.
6586 */
6587 for (;;)
6588 {
6589 if (STRNCMP(arg, "line=", 5) == 0)
6590 {
6591 arg += 5;
6592 lnum = atoi((char *)arg);
6593 arg = skiptowhite(arg);
6594 }
6595 else if (STRNCMP(arg, "name=", 5) == 0)
6596 {
6597 arg += 5;
6598 sign_name = arg;
6599 arg = skiptowhite(arg);
6600 if (*arg != NUL)
6601 *arg++ = NUL;
6602 }
6603 else if (STRNCMP(arg, "file=", 5) == 0)
6604 {
6605 arg += 5;
6606 buf = buflist_findname(arg);
6607 break;
6608 }
6609 else if (STRNCMP(arg, "buffer=", 7) == 0)
6610 {
6611 arg += 7;
6612 buf = buflist_findnr((int)getdigits(&arg));
6613 if (*skipwhite(arg) != NUL)
6614 EMSG(_(e_trailing));
6615 break;
6616 }
6617 else
6618 {
6619 EMSG(_(e_invarg));
6620 return;
6621 }
6622 arg = skipwhite(arg);
6623 }
6624
6625 if (buf == NULL)
6626 {
6627 EMSG2(_("E158: Invalid buffer name: %s"), arg);
6628 }
6629 else if (id <= 0)
6630 {
6631 if (lnum >= 0 || sign_name != NULL)
6632 EMSG(_(e_invarg));
6633 else
6634 /* ":sign place file={fname}": list placed signs in one file */
6635 sign_list_placed(buf);
6636 }
6637 else if (idx == SIGNCMD_JUMP)
6638 {
6639 /* ":sign jump {id} file={fname}" */
6640 if (lnum >= 0 || sign_name != NULL)
6641 EMSG(_(e_invarg));
6642 else if ((lnum = buf_findsign(buf, id)) > 0)
6643 { /* goto a sign ... */
6644 if (buf_jump_open_win(buf) != NULL)
6645 { /* ... in a current window */
6646 curwin->w_cursor.lnum = lnum;
6647 check_cursor_lnum();
6648 beginline(BL_WHITE);
6649 }
6650 else
6651 { /* ... not currently in a window */
6652 char_u *cmd;
6653
6654 cmd = alloc((unsigned)STRLEN(buf->b_fname) + 25);
6655 if (cmd == NULL)
6656 return;
6657 sprintf((char *)cmd, "e +%ld %s", (long)lnum, buf->b_fname);
6658 do_cmdline_cmd(cmd);
6659 vim_free(cmd);
6660 }
6661#ifdef FEAT_FOLDING
6662 foldOpenCursor();
6663#endif
6664 }
6665 else
6666 EMSGN(_("E157: Invalid sign ID: %ld"), id);
6667 }
6668 else if (idx == SIGNCMD_UNPLACE)
6669 {
6670 /* ":sign unplace {id} file={fname}" */
6671 if (lnum >= 0 || sign_name != NULL)
6672 EMSG(_(e_invarg));
6673 else
6674 {
6675 lnum = buf_delsign(buf, id);
6676 update_debug_sign(buf, lnum);
6677 }
6678 }
6679 /* idx == SIGNCMD_PLACE */
6680 else if (sign_name != NULL)
6681 {
6682 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6683 if (STRCMP(sp->sn_name, sign_name) == 0)
6684 break;
6685 if (sp == NULL)
6686 {
6687 EMSG2(_("E155: Unknown sign: %s"), sign_name);
6688 return;
6689 }
6690 if (lnum > 0)
6691 /* ":sign place {id} line={lnum} name={name} file={fname}":
6692 * place a sign */
6693 buf_addsign(buf, id, lnum, sp->sn_typenr);
6694 else
6695 /* ":sign place {id} file={fname}": change sign type */
6696 lnum = buf_change_sign_type(buf, id, sp->sn_typenr);
6697 update_debug_sign(buf, lnum);
6698 }
6699 else
6700 EMSG(_(e_invarg));
6701 }
6702}
6703
6704#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6705/*
6706 * Allocate the icons. Called when the GUI has started. Allows defining
6707 * signs before it starts.
6708 */
6709 void
6710sign_gui_started()
6711{
6712 sign_T *sp;
6713
6714 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6715 if (sp->sn_icon != NULL)
6716 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6717}
6718#endif
6719
6720/*
6721 * List one sign.
6722 */
6723 static void
6724sign_list_defined(sp)
6725 sign_T *sp;
6726{
6727 char_u *p;
6728
Bram Moolenaar555b2802005-05-19 21:08:39 +00006729 smsg((char_u *)"sign %s", sp->sn_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 if (sp->sn_icon != NULL)
6731 {
6732 MSG_PUTS(" icon=");
6733 msg_outtrans(sp->sn_icon);
6734#ifdef FEAT_SIGN_ICONS
6735 if (sp->sn_image == NULL)
6736 MSG_PUTS(_(" (NOT FOUND)"));
6737#else
6738 MSG_PUTS(_(" (not supported)"));
6739#endif
6740 }
6741 if (sp->sn_text != NULL)
6742 {
6743 MSG_PUTS(" text=");
6744 msg_outtrans(sp->sn_text);
6745 }
6746 if (sp->sn_line_hl > 0)
6747 {
6748 MSG_PUTS(" linehl=");
6749 p = get_highlight_name(NULL, sp->sn_line_hl - 1);
6750 if (p == NULL)
6751 MSG_PUTS("NONE");
6752 else
6753 msg_puts(p);
6754 }
6755 if (sp->sn_text_hl > 0)
6756 {
6757 MSG_PUTS(" texthl=");
6758 p = get_highlight_name(NULL, sp->sn_text_hl - 1);
6759 if (p == NULL)
6760 MSG_PUTS("NONE");
6761 else
6762 msg_puts(p);
6763 }
6764}
6765
6766/*
6767 * Get highlighting attribute for sign "typenr".
6768 * If "line" is TRUE: line highl, if FALSE: text highl.
6769 */
6770 int
6771sign_get_attr(typenr, line)
6772 int typenr;
6773 int line;
6774{
6775 sign_T *sp;
6776
6777 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6778 if (sp->sn_typenr == typenr)
6779 {
6780 if (line)
6781 {
6782 if (sp->sn_line_hl > 0)
6783 return syn_id2attr(sp->sn_line_hl);
6784 }
6785 else
6786 {
6787 if (sp->sn_text_hl > 0)
6788 return syn_id2attr(sp->sn_text_hl);
6789 }
6790 break;
6791 }
6792 return 0;
6793}
6794
6795/*
6796 * Get text mark for sign "typenr".
6797 * Returns NULL if there isn't one.
6798 */
6799 char_u *
6800sign_get_text(typenr)
6801 int typenr;
6802{
6803 sign_T *sp;
6804
6805 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6806 if (sp->sn_typenr == typenr)
6807 return sp->sn_text;
6808 return NULL;
6809}
6810
6811#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6812 void *
6813sign_get_image(typenr)
6814 int typenr; /* the attribute which may have a sign */
6815{
6816 sign_T *sp;
6817
6818 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6819 if (sp->sn_typenr == typenr)
6820 return sp->sn_image;
6821 return NULL;
6822}
6823#endif
6824
6825/*
6826 * Get the name of a sign by its typenr.
6827 */
6828 char_u *
6829sign_typenr2name(typenr)
6830 int typenr;
6831{
6832 sign_T *sp;
6833
6834 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6835 if (sp->sn_typenr == typenr)
6836 return sp->sn_name;
6837 return (char_u *)_("[Deleted]");
6838}
6839
6840#endif
6841
6842#if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
6843/*
6844 * ":drop"
6845 * Opens the first argument in a window. When there are two or more arguments
6846 * the argument list is redefined.
6847 */
6848 void
6849ex_drop(eap)
6850 exarg_T *eap;
6851{
6852 int split = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 win_T *wp;
6854 buf_T *buf;
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006855# ifdef FEAT_WINDOWS
6856 tabpage_T *tp;
6857# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858
6859 /*
6860 * Check if the first argument is already being edited in a window. If
6861 * so, jump to that window.
6862 * We would actually need to check all arguments, but that's complicated
6863 * and mostly only one file is dropped.
6864 * This also ignores wildcards, since it is very unlikely the user is
6865 * editing a file name with a wildcard character.
6866 */
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006867 set_arglist(eap->arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006869# ifdef FEAT_WINDOWS
6870 if (cmdmod.tab)
6871 {
6872 /* ":tab drop file ...": open a tab for each argument that isn't
6873 * edited in a window yet. It's like ":tab all" but without closing
6874 * windows or tabs. */
6875 ex_all(eap);
6876 }
6877 else
6878# endif
6879 {
6880 /* ":drop file ...": Edit the first argument. Jump to an existing
6881 * window if possible, edit in current window if the current buffer
6882 * can be abandoned, otherwise open a new window. */
6883 buf = buflist_findnr(ARGLIST[0].ae_fnum);
6884
6885 FOR_ALL_TAB_WINDOWS(tp, wp)
6886 {
6887 if (wp->w_buffer == buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 {
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006889# ifdef FEAT_WINDOWS
6890 goto_tabpage_tp(tp);
6891 win_enter(wp, TRUE);
6892# ifdef FEAT_GUI_TABLINE
6893 if (gui_use_tabline())
6894 gui_mch_set_curtab(tabpage_index(curtab));
6895# endif
6896# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 curwin->w_arg_idx = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 return;
6899 }
6900 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006902 /*
6903 * Check whether the current buffer is changed. If so, we will need
6904 * to split the current window or data could be lost.
6905 * Skip the check if the 'hidden' option is set, as in this case the
6906 * buffer won't be lost.
6907 */
6908 if (!P_HID(curbuf))
6909 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910# ifdef FEAT_WINDOWS
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006911 ++emsg_off;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912# endif
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006913 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914# ifdef FEAT_WINDOWS
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006915 --emsg_off;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916# else
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006917 if (split)
6918 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919# endif
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006920 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006922 /* Fake a ":sfirst" or ":first" command edit the first argument. */
6923 if (split)
6924 {
6925 eap->cmdidx = CMD_sfirst;
6926 eap->cmd[0] = 's';
6927 }
6928 else
6929 eap->cmdidx = CMD_first;
6930 ex_rewind(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932}
6933#endif