blob: 37cef12a5ed15cf9991b3c4d98467c28ac789e26 [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 Moolenaara5792f52005-11-23 21:25:05 +00001814 int fd;
1815
1816 /* Use mch_open() to be able to use O_NOFOLLOW and set file
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001817 * protection:
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001818 * Unix: same as original file, but strip s-bit. Reset umask to
1819 * avoid it getting in the way.
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001820 * Others: r&w for user only. */
Bram Moolenaarbba577a2005-11-28 23:05:55 +00001821#ifdef UNIX
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001822 umask_save = umask(0);
Bram Moolenaara5792f52005-11-23 21:25:05 +00001823 fd = mch_open((char *)tempname,
1824 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW,
Bram Moolenaarbba577a2005-11-28 23:05:55 +00001825 (int)((st_old.st_mode & 0777) | 0600));
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001826 (void)umask(umask_save);
Bram Moolenaar12625ca2005-11-25 19:58:47 +00001827#else
Bram Moolenaarbba577a2005-11-28 23:05:55 +00001828 fd = mch_open((char *)tempname,
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001829 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW, 0600);
Bram Moolenaar12625ca2005-11-25 19:58:47 +00001830#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +00001831 if (fd < 0)
1832 fp_out = NULL;
1833 else
1834 fp_out = fdopen(fd, WRITEBIN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835
1836 /*
1837 * If we can't create in the same directory, try creating a
1838 * "normal" temp file.
1839 */
1840 if (fp_out == NULL)
1841 {
1842 vim_free(tempname);
1843 if ((tempname = vim_tempname('o')) != NULL)
1844 fp_out = mch_fopen((char *)tempname, WRITEBIN);
1845 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00001846
1847#if defined(UNIX) && defined(HAVE_FCHOWN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848 /*
Bram Moolenaara5792f52005-11-23 21:25:05 +00001849 * Make sure the owner can read/write it. This only works for
1850 * root.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 */
1852 if (fp_out != NULL)
Bram Moolenaara5792f52005-11-23 21:25:05 +00001853 (void)fchown(fileno(fp_out), st_old.st_uid, st_old.st_gid);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854#endif
1855 }
1856 }
1857
1858 /*
1859 * Check if the new viminfo file can be written to.
1860 */
1861 if (fp_out == NULL)
1862 {
1863 EMSG2(_("E138: Can't write viminfo file %s!"),
Bram Moolenaar75c50c42005-06-04 22:06:24 +00001864 (fp_in == NULL || tempname == NULL) ? fname : tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 if (fp_in != NULL)
1866 fclose(fp_in);
1867 goto end;
1868 }
1869
1870 if (p_verbose > 0)
Bram Moolenaar54ee7752005-05-31 22:22:17 +00001871 {
1872 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00001873 smsg((char_u *)_("Writing viminfo file \"%s\""), fname);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00001874 verbose_leave();
1875 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876
1877 viminfo_errcnt = 0;
1878 do_viminfo(fp_in, fp_out, !forceit, !forceit, FALSE);
1879
1880 fclose(fp_out); /* errors are ignored !? */
1881 if (fp_in != NULL)
1882 {
1883 fclose(fp_in);
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001884
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885 /*
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001886 * In case of an error keep the original viminfo file.
1887 * Otherwise rename the newly written file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888 */
1889 if (viminfo_errcnt || vim_rename(tempname, fname) == -1)
1890 mch_remove(tempname);
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001891
1892#ifdef WIN3264
1893 /* If the viminfo file was hidden then also hide the new file. */
1894 if (perm > 0 && (perm & FILE_ATTRIBUTE_HIDDEN))
1895 mch_hide(fname);
1896#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 }
Bram Moolenaarbca84a12005-12-14 22:08:35 +00001898
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899end:
1900 vim_free(fname);
1901 vim_free(tempname);
1902}
1903
1904/*
1905 * Get the viminfo file name to use.
1906 * If "file" is given and not empty, use it (has already been expanded by
1907 * cmdline functions).
1908 * Otherwise use "-i file_name", value from 'viminfo' or the default, and
1909 * expand environment variables.
1910 * Returns an allocated string. NULL when out of memory.
1911 */
1912 static char_u *
1913viminfo_filename(file)
1914 char_u *file;
1915{
1916 if (file == NULL || *file == NUL)
1917 {
1918 if (use_viminfo != NULL)
1919 file = use_viminfo;
1920 else if ((file = find_viminfo_parameter('n')) == NULL || *file == NUL)
1921 {
1922#ifdef VIMINFO_FILE2
1923 /* don't use $HOME when not defined (turned into "c:/"!). */
1924# ifdef VMS
1925 if (mch_getenv((char_u *)"SYS$LOGIN") == NULL)
1926# else
1927 if (mch_getenv((char_u *)"HOME") == NULL)
1928# endif
1929 {
1930 /* don't use $VIM when not available. */
1931 expand_env((char_u *)"$VIM", NameBuff, MAXPATHL);
1932 if (STRCMP("$VIM", NameBuff) != 0) /* $VIM was expanded */
1933 file = (char_u *)VIMINFO_FILE2;
1934 else
1935 file = (char_u *)VIMINFO_FILE;
1936 }
1937 else
1938#endif
1939 file = (char_u *)VIMINFO_FILE;
1940 }
1941 expand_env(file, NameBuff, MAXPATHL);
1942 file = NameBuff;
1943 }
1944 return vim_strsave(file);
1945}
1946
1947/*
1948 * do_viminfo() -- Should only be called from read_viminfo() & write_viminfo().
1949 */
1950 static void
1951do_viminfo(fp_in, fp_out, want_info, want_marks, force_read)
1952 FILE *fp_in;
1953 FILE *fp_out;
1954 int want_info;
1955 int want_marks;
1956 int force_read;
1957{
1958 int count = 0;
1959 int eof = FALSE;
1960 vir_T vir;
1961
1962 if ((vir.vir_line = alloc(LSIZE)) == NULL)
1963 return;
1964 vir.vir_fd = fp_in;
1965#ifdef FEAT_MBYTE
1966 vir.vir_conv.vc_type = CONV_NONE;
1967#endif
1968
1969 if (fp_in != NULL)
1970 {
1971 if (want_info)
1972 eof = read_viminfo_up_to_marks(&vir, force_read, fp_out != NULL);
1973 else
1974 /* Skip info, find start of marks */
1975 while (!(eof = viminfo_readline(&vir))
1976 && vir.vir_line[0] != '>')
1977 ;
1978 }
1979 if (fp_out != NULL)
1980 {
1981 /* Write the info: */
1982 fprintf(fp_out, _("# This viminfo file was generated by Vim %s.\n"),
1983 VIM_VERSION_MEDIUM);
1984 fprintf(fp_out, _("# You may edit it if you're careful!\n\n"));
1985#ifdef FEAT_MBYTE
1986 fprintf(fp_out, _("# Value of 'encoding' when this file was written\n"));
1987 fprintf(fp_out, "*encoding=%s\n\n", p_enc);
1988#endif
1989 write_viminfo_search_pattern(fp_out);
1990 write_viminfo_sub_string(fp_out);
1991#ifdef FEAT_CMDHIST
1992 write_viminfo_history(fp_out);
1993#endif
1994 write_viminfo_registers(fp_out);
1995#ifdef FEAT_EVAL
1996 write_viminfo_varlist(fp_out);
1997#endif
1998 write_viminfo_filemarks(fp_out);
1999 write_viminfo_bufferlist(fp_out);
2000 count = write_viminfo_marks(fp_out);
2001 }
2002 if (fp_in != NULL && want_marks)
2003 copy_viminfo_marks(&vir, fp_out, count, eof);
2004
2005 vim_free(vir.vir_line);
2006#ifdef FEAT_MBYTE
2007 if (vir.vir_conv.vc_type != CONV_NONE)
2008 convert_setup(&vir.vir_conv, NULL, NULL);
2009#endif
2010}
2011
2012/*
2013 * read_viminfo_up_to_marks() -- Only called from do_viminfo(). Reads in the
2014 * first part of the viminfo file which contains everything but the marks that
2015 * are local to a file. Returns TRUE when end-of-file is reached. -- webb
2016 */
2017 static int
2018read_viminfo_up_to_marks(virp, forceit, writing)
2019 vir_T *virp;
2020 int forceit;
2021 int writing;
2022{
2023 int eof;
2024 buf_T *buf;
2025
2026#ifdef FEAT_CMDHIST
2027 prepare_viminfo_history(forceit ? 9999 : 0);
2028#endif
2029 eof = viminfo_readline(virp);
2030 while (!eof && virp->vir_line[0] != '>')
2031 {
2032 switch (virp->vir_line[0])
2033 {
2034 /* Characters reserved for future expansion, ignored now */
2035 case '+': /* "+40 /path/dir file", for running vim without args */
2036 case '|': /* to be defined */
2037 case '^': /* to be defined */
2038 case '<': /* long line - ignored */
2039 /* A comment or empty line. */
2040 case NUL:
2041 case '\r':
2042 case '\n':
2043 case '#':
2044 eof = viminfo_readline(virp);
2045 break;
2046 case '*': /* "*encoding=value" */
2047 eof = viminfo_encoding(virp);
2048 break;
2049 case '!': /* global variable */
2050#ifdef FEAT_EVAL
2051 eof = read_viminfo_varlist(virp, writing);
2052#else
2053 eof = viminfo_readline(virp);
2054#endif
2055 break;
2056 case '%': /* entry for buffer list */
2057 eof = read_viminfo_bufferlist(virp, writing);
2058 break;
2059 case '"':
2060 eof = read_viminfo_register(virp, forceit);
2061 break;
2062 case '/': /* Search string */
2063 case '&': /* Substitute search string */
2064 case '~': /* Last search string, followed by '/' or '&' */
2065 eof = read_viminfo_search_pattern(virp, forceit);
2066 break;
2067 case '$':
2068 eof = read_viminfo_sub_string(virp, forceit);
2069 break;
2070 case ':':
2071 case '?':
2072 case '=':
2073 case '@':
2074#ifdef FEAT_CMDHIST
2075 eof = read_viminfo_history(virp);
2076#else
2077 eof = viminfo_readline(virp);
2078#endif
2079 break;
2080 case '-':
2081 case '\'':
2082 eof = read_viminfo_filemark(virp, forceit);
2083 break;
2084 default:
2085 if (viminfo_error("E575: ", _("Illegal starting char"),
2086 virp->vir_line))
2087 eof = TRUE;
2088 else
2089 eof = viminfo_readline(virp);
2090 break;
2091 }
2092 }
2093
2094#ifdef FEAT_CMDHIST
2095 /* Finish reading history items. */
2096 finish_viminfo_history();
2097#endif
2098
2099 /* Change file names to buffer numbers for fmarks. */
2100 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2101 fmarks_check_names(buf);
2102
2103 return eof;
2104}
2105
2106/*
2107 * Compare the 'encoding' value in the viminfo file with the current value of
2108 * 'encoding'. If different and the 'c' flag is in 'viminfo', setup for
2109 * conversion of text with iconv() in viminfo_readstring().
2110 */
2111 static int
2112viminfo_encoding(virp)
2113 vir_T *virp;
2114{
2115#ifdef FEAT_MBYTE
2116 char_u *p;
2117 int i;
2118
2119 if (get_viminfo_parameter('c') != 0)
2120 {
2121 p = vim_strchr(virp->vir_line, '=');
2122 if (p != NULL)
2123 {
2124 /* remove trailing newline */
2125 ++p;
2126 for (i = 0; vim_isprintc(p[i]); ++i)
2127 ;
2128 p[i] = NUL;
2129
2130 convert_setup(&virp->vir_conv, p, p_enc);
2131 }
2132 }
2133#endif
2134 return viminfo_readline(virp);
2135}
2136
2137/*
2138 * Read a line from the viminfo file.
2139 * Returns TRUE for end-of-file;
2140 */
2141 int
2142viminfo_readline(virp)
2143 vir_T *virp;
2144{
2145 return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
2146}
2147
2148/*
2149 * check string read from viminfo file
2150 * remove '\n' at the end of the line
2151 * - replace CTRL-V CTRL-V with CTRL-V
2152 * - replace CTRL-V 'n' with '\n'
2153 *
2154 * Check for a long line as written by viminfo_writestring().
2155 *
2156 * Return the string in allocated memory (NULL when out of memory).
2157 */
2158/*ARGSUSED*/
2159 char_u *
2160viminfo_readstring(virp, off, convert)
2161 vir_T *virp;
2162 int off; /* offset for virp->vir_line */
2163 int convert; /* convert the string */
2164{
2165 char_u *retval;
2166 char_u *s, *d;
2167 long len;
2168
2169 if (virp->vir_line[off] == Ctrl_V && vim_isdigit(virp->vir_line[off + 1]))
2170 {
2171 len = atol((char *)virp->vir_line + off + 1);
2172 retval = lalloc(len, TRUE);
2173 if (retval == NULL)
2174 {
2175 /* Line too long? File messed up? Skip next line. */
2176 (void)vim_fgets(virp->vir_line, 10, virp->vir_fd);
2177 return NULL;
2178 }
2179 (void)vim_fgets(retval, (int)len, virp->vir_fd);
2180 s = retval + 1; /* Skip the leading '<' */
2181 }
2182 else
2183 {
2184 retval = vim_strsave(virp->vir_line + off);
2185 if (retval == NULL)
2186 return NULL;
2187 s = retval;
2188 }
2189
2190 /* Change CTRL-V CTRL-V to CTRL-V and CTRL-V n to \n in-place. */
2191 d = retval;
2192 while (*s != NUL && *s != '\n')
2193 {
2194 if (s[0] == Ctrl_V && s[1] != NUL)
2195 {
2196 if (s[1] == 'n')
2197 *d++ = '\n';
2198 else
2199 *d++ = Ctrl_V;
2200 s += 2;
2201 }
2202 else
2203 *d++ = *s++;
2204 }
2205 *d = NUL;
2206
2207#ifdef FEAT_MBYTE
2208 if (convert && virp->vir_conv.vc_type != CONV_NONE && *retval != NUL)
2209 {
2210 d = string_convert(&virp->vir_conv, retval, NULL);
2211 if (d != NULL)
2212 {
2213 vim_free(retval);
2214 retval = d;
2215 }
2216 }
2217#endif
2218
2219 return retval;
2220}
2221
2222/*
2223 * write string to viminfo file
2224 * - replace CTRL-V with CTRL-V CTRL-V
2225 * - replace '\n' with CTRL-V 'n'
2226 * - add a '\n' at the end
2227 *
2228 * For a long line:
2229 * - write " CTRL-V <length> \n " in first line
2230 * - write " < <string> \n " in second line
2231 */
2232 void
2233viminfo_writestring(fd, p)
2234 FILE *fd;
2235 char_u *p;
2236{
2237 int c;
2238 char_u *s;
2239 int len = 0;
2240
2241 for (s = p; *s != NUL; ++s)
2242 {
2243 if (*s == Ctrl_V || *s == '\n')
2244 ++len;
2245 ++len;
2246 }
2247
2248 /* If the string will be too long, write its length and put it in the next
2249 * line. Take into account that some room is needed for what comes before
2250 * the string (e.g., variable name). Add something to the length for the
2251 * '<', NL and trailing NUL. */
2252 if (len > LSIZE / 2)
2253 fprintf(fd, IF_EB("\026%d\n<", CTRL_V_STR "%d\n<"), len + 3);
2254
2255 while ((c = *p++) != NUL)
2256 {
2257 if (c == Ctrl_V || c == '\n')
2258 {
2259 putc(Ctrl_V, fd);
2260 if (c == '\n')
2261 c = 'n';
2262 }
2263 putc(c, fd);
2264 }
2265 putc('\n', fd);
2266}
2267#endif /* FEAT_VIMINFO */
2268
2269/*
2270 * Implementation of ":fixdel", also used by get_stty().
2271 * <BS> resulting <Del>
2272 * ^? ^H
2273 * not ^? ^?
2274 */
2275/*ARGSUSED*/
2276 void
2277do_fixdel(eap)
2278 exarg_T *eap;
2279{
2280 char_u *p;
2281
2282 p = find_termcode((char_u *)"kb");
2283 add_termcode((char_u *)"kD", p != NULL
2284 && *p == DEL ? (char_u *)CTRL_H_STR : DEL_STR, FALSE);
2285}
2286
2287 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002288print_line_no_prefix(lnum, use_number, list)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 linenr_T lnum;
2290 int use_number;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002291 int list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292{
Bram Moolenaar592e0a22004-07-03 16:05:59 +00002293 char_u numbuf[30];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294
2295 if (curwin->w_p_nu || use_number)
2296 {
Bram Moolenaar592e0a22004-07-03 16:05:59 +00002297 sprintf((char *)numbuf, "%*ld ", number_width(curwin), (long)lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 msg_puts_attr(numbuf, hl_attr(HLF_N)); /* Highlight line nrs */
2299 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002300 msg_prt_line(ml_get(lnum), list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301}
2302
2303/*
2304 * Print a text line. Also in silent mode ("ex -s").
2305 */
2306 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002307print_line(lnum, use_number, list)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 linenr_T lnum;
2309 int use_number;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002310 int list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311{
2312 int save_silent = silent_mode;
2313
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314 msg_start();
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002315 silent_mode = FALSE;
2316 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
2317 print_line_no_prefix(lnum, use_number, list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 if (save_silent)
2319 {
2320 msg_putchar('\n');
2321 cursor_on(); /* msg_start() switches it off */
2322 out_flush();
2323 silent_mode = save_silent;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00002324 info_message = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 }
2326}
2327
2328/*
2329 * ":file[!] [fname]".
2330 */
2331 void
2332ex_file(eap)
2333 exarg_T *eap;
2334{
2335 char_u *fname, *sfname, *xfname;
2336 buf_T *buf;
2337
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002338 /* ":0file" removes the file name. Check for illegal uses ":3file",
2339 * "0file name", etc. */
2340 if (eap->addr_count > 0
2341 && (*eap->arg != NUL
2342 || eap->line2 > 0
2343 || eap->addr_count > 1))
2344 {
2345 EMSG(_(e_invarg));
2346 return;
2347 }
2348
2349 if (*eap->arg != NUL || eap->addr_count == 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 {
2351#ifdef FEAT_AUTOCMD
2352 buf = curbuf;
2353 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
2354 /* buffer changed, don't change name now */
2355 if (buf != curbuf)
2356 return;
2357# ifdef FEAT_EVAL
2358 if (aborting()) /* autocmds may abort script processing */
2359 return;
2360# endif
2361#endif
2362 /*
2363 * The name of the current buffer will be changed.
2364 * A new (unlisted) buffer entry needs to be made to hold the old file
2365 * name, which will become the alternate file name.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002366 * But don't set the alternate file name if the buffer didn't have a
2367 * name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 */
2369 fname = curbuf->b_ffname;
2370 sfname = curbuf->b_sfname;
2371 xfname = curbuf->b_fname;
2372 curbuf->b_ffname = NULL;
2373 curbuf->b_sfname = NULL;
2374 if (setfname(curbuf, eap->arg, NULL, TRUE) == FAIL)
2375 {
2376 curbuf->b_ffname = fname;
2377 curbuf->b_sfname = sfname;
2378 return;
2379 }
2380 curbuf->b_flags |= BF_NOTEDITED;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002381 if (xfname != NULL && *xfname != NUL)
2382 {
2383 buf = buflist_new(fname, xfname, curwin->w_cursor.lnum, 0);
2384 if (buf != NULL && !cmdmod.keepalt)
2385 curwin->w_alt_fnum = buf->b_fnum;
2386 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 vim_free(fname);
2388 vim_free(sfname);
2389#ifdef FEAT_AUTOCMD
2390 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
2391#endif
2392 }
2393 /* print full file name if :cd used */
2394 fileinfo(FALSE, FALSE, eap->forceit);
2395}
2396
2397/*
2398 * ":update".
2399 */
2400 void
2401ex_update(eap)
2402 exarg_T *eap;
2403{
2404 if (curbufIsChanged())
2405 (void)do_write(eap);
2406}
2407
2408/*
2409 * ":write" and ":saveas".
2410 */
2411 void
2412ex_write(eap)
2413 exarg_T *eap;
2414{
2415 if (eap->usefilter) /* input lines to shell command */
2416 do_bang(1, eap, FALSE, TRUE, FALSE);
2417 else
2418 (void)do_write(eap);
2419}
2420
2421/*
2422 * write current buffer to file 'eap->arg'
2423 * if 'eap->append' is TRUE, append to the file
2424 *
2425 * if *eap->arg == NUL write to current file
2426 *
2427 * return FAIL for failure, OK otherwise
2428 */
2429 int
2430do_write(eap)
2431 exarg_T *eap;
2432{
2433 int other;
2434 char_u *fname = NULL; /* init to shut up gcc */
2435 char_u *ffname;
2436 int retval = FAIL;
2437 char_u *free_fname = NULL;
2438#ifdef FEAT_BROWSE
2439 char_u *browse_file = NULL;
2440#endif
2441 buf_T *alt_buf = NULL;
2442
2443 if (not_writing()) /* check 'write' option */
2444 return FAIL;
2445
2446 ffname = eap->arg;
2447#ifdef FEAT_BROWSE
2448 if (cmdmod.browse)
2449 {
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002450 browse_file = do_browse(BROWSE_SAVE, (char_u *)_("Save As"), ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 NULL, NULL, NULL, curbuf);
2452 if (browse_file == NULL)
2453 goto theend;
2454 ffname = browse_file;
2455 }
2456#endif
2457 if (*ffname == NUL)
2458 {
2459 if (eap->cmdidx == CMD_saveas)
2460 {
2461 EMSG(_(e_argreq));
2462 goto theend;
2463 }
2464 other = FALSE;
2465 }
2466 else
2467 {
2468 fname = ffname;
2469 free_fname = fix_fname(ffname);
2470 /*
2471 * When out-of-memory, keep unexpanded file name, because we MUST be
2472 * able to write the file in this situation.
2473 */
2474 if (free_fname != NULL)
2475 ffname = free_fname;
2476 other = otherfile(ffname);
2477 }
2478
2479 /*
2480 * If we have a new file, put its name in the list of alternate file names.
2481 */
2482 if (other)
2483 {
2484 if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL
2485 || eap->cmdidx == CMD_saveas)
2486 alt_buf = setaltfname(ffname, fname, (linenr_T)1);
2487 else
2488 alt_buf = buflist_findname(ffname);
2489 if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL)
2490 {
2491 /* Overwriting a file that is loaded in another buffer is not a
2492 * good idea. */
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002493 EMSG(_(e_bufloaded));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 goto theend;
2495 }
2496 }
2497
2498 /*
2499 * Writing to the current file is not allowed in readonly mode
2500 * and a file name is required.
2501 * "nofile" and "nowrite" buffers cannot be written implicitly either.
2502 */
2503 if (!other && (
2504#ifdef FEAT_QUICKFIX
2505 bt_dontwrite_msg(curbuf) ||
2506#endif
2507 check_fname() == FAIL || check_readonly(&eap->forceit, curbuf)))
2508 goto theend;
2509
2510 if (!other)
2511 {
2512 ffname = curbuf->b_ffname;
2513 fname = curbuf->b_fname;
2514 /*
2515 * Not writing the whole file is only allowed with '!'.
2516 */
2517 if ( (eap->line1 != 1
2518 || eap->line2 != curbuf->b_ml.ml_line_count)
2519 && !eap->forceit
2520 && !eap->append
2521 && !p_wa)
2522 {
2523#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2524 if (p_confirm || cmdmod.confirm)
2525 {
2526 if (vim_dialog_yesno(VIM_QUESTION, NULL,
2527 (char_u *)_("Write partial file?"), 2) != VIM_YES)
2528 goto theend;
2529 eap->forceit = TRUE;
2530 }
2531 else
2532#endif
2533 {
2534 EMSG(_("E140: Use ! to write partial buffer"));
2535 goto theend;
2536 }
2537 }
2538 }
2539
2540 if (check_overwrite(eap, curbuf, fname, ffname, other) == OK)
2541 {
2542 if (eap->cmdidx == CMD_saveas && alt_buf != NULL)
2543 {
2544#ifdef FEAT_AUTOCMD
2545 buf_T *was_curbuf = curbuf;
2546
2547 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
Bram Moolenaar269ec652004-07-29 08:43:53 +00002548 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549# ifdef FEAT_EVAL
2550 if (curbuf != was_curbuf || aborting())
2551# else
2552 if (curbuf != was_curbuf)
2553# endif
2554 {
2555 /* buffer changed, don't change name now */
2556 retval = FAIL;
2557 goto theend;
2558 }
2559#endif
2560 /* Exchange the file names for the current and the alternate
2561 * buffer. This makes it look like we are now editing the buffer
2562 * under the new name. Must be done before buf_write(), because
2563 * if there is no file name and 'cpo' contains 'F', it will set
2564 * the file name. */
2565 fname = alt_buf->b_fname;
2566 alt_buf->b_fname = curbuf->b_fname;
2567 curbuf->b_fname = fname;
2568 fname = alt_buf->b_ffname;
2569 alt_buf->b_ffname = curbuf->b_ffname;
2570 curbuf->b_ffname = fname;
2571 fname = alt_buf->b_sfname;
2572 alt_buf->b_sfname = curbuf->b_sfname;
2573 curbuf->b_sfname = fname;
2574 buf_name_changed(curbuf);
2575#ifdef FEAT_AUTOCMD
2576 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
Bram Moolenaar269ec652004-07-29 08:43:53 +00002577 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, alt_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 if (!alt_buf->b_p_bl)
2579 {
2580 alt_buf->b_p_bl = TRUE;
2581 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, alt_buf);
2582 }
2583# ifdef FEAT_EVAL
2584 if (curbuf != was_curbuf || aborting())
2585# else
2586 if (curbuf != was_curbuf)
2587# endif
2588 {
2589 /* buffer changed, don't write the file */
2590 retval = FAIL;
2591 goto theend;
2592 }
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002593
2594 /* If 'filetype' was empty try detecting it now. */
2595 if (*curbuf->b_p_ft == NUL)
2596 {
2597 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00002598 do_modelines(0);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600#endif
2601 }
2602
2603 retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2,
2604 eap, eap->append, eap->forceit, TRUE, FALSE);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002605
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 }
2607
2608theend:
2609#ifdef FEAT_BROWSE
2610 vim_free(browse_file);
2611#endif
2612 vim_free(free_fname);
2613 return retval;
2614}
2615
2616/*
2617 * Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED,
2618 * BF_NEW or BF_READERR, check for overwriting current file.
2619 * May set eap->forceit if a dialog says it's OK to overwrite.
2620 * Return OK if it's OK, FAIL if it is not.
2621 */
2622/*ARGSUSED*/
2623 static int
2624check_overwrite(eap, buf, fname, ffname, other)
2625 exarg_T *eap;
2626 buf_T *buf;
2627 char_u *fname; /* file name to be used (can differ from
2628 buf->ffname) */
2629 char_u *ffname; /* full path version of fname */
2630 int other; /* writing under other name */
2631{
2632 /*
2633 * write to other file or b_flags set or not writing the whole file:
2634 * overwriting only allowed with '!'
2635 */
2636 if ( (other
2637 || (buf->b_flags & BF_NOTEDITED)
2638 || ((buf->b_flags & BF_NEW)
2639 && vim_strchr(p_cpo, CPO_OVERNEW) == NULL)
2640 || (buf->b_flags & BF_READERR))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641 && !p_wa
2642 && vim_fexists(ffname))
2643 {
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002644 if (!eap->forceit && !eap->append)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645 {
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002646#ifdef UNIX
Bram Moolenaar0ac93792006-01-21 22:16:51 +00002647 /* with UNIX it is possible to open a directory */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002648 if (mch_isdir(ffname))
2649 {
2650 EMSG2(_(e_isadir2), ffname);
2651 return FAIL;
2652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653#endif
2654#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002655 if (p_confirm || cmdmod.confirm)
2656 {
2657 char_u buff[IOSIZE];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002659 dialog_msg(buff, _("Overwrite existing file \"%s\"?"), fname);
2660 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES)
2661 return FAIL;
2662 eap->forceit = TRUE;
2663 }
2664 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665#endif
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002666 {
2667 EMSG(_(e_exists));
2668 return FAIL;
2669 }
2670 }
2671
2672 /* For ":w! filename" check that no swap file exists for "filename". */
2673 if (other && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 {
Bram Moolenaar04a09c12005-08-01 22:02:32 +00002675 char_u dir[MAXPATHL];
2676 char_u *p;
2677 int r;
2678 char_u *swapname;
2679
2680 /* We only try the first entry in 'directory', without checking if
2681 * it's writable. If the "." directory is not writable the write
2682 * will probably fail anyway.
2683 * Use 'shortname' of the current buffer, since there is no buffer
2684 * for the written file. */
2685 if (*p_dir == NUL)
2686 STRCPY(dir, ".");
2687 else
2688 {
2689 p = p_dir;
2690 copy_option_part(&p, dir, MAXPATHL, ",");
2691 }
2692 swapname = makeswapname(fname, ffname, curbuf, dir);
2693 r = vim_fexists(swapname);
2694 vim_free(swapname);
2695 if (r)
2696 {
2697#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2698 if (p_confirm || cmdmod.confirm)
2699 {
2700 char_u buff[IOSIZE];
2701
2702 dialog_msg(buff,
2703 _("Swap file \"%s\" exists, overwrite anyway?"),
2704 swapname);
2705 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2)
2706 != VIM_YES)
2707 return FAIL;
2708 eap->forceit = TRUE;
2709 }
2710 else
2711#endif
2712 {
2713 EMSG2(_("E768: Swap file exists: %s (:silent! overrides)"),
2714 swapname);
2715 return FAIL;
2716 }
2717 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 }
2719 }
2720 return OK;
2721}
2722
2723/*
2724 * Handle ":wnext", ":wNext" and ":wprevious" commands.
2725 */
2726 void
2727ex_wnext(eap)
2728 exarg_T *eap;
2729{
2730 int i;
2731
2732 if (eap->cmd[1] == 'n')
2733 i = curwin->w_arg_idx + (int)eap->line2;
2734 else
2735 i = curwin->w_arg_idx - (int)eap->line2;
2736 eap->line1 = 1;
2737 eap->line2 = curbuf->b_ml.ml_line_count;
2738 if (do_write(eap) != FAIL)
2739 do_argfile(eap, i);
2740}
2741
2742/*
2743 * ":wall", ":wqall" and ":xall": Write all changed files (and exit).
2744 */
2745 void
2746do_wqall(eap)
2747 exarg_T *eap;
2748{
2749 buf_T *buf;
2750 int error = 0;
2751 int save_forceit = eap->forceit;
2752
2753 if (eap->cmdidx == CMD_xall || eap->cmdidx == CMD_wqall)
2754 exiting = TRUE;
2755
2756 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2757 {
2758 if (bufIsChanged(buf))
2759 {
2760 /*
2761 * Check if there is a reason the buffer cannot be written:
2762 * 1. if the 'write' option is set
2763 * 2. if there is no file name (even after browsing)
2764 * 3. if the 'readonly' is set (even after a dialog)
2765 * 4. if overwriting is allowed (even after a dialog)
2766 */
2767 if (not_writing())
2768 {
2769 ++error;
2770 break;
2771 }
2772#ifdef FEAT_BROWSE
2773 /* ":browse wall": ask for file name if there isn't one */
2774 if (buf->b_ffname == NULL && cmdmod.browse)
2775 browse_save_fname(buf);
2776#endif
2777 if (buf->b_ffname == NULL)
2778 {
2779 EMSGN(_("E141: No file name for buffer %ld"), (long)buf->b_fnum);
2780 ++error;
2781 }
2782 else if (check_readonly(&eap->forceit, buf)
2783 || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname,
2784 FALSE) == FAIL)
2785 {
2786 ++error;
2787 }
2788 else
2789 {
2790 if (buf_write_all(buf, eap->forceit) == FAIL)
2791 ++error;
2792#ifdef FEAT_AUTOCMD
2793 /* an autocommand may have deleted the buffer */
2794 if (!buf_valid(buf))
2795 buf = firstbuf;
2796#endif
2797 }
2798 eap->forceit = save_forceit; /* check_overwrite() may set it */
2799 }
2800 }
2801 if (exiting)
2802 {
2803 if (!error)
2804 getout(0); /* exit Vim */
2805 not_exiting();
2806 }
2807}
2808
2809/*
2810 * Check the 'write' option.
2811 * Return TRUE and give a message when it's not st.
2812 */
2813 int
2814not_writing()
2815{
2816 if (p_write)
2817 return FALSE;
2818 EMSG(_("E142: File not written: Writing is disabled by 'write' option"));
2819 return TRUE;
2820}
2821
2822/*
2823 * Check if a buffer is read-only. Ask for overruling in a dialog.
2824 * Return TRUE and give an error message when the buffer is readonly.
2825 */
2826 static int
2827check_readonly(forceit, buf)
2828 int *forceit;
2829 buf_T *buf;
2830{
2831 if (!*forceit && buf->b_p_ro)
2832 {
2833#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2834 if ((p_confirm || cmdmod.confirm) && buf->b_fname != NULL)
2835 {
2836 char_u buff[IOSIZE];
2837
Bram Moolenaar0e4d8772005-06-07 21:12:49 +00002838 dialog_msg(buff, _("'readonly' option is set for \"%s\".\nDo you wish to write anyway?"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 buf->b_fname);
2840
2841 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES)
2842 {
2843 /* Set forceit, to force the writing of a readonly file */
2844 *forceit = TRUE;
2845 return FALSE;
2846 }
2847 else
2848 return TRUE;
2849 }
2850 else
2851#endif
2852 EMSG(_(e_readonly));
2853 return TRUE;
2854 }
2855 return FALSE;
2856}
2857
2858/*
Bram Moolenaar8ada17c2006-01-19 22:16:24 +00002859 * Try to abandon current file and edit a new or existing file.
2860 * 'fnum' is the number of the file, if zero use ffname/sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 *
Bram Moolenaar8ada17c2006-01-19 22:16:24 +00002862 * Return 1 for "normal" error, 2 for "not written" error, 0 for success
2863 * -1 for succesfully opening another file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864 * 'lnum' is the line number for the cursor in the new file (if non-zero).
2865 */
2866 int
2867getfile(fnum, ffname, sfname, setpm, lnum, forceit)
2868 int fnum;
2869 char_u *ffname;
2870 char_u *sfname;
2871 int setpm;
2872 linenr_T lnum;
2873 int forceit;
2874{
2875 int other;
2876 int retval;
2877 char_u *free_me = NULL;
2878
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00002879 if (text_locked())
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 return 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881
2882 if (fnum == 0)
2883 {
2884 /* make ffname full path, set sfname */
2885 fname_expand(curbuf, &ffname, &sfname);
2886 other = otherfile(ffname);
2887 free_me = ffname; /* has been allocated, free() later */
2888 }
2889 else
2890 other = (fnum != curbuf->b_fnum);
2891
2892 if (other)
2893 ++no_wait_return; /* don't wait for autowrite message */
2894 if (other && !forceit && curbuf->b_nwindows == 1 && !P_HID(curbuf)
2895 && curbufIsChanged() && autowrite(curbuf, forceit) == FAIL)
2896 {
2897#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2898 if (p_confirm && p_write)
2899 dialog_changed(curbuf, FALSE);
2900 if (curbufIsChanged())
2901#endif
2902 {
2903 if (other)
2904 --no_wait_return;
2905 EMSG(_(e_nowrtmsg));
2906 retval = 2; /* file has been changed */
2907 goto theend;
2908 }
2909 }
2910 if (other)
2911 --no_wait_return;
2912 if (setpm)
2913 setpcmark();
2914 if (!other)
2915 {
2916 if (lnum != 0)
2917 curwin->w_cursor.lnum = lnum;
2918 check_cursor_lnum();
2919 beginline(BL_SOL | BL_FIX);
2920 retval = 0; /* it's in the same file */
2921 }
2922 else if (do_ecmd(fnum, ffname, sfname, NULL, lnum,
2923 (P_HID(curbuf) ? ECMD_HIDE : 0) + (forceit ? ECMD_FORCEIT : 0)) == OK)
2924 retval = -1; /* opened another file */
2925 else
2926 retval = 1; /* error encountered */
2927
2928theend:
2929 vim_free(free_me);
2930 return retval;
2931}
2932
2933/*
2934 * start editing a new file
2935 *
2936 * fnum: file number; if zero use ffname/sfname
2937 * ffname: the file name
2938 * - full path if sfname used,
2939 * - any file name if sfname is NULL
2940 * - empty string to re-edit with the same file name (but may be
2941 * in a different directory)
2942 * - NULL to start an empty buffer
2943 * sfname: the short file name (or NULL)
2944 * eap: contains the command to be executed after loading the file and
2945 * forced 'ff' and 'fenc'
2946 * newlnum: if > 0: put cursor on this line number (if possible)
2947 * if ECMD_LASTL: use last position in loaded file
2948 * if ECMD_LAST: use last position in all files
2949 * if ECMD_ONE: use first line
2950 * flags:
2951 * ECMD_HIDE: if TRUE don't free the current buffer
2952 * ECMD_SET_HELP: set b_help flag of (new) buffer before opening file
2953 * ECMD_OLDBUF: use existing buffer if it exists
2954 * ECMD_FORCEIT: ! used for Ex command
2955 * ECMD_ADDBUF: don't edit, just add to buffer list
2956 *
2957 * return FAIL for failure, OK otherwise
2958 */
2959 int
2960do_ecmd(fnum, ffname, sfname, eap, newlnum, flags)
2961 int fnum;
2962 char_u *ffname;
2963 char_u *sfname;
2964 exarg_T *eap; /* can be NULL! */
2965 linenr_T newlnum;
2966 int flags;
2967{
2968 int other_file; /* TRUE if editing another file */
2969 int oldbuf; /* TRUE if using existing buffer */
2970#ifdef FEAT_AUTOCMD
2971 int auto_buf = FALSE; /* TRUE if autocommands brought us
2972 into the buffer unexpectedly */
2973 char_u *new_name = NULL;
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00002974 int did_set_swapcommand = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975#endif
2976 buf_T *buf;
2977#if defined(FEAT_AUTOCMD) || defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2978 buf_T *old_curbuf = curbuf;
2979#endif
2980 char_u *free_fname = NULL;
2981#ifdef FEAT_BROWSE
2982 char_u *browse_file = NULL;
2983#endif
2984 int retval = FAIL;
2985 long n;
2986 linenr_T lnum;
2987 linenr_T topline = 0;
2988 int newcol = -1;
2989 int solcol = -1;
2990 pos_T *pos;
2991#ifdef FEAT_SUN_WORKSHOP
2992 char_u *cp;
2993#endif
2994 char_u *command = NULL;
2995
2996 if (eap != NULL)
2997 command = eap->do_ecmd_cmd;
2998
2999 if (fnum != 0)
3000 {
3001 if (fnum == curbuf->b_fnum) /* file is already being edited */
3002 return OK; /* nothing to do */
3003 other_file = TRUE;
3004 }
3005 else
3006 {
3007#ifdef FEAT_BROWSE
3008 if (cmdmod.browse)
3009 {
Bram Moolenaar0be6e642005-08-04 21:32:22 +00003010 if (
3011# ifdef FEAT_GUI
3012 !gui.in_use &&
3013# endif
3014 au_has_group((char_u *)"FileExplorer"))
3015 {
3016 /* No browsing supported but we do have the file explorer:
3017 * Edit the directory. */
3018 if (ffname == NULL || !mch_isdir(ffname))
3019 ffname = (char_u *)".";
3020 }
3021 else
3022 {
3023 browse_file = do_browse(0, (char_u *)_("Edit File"), ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024 NULL, NULL, NULL, curbuf);
Bram Moolenaar0be6e642005-08-04 21:32:22 +00003025 if (browse_file == NULL)
3026 goto theend;
3027 ffname = browse_file;
3028 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 }
3030#endif
3031 /* if no short name given, use ffname for short name */
3032 if (sfname == NULL)
3033 sfname = ffname;
3034#ifdef USE_FNAME_CASE
3035# ifdef USE_LONG_FNAME
3036 if (USE_LONG_FNAME)
3037# endif
Bram Moolenaar342337a2005-07-21 21:11:17 +00003038 if (sfname != NULL)
3039 fname_case(sfname, 0); /* set correct case for sfname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040#endif
3041
3042#ifdef FEAT_LISTCMDS
3043 if ((flags & ECMD_ADDBUF) && (ffname == NULL || *ffname == NUL))
3044 goto theend;
3045#endif
3046
3047 if (ffname == NULL)
3048 other_file = TRUE;
3049 /* there is no file name */
3050 else if (*ffname == NUL && curbuf->b_ffname == NULL)
3051 other_file = FALSE;
3052 else
3053 {
3054 if (*ffname == NUL) /* re-edit with same file name */
3055 {
3056 ffname = curbuf->b_ffname;
3057 sfname = curbuf->b_fname;
3058 }
3059 free_fname = fix_fname(ffname); /* may expand to full path name */
3060 if (free_fname != NULL)
3061 ffname = free_fname;
3062 other_file = otherfile(ffname);
3063#ifdef FEAT_SUN_WORKSHOP
3064 if (usingSunWorkShop && p_acd
3065 && (cp = vim_strrchr(sfname, '/')) != NULL)
3066 sfname = ++cp;
3067#endif
3068 }
3069 }
3070
3071 /*
3072 * if the file was changed we may not be allowed to abandon it
3073 * - if we are going to re-edit the same file
3074 * - or if we are the only window on this file and if ECMD_HIDE is FALSE
3075 */
3076 if ( ((!other_file && !(flags & ECMD_OLDBUF))
3077 || (curbuf->b_nwindows == 1
3078 && !(flags & (ECMD_HIDE | ECMD_ADDBUF))))
3079 && check_changed(curbuf, p_awa, !other_file,
3080 (flags & ECMD_FORCEIT), FALSE))
3081 {
3082 if (fnum == 0 && other_file && ffname != NULL)
3083 (void)setaltfname(ffname, sfname, newlnum < 0 ? 0 : newlnum);
3084 goto theend;
3085 }
3086
3087#ifdef FEAT_VISUAL
3088 /*
3089 * End Visual mode before switching to another buffer, so the text can be
3090 * copied into the GUI selection buffer.
3091 */
3092 reset_VIsual();
3093#endif
3094
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00003095#ifdef FEAT_AUTOCMD
3096 if ((command != NULL || newlnum > (linenr_T)0)
3097 && *get_vim_var_str(VV_SWAPCOMMAND) == NUL)
3098 {
3099 int len;
3100 char_u *p;
3101
3102 /* Set v:swapcommand for the SwapExists autocommands. */
3103 if (command != NULL)
3104 len = STRLEN(command) + 3;
3105 else
3106 len = 30;
3107 p = alloc((unsigned)len);
3108 if (p != NULL)
3109 {
3110 if (command != NULL)
3111 vim_snprintf((char *)p, len, ":%s\r", command);
3112 else
3113 vim_snprintf((char *)p, len, "%ldG", (long)newlnum);
3114 set_vim_var_string(VV_SWAPCOMMAND, p, -1);
3115 did_set_swapcommand = TRUE;
3116 vim_free(p);
3117 }
3118 }
3119#endif
3120
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121 /*
3122 * If we are starting to edit another file, open a (new) buffer.
3123 * Otherwise we re-use the current buffer.
3124 */
3125 if (other_file)
3126 {
3127#ifdef FEAT_LISTCMDS
3128 if (!(flags & ECMD_ADDBUF))
3129#endif
3130 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003131 if (!cmdmod.keepalt)
3132 curwin->w_alt_fnum = curbuf->b_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 buflist_altfpos();
3134 }
3135
3136 if (fnum)
3137 buf = buflist_findnr(fnum);
3138 else
3139 {
3140#ifdef FEAT_LISTCMDS
3141 if (flags & ECMD_ADDBUF)
3142 {
3143 linenr_T tlnum = 1L;
3144
3145 if (command != NULL)
3146 {
3147 tlnum = atol((char *)command);
3148 if (tlnum <= 0)
3149 tlnum = 1L;
3150 }
3151 (void)buflist_new(ffname, sfname, tlnum, BLN_LISTED);
3152 goto theend;
3153 }
3154#endif
3155 buf = buflist_new(ffname, sfname, 0L,
3156 BLN_CURBUF | ((flags & ECMD_SET_HELP) ? 0 : BLN_LISTED));
3157 }
3158 if (buf == NULL)
3159 goto theend;
3160 if (buf->b_ml.ml_mfp == NULL) /* no memfile yet */
3161 {
3162 oldbuf = FALSE;
3163 buf->b_nwindows = 0;
3164 }
3165 else /* existing memfile */
3166 {
3167 oldbuf = TRUE;
3168 (void)buf_check_timestamp(buf, FALSE);
3169 /* Check if autocommands made buffer invalid or changed the current
3170 * buffer. */
3171 if (!buf_valid(buf)
3172#ifdef FEAT_AUTOCMD
3173 || curbuf != old_curbuf
3174#endif
3175 )
3176 goto theend;
3177#ifdef FEAT_EVAL
3178 if (aborting()) /* autocmds may abort script processing */
3179 goto theend;
3180#endif
3181 }
3182
3183 /* May jump to last used line number for a loaded buffer or when asked
3184 * for explicitly */
3185 if ((oldbuf && newlnum == ECMD_LASTL) || newlnum == ECMD_LAST)
3186 {
3187 pos = buflist_findfpos(buf);
3188 newlnum = pos->lnum;
3189 solcol = pos->col;
3190 }
3191
3192 /*
3193 * Make the (new) buffer the one used by the current window.
3194 * If the old buffer becomes unused, free it if ECMD_HIDE is FALSE.
3195 * If the current buffer was empty and has no file name, curbuf
3196 * is returned by buflist_new().
3197 */
3198 if (buf != curbuf)
3199 {
3200#ifdef FEAT_AUTOCMD
3201 /*
3202 * Be careful: The autocommands may delete any buffer and change
3203 * the current buffer.
3204 * - If the buffer we are going to edit is deleted, give up.
3205 * - If the current buffer is deleted, prefer to load the new
3206 * buffer when loading a buffer is required. This avoids
3207 * loading another buffer which then must be closed again.
3208 * - If we ended up in the new buffer already, need to skip a few
3209 * things, set auto_buf.
3210 */
3211 if (buf->b_fname != NULL)
3212 new_name = vim_strsave(buf->b_fname);
3213 au_new_curbuf = buf;
3214 apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
3215 if (!buf_valid(buf)) /* new buffer has been deleted */
3216 {
3217 delbuf_msg(new_name); /* frees new_name */
3218 goto theend;
3219 }
3220# ifdef FEAT_EVAL
3221 if (aborting()) /* autocmds may abort script processing */
3222 {
3223 vim_free(new_name);
3224 goto theend;
3225 }
3226# endif
3227 if (buf == curbuf) /* already in new buffer */
3228 auto_buf = TRUE;
3229 else
3230 {
3231 if (curbuf == old_curbuf)
3232#endif
3233 buf_copy_options(buf, BCO_ENTER);
3234
3235 /* close the link to the current buffer */
3236 close_buffer(curwin, curbuf,
3237 (flags & ECMD_HIDE) ? 0 : DOBUF_UNLOAD);
3238
3239#ifdef FEAT_AUTOCMD
3240# ifdef FEAT_EVAL
3241 if (aborting()) /* autocmds may abort script processing */
3242 {
3243 vim_free(new_name);
3244 goto theend;
3245 }
3246# endif
3247 /* Be careful again, like above. */
3248 if (!buf_valid(buf)) /* new buffer has been deleted */
3249 {
3250 delbuf_msg(new_name); /* frees new_name */
3251 goto theend;
3252 }
3253 if (buf == curbuf) /* already in new buffer */
3254 auto_buf = TRUE;
3255 else
3256#endif
3257 {
3258 curwin->w_buffer = buf;
3259 curbuf = buf;
3260 ++curbuf->b_nwindows;
3261 /* set 'fileformat' */
3262 if (*p_ffs && !oldbuf)
3263 set_fileformat(default_fileformat(), OPT_LOCAL);
3264 }
3265
3266 /* May get the window options from the last time this buffer
3267 * was in this window (or another window). If not used
3268 * before, reset the local window options to the global
3269 * values. Also restores old folding stuff. */
3270 get_winopts(buf);
3271
3272#ifdef FEAT_AUTOCMD
3273 }
3274 vim_free(new_name);
3275 au_new_curbuf = NULL;
3276#endif
3277 }
3278 else
3279 ++curbuf->b_nwindows;
3280
3281 curwin->w_pcmark.lnum = 1;
3282 curwin->w_pcmark.col = 0;
3283 }
3284 else /* !other_file */
3285 {
3286 if (
3287#ifdef FEAT_LISTCMDS
3288 (flags & ECMD_ADDBUF) ||
3289#endif
3290 check_fname() == FAIL)
3291 goto theend;
3292 oldbuf = (flags & ECMD_OLDBUF);
3293 }
3294
3295 if ((flags & ECMD_SET_HELP) || keep_help_flag)
3296 {
3297 char_u *p;
3298
3299 curbuf->b_help = TRUE;
3300#ifdef FEAT_QUICKFIX
3301 set_string_option_direct((char_u *)"buftype", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003302 (char_u *)"help", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303#endif
3304
3305 /*
3306 * Always set these options after jumping to a help tag, because the
3307 * user may have an autocommand that gets in the way.
3308 * Accept all ASCII chars for keywords, except ' ', '*', '"', '|', and
3309 * latin1 word characters (for translated help files).
3310 * Only set it when needed, buf_init_chartab() is some work.
3311 */
3312 p =
3313#ifdef EBCDIC
3314 (char_u *)"65-255,^*,^|,^\"";
3315#else
3316 (char_u *)"!-~,^*,^|,^\",192-255";
3317#endif
3318 if (STRCMP(curbuf->b_p_isk, p) != 0)
3319 {
3320 set_string_option_direct((char_u *)"isk", -1, p,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003321 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 check_buf_options(curbuf);
3323 (void)buf_init_chartab(curbuf, FALSE);
3324 }
3325
3326 curbuf->b_p_ts = 8; /* 'tabstop' is 8 */
3327 curwin->w_p_list = FALSE; /* no list mode */
3328
3329 curbuf->b_p_ma = FALSE; /* not modifiable */
3330 curbuf->b_p_bin = FALSE; /* reset 'bin' before reading file */
3331 curwin->w_p_nu = 0; /* no line numbers */
3332#ifdef FEAT_SCROLLBIND
3333 curwin->w_p_scb = FALSE; /* no scroll binding */
3334#endif
3335#ifdef FEAT_ARABIC
3336 curwin->w_p_arab = FALSE; /* no arabic mode */
3337#endif
3338#ifdef FEAT_RIGHTLEFT
3339 curwin->w_p_rl = FALSE; /* help window is left-to-right */
3340#endif
3341#ifdef FEAT_FOLDING
3342 curwin->w_p_fen = FALSE; /* No folding in the help window */
3343#endif
3344#ifdef FEAT_DIFF
3345 curwin->w_p_diff = FALSE; /* No 'diff' */
3346#endif
Bram Moolenaara1956f62006-03-12 22:18:00 +00003347#ifdef FEAT_SPELL
Bram Moolenaar9a50b1b2005-06-27 22:48:21 +00003348 curwin->w_p_spell = FALSE; /* No spell checking */
3349#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350
3351#ifdef FEAT_AUTOCMD
3352 buf = curbuf;
3353#endif
3354 set_buflisted(FALSE);
3355 }
3356 else
3357 {
3358#ifdef FEAT_AUTOCMD
3359 buf = curbuf;
3360#endif
3361 /* Don't make a buffer listed if it's a help buffer. Useful when
3362 * using CTRL-O to go back to a help file. */
3363 if (!curbuf->b_help)
3364 set_buflisted(TRUE);
3365 }
3366
3367#ifdef FEAT_AUTOCMD
3368 /* If autocommands change buffers under our fingers, forget about
3369 * editing the file. */
3370 if (buf != curbuf)
3371 goto theend;
3372# ifdef FEAT_EVAL
3373 if (aborting()) /* autocmds may abort script processing */
3374 goto theend;
3375# endif
3376
3377 /* Since we are starting to edit a file, consider the filetype to be
3378 * unset. Helps for when an autocommand changes files and expects syntax
3379 * highlighting to work in the other file. */
3380 did_filetype = FALSE;
3381#endif
3382
3383/*
3384 * other_file oldbuf
3385 * FALSE FALSE re-edit same file, buffer is re-used
3386 * FALSE TRUE re-edit same file, nothing changes
3387 * TRUE FALSE start editing new file, new buffer
3388 * TRUE TRUE start editing in existing buffer (nothing to do)
3389 */
3390 if (!other_file && !oldbuf) /* re-use the buffer */
3391 {
3392 set_last_cursor(curwin); /* may set b_last_cursor */
3393 if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL)
3394 {
3395 newlnum = curwin->w_cursor.lnum;
3396 solcol = curwin->w_cursor.col;
3397 }
3398#ifdef FEAT_AUTOCMD
3399 buf = curbuf;
3400 if (buf->b_fname != NULL)
3401 new_name = vim_strsave(buf->b_fname);
3402 else
3403 new_name = NULL;
3404#endif
3405 buf_freeall(curbuf, FALSE, FALSE); /* free all things for buffer */
3406#ifdef FEAT_AUTOCMD
3407 /* If autocommands deleted the buffer we were going to re-edit, give
3408 * up and jump to the end. */
3409 if (!buf_valid(buf))
3410 {
3411 delbuf_msg(new_name); /* frees new_name */
3412 goto theend;
3413 }
3414 vim_free(new_name);
3415
3416 /* If autocommands change buffers under our fingers, forget about
3417 * re-editing the file. Should do the buf_clear_file(), but perhaps
3418 * the autocommands changed the buffer... */
3419 if (buf != curbuf)
3420 goto theend;
3421# ifdef FEAT_EVAL
3422 if (aborting()) /* autocmds may abort script processing */
3423 goto theend;
3424# endif
3425#endif
3426 buf_clear_file(curbuf);
3427 curbuf->b_op_start.lnum = 0; /* clear '[ and '] marks */
3428 curbuf->b_op_end.lnum = 0;
3429 }
3430
3431/*
3432 * If we get here we are sure to start editing
3433 */
3434 /* don't redraw until the cursor is in the right line */
3435 ++RedrawingDisabled;
3436
3437 /* Assume success now */
3438 retval = OK;
3439
3440 /*
3441 * Reset cursor position, could be used by autocommands.
3442 */
3443 check_cursor();
3444
3445 /*
3446 * Check if we are editing the w_arg_idx file in the argument list.
3447 */
3448 check_arg_idx(curwin);
3449
3450#ifdef FEAT_AUTOCMD
3451 if (!auto_buf)
3452#endif
3453 {
3454 /*
3455 * Set cursor and init window before reading the file and executing
3456 * autocommands. This allows for the autocommands to position the
3457 * cursor.
3458 */
Bram Moolenaarfaa959a2006-02-20 21:37:40 +00003459 curwin_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460
3461#ifdef FEAT_FOLDING
3462 /* It's like all lines in the buffer changed. Need to update
3463 * automatic folding. */
3464 foldUpdateAll(curwin);
3465#endif
3466
3467#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
3468 if (p_acd && curbuf->b_ffname != NULL
3469 && vim_chdirfile(curbuf->b_ffname) == OK)
3470 shorten_fnames(TRUE);
3471#endif
3472 /*
3473 * Careful: open_buffer() and apply_autocmds() may change the current
3474 * buffer and window.
3475 */
3476 lnum = curwin->w_cursor.lnum;
3477 topline = curwin->w_topline;
3478 if (!oldbuf) /* need to read the file */
3479 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003480#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 swap_exists_action = SEA_DIALOG;
3482#endif
3483 curbuf->b_flags |= BF_CHECK_RO; /* set/reset 'ro' flag */
3484
3485 /*
3486 * Open the buffer and read the file.
3487 */
3488#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
3489 if (should_abort(open_buffer(FALSE, eap)))
3490 retval = FAIL;
3491#else
3492 (void)open_buffer(FALSE, eap);
3493#endif
3494
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003495#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 if (swap_exists_action == SEA_QUIT)
3497 retval = FAIL;
3498 handle_swap_exists(old_curbuf);
3499#endif
3500 }
3501#ifdef FEAT_AUTOCMD
3502 else
3503 {
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00003504 /* Read the modelines, but only to set window-local options. Any
3505 * buffer-local options have already been set and may have been
3506 * changed by the user. */
Bram Moolenaara3227e22006-03-08 21:32:40 +00003507 do_modelines(OPT_WINONLY);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00003508
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf,
3510 &retval);
3511 apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf,
3512 &retval);
3513 }
3514 check_arg_idx(curwin);
3515#endif
3516
3517 /*
3518 * If autocommands change the cursor position or topline, we should
3519 * keep it.
3520 */
3521 if (curwin->w_cursor.lnum != lnum)
3522 {
3523 newlnum = curwin->w_cursor.lnum;
3524 newcol = curwin->w_cursor.col;
3525 }
3526 if (curwin->w_topline == topline)
3527 topline = 0;
3528
3529 /* Even when cursor didn't move we need to recompute topline. */
3530 changed_line_abv_curs();
3531
3532#ifdef FEAT_TITLE
3533 maketitle();
3534#endif
3535 }
3536
3537#ifdef FEAT_DIFF
3538 /* Tell the diff stuff that this buffer is new and/or needs updating.
3539 * Also needed when re-editing the same buffer, because unloading will
3540 * have removed it as a diff buffer. */
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003541 if (curwin->w_p_diff)
3542 {
3543 diff_buf_add(curbuf);
3544 diff_invalidate(curbuf);
3545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546#endif
3547
3548 if (command == NULL)
3549 {
3550 if (newcol >= 0) /* position set by autocommands */
3551 {
3552 curwin->w_cursor.lnum = newlnum;
3553 curwin->w_cursor.col = newcol;
3554 check_cursor();
3555 }
3556 else if (newlnum > 0) /* line number from caller or old position */
3557 {
3558 curwin->w_cursor.lnum = newlnum;
3559 check_cursor_lnum();
3560 if (solcol >= 0 && !p_sol)
3561 {
3562 /* 'sol' is off: Use last known column. */
3563 curwin->w_cursor.col = solcol;
3564 check_cursor_col();
3565#ifdef FEAT_VIRTUALEDIT
3566 curwin->w_cursor.coladd = 0;
3567#endif
3568 curwin->w_set_curswant = TRUE;
3569 }
3570 else
3571 beginline(BL_SOL | BL_FIX);
3572 }
3573 else /* no line number, go to last line in Ex mode */
3574 {
3575 if (exmode_active)
3576 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3577 beginline(BL_WHITE | BL_FIX);
3578 }
3579 }
3580
3581#ifdef FEAT_WINDOWS
3582 /* Check if cursors in other windows on the same buffer are still valid */
3583 check_lnums(FALSE);
3584#endif
3585
3586 /*
3587 * Did not read the file, need to show some info about the file.
3588 * Do this after setting the cursor.
3589 */
3590 if (oldbuf
3591#ifdef FEAT_AUTOCMD
3592 && !auto_buf
3593#endif
3594 )
3595 {
3596 int msg_scroll_save = msg_scroll;
3597
3598 /* Obey the 'O' flag in 'cpoptions': overwrite any previous file
3599 * message. */
3600 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
3601 msg_scroll = FALSE;
3602 if (!msg_scroll) /* wait a bit when overwriting an error msg */
3603 check_for_delay(FALSE);
3604 msg_start();
3605 msg_scroll = msg_scroll_save;
3606 msg_scrolled_ign = TRUE;
3607
3608 fileinfo(FALSE, TRUE, FALSE);
3609
3610 msg_scrolled_ign = FALSE;
3611 }
3612
3613 if (command != NULL)
3614 do_cmdline(command, NULL, NULL, DOCMD_VERBOSE);
3615
3616#ifdef FEAT_KEYMAP
3617 if (curbuf->b_kmap_state & KEYMAP_INIT)
3618 keymap_init();
3619#endif
3620
3621 --RedrawingDisabled;
3622 if (!skip_redraw)
3623 {
3624 n = p_so;
3625 if (topline == 0 && command == NULL)
3626 p_so = 999; /* force cursor halfway the window */
3627 update_topline();
3628#ifdef FEAT_SCROLLBIND
3629 curwin->w_scbind_pos = curwin->w_topline;
3630#endif
3631 p_so = n;
3632 redraw_curbuf_later(NOT_VALID); /* redraw this buffer later */
3633 }
3634
3635 if (p_im)
3636 need_start_insertmode = TRUE;
3637
3638#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
3639 /* Change directories when the acd option is set on. */
3640 if (p_acd && curbuf->b_ffname != NULL
3641 && vim_chdirfile(curbuf->b_ffname) == OK)
3642 shorten_fnames(TRUE);
3643
3644 if (gui.in_use && curbuf->b_ffname != NULL)
3645 {
3646# ifdef FEAT_SUN_WORKSHOP
3647 if (usingSunWorkShop)
3648 workshop_file_opened((char *)curbuf->b_ffname, curbuf->b_p_ro);
3649# endif
3650# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003651 if (usingNetbeans & ((flags & ECMD_SET_HELP) != ECMD_SET_HELP))
3652 netbeans_file_opened(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653# endif
3654 }
3655#endif
3656
3657theend:
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00003658#ifdef FEAT_AUTOCMD
3659 if (did_set_swapcommand)
3660 set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
3661#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662#ifdef FEAT_BROWSE
3663 vim_free(browse_file);
3664#endif
3665 vim_free(free_fname);
3666 return retval;
3667}
3668
3669#ifdef FEAT_AUTOCMD
3670 static void
3671delbuf_msg(name)
3672 char_u *name;
3673{
3674 EMSG2(_("E143: Autocommands unexpectedly deleted new buffer %s"),
3675 name == NULL ? (char_u *)"" : name);
3676 vim_free(name);
3677 au_new_curbuf = NULL;
3678}
3679#endif
3680
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003681static int append_indent = 0; /* autoindent for first line */
3682
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683/*
3684 * ":insert" and ":append", also used by ":change"
3685 */
3686 void
3687ex_append(eap)
3688 exarg_T *eap;
3689{
3690 char_u *theline;
3691 int did_undo = FALSE;
3692 linenr_T lnum = eap->line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003693 int indent = 0;
3694 char_u *p;
3695 int vcol;
3696 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003698 /* the ! flag toggles autoindent */
3699 if (eap->forceit)
3700 curbuf->b_p_ai = !curbuf->b_p_ai;
3701
3702 /* First autoindent comes from the line we start on */
3703 if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0)
3704 append_indent = get_indent_lnum(lnum);
3705
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 if (eap->cmdidx != CMD_append)
3707 --lnum;
3708
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003709 /* when the buffer is empty append to line 0 and delete the dummy line */
3710 if (empty && lnum == 1)
3711 lnum = 0;
3712
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 State = INSERT; /* behave like in Insert mode */
3714 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
3715 State |= LANGMAP;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003716
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00003717 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 {
3719 msg_scroll = TRUE;
3720 need_wait_return = FALSE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003721 if (curbuf->b_p_ai)
3722 {
3723 if (append_indent >= 0)
3724 {
3725 indent = append_indent;
3726 append_indent = -1;
3727 }
3728 else if (lnum > 0)
3729 indent = get_indent_lnum(lnum);
3730 }
3731 ex_keep_indent = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 if (eap->getline == NULL)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003733 {
3734 /* No getline() function, use the lines that follow. This ends
3735 * when there is no more. */
3736 if (eap->nextcmd == NULL || *eap->nextcmd == NUL)
3737 break;
3738 p = vim_strchr(eap->nextcmd, NL);
3739 if (p == NULL)
3740 p = eap->nextcmd + STRLEN(eap->nextcmd);
3741 theline = vim_strnsave(eap->nextcmd, (int)(p - eap->nextcmd));
3742 if (*p != NUL)
3743 ++p;
3744 eap->nextcmd = p;
3745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 else
3747 theline = eap->getline(
3748#ifdef FEAT_EVAL
Bram Moolenaar3d60ec22005-01-05 22:19:46 +00003749 eap->cstack->cs_looplevel > 0 ? -1 :
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750#endif
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003751 NUL, eap->cookie, indent);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752 lines_left = Rows - 1;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003753 if (theline == NULL)
3754 break;
3755
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003756 /* Using ^ CTRL-D in getexmodeline() makes us repeat the indent. */
3757 if (ex_keep_indent)
3758 append_indent = indent;
3759
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003760 /* Look for the "." after automatic indent. */
3761 vcol = 0;
3762 for (p = theline; indent > vcol; ++p)
3763 {
3764 if (*p == ' ')
3765 ++vcol;
3766 else if (*p == TAB)
3767 vcol += 8 - vcol % 8;
3768 else
3769 break;
3770 }
3771 if ((p[0] == '.' && p[1] == NUL)
Bram Moolenaareaa48e72005-06-08 22:07:37 +00003772 || (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0))
3773 == FAIL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 {
3775 vim_free(theline);
3776 break;
3777 }
3778
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003779 /* don't use autoindent if nothing was typed. */
3780 if (p[0] == NUL)
3781 theline[0] = NUL;
3782
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 did_undo = TRUE;
3784 ml_append(lnum, theline, (colnr_T)0, FALSE);
3785 appended_lines_mark(lnum, 1L);
3786
3787 vim_free(theline);
3788 ++lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003789
3790 if (empty)
3791 {
3792 ml_delete(2L, FALSE);
3793 empty = FALSE;
3794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 }
3796 State = NORMAL;
3797
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003798 if (eap->forceit)
3799 curbuf->b_p_ai = !curbuf->b_p_ai;
3800
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801 /* "start" is set to eap->line2+1 unless that position is invalid (when
3802 * eap->line2 pointed to the end of the buffer and nothig was appended)
3803 * "end" is set to lnum when something has been appended, otherwise
3804 * it is the same than "start" -- Acevedo */
3805 curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
3806 eap->line2 + 1 : curbuf->b_ml.ml_line_count;
3807 if (eap->cmdidx != CMD_append)
3808 --curbuf->b_op_start.lnum;
3809 curbuf->b_op_end.lnum = (eap->line2 < lnum)
3810 ? lnum : curbuf->b_op_start.lnum;
3811 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
3812 curwin->w_cursor.lnum = lnum;
3813 check_cursor_lnum();
3814 beginline(BL_SOL | BL_FIX);
3815
3816 need_wait_return = FALSE; /* don't use wait_return() now */
3817 ex_no_reprint = TRUE;
3818}
3819
3820/*
3821 * ":change"
3822 */
3823 void
3824ex_change(eap)
3825 exarg_T *eap;
3826{
3827 linenr_T lnum;
3828
3829 if (eap->line2 >= eap->line1
3830 && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
3831 return;
3832
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003833 /* the ! flag toggles autoindent */
3834 if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai)
3835 append_indent = get_indent_lnum(eap->line1);
3836
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 for (lnum = eap->line2; lnum >= eap->line1; --lnum)
3838 {
3839 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
3840 break;
3841 ml_delete(eap->line1, FALSE);
3842 }
3843 deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum));
3844
3845 /* ":append" on the line above the deleted lines. */
3846 eap->line2 = eap->line1;
3847 ex_append(eap);
3848}
3849
3850 void
3851ex_z(eap)
3852 exarg_T *eap;
3853{
3854 char_u *x;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003855 int bigness;
3856 char_u *kind;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 int minus = 0;
3858 linenr_T start, end, curs, i;
3859 int j;
3860 linenr_T lnum = eap->line2;
3861
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003862 /* Vi compatible: ":z!" uses display height, without a count uses
3863 * 'scroll' */
3864 if (eap->forceit)
3865 bigness = curwin->w_height;
3866 else if (firstwin == lastwin)
3867 bigness = curwin->w_p_scr * 2;
3868 else
3869 bigness = curwin->w_height - 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870 if (bigness < 1)
3871 bigness = 1;
3872
3873 x = eap->arg;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003874 kind = x;
3875 if (*kind == '-' || *kind == '+' || *kind == '='
3876 || *kind == '^' || *kind == '.')
3877 ++x;
3878 while (*x == '-' || *x == '+')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879 ++x;
3880
3881 if (*x != 0)
3882 {
3883 if (!VIM_ISDIGIT(*x))
3884 {
3885 EMSG(_("E144: non-numeric argument to :z"));
3886 return;
3887 }
3888 else
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003889 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 bigness = atoi((char *)x);
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003891 p_window = bigness;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003892 if (*kind == '=')
3893 bigness += 2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003894 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895 }
3896
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003897 /* the number of '-' and '+' multiplies the distance */
3898 if (*kind == '-' || *kind == '+')
3899 for (x = kind + 1; *x == *kind; ++x)
3900 ;
3901
3902 switch (*kind)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 {
3904 case '-':
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003905 start = lnum - bigness * (x - kind);
3906 end = start + bigness;
3907 curs = end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908 break;
3909
3910 case '=':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003911 start = lnum - (bigness + 1) / 2 + 1;
3912 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 curs = lnum;
3914 minus = 1;
3915 break;
3916
3917 case '^':
3918 start = lnum - bigness * 2;
3919 end = lnum - bigness;
3920 curs = lnum - bigness;
3921 break;
3922
3923 case '.':
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00003924 start = lnum - (bigness + 1) / 2 + 1;
3925 end = lnum + (bigness + 1) / 2 - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 curs = end;
3927 break;
3928
3929 default: /* '+' */
3930 start = lnum;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00003931 if (*kind == '+')
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003932 start += bigness * (x - kind - 1) + 1;
3933 else if (eap->addr_count == 0)
3934 ++start;
3935 end = start + bigness - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936 curs = end;
3937 break;
3938 }
3939
3940 if (start < 1)
3941 start = 1;
3942
3943 if (end > curbuf->b_ml.ml_line_count)
3944 end = curbuf->b_ml.ml_line_count;
3945
3946 if (curs > curbuf->b_ml.ml_line_count)
3947 curs = curbuf->b_ml.ml_line_count;
3948
3949 for (i = start; i <= end; i++)
3950 {
3951 if (minus && i == lnum)
3952 {
3953 msg_putchar('\n');
3954
3955 for (j = 1; j < Columns; j++)
3956 msg_putchar('-');
3957 }
3958
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003959 print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960
3961 if (minus && i == lnum)
3962 {
3963 msg_putchar('\n');
3964
3965 for (j = 1; j < Columns; j++)
3966 msg_putchar('-');
3967 }
3968 }
3969
3970 curwin->w_cursor.lnum = curs;
3971 ex_no_reprint = TRUE;
3972}
3973
3974/*
3975 * Check if the restricted flag is set.
3976 * If so, give an error message and return TRUE.
3977 * Otherwise, return FALSE.
3978 */
3979 int
3980check_restricted()
3981{
3982 if (restricted)
3983 {
3984 EMSG(_("E145: Shell commands not allowed in rvim"));
3985 return TRUE;
3986 }
3987 return FALSE;
3988}
3989
3990/*
3991 * Check if the secure flag is set (.exrc or .vimrc in current directory).
3992 * If so, give an error message and return TRUE.
3993 * Otherwise, return FALSE.
3994 */
3995 int
3996check_secure()
3997{
3998 if (secure)
3999 {
4000 secure = 2;
4001 EMSG(_(e_curdir));
4002 return TRUE;
4003 }
4004#ifdef HAVE_SANDBOX
4005 /*
4006 * In the sandbox more things are not allowed, including the things
4007 * disallowed in secure mode.
4008 */
4009 if (sandbox != 0)
4010 {
4011 EMSG(_(e_sandbox));
4012 return TRUE;
4013 }
4014#endif
4015 return FALSE;
4016}
4017
4018static char_u *old_sub = NULL; /* previous substitute pattern */
4019static int global_need_beginline; /* call beginline() after ":g" */
4020
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021/* do_sub()
4022 *
4023 * Perform a substitution from line eap->line1 to line eap->line2 using the
4024 * command pointed to by eap->arg which should be of the form:
4025 *
4026 * /pattern/substitution/{flags}
4027 *
4028 * The usual escapes are supported as described in the regexp docs.
4029 */
4030 void
4031do_sub(eap)
4032 exarg_T *eap;
4033{
4034 linenr_T lnum;
4035 long i = 0;
4036 regmmatch_T regmatch;
4037 static int do_all = FALSE; /* do multiple substitutions per line */
4038 static int do_ask = FALSE; /* ask for confirmation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004039 static int do_count = FALSE; /* count only */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 static int do_error = TRUE; /* if false, ignore errors */
4041 static int do_print = FALSE; /* print last line with subs. */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004042 static int do_list = FALSE; /* list last line with subs. */
4043 static int do_number = FALSE; /* list last line with line nr*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044 static int do_ic = 0; /* ignore case flag */
4045 char_u *pat = NULL, *sub = NULL; /* init for GCC */
4046 int delimiter;
4047 int sublen;
4048 int got_quit = FALSE;
4049 int got_match = FALSE;
4050 int temp;
4051 int which_pat;
4052 char_u *cmd;
4053 int save_State;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00004054 linenr_T first_line = 0; /* first changed line */
4055 linenr_T last_line= 0; /* below last changed line AFTER the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004056 * change */
4057 linenr_T old_line_count = curbuf->b_ml.ml_line_count;
4058 linenr_T line2;
Bram Moolenaar81bf7082005-02-12 14:31:42 +00004059 long nmatch; /* number of lines in match */
4060 linenr_T sub_firstlnum; /* nr of first sub line */
4061 char_u *sub_firstline; /* allocated copy of first sub line */
4062 int endcolumn = FALSE; /* cursor in last column when done */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004063 pos_T old_cursor = curwin->w_cursor;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064
4065 cmd = eap->arg;
4066 if (!global_busy)
4067 {
4068 sub_nsubs = 0;
4069 sub_nlines = 0;
4070 }
4071
4072#ifdef FEAT_FKMAP /* reverse the flow of the Farsi characters */
4073 if (p_altkeymap && curwin->w_p_rl)
4074 lrF_sub(cmd);
4075#endif
4076
4077 if (eap->cmdidx == CMD_tilde)
4078 which_pat = RE_LAST; /* use last used regexp */
4079 else
4080 which_pat = RE_SUBST; /* use last substitute regexp */
4081
4082 /* new pattern and substitution */
4083 if (eap->cmd[0] == 's' && *cmd != NUL && !vim_iswhite(*cmd)
4084 && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
4085 {
4086 /* don't accept alphanumeric for separator */
4087 if (isalpha(*cmd))
4088 {
4089 EMSG(_("E146: Regular expressions can't be delimited by letters"));
4090 return;
4091 }
4092 /*
4093 * undocumented vi feature:
4094 * "\/sub/" and "\?sub?" use last used search pattern (almost like
4095 * //sub/r). "\&sub&" use last substitute pattern (like //sub/).
4096 */
4097 if (*cmd == '\\')
4098 {
4099 ++cmd;
4100 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
4101 {
4102 EMSG(_(e_backslash));
4103 return;
4104 }
4105 if (*cmd != '&')
4106 which_pat = RE_SEARCH; /* use last '/' pattern */
4107 pat = (char_u *)""; /* empty search pattern */
4108 delimiter = *cmd++; /* remember delimiter character */
4109 }
4110 else /* find the end of the regexp */
4111 {
4112 which_pat = RE_LAST; /* use last used regexp */
4113 delimiter = *cmd++; /* remember delimiter character */
4114 pat = cmd; /* remember start of search pat */
4115 cmd = skip_regexp(cmd, delimiter, p_magic, &eap->arg);
4116 if (cmd[0] == delimiter) /* end delimiter found */
4117 *cmd++ = NUL; /* replace it with a NUL */
4118 }
4119
4120 /*
4121 * Small incompatibility: vi sees '\n' as end of the command, but in
4122 * Vim we want to use '\n' to find/substitute a NUL.
4123 */
4124 sub = cmd; /* remember the start of the substitution */
4125
4126 while (cmd[0])
4127 {
4128 if (cmd[0] == delimiter) /* end delimiter found */
4129 {
4130 *cmd++ = NUL; /* replace it with a NUL */
4131 break;
4132 }
4133 if (cmd[0] == '\\' && cmd[1] != 0) /* skip escaped characters */
4134 ++cmd;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004135 mb_ptr_adv(cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 }
4137
4138 if (!eap->skip)
4139 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004140 /* In POSIX vi ":s/pat/%/" uses the previous subst. string. */
4141 if (STRCMP(sub, "%") == 0
4142 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
4143 {
4144 if (old_sub == NULL) /* there is no previous command */
4145 {
4146 EMSG(_(e_nopresub));
4147 return;
4148 }
4149 sub = old_sub;
4150 }
4151 else
4152 {
4153 vim_free(old_sub);
4154 old_sub = vim_strsave(sub);
4155 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 }
4157 }
4158 else if (!eap->skip) /* use previous pattern and substitution */
4159 {
4160 if (old_sub == NULL) /* there is no previous command */
4161 {
4162 EMSG(_(e_nopresub));
4163 return;
4164 }
4165 pat = NULL; /* search_regcomp() will use previous pattern */
4166 sub = old_sub;
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004167
4168 /* Vi compatibility quirk: repeating with ":s" keeps the cursor in the
4169 * last column after using "$". */
4170 endcolumn = (curwin->w_curswant == MAXCOL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 }
4172
4173 /*
4174 * Find trailing options. When '&' is used, keep old options.
4175 */
4176 if (*cmd == '&')
4177 ++cmd;
4178 else
4179 {
4180 if (!p_ed)
4181 {
4182 if (p_gd) /* default is global on */
4183 do_all = TRUE;
4184 else
4185 do_all = FALSE;
4186 do_ask = FALSE;
4187 }
4188 do_error = TRUE;
4189 do_print = FALSE;
Bram Moolenaarcc016f52005-12-10 20:23:46 +00004190 do_count = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 do_ic = 0;
4192 }
4193 while (*cmd)
4194 {
4195 /*
4196 * Note that 'g' and 'c' are always inverted, also when p_ed is off.
4197 * 'r' is never inverted.
4198 */
4199 if (*cmd == 'g')
4200 do_all = !do_all;
4201 else if (*cmd == 'c')
4202 do_ask = !do_ask;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004203 else if (*cmd == 'n')
4204 do_count = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205 else if (*cmd == 'e')
4206 do_error = !do_error;
4207 else if (*cmd == 'r') /* use last used regexp */
4208 which_pat = RE_LAST;
4209 else if (*cmd == 'p')
4210 do_print = TRUE;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004211 else if (*cmd == '#')
4212 {
4213 do_print = TRUE;
4214 do_number = TRUE;
4215 }
4216 else if (*cmd == 'l')
4217 {
4218 do_print = TRUE;
4219 do_list = TRUE;
4220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 else if (*cmd == 'i') /* ignore case */
4222 do_ic = 'i';
4223 else if (*cmd == 'I') /* don't ignore case */
4224 do_ic = 'I';
4225 else
4226 break;
4227 ++cmd;
4228 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00004229 if (do_count)
4230 do_ask = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231
4232 /*
4233 * check for a trailing count
4234 */
4235 cmd = skipwhite(cmd);
4236 if (VIM_ISDIGIT(*cmd))
4237 {
4238 i = getdigits(&cmd);
4239 if (i <= 0 && !eap->skip && do_error)
4240 {
4241 EMSG(_(e_zerocount));
4242 return;
4243 }
4244 eap->line1 = eap->line2;
4245 eap->line2 += i - 1;
4246 if (eap->line2 > curbuf->b_ml.ml_line_count)
4247 eap->line2 = curbuf->b_ml.ml_line_count;
4248 }
4249
4250 /*
4251 * check for trailing command or garbage
4252 */
4253 cmd = skipwhite(cmd);
4254 if (*cmd && *cmd != '"') /* if not end-of-line or comment */
4255 {
4256 eap->nextcmd = check_nextcmd(cmd);
4257 if (eap->nextcmd == NULL)
4258 {
4259 EMSG(_(e_trailing));
4260 return;
4261 }
4262 }
4263
4264 if (eap->skip) /* not executing commands, only parsing */
4265 return;
4266
4267 if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4268 {
4269 if (do_error)
4270 EMSG(_(e_invcmd));
4271 return;
4272 }
4273
4274 /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
4275 if (do_ic == 'i')
4276 regmatch.rmm_ic = TRUE;
4277 else if (do_ic == 'I')
4278 regmatch.rmm_ic = FALSE;
4279
4280 sub_firstline = NULL;
4281
4282 /*
4283 * ~ in the substitute pattern is replaced with the old pattern.
4284 * We do it here once to avoid it to be replaced over and over again.
4285 * But don't do it when it starts with "\=", then it's an expression.
4286 */
4287 if (!(sub[0] == '\\' && sub[1] == '='))
4288 sub = regtilde(sub, p_magic);
4289
4290 /*
4291 * Check for a match on each line.
4292 */
4293 line2 = eap->line2;
4294 for (lnum = eap->line1; lnum <= line2 && !(got_quit
4295#if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
4296 || aborting()
4297#endif
4298 ); ++lnum)
4299 {
4300 sub_firstlnum = lnum;
4301 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
4302 if (nmatch)
4303 {
4304 colnr_T copycol;
4305 colnr_T matchcol;
4306 colnr_T prev_matchcol = MAXCOL;
4307 char_u *new_end, *new_start = NULL;
4308 unsigned new_start_len = 0;
4309 char_u *p1;
4310 int did_sub = FALSE;
4311 int lastone;
4312 unsigned len, needed_len;
4313 long nmatch_tl = 0; /* nr of lines matched below lnum */
4314 int do_again; /* do it again after joining lines */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004315 int skip_match = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316
4317 /*
4318 * The new text is build up step by step, to avoid too much
4319 * copying. There are these pieces:
4320 * sub_firstline The old text, unmodifed.
4321 * copycol Column in the old text where we started
4322 * looking for a match; from here old text still
4323 * needs to be copied to the new text.
4324 * matchcol Column number of the old text where to look
4325 * for the next match. It's just after the
4326 * previous match or one further.
4327 * prev_matchcol Column just after the previous match (if any).
4328 * Mostly equal to matchcol, except for the first
4329 * match and after skipping an empty match.
4330 * regmatch.*pos Where the pattern matched in the old text.
4331 * new_start The new text, all that has been produced so
4332 * far.
4333 * new_end The new text, where to append new text.
4334 *
4335 * lnum The line number where we were looking for the
4336 * first match in the old line.
4337 * sub_firstlnum The line number in the buffer where to look
4338 * for a match. Can be different from "lnum"
4339 * when the pattern or substitute string contains
4340 * line breaks.
4341 *
4342 * Special situations:
4343 * - When the substitute string contains a line break, the part up
4344 * to the line break is inserted in the text, but the copy of
4345 * the original line is kept. "sub_firstlnum" is adjusted for
4346 * the inserted lines.
4347 * - When the matched pattern contains a line break, the old line
4348 * is taken from the line at the end of the pattern. The lines
4349 * in the match are deleted later, "sub_firstlnum" is adjusted
4350 * accordingly.
4351 *
4352 * The new text is built up in new_start[]. It has some extra
4353 * room to avoid using alloc()/free() too often. new_start_len is
4354 * the lenght of the allocated memory at new_start.
4355 *
4356 * Make a copy of the old line, so it won't be taken away when
4357 * updating the screen or handling a multi-line match. The "old_"
4358 * pointers point into this copy.
4359 */
4360 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4361 if (sub_firstline == NULL)
4362 {
4363 vim_free(new_start);
4364 goto outofmem;
4365 }
4366 copycol = 0;
4367 matchcol = 0;
4368
4369 /* At first match, remember current cursor position. */
4370 if (!got_match)
4371 {
4372 setpcmark();
4373 got_match = TRUE;
4374 }
4375
4376 /*
4377 * Loop until nothing more to replace in this line.
4378 * 1. Handle match with empty string.
4379 * 2. If do_ask is set, ask for confirmation.
4380 * 3. substitute the string.
4381 * 4. if do_all is set, find next match
4382 * 5. break if there isn't another match in this line
4383 */
4384 for (;;)
4385 {
4386 /* Save the line number of the last change for the final
4387 * cursor position (just like Vi). */
4388 curwin->w_cursor.lnum = lnum;
4389 do_again = FALSE;
4390
4391 /*
4392 * 1. Match empty string does not count, except for first
4393 * match. This reproduces the strange vi behaviour.
4394 * This also catches endless loops.
4395 */
4396 if (matchcol == prev_matchcol
4397 && regmatch.endpos[0].lnum == 0
4398 && matchcol == regmatch.endpos[0].col)
4399 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00004400 if (sub_firstline[matchcol] == NUL)
4401 /* We already were at the end of the line. Don't look
4402 * for a match in this line again. */
4403 skip_match = TRUE;
4404 else
4405 ++matchcol; /* search for a match at next column */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406 goto skip;
4407 }
4408
4409 /* Normally we continue searching for a match just after the
4410 * previous match. */
4411 matchcol = regmatch.endpos[0].col;
4412 prev_matchcol = matchcol;
4413
4414 /*
Bram Moolenaar05159a02005-02-26 23:04:13 +00004415 * 2. If do_count is set only increase the counter.
4416 * If do_ask is set, ask for confirmation.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004417 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004418 if (do_count)
4419 {
4420 /* For a multi-line match, put matchcol at the NUL at
4421 * the end of the line and set nmatch to one, so that
4422 * we continue looking for a match on the next line.
4423 * Avoids that ":s/\nB\@=//gc" get stuck. */
4424 if (nmatch > 1)
4425 {
4426 matchcol = STRLEN(sub_firstline);
4427 nmatch = 1;
4428 }
4429 sub_nsubs++;
4430 did_sub = TRUE;
4431 goto skip;
4432 }
4433
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 if (do_ask)
4435 {
4436 /* change State to CONFIRM, so that the mouse works
4437 * properly */
4438 save_State = State;
4439 State = CONFIRM;
4440#ifdef FEAT_MOUSE
4441 setmouse(); /* disable mouse in xterm */
4442#endif
4443 curwin->w_cursor.col = regmatch.startpos[0].col;
4444
4445 /* When 'cpoptions' contains "u" don't sync undo when
4446 * asking for confirmation. */
4447 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4448 ++no_u_sync;
4449
4450 /*
4451 * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
4452 */
4453 while (do_ask)
4454 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004455 if (exmode_active)
4456 {
4457 char_u *resp;
4458 colnr_T sc, ec;
4459
4460 print_line_no_prefix(lnum, FALSE, FALSE);
4461
4462 getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
4463 curwin->w_cursor.col = regmatch.endpos[0].col - 1;
4464 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
4465 msg_start();
Bram Moolenaar05159a02005-02-26 23:04:13 +00004466 for (i = 0; i < (long)sc; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004467 msg_putchar(' ');
Bram Moolenaar05159a02005-02-26 23:04:13 +00004468 for ( ; i <= (long)ec; ++i)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004469 msg_putchar('^');
4470
4471 resp = getexmodeline('?', NULL, 0);
4472 if (resp != NULL)
4473 {
4474 i = *resp;
4475 vim_free(resp);
4476 }
4477 }
4478 else
4479 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004481 int save_p_fen = curwin->w_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004483 curwin->w_p_fen = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004485 /* Invert the matched string.
4486 * Remove the inversion afterwards. */
4487 temp = RedrawingDisabled;
4488 RedrawingDisabled = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004490 search_match_lines = regmatch.endpos[0].lnum;
4491 search_match_endcol = regmatch.endpos[0].col;
4492 highlight_match = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004494 update_topline();
4495 validate_cursor();
Bram Moolenaara1956f62006-03-12 22:18:00 +00004496 update_screen(SOME_VALID);
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004497 highlight_match = FALSE;
Bram Moolenaara1956f62006-03-12 22:18:00 +00004498 redraw_later(SOME_VALID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499
4500#ifdef FEAT_FOLDING
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004501 curwin->w_p_fen = save_p_fen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004503 if (msg_row == Rows - 1)
4504 msg_didout = FALSE; /* avoid a scroll-up */
4505 msg_starthere();
4506 i = msg_scroll;
4507 msg_scroll = 0; /* truncate msg when
4508 needed */
4509 msg_no_more = TRUE;
4510 /* write message same highlighting as for
4511 * wait_return */
4512 smsg_attr(hl_attr(HLF_R),
4513 (char_u *)_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
4514 msg_no_more = FALSE;
4515 msg_scroll = i;
4516 showruler(TRUE);
4517 windgoto(msg_row, msg_col);
4518 RedrawingDisabled = temp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519
4520#ifdef USE_ON_FLY_SCROLL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004521 dont_scroll = FALSE; /* allow scrolling here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522#endif
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004523 ++no_mapping; /* don't map this key */
4524 ++allow_keys; /* allow special keys */
4525 i = safe_vgetc();
4526 --allow_keys;
4527 --no_mapping;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004529 /* clear the question */
4530 msg_didout = FALSE; /* don't scroll up */
4531 msg_col = 0;
4532 gotocmdline(TRUE);
4533 }
4534
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 need_wait_return = FALSE; /* no hit-return prompt */
4536 if (i == 'q' || i == ESC || i == Ctrl_C
4537#ifdef UNIX
4538 || i == intr_char
4539#endif
4540 )
4541 {
4542 got_quit = TRUE;
4543 break;
4544 }
4545 if (i == 'n')
4546 break;
4547 if (i == 'y')
4548 break;
4549 if (i == 'l')
4550 {
4551 /* last: replace and then stop */
4552 do_all = FALSE;
4553 line2 = lnum;
4554 break;
4555 }
4556 if (i == 'a')
4557 {
4558 do_ask = FALSE;
4559 break;
4560 }
4561#ifdef FEAT_INS_EXPAND
4562 if (i == Ctrl_E)
4563 scrollup_clamp();
4564 else if (i == Ctrl_Y)
4565 scrolldown_clamp();
4566#endif
4567 }
4568 State = save_State;
4569#ifdef FEAT_MOUSE
4570 setmouse();
4571#endif
4572 if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4573 --no_u_sync;
4574
4575 if (i == 'n')
4576 {
4577 /* For a multi-line match, put matchcol at the NUL at
4578 * the end of the line and set nmatch to one, so that
4579 * we continue looking for a match on the next line.
4580 * Avoids that ":s/\nB\@=//gc" get stuck. */
4581 if (nmatch > 1)
4582 {
4583 matchcol = STRLEN(sub_firstline);
4584 nmatch = 1;
4585 }
4586 goto skip;
4587 }
4588 if (got_quit)
4589 break;
4590 }
4591
4592 /* Move the cursor to the start of the match, so that we can
4593 * use "\=col("."). */
4594 curwin->w_cursor.col = regmatch.startpos[0].col;
4595
4596 /*
4597 * 3. substitute the string.
4598 */
4599 /* get length of substitution part */
4600 sublen = vim_regsub_multi(&regmatch, sub_firstlnum,
4601 sub, sub_firstline, FALSE, p_magic, TRUE);
4602
Bram Moolenaar4463f292005-09-25 22:20:24 +00004603 /* When the match included the "$" of the last line it may
4604 * include one line too much. */
4605 if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)
4606 {
4607 nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
4608 skip_match = TRUE;
4609 }
4610
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 /* Need room for:
4612 * - result so far in new_start (not for first sub in line)
4613 * - original text up to match
4614 * - length of substituted part
4615 * - original text after match
4616 */
4617 if (nmatch == 1)
4618 p1 = sub_firstline;
4619 else
4620 {
4621 p1 = ml_get(sub_firstlnum + nmatch - 1);
4622 nmatch_tl += nmatch - 1;
4623 }
4624 i = regmatch.startpos[0].col - copycol;
4625 needed_len = i + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col)
4626 + sublen + 1;
4627 if (new_start == NULL)
4628 {
4629 /*
4630 * Get some space for a temporary buffer to do the
4631 * substitution into (and some extra space to avoid
4632 * too many calls to alloc()/free()).
4633 */
4634 new_start_len = needed_len + 50;
4635 if ((new_start = alloc_check(new_start_len)) == NULL)
4636 goto outofmem;
4637 *new_start = NUL;
4638 new_end = new_start;
4639 }
4640 else
4641 {
4642 /*
4643 * Check if the temporary buffer is long enough to do the
4644 * substitution into. If not, make it larger (with a bit
4645 * extra to avoid too many calls to alloc()/free()).
4646 */
4647 len = (unsigned)STRLEN(new_start);
4648 needed_len += len;
4649 if (needed_len > new_start_len)
4650 {
4651 new_start_len = needed_len + 50;
4652 if ((p1 = alloc_check(new_start_len)) == NULL)
4653 {
4654 vim_free(new_start);
4655 goto outofmem;
4656 }
4657 mch_memmove(p1, new_start, (size_t)(len + 1));
4658 vim_free(new_start);
4659 new_start = p1;
4660 }
4661 new_end = new_start + len;
4662 }
4663
4664 /*
4665 * copy the text up to the part that matched
4666 */
4667 mch_memmove(new_end, sub_firstline + copycol, (size_t)i);
4668 new_end += i;
4669
4670 (void)vim_regsub_multi(&regmatch, sub_firstlnum,
4671 sub, new_end, TRUE, p_magic, TRUE);
4672 sub_nsubs++;
4673 did_sub = TRUE;
4674
4675 /* Move the cursor to the start of the line, to avoid that it
4676 * is beyond the end of the line after the substitution. */
4677 curwin->w_cursor.col = 0;
4678
4679 /* For a multi-line match, make a copy of the last matched
4680 * line and continue in that one. */
4681 if (nmatch > 1)
4682 {
4683 sub_firstlnum += nmatch - 1;
4684 vim_free(sub_firstline);
4685 sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4686 /* When going beyond the last line, stop substituting. */
4687 if (sub_firstlnum <= line2)
4688 do_again = TRUE;
4689 else
4690 do_all = FALSE;
4691 }
4692
4693 /* Remember next character to be copied. */
4694 copycol = regmatch.endpos[0].col;
4695
4696 /*
4697 * Now the trick is to replace CTRL-M chars with a real line
4698 * break. This would make it impossible to insert a CTRL-M in
4699 * the text. The line break can be avoided by preceding the
4700 * CTRL-M with a backslash. To be able to insert a backslash,
4701 * they must be doubled in the string and are halved here.
4702 * That is Vi compatible.
4703 */
4704 for (p1 = new_end; *p1; ++p1)
4705 {
4706 if (p1[0] == '\\' && p1[1] != NUL) /* remove backslash */
4707 mch_memmove(p1, p1 + 1, STRLEN(p1));
4708 else if (*p1 == CAR)
4709 {
4710 if (u_inssub(lnum) == OK) /* prepare for undo */
4711 {
4712 *p1 = NUL; /* truncate up to the CR */
4713 ml_append(lnum - 1, new_start,
4714 (colnr_T)(p1 - new_start + 1), FALSE);
4715 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
4716 if (do_ask)
4717 appended_lines(lnum - 1, 1L);
4718 else
4719 {
4720 if (first_line == 0)
4721 first_line = lnum;
4722 last_line = lnum + 1;
4723 }
4724 /* All line numbers increase. */
4725 ++sub_firstlnum;
4726 ++lnum;
4727 ++line2;
4728 /* move the cursor to the new line, like Vi */
4729 ++curwin->w_cursor.lnum;
4730 STRCPY(new_start, p1 + 1); /* copy the rest */
4731 p1 = new_start - 1;
4732 }
4733 }
4734#ifdef FEAT_MBYTE
4735 else if (has_mbyte)
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004736 p1 += (*mb_ptr2len)(p1) - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737#endif
4738 }
4739
4740 /*
4741 * 4. If do_all is set, find next match.
4742 * Prevent endless loop with patterns that match empty
4743 * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
4744 * But ":s/\n/#/" is OK.
4745 */
4746skip:
4747 /* We already know that we did the last subst when we are at
4748 * the end of the line, except that a pattern like
4749 * "bar\|\nfoo" may match at the NUL. */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004750 lastone = (skip_match
4751 || got_int
4752 || got_quit
4753 || !(do_all || do_again)
4754 || (sub_firstline[matchcol] == NUL && nmatch <= 1
4755 && !re_multiline(regmatch.regprog)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 nmatch = -1;
4757
4758 /*
4759 * Replace the line in the buffer when needed. This is
4760 * skipped when there are more matches.
4761 * The check for nmatch_tl is needed for when multi-line
4762 * matching must replace the lines before trying to do another
4763 * match, otherwise "\@<=" won't work.
4764 * When asking the user we like to show the already replaced
4765 * text, but don't do it when "\<@=" or "\<@!" is used, it
4766 * changes what matches.
4767 */
4768 if (lastone
4769 || (do_ask && !re_lookbehind(regmatch.regprog))
4770 || nmatch_tl > 0
4771 || (nmatch = vim_regexec_multi(&regmatch, curwin,
4772 curbuf, sub_firstlnum, matchcol)) == 0)
4773 {
4774 if (new_start != NULL)
4775 {
4776 /*
4777 * Copy the rest of the line, that didn't match.
4778 * "matchcol" has to be adjusted, we use the end of
4779 * the line as reference, because the substitute may
4780 * have changed the number of characters. Same for
4781 * "prev_matchcol".
4782 */
4783 STRCAT(new_start, sub_firstline + copycol);
4784 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4785 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4786 - prev_matchcol;
4787
4788 if (u_savesub(lnum) != OK)
4789 break;
4790 ml_replace(lnum, new_start, TRUE);
4791
4792 if (nmatch_tl > 0)
4793 {
4794 /*
4795 * Matched lines have now been substituted and are
4796 * useless, delete them. The part after the match
4797 * has been appended to new_start, we don't need
4798 * it in the buffer.
4799 */
4800 ++lnum;
4801 if (u_savedel(lnum, nmatch_tl) != OK)
4802 break;
4803 for (i = 0; i < nmatch_tl; ++i)
4804 ml_delete(lnum, (int)FALSE);
4805 mark_adjust(lnum, lnum + nmatch_tl - 1,
4806 (long)MAXLNUM, -nmatch_tl);
4807 if (do_ask)
4808 deleted_lines(lnum, nmatch_tl);
4809 --lnum;
4810 line2 -= nmatch_tl; /* nr of lines decreases */
4811 nmatch_tl = 0;
4812 }
4813
4814 /* When asking, undo is saved each time, must also set
4815 * changed flag each time. */
4816 if (do_ask)
4817 changed_bytes(lnum, 0);
4818 else
4819 {
4820 if (first_line == 0)
4821 first_line = lnum;
4822 last_line = lnum + 1;
4823 }
4824
4825 sub_firstlnum = lnum;
4826 vim_free(sub_firstline); /* free the temp buffer */
4827 sub_firstline = new_start;
4828 new_start = NULL;
4829 matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4830 prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4831 - prev_matchcol;
4832 copycol = 0;
4833 }
4834 if (nmatch == -1 && !lastone)
4835 nmatch = vim_regexec_multi(&regmatch, curwin, curbuf,
4836 sub_firstlnum, matchcol);
4837
4838 /*
4839 * 5. break if there isn't another match in this line
4840 */
4841 if (nmatch <= 0)
4842 break;
4843 }
4844
4845 line_breakcheck();
4846 }
4847
4848 if (did_sub)
4849 ++sub_nlines;
4850 vim_free(sub_firstline); /* free the copy of the original line */
4851 sub_firstline = NULL;
4852 }
4853
4854 line_breakcheck();
4855 }
4856
4857 if (first_line != 0)
4858 {
4859 /* Need to subtract the number of added lines from "last_line" to get
4860 * the line number before the change (same as adding the number of
4861 * deleted lines). */
4862 i = curbuf->b_ml.ml_line_count - old_line_count;
4863 changed_lines(first_line, 0, last_line - i, i);
4864 }
4865
4866outofmem:
4867 vim_free(sub_firstline); /* may have to free allocated copy of the line */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004868
4869 /* ":s/pat//n" doesn't move the cursor */
4870 if (do_count)
4871 curwin->w_cursor = old_cursor;
4872
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 if (sub_nsubs)
4874 {
4875 /* Set the '[ and '] marks. */
4876 curbuf->b_op_start.lnum = eap->line1;
4877 curbuf->b_op_end.lnum = line2;
4878 curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
4879
4880 if (!global_busy)
4881 {
Bram Moolenaarb11bd7e2005-02-07 22:05:52 +00004882 if (endcolumn)
4883 coladvance((colnr_T)MAXCOL);
4884 else
4885 beginline(BL_WHITE | BL_FIX);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004886 if (!do_sub_msg(do_count) && do_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 MSG("");
4888 }
4889 else
4890 global_need_beginline = TRUE;
4891 if (do_print)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004892 print_line(curwin->w_cursor.lnum, do_number, do_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 }
4894 else if (!global_busy)
4895 {
4896 if (got_int) /* interrupted */
4897 EMSG(_(e_interr));
4898 else if (got_match) /* did find something but nothing substituted */
4899 MSG("");
4900 else if (do_error) /* nothing found */
4901 EMSG2(_(e_patnotf2), get_search_pat());
4902 }
4903
4904 vim_free(regmatch.regprog);
4905}
4906
4907/*
4908 * Give message for number of substitutions.
4909 * Can also be used after a ":global" command.
4910 * Return TRUE if a message was given.
4911 */
Bram Moolenaar8aff23a2005-08-19 20:40:30 +00004912 int
Bram Moolenaar05159a02005-02-26 23:04:13 +00004913do_sub_msg(count_only)
4914 int count_only; /* used 'n' flag for ":s" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915{
Bram Moolenaar555b2802005-05-19 21:08:39 +00004916 int len = 0;
4917
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 /*
4919 * Only report substitutions when:
4920 * - more than 'report' substitutions
4921 * - command was typed by user, or number of changed lines > 'report'
4922 * - giving messages is not disabled by 'lazyredraw'
4923 */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004924 if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
4925 || count_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 && messaging())
4927 {
4928 if (got_int)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004929 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 STRCPY(msg_buf, _("(Interrupted) "));
Bram Moolenaar555b2802005-05-19 21:08:39 +00004931 len = STRLEN(msg_buf);
4932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933 if (sub_nsubs == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004934 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4935 "%s", count_only ? _("1 match") : _("1 substitution"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004937 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
Bram Moolenaar05159a02005-02-26 23:04:13 +00004938 count_only ? _("%ld matches") : _("%ld substitutions"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 sub_nsubs);
Bram Moolenaar555b2802005-05-19 21:08:39 +00004940 len = STRLEN(msg_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004941 if (sub_nlines == 1)
Bram Moolenaar555b2802005-05-19 21:08:39 +00004942 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4943 "%s", _(" on 1 line"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00004945 vim_snprintf((char *)msg_buf + len, sizeof(msg_buf) - len,
4946 _(" on %ld lines"), (long)sub_nlines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947 if (msg(msg_buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948 /* save message to display it after redraw */
Bram Moolenaar238a5642006-02-21 22:12:05 +00004949 set_keep_msg(msg_buf, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 return TRUE;
4951 }
4952 if (got_int)
4953 {
4954 EMSG(_(e_interr));
4955 return TRUE;
4956 }
4957 return FALSE;
4958}
4959
4960/*
4961 * Execute a global command of the form:
4962 *
4963 * g/pattern/X : execute X on all lines where pattern matches
4964 * v/pattern/X : execute X on all lines where pattern does not match
4965 *
4966 * where 'X' is an EX command
4967 *
4968 * The command character (as well as the trailing slash) is optional, and
4969 * is assumed to be 'p' if missing.
4970 *
4971 * This is implemented in two passes: first we scan the file for the pattern and
4972 * set a mark for each line that (not) matches. secondly we execute the command
4973 * for each line that has a mark. This is required because after deleting
4974 * lines we do not know where to search for the next match.
4975 */
4976 void
4977ex_global(eap)
4978 exarg_T *eap;
4979{
4980 linenr_T lnum; /* line number according to old situation */
Bram Moolenaar05159a02005-02-26 23:04:13 +00004981 int ndone = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 int type; /* first char of cmd: 'v' or 'g' */
4983 char_u *cmd; /* command argument */
4984
4985 char_u delim; /* delimiter, normally '/' */
4986 char_u *pat;
4987 regmmatch_T regmatch;
4988 int match;
4989 int which_pat;
4990
4991 if (global_busy)
4992 {
4993 EMSG(_("E147: Cannot do :global recursive")); /* will increment global_busy */
4994 return;
4995 }
4996
4997 if (eap->forceit) /* ":global!" is like ":vglobal" */
4998 type = 'v';
4999 else
5000 type = *eap->cmd;
5001 cmd = eap->arg;
5002 which_pat = RE_LAST; /* default: use last used regexp */
5003 sub_nsubs = 0;
5004 sub_nlines = 0;
5005
5006 /*
5007 * undocumented vi feature:
5008 * "\/" and "\?": use previous search pattern.
5009 * "\&": use previous substitute pattern.
5010 */
5011 if (*cmd == '\\')
5012 {
5013 ++cmd;
5014 if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
5015 {
5016 EMSG(_(e_backslash));
5017 return;
5018 }
5019 if (*cmd == '&')
5020 which_pat = RE_SUBST; /* use previous substitute pattern */
5021 else
5022 which_pat = RE_SEARCH; /* use previous search pattern */
5023 ++cmd;
5024 pat = (char_u *)"";
5025 }
5026 else if (*cmd == NUL)
5027 {
5028 EMSG(_("E148: Regular expression missing from global"));
5029 return;
5030 }
5031 else
5032 {
5033 delim = *cmd; /* get the delimiter */
5034 if (delim)
5035 ++cmd; /* skip delimiter if there is one */
5036 pat = cmd; /* remember start of pattern */
5037 cmd = skip_regexp(cmd, delim, p_magic, &eap->arg);
5038 if (cmd[0] == delim) /* end delimiter found */
5039 *cmd++ = NUL; /* replace it with a NUL */
5040 }
5041
5042#ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */
5043 if (p_altkeymap && curwin->w_p_rl)
5044 lrFswap(pat,0);
5045#endif
5046
5047 if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, &regmatch) == FAIL)
5048 {
5049 EMSG(_(e_invcmd));
5050 return;
5051 }
5052
5053 /*
5054 * pass 1: set marks for each (not) matching line
5055 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 for (lnum = eap->line1; lnum <= eap->line2 && !got_int; ++lnum)
5057 {
5058 /* a match on this line? */
5059 match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0);
5060 if ((type == 'g' && match) || (type == 'v' && !match))
5061 {
5062 ml_setmarked(lnum);
5063 ndone++;
5064 }
5065 line_breakcheck();
5066 }
5067
5068 /*
5069 * pass 2: execute the command for each line that has been marked
5070 */
5071 if (got_int)
5072 MSG(_(e_interr));
5073 else if (ndone == 0)
5074 {
5075 if (type == 'v')
Bram Moolenaar555b2802005-05-19 21:08:39 +00005076 smsg((char_u *)_("Pattern found in every line: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00005078 smsg((char_u *)_(e_patnotf2), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005079 }
5080 else
5081 global_exe(cmd);
5082
5083 ml_clearmarked(); /* clear rest of the marks */
5084 vim_free(regmatch.regprog);
5085}
5086
5087/*
5088 * Execute "cmd" on lines marked with ml_setmarked().
5089 */
5090 void
5091global_exe(cmd)
5092 char_u *cmd;
5093{
5094 linenr_T old_lcount; /* b_ml.ml_line_count before the command */
5095 linenr_T lnum; /* line number according to old situation */
5096
5097 /*
5098 * Set current position only once for a global command.
5099 * If global_busy is set, setpcmark() will not do anything.
5100 * If there is an error, global_busy will be incremented.
5101 */
5102 setpcmark();
5103
5104 /* When the command writes a message, don't overwrite the command. */
5105 msg_didout = TRUE;
5106
5107 global_need_beginline = FALSE;
5108 global_busy = 1;
5109 old_lcount = curbuf->b_ml.ml_line_count;
5110 while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1)
5111 {
5112 curwin->w_cursor.lnum = lnum;
5113 curwin->w_cursor.col = 0;
5114 if (*cmd == NUL || *cmd == '\n')
5115 do_cmdline((char_u *)"p", NULL, NULL, DOCMD_NOWAIT);
5116 else
5117 do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
5118 ui_breakcheck();
5119 }
5120
5121 global_busy = 0;
5122 if (global_need_beginline)
5123 beginline(BL_WHITE | BL_FIX);
5124 else
5125 check_cursor(); /* cursor may be beyond the end of the line */
5126
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005127 /* the cursor may not have moved in the text but a change in a previous
5128 * line may move it on the screen */
5129 changed_line_abv_curs();
5130
Bram Moolenaar071d4272004-06-13 20:20:40 +00005131 /* If it looks like no message was written, allow overwriting the
5132 * command with the report for number of changes. */
5133 if (msg_col == 0 && msg_scrolled == 0)
5134 msg_didout = FALSE;
5135
5136 /* If subsitutes done, report number of substitues, otherwise report
5137 * number of extra or deleted lines. */
Bram Moolenaar05159a02005-02-26 23:04:13 +00005138 if (!do_sub_msg(FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005139 msgmore(curbuf->b_ml.ml_line_count - old_lcount);
5140}
5141
5142#ifdef FEAT_VIMINFO
5143 int
5144read_viminfo_sub_string(virp, force)
5145 vir_T *virp;
5146 int force;
5147{
5148 if (old_sub != NULL && force)
5149 vim_free(old_sub);
5150 if (force || old_sub == NULL)
5151 old_sub = viminfo_readstring(virp, 1, TRUE);
5152 return viminfo_readline(virp);
5153}
5154
5155 void
5156write_viminfo_sub_string(fp)
5157 FILE *fp;
5158{
5159 if (get_viminfo_parameter('/') != 0 && old_sub != NULL)
5160 {
5161 fprintf(fp, _("\n# Last Substitute String:\n$"));
5162 viminfo_writestring(fp, old_sub);
5163 }
5164}
5165#endif /* FEAT_VIMINFO */
5166
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005167#if defined(EXITFREE) || defined(PROTO)
5168 void
5169free_old_sub()
5170{
5171 vim_free(old_sub);
5172}
5173#endif
5174
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175#if (defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)) || defined(PROTO)
5176/*
5177 * Set up for a tagpreview.
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005178 * Return TRUE when it was created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179 */
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005180 int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181prepare_tagpreview()
5182{
5183 win_T *wp;
5184
5185# ifdef FEAT_GUI
5186 need_mouse_correct = TRUE;
5187# endif
5188
5189 /*
5190 * If there is already a preview window open, use that one.
5191 */
5192 if (!curwin->w_p_pvw)
5193 {
5194 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5195 if (wp->w_p_pvw)
5196 break;
5197 if (wp != NULL)
5198 win_enter(wp, TRUE);
5199 else
5200 {
5201 /*
5202 * There is no preview window open yet. Create one.
5203 */
5204 if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0)
5205 == FAIL)
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005206 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 curwin->w_p_pvw = TRUE;
5208 curwin->w_p_wfh = TRUE;
5209# ifdef FEAT_SCROLLBIND
5210 curwin->w_p_scb = FALSE; /* don't take over 'scrollbind' */
5211# endif
5212# ifdef FEAT_DIFF
5213 curwin->w_p_diff = FALSE; /* no 'diff' */
5214# endif
5215# ifdef FEAT_FOLDING
5216 curwin->w_p_fdc = 0; /* no 'foldcolumn' */
5217# endif
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005218 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 }
5220 }
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00005221 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222}
5223
5224#endif
5225
5226
5227/*
5228 * ":help": open a read-only window on a help file
5229 */
5230 void
5231ex_help(eap)
5232 exarg_T *eap;
5233{
5234 char_u *arg;
5235 char_u *tag;
5236 FILE *helpfd; /* file descriptor of help file */
5237 int n;
5238 int i;
5239#ifdef FEAT_WINDOWS
5240 win_T *wp;
5241#endif
5242 int num_matches;
5243 char_u **matches;
5244 char_u *p;
5245 int empty_fnum = 0;
5246 int alt_fnum = 0;
5247 buf_T *buf;
5248#ifdef FEAT_MULTI_LANG
5249 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005250 char_u *lang;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005251#endif
5252
5253 if (eap != NULL)
5254 {
5255 /*
5256 * A ":help" command ends at the first LF, or at a '|' that is
5257 * followed by some text. Set nextcmd to the following command.
5258 */
5259 for (arg = eap->arg; *arg; ++arg)
5260 {
5261 if (*arg == '\n' || *arg == '\r'
5262 || (*arg == '|' && arg[1] != NUL && arg[1] != '|'))
5263 {
5264 *arg++ = NUL;
5265 eap->nextcmd = arg;
5266 break;
5267 }
5268 }
5269 arg = eap->arg;
5270
5271 if (eap->forceit && *arg == NUL)
5272 {
5273 EMSG(_("E478: Don't panic!"));
5274 return;
5275 }
5276
5277 if (eap->skip) /* not executing commands */
5278 return;
5279 }
5280 else
5281 arg = (char_u *)"";
5282
5283 /* remove trailing blanks */
5284 p = arg + STRLEN(arg) - 1;
5285 while (p > arg && vim_iswhite(*p) && p[-1] != '\\')
5286 *p-- = NUL;
5287
5288#ifdef FEAT_MULTI_LANG
5289 /* Check for a specified language */
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005290 lang = check_help_lang(arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291#endif
5292
5293 /* When no argument given go to the index. */
5294 if (*arg == NUL)
5295 arg = (char_u *)"help.txt";
5296
5297 /*
5298 * Check if there is a match for the argument.
5299 */
5300 n = find_help_tags(arg, &num_matches, &matches,
5301 eap != NULL && eap->forceit);
5302
5303 i = 0;
5304#ifdef FEAT_MULTI_LANG
5305 if (n != FAIL && lang != NULL)
5306 /* Find first item with the requested language. */
5307 for (i = 0; i < num_matches; ++i)
5308 {
5309 len = STRLEN(matches[i]);
5310 if (len > 3 && matches[i][len - 3] == '@'
5311 && STRICMP(matches[i] + len - 2, lang) == 0)
5312 break;
5313 }
5314#endif
5315 if (i >= num_matches || n == FAIL)
5316 {
5317#ifdef FEAT_MULTI_LANG
5318 if (lang != NULL)
5319 EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg);
5320 else
5321#endif
5322 EMSG2(_("E149: Sorry, no help for %s"), arg);
5323 if (n != FAIL)
5324 FreeWild(num_matches, matches);
5325 return;
5326 }
5327
5328 /* The first match (in the requested language) is the best match. */
5329 tag = vim_strsave(matches[i]);
5330 FreeWild(num_matches, matches);
5331
5332#ifdef FEAT_GUI
5333 need_mouse_correct = TRUE;
5334#endif
5335
5336 /*
5337 * Re-use an existing help window or open a new one.
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005338 * Always open a new one for ":tab help".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339 */
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005340 if (!curwin->w_buffer->b_help
5341#ifdef FEAT_WINDOWS
5342 || cmdmod.tab != 0
5343#endif
5344 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 {
5346#ifdef FEAT_WINDOWS
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005347 if (cmdmod.tab != 0)
5348 wp = NULL;
5349 else
5350 for (wp = firstwin; wp != NULL; wp = wp->w_next)
5351 if (wp->w_buffer != NULL && wp->w_buffer->b_help)
5352 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353 if (wp != NULL && wp->w_buffer->b_nwindows > 0)
5354 win_enter(wp, TRUE);
5355 else
5356#endif
5357 {
5358 /*
5359 * There is no help window yet.
5360 * Try to open the file specified by the "helpfile" option.
5361 */
5362 if ((helpfd = mch_fopen((char *)p_hf, READBIN)) == NULL)
5363 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00005364 smsg((char_u *)_("Sorry, help file \"%s\" not found"), p_hf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365 goto erret;
5366 }
5367 fclose(helpfd);
5368
5369#ifdef FEAT_WINDOWS
5370 /* Split off help window; put it at far top if no position
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005371 * specified, the current window is vertically split and
5372 * narrow. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373 n = WSP_HELP;
5374# ifdef FEAT_VERTSPLIT
5375 if (cmdmod.split == 0 && curwin->w_width != Columns
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005376 && curwin->w_width < 80)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377 n |= WSP_TOP;
5378# endif
5379 if (win_split(0, n) == FAIL)
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005380 goto erret;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381#else
5382 /* use current window */
5383 if (!can_abandon(curbuf, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384 goto erret;
Bram Moolenaar2a3f7ee2006-02-23 21:34:44 +00005385#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386
5387#ifdef FEAT_WINDOWS
5388 if (curwin->w_height < p_hh)
5389 win_setheight((int)p_hh);
5390#endif
5391
5392 /*
5393 * Open help file (do_ecmd() will set b_help flag, readfile() will
5394 * set b_p_ro flag).
5395 * Set the alternate file to the previously edited file.
5396 */
5397 alt_fnum = curbuf->b_fnum;
5398 (void)do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL,
5399 ECMD_HIDE + ECMD_SET_HELP);
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005400 if (!cmdmod.keepalt)
5401 curwin->w_alt_fnum = alt_fnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 empty_fnum = curbuf->b_fnum;
5403 }
5404 }
5405
5406 if (!p_im)
5407 restart_edit = 0; /* don't want insert mode in help file */
5408
5409 if (tag != NULL)
5410 do_tag(tag, DT_HELP, 1, FALSE, TRUE);
5411
5412 /* Delete the empty buffer if we're not using it. */
5413 if (empty_fnum != 0 && curbuf->b_fnum != empty_fnum)
5414 {
5415 buf = buflist_findnr(empty_fnum);
5416 if (buf != NULL)
5417 wipe_buffer(buf, TRUE);
5418 }
5419
5420 /* keep the previous alternate file */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005421 if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005422 curwin->w_alt_fnum = alt_fnum;
5423
5424erret:
5425 vim_free(tag);
5426}
5427
5428
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005429#if defined(FEAT_MULTI_LANG) || defined(PROTO)
5430/*
5431 * In an argument search for a language specifiers in the form "@xx".
5432 * Changes the "@" to NUL if found, and returns a pointer to "xx".
5433 * Returns NULL if not found.
5434 */
5435 char_u *
5436check_help_lang(arg)
5437 char_u *arg;
5438{
5439 int len = STRLEN(arg);
5440
5441 if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2])
5442 && ASCII_ISALPHA(arg[len - 1]))
5443 {
5444 arg[len - 3] = NUL; /* remove the '@' */
5445 return arg + len - 2;
5446 }
5447 return NULL;
5448}
5449#endif
5450
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451/*
5452 * Return a heuristic indicating how well the given string matches. The
5453 * smaller the number, the better the match. This is the order of priorities,
5454 * from best match to worst match:
5455 * - Match with least alpha-numeric characters is better.
5456 * - Match with least total characters is better.
5457 * - Match towards the start is better.
5458 * - Match starting with "+" is worse (feature instead of command)
5459 * Assumption is made that the matched_string passed has already been found to
5460 * match some string for which help is requested. webb.
5461 */
5462 int
5463help_heuristic(matched_string, offset, wrong_case)
5464 char_u *matched_string;
5465 int offset; /* offset for match */
5466 int wrong_case; /* no matching case */
5467{
5468 int num_letters;
5469 char_u *p;
5470
5471 num_letters = 0;
5472 for (p = matched_string; *p; p++)
5473 if (ASCII_ISALNUM(*p))
5474 num_letters++;
5475
5476 /*
5477 * Multiply the number of letters by 100 to give it a much bigger
5478 * weighting than the number of characters.
5479 * If there only is a match while ignoring case, add 5000.
5480 * If the match starts in the middle of a word, add 10000 to put it
5481 * somewhere in the last half.
5482 * If the match is more than 2 chars from the start, multiply by 200 to
5483 * put it after matches at the start.
5484 */
5485 if (ASCII_ISALNUM(matched_string[offset]) && offset > 0
5486 && ASCII_ISALNUM(matched_string[offset - 1]))
5487 offset += 10000;
5488 else if (offset > 2)
5489 offset *= 200;
5490 if (wrong_case)
5491 offset += 5000;
5492 /* Features are less interesting than the subjects themselves, but "+"
5493 * alone is not a feature. */
5494 if (matched_string[0] == '+' && matched_string[1] != NUL)
5495 offset += 100;
5496 return (int)(100 * num_letters + STRLEN(matched_string) + offset);
5497}
5498
5499/*
5500 * Compare functions for qsort() below, that checks the help heuristics number
5501 * that has been put after the tagname by find_tags().
5502 */
5503 static int
5504#ifdef __BORLANDC__
5505_RTLENTRYF
5506#endif
5507help_compare(s1, s2)
5508 const void *s1;
5509 const void *s2;
5510{
5511 char *p1;
5512 char *p2;
5513
5514 p1 = *(char **)s1 + strlen(*(char **)s1) + 1;
5515 p2 = *(char **)s2 + strlen(*(char **)s2) + 1;
5516 return strcmp(p1, p2);
5517}
5518
5519/*
5520 * Find all help tags matching "arg", sort them and return in matches[], with
5521 * the number of matches in num_matches.
5522 * The matches will be sorted with a "best" match algorithm.
5523 * When "keep_lang" is TRUE try keeping the language of the current buffer.
5524 */
5525 int
5526find_help_tags(arg, num_matches, matches, keep_lang)
5527 char_u *arg;
5528 int *num_matches;
5529 char_u ***matches;
5530 int keep_lang;
5531{
5532 char_u *s, *d;
5533 int i;
5534 static char *(mtable[]) = {"*", "g*", "[*", "]*", ":*",
Bram Moolenaar231334e2005-07-25 20:46:57 +00005535 "/*", "/\\*", "\"*", "**",
5536 "/\\(\\)",
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005537 "?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005538 "/\\?", "/\\z(\\)", "\\=", ":s\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539 "[count]", "[quotex]", "[range]",
5540 "[pattern]", "\\|", "\\%$"};
5541 static char *(rtable[]) = {"star", "gstar", "[star", "]star", ":star",
Bram Moolenaar231334e2005-07-25 20:46:57 +00005542 "/star", "/\\\\star", "quotestar", "starstar",
5543 "/\\\\(\\\\)",
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005544 "?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
Bram Moolenaarf4630b62005-05-20 21:31:17 +00005545 "/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005546 "\\[count]", "\\[quotex]", "\\[range]",
5547 "\\[pattern]", "\\\\bar", "/\\\\%\\$"};
5548 int flags;
5549
5550 d = IObuff; /* assume IObuff is long enough! */
5551
5552 /*
5553 * Recognize a few exceptions to the rule. Some strings that contain '*'
5554 * with "star". Otherwise '*' is recognized as a wildcard.
5555 */
5556 for (i = sizeof(mtable) / sizeof(char *); --i >= 0; )
5557 if (STRCMP(arg, mtable[i]) == 0)
5558 {
5559 STRCPY(d, rtable[i]);
5560 break;
5561 }
5562
5563 if (i < 0) /* no match in table */
5564 {
5565 /* Replace "\S" with "/\\S", etc. Otherwise every tag is matched.
5566 * Also replace "\%^" and "\%(", they match every tag too.
5567 * Also "\zs", "\z1", etc.
5568 * Also "\@<", "\@=", "\@<=", etc.
5569 * And also "\_$" and "\_^". */
5570 if (arg[0] == '\\'
5571 && ((arg[1] != NUL && arg[2] == NUL)
5572 || (vim_strchr((char_u *)"%_z@", arg[1]) != NULL
5573 && arg[2] != NUL)))
5574 {
5575 STRCPY(d, "/\\\\");
5576 STRCPY(d + 3, arg + 1);
5577 /* Check for "/\\_$", should be "/\\_\$" */
5578 if (d[3] == '_' && d[4] == '$')
5579 STRCPY(d + 4, "\\$");
5580 }
5581 else
5582 {
5583 /* replace "[:...:]" with "\[:...:]"; "[+...]" with "\[++...]" */
5584 if (arg[0] == '[' && (arg[1] == ':'
5585 || (arg[1] == '+' && arg[2] == '+')))
5586 *d++ = '\\';
5587
5588 for (s = arg; *s; ++s)
5589 {
5590 /*
5591 * Replace "|" with "bar" and '"' with "quote" to match the name of
5592 * the tags for these commands.
5593 * Replace "*" with ".*" and "?" with "." to match command line
5594 * completion.
5595 * Insert a backslash before '~', '$' and '.' to avoid their
5596 * special meaning.
5597 */
5598 if (d - IObuff > IOSIZE - 10) /* getting too long!? */
5599 break;
5600 switch (*s)
5601 {
5602 case '|': STRCPY(d, "bar");
5603 d += 3;
5604 continue;
5605 case '"': STRCPY(d, "quote");
5606 d += 5;
5607 continue;
5608 case '*': *d++ = '.';
5609 break;
5610 case '?': *d++ = '.';
5611 continue;
5612 case '$':
5613 case '.':
5614 case '~': *d++ = '\\';
5615 break;
5616 }
5617
5618 /*
5619 * Replace "^x" by "CTRL-X". Don't do this for "^_" to make
5620 * ":help i_^_CTRL-D" work.
5621 * Insert '-' before and after "CTRL-X" when applicable.
5622 */
5623 if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1])
5624 || vim_strchr((char_u *)"?@[\\]^", s[1]) != NULL)))
5625 {
5626 if (d > IObuff && d[-1] != '_')
5627 *d++ = '_'; /* prepend a '_' */
5628 STRCPY(d, "CTRL-");
5629 d += 5;
5630 if (*s < ' ')
5631 {
5632#ifdef EBCDIC
5633 *d++ = CtrlChar(*s);
5634#else
5635 *d++ = *s + '@';
5636#endif
5637 if (d[-1] == '\\')
5638 *d++ = '\\'; /* double a backslash */
5639 }
5640 else
5641 *d++ = *++s;
5642 if (s[1] != NUL && s[1] != '_')
5643 *d++ = '_'; /* append a '_' */
5644 continue;
5645 }
5646 else if (*s == '^') /* "^" or "CTRL-^" or "^_" */
5647 *d++ = '\\';
5648
5649 /*
5650 * Insert a backslash before a backslash after a slash, for search
5651 * pattern tags: "/\|" --> "/\\|".
5652 */
5653 else if (s[0] == '\\' && s[1] != '\\'
5654 && *arg == '/' && s == arg + 1)
5655 *d++ = '\\';
5656
5657 /* "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in
5658 * "CTRL-\_CTRL-N" */
5659 if (STRNICMP(s, "CTRL-\\_", 7) == 0)
5660 {
5661 STRCPY(d, "CTRL-\\\\");
5662 d += 7;
5663 s += 6;
5664 }
5665
5666 *d++ = *s;
5667
5668 /*
5669 * If tag starts with ', toss everything after a second '. Fixes
5670 * CTRL-] on 'option'. (would include the trailing '.').
5671 */
5672 if (*s == '\'' && s > arg && *arg == '\'')
5673 break;
5674 }
5675 *d = NUL;
5676 }
5677 }
5678
5679 *matches = (char_u **)"";
5680 *num_matches = 0;
5681 flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE;
5682 if (keep_lang)
5683 flags |= TAG_KEEP_LANG;
5684 if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK
5685 && *num_matches > 0)
5686 /* Sort the matches found on the heuristic number that is after the
5687 * tag name. */
5688 qsort((void *)*matches, (size_t)*num_matches,
5689 sizeof(char_u *), help_compare);
5690 return OK;
5691}
5692
5693/*
5694 * After reading a help file: May cleanup a help buffer when syntax
5695 * highlighting is not used.
5696 */
5697 void
5698fix_help_buffer()
5699{
5700 linenr_T lnum;
5701 char_u *line;
5702 int in_example = FALSE;
5703 int len;
5704 char_u *p;
5705 char_u *rt;
5706 int mustfree;
5707
5708 /* set filetype to "help". */
5709 set_option_value((char_u *)"ft", 0L, (char_u *)"help", OPT_LOCAL);
5710
5711#ifdef FEAT_SYN_HL
5712 if (!syntax_present(curbuf))
5713#endif
5714 {
5715 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
5716 {
5717 line = ml_get_buf(curbuf, lnum, FALSE);
5718 len = (int)STRLEN(line);
5719 if (in_example && len > 0 && !vim_iswhite(line[0]))
5720 {
5721 /* End of example: non-white or '<' in first column. */
5722 if (line[0] == '<')
5723 {
5724 /* blank-out a '<' in the first column */
5725 line = ml_get_buf(curbuf, lnum, TRUE);
5726 line[0] = ' ';
5727 }
5728 in_example = FALSE;
5729 }
5730 if (!in_example && len > 0)
5731 {
5732 if (line[len - 1] == '>' && (len == 1 || line[len - 2] == ' '))
5733 {
5734 /* blank-out a '>' in the last column (start of example) */
5735 line = ml_get_buf(curbuf, lnum, TRUE);
5736 line[len - 1] = ' ';
5737 in_example = TRUE;
5738 }
5739 else if (line[len - 1] == '~')
5740 {
5741 /* blank-out a '~' at the end of line (header marker) */
5742 line = ml_get_buf(curbuf, lnum, TRUE);
5743 line[len - 1] = ' ';
5744 }
5745 }
5746 }
5747 }
5748
5749 /*
5750 * In the "help.txt" file, add the locally added help files.
5751 * This uses the very first line in the help file.
5752 */
5753 if (fnamecmp(gettail(curbuf->b_fname), "help.txt") == 0)
5754 {
5755 for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; ++lnum)
5756 {
5757 line = ml_get_buf(curbuf, lnum, FALSE);
5758 if (strstr((char *)line, "*local-additions*") != NULL)
5759 {
5760 /* Go through all directories in 'runtimepath', skipping
5761 * $VIMRUNTIME. */
5762 p = p_rtp;
5763 while (*p != NUL)
5764 {
5765 copy_option_part(&p, NameBuff, MAXPATHL, ",");
5766 mustfree = FALSE;
5767 rt = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
5768 if (fullpathcmp(rt, NameBuff, FALSE) != FPC_SAME)
5769 {
5770 int fcount;
5771 char_u **fnames;
5772 FILE *fd;
5773 char_u *s;
5774 int fi;
5775#ifdef FEAT_MBYTE
5776 vimconv_T vc;
5777 char_u *cp;
5778#endif
5779
5780 /* Find all "doc/ *.txt" files in this directory. */
5781 add_pathsep(NameBuff);
5782 STRCAT(NameBuff, "doc/*.txt");
5783 if (gen_expand_wildcards(1, &NameBuff, &fcount,
5784 &fnames, EW_FILE|EW_SILENT) == OK
5785 && fcount > 0)
5786 {
5787 for (fi = 0; fi < fcount; ++fi)
5788 {
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00005789 fd = mch_fopen((char *)fnames[fi], "r");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 if (fd != NULL)
5791 {
5792 vim_fgets(IObuff, IOSIZE, fd);
5793 if (IObuff[0] == '*'
5794 && (s = vim_strchr(IObuff + 1, '*'))
5795 != NULL)
5796 {
5797#ifdef FEAT_MBYTE
5798 int this_utf = MAYBE;
5799#endif
5800 /* Change tag definition to a
5801 * reference and remove <CR>/<NL>. */
5802 IObuff[0] = '|';
5803 *s = '|';
5804 while (*s != NUL)
5805 {
5806 if (*s == '\r' || *s == '\n')
5807 *s = NUL;
5808#ifdef FEAT_MBYTE
5809 /* The text is utf-8 when a byte
5810 * above 127 is found and no
5811 * illegal byte sequence is found.
5812 */
5813 if (*s >= 0x80 && this_utf != FALSE)
5814 {
5815 int l;
5816
5817 this_utf = TRUE;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005818 l = utf_ptr2len(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819 if (l == 1)
5820 this_utf = FALSE;
5821 s += l - 1;
5822 }
5823#endif
5824 ++s;
5825 }
5826#ifdef FEAT_MBYTE
5827 /* The help file is latin1 or utf-8;
5828 * conversion to the current
5829 * 'encoding' may be required. */
5830 vc.vc_type = CONV_NONE;
5831 convert_setup(&vc, (char_u *)(
5832 this_utf == TRUE ? "utf-8"
5833 : "latin1"), p_enc);
5834 if (vc.vc_type == CONV_NONE)
5835 /* No conversion needed. */
5836 cp = IObuff;
5837 else
5838 {
5839 /* Do the conversion. If it fails
5840 * use the unconverted text. */
5841 cp = string_convert(&vc, IObuff,
5842 NULL);
5843 if (cp == NULL)
5844 cp = IObuff;
5845 }
5846 convert_setup(&vc, NULL, NULL);
5847
5848 ml_append(lnum, cp, (colnr_T)0, FALSE);
5849 if (cp != IObuff)
5850 vim_free(cp);
5851#else
5852 ml_append(lnum, IObuff, (colnr_T)0,
5853 FALSE);
5854#endif
5855 ++lnum;
5856 }
5857 fclose(fd);
5858 }
5859 }
5860 FreeWild(fcount, fnames);
5861 }
5862 }
5863 if (mustfree)
5864 vim_free(rt);
5865 }
5866 break;
5867 }
5868 }
5869 }
5870}
5871
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00005872/*
5873 * ":exusage"
5874 */
5875/*ARGSUSED*/
5876 void
5877ex_exusage(eap)
5878 exarg_T *eap;
5879{
5880 do_cmdline_cmd((char_u *)"help ex-cmd-index");
5881}
5882
5883/*
5884 * ":viusage"
5885 */
5886/*ARGSUSED*/
5887 void
5888ex_viusage(eap)
5889 exarg_T *eap;
5890{
5891 do_cmdline_cmd((char_u *)"help normal-index");
5892}
5893
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894#if defined(FEAT_EX_EXTRA) || defined(PROTO)
5895static void helptags_one __ARGS((char_u *dir, char_u *ext, char_u *lang));
5896
5897/*
5898 * ":helptags"
5899 */
5900 void
5901ex_helptags(eap)
5902 exarg_T *eap;
5903{
5904 garray_T ga;
5905 int i, j;
5906 int len;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005907#ifdef FEAT_MULTI_LANG
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908 char_u lang[2];
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005909#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 char_u ext[5];
5911 char_u fname[8];
5912 int filecount;
5913 char_u **files;
5914
5915 if (!mch_isdir(eap->arg))
5916 {
5917 EMSG2(_("E150: Not a directory: %s"), eap->arg);
5918 return;
5919 }
5920
5921#ifdef FEAT_MULTI_LANG
5922 /* Get a list of all files in the directory. */
5923 STRCPY(NameBuff, eap->arg);
5924 add_pathsep(NameBuff);
5925 STRCAT(NameBuff, "*");
5926 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
5927 EW_FILE|EW_SILENT) == FAIL
5928 || filecount == 0)
5929 {
5930 EMSG2("E151: No match: %s", NameBuff);
5931 return;
5932 }
5933
5934 /* Go over all files in the directory to find out what languages are
5935 * present. */
5936 ga_init2(&ga, 1, 10);
5937 for (i = 0; i < filecount; ++i)
5938 {
5939 len = STRLEN(files[i]);
5940 if (len > 4)
5941 {
5942 if (STRICMP(files[i] + len - 4, ".txt") == 0)
5943 {
5944 /* ".txt" -> language "en" */
5945 lang[0] = 'e';
5946 lang[1] = 'n';
5947 }
5948 else if (files[i][len - 4] == '.'
5949 && ASCII_ISALPHA(files[i][len - 3])
5950 && ASCII_ISALPHA(files[i][len - 2])
5951 && TOLOWER_ASC(files[i][len - 1]) == 'x')
5952 {
5953 /* ".abx" -> language "ab" */
5954 lang[0] = TOLOWER_ASC(files[i][len - 3]);
5955 lang[1] = TOLOWER_ASC(files[i][len - 2]);
5956 }
5957 else
5958 continue;
5959
5960 /* Did we find this language already? */
5961 for (j = 0; j < ga.ga_len; j += 2)
5962 if (STRNCMP(lang, ((char_u *)ga.ga_data) + j, 2) == 0)
5963 break;
5964 if (j == ga.ga_len)
5965 {
5966 /* New language, add it. */
5967 if (ga_grow(&ga, 2) == FAIL)
5968 break;
5969 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[0];
5970 ((char_u *)ga.ga_data)[ga.ga_len++] = lang[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971 }
5972 }
5973 }
5974
5975 /*
5976 * Loop over the found languages to generate a tags file for each one.
5977 */
5978 for (j = 0; j < ga.ga_len; j += 2)
5979 {
5980 STRCPY(fname, "tags-xx");
5981 fname[5] = ((char_u *)ga.ga_data)[j];
5982 fname[6] = ((char_u *)ga.ga_data)[j + 1];
5983 if (fname[5] == 'e' && fname[6] == 'n')
5984 {
5985 /* English is an exception: use ".txt" and "tags". */
5986 fname[4] = NUL;
5987 STRCPY(ext, ".txt");
5988 }
5989 else
5990 {
5991 /* Language "ab" uses ".abx" and "tags-ab". */
5992 STRCPY(ext, ".xxx");
5993 ext[1] = fname[5];
5994 ext[2] = fname[6];
5995 }
5996 helptags_one(eap->arg, ext, fname);
5997 }
5998
5999 ga_clear(&ga);
6000 FreeWild(filecount, files);
6001
6002#else
6003 /* No language support, just use "*.txt" and "tags". */
6004 helptags_one(eap->arg, (char_u *)".txt", (char_u *)"tags");
6005#endif
6006}
6007
6008 static void
6009helptags_one(dir, ext, tagfname)
6010 char_u *dir; /* doc directory */
6011 char_u *ext; /* suffix, ".txt", ".itx", ".frx", etc. */
6012 char_u *tagfname; /* "tags" for English, "tags-it" for Italian. */
6013{
6014 FILE *fd_tags;
6015 FILE *fd;
6016 garray_T ga;
6017 int filecount;
6018 char_u **files;
6019 char_u *p1, *p2;
6020 int fi;
6021 char_u *s;
6022 int i;
6023 char_u *fname;
6024# ifdef FEAT_MBYTE
6025 int utf8 = MAYBE;
6026 int this_utf8;
6027 int firstline;
6028 int mix = FALSE; /* detected mixed encodings */
6029# endif
6030
6031 /*
6032 * Find all *.txt files.
6033 */
6034 STRCPY(NameBuff, dir);
6035 add_pathsep(NameBuff);
6036 STRCAT(NameBuff, "*");
6037 STRCAT(NameBuff, ext);
6038 if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
6039 EW_FILE|EW_SILENT) == FAIL
6040 || filecount == 0)
6041 {
6042 if (!got_int)
6043 EMSG2("E151: No match: %s", NameBuff);
6044 return;
6045 }
6046
6047 /*
6048 * Open the tags file for writing.
6049 * Do this before scanning through all the files.
6050 */
6051 STRCPY(NameBuff, dir);
6052 add_pathsep(NameBuff);
6053 STRCAT(NameBuff, tagfname);
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00006054 fd_tags = mch_fopen((char *)NameBuff, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 if (fd_tags == NULL)
6056 {
6057 EMSG2(_("E152: Cannot open %s for writing"), NameBuff);
6058 FreeWild(filecount, files);
6059 return;
6060 }
6061
6062 /*
6063 * If generating tags for "$VIMRUNTIME/doc" add the "help-tags" tag.
6064 */
6065 ga_init2(&ga, (int)sizeof(char_u *), 100);
6066 if (fullpathcmp((char_u *)"$VIMRUNTIME/doc", dir, FALSE) == FPC_SAME)
6067 {
6068 if (ga_grow(&ga, 1) == FAIL)
6069 got_int = TRUE;
6070 else
6071 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00006072 s = alloc(18 + STRLEN(tagfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073 if (s == NULL)
6074 got_int = TRUE;
6075 else
6076 {
6077 sprintf((char *)s, "help-tags\t%s\t1\n", tagfname);
6078 ((char_u **)ga.ga_data)[ga.ga_len] = s;
6079 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 }
6081 }
6082 }
6083
6084 /*
6085 * Go over all the files and extract the tags.
6086 */
6087 for (fi = 0; fi < filecount && !got_int; ++fi)
6088 {
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00006089 fd = mch_fopen((char *)files[fi], "r");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090 if (fd == NULL)
6091 {
6092 EMSG2(_("E153: Unable to open %s for reading"), files[fi]);
6093 continue;
6094 }
6095 fname = gettail(files[fi]);
6096
6097# ifdef FEAT_MBYTE
6098 firstline = TRUE;
6099# endif
6100 while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int)
6101 {
6102# ifdef FEAT_MBYTE
6103 if (firstline)
6104 {
6105 /* Detect utf-8 file by a non-ASCII char in the first line. */
6106 this_utf8 = MAYBE;
6107 for (s = IObuff; *s != NUL; ++s)
6108 if (*s >= 0x80)
6109 {
6110 int l;
6111
6112 this_utf8 = TRUE;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00006113 l = utf_ptr2len(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 if (l == 1)
6115 {
6116 /* Illegal UTF-8 byte sequence. */
6117 this_utf8 = FALSE;
6118 break;
6119 }
6120 s += l - 1;
6121 }
6122 if (this_utf8 == MAYBE) /* only ASCII characters found */
6123 this_utf8 = FALSE;
6124 if (utf8 == MAYBE) /* first file */
6125 utf8 = this_utf8;
6126 else if (utf8 != this_utf8)
6127 {
6128 EMSG2(_("E670: Mix of help file encodings within a language: %s"), files[fi]);
6129 mix = !got_int;
6130 got_int = TRUE;
6131 }
6132 firstline = FALSE;
6133 }
6134# endif
6135 p1 = vim_strchr(IObuff, '*'); /* find first '*' */
6136 while (p1 != NULL)
6137 {
6138 p2 = vim_strchr(p1 + 1, '*'); /* find second '*' */
6139 if (p2 != NULL && p2 > p1 + 1) /* skip "*" and "**" */
6140 {
6141 for (s = p1 + 1; s < p2; ++s)
6142 if (*s == ' ' || *s == '\t' || *s == '|')
6143 break;
6144
6145 /*
6146 * Only accept a *tag* when it consists of valid
6147 * characters, there is white space before it and is
6148 * followed by a white character or end-of-line.
6149 */
6150 if (s == p2
6151 && (p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
6152 && (vim_strchr((char_u *)" \t\n\r", s[1]) != NULL
6153 || s[1] == '\0'))
6154 {
6155 *p2 = '\0';
6156 ++p1;
6157 if (ga_grow(&ga, 1) == FAIL)
6158 {
6159 got_int = TRUE;
6160 break;
6161 }
6162 s = alloc((unsigned)(p2 - p1 + STRLEN(fname) + 2));
6163 if (s == NULL)
6164 {
6165 got_int = TRUE;
6166 break;
6167 }
6168 ((char_u **)ga.ga_data)[ga.ga_len] = s;
6169 ++ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 sprintf((char *)s, "%s\t%s", p1, fname);
6171
6172 /* find next '*' */
6173 p2 = vim_strchr(p2 + 1, '*');
6174 }
6175 }
6176 p1 = p2;
6177 }
6178 line_breakcheck();
6179 }
6180
6181 fclose(fd);
6182 }
6183
6184 FreeWild(filecount, files);
6185
6186 if (!got_int)
6187 {
6188 /*
6189 * Sort the tags.
6190 */
6191 sort_strings((char_u **)ga.ga_data, ga.ga_len);
6192
6193 /*
6194 * Check for duplicates.
6195 */
6196 for (i = 1; i < ga.ga_len; ++i)
6197 {
6198 p1 = ((char_u **)ga.ga_data)[i - 1];
6199 p2 = ((char_u **)ga.ga_data)[i];
6200 while (*p1 == *p2)
6201 {
6202 if (*p2 == '\t')
6203 {
6204 *p2 = NUL;
Bram Moolenaar555b2802005-05-19 21:08:39 +00006205 vim_snprintf((char *)NameBuff, MAXPATHL,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 _("E154: Duplicate tag \"%s\" in file %s/%s"),
6207 ((char_u **)ga.ga_data)[i], dir, p2 + 1);
6208 EMSG(NameBuff);
6209 *p2 = '\t';
6210 break;
6211 }
6212 ++p1;
6213 ++p2;
6214 }
6215 }
6216
6217# ifdef FEAT_MBYTE
6218 if (utf8 == TRUE)
6219 fprintf(fd_tags, "!_TAG_FILE_ENCODING\tutf-8\t//\n");
6220# endif
6221
6222 /*
6223 * Write the tags into the file.
6224 */
6225 for (i = 0; i < ga.ga_len; ++i)
6226 {
6227 s = ((char_u **)ga.ga_data)[i];
6228 if (STRNCMP(s, "help-tags", 9) == 0)
6229 /* help-tags entry was added in formatted form */
6230 fprintf(fd_tags, (char *)s);
6231 else
6232 {
6233 fprintf(fd_tags, "%s\t/*", s);
6234 for (p1 = s; *p1 != '\t'; ++p1)
6235 {
6236 /* insert backslash before '\\' and '/' */
6237 if (*p1 == '\\' || *p1 == '/')
6238 putc('\\', fd_tags);
6239 putc(*p1, fd_tags);
6240 }
6241 fprintf(fd_tags, "*\n");
6242 }
6243 }
6244 }
6245#ifdef FEAT_MBYTE
6246 if (mix)
6247 got_int = FALSE; /* continue with other languages */
6248#endif
6249
6250 for (i = 0; i < ga.ga_len; ++i)
6251 vim_free(((char_u **)ga.ga_data)[i]);
6252 ga_clear(&ga);
6253 fclose(fd_tags); /* there is no check for an error... */
6254}
6255#endif
6256
6257#if defined(FEAT_SIGNS) || defined(PROTO)
6258
6259/*
6260 * Struct to hold the sign properties.
6261 */
6262typedef struct sign sign_T;
6263
6264struct sign
6265{
6266 sign_T *sn_next; /* next sign in list */
6267 int sn_typenr; /* type number of sign (negative if not equal
6268 to name) */
6269 char_u *sn_name; /* name of sign */
6270 char_u *sn_icon; /* name of pixmap */
6271#ifdef FEAT_SIGN_ICONS
6272 void *sn_image; /* icon image */
6273#endif
6274 char_u *sn_text; /* text used instead of pixmap */
6275 int sn_line_hl; /* highlight ID for line */
6276 int sn_text_hl; /* highlight ID for text */
6277};
6278
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279static sign_T *first_sign = NULL;
6280static int last_sign_typenr = MAX_TYPENR; /* is decremented */
6281
6282static void sign_list_defined __ARGS((sign_T *sp));
6283
6284/*
6285 * ":sign" command
6286 */
6287 void
6288ex_sign(eap)
6289 exarg_T *eap;
6290{
6291 char_u *arg = eap->arg;
6292 char_u *p;
6293 int idx;
6294 sign_T *sp;
6295 sign_T *sp_prev;
6296 buf_T *buf;
6297 static char *cmds[] = {
6298 "define",
6299#define SIGNCMD_DEFINE 0
6300 "undefine",
6301#define SIGNCMD_UNDEFINE 1
6302 "list",
6303#define SIGNCMD_LIST 2
6304 "place",
6305#define SIGNCMD_PLACE 3
6306 "unplace",
6307#define SIGNCMD_UNPLACE 4
6308 "jump",
6309#define SIGNCMD_JUMP 5
6310#define SIGNCMD_LAST 6
6311 };
6312
6313 /* Parse the subcommand. */
6314 p = skiptowhite(arg);
6315 if (*p != NUL)
6316 *p++ = NUL;
6317 for (idx = 0; ; ++idx)
6318 {
6319 if (idx == SIGNCMD_LAST)
6320 {
6321 EMSG2(_("E160: Unknown sign command: %s"), arg);
6322 return;
6323 }
6324 if (STRCMP(arg, cmds[idx]) == 0)
6325 break;
6326 }
6327 arg = skipwhite(p);
6328
6329 if (idx <= SIGNCMD_LIST)
6330 {
6331 /*
6332 * Define, undefine or list signs.
6333 */
6334 if (idx == SIGNCMD_LIST && *arg == NUL)
6335 {
6336 /* ":sign list": list all defined signs */
6337 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6338 sign_list_defined(sp);
6339 }
6340 else if (*arg == NUL)
6341 EMSG(_("E156: Missing sign name"));
6342 else
6343 {
6344 p = skiptowhite(arg);
6345 if (*p != NUL)
6346 *p++ = NUL;
6347 sp_prev = NULL;
6348 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6349 {
6350 if (STRCMP(sp->sn_name, arg) == 0)
6351 break;
6352 sp_prev = sp;
6353 }
6354 if (idx == SIGNCMD_DEFINE)
6355 {
6356 /* ":sign define {name} ...": define a sign */
6357 if (sp == NULL)
6358 {
6359 /* Allocate a new sign. */
6360 sp = (sign_T *)alloc_clear((unsigned)sizeof(sign_T));
6361 if (sp == NULL)
6362 return;
6363 if (sp_prev == NULL)
6364 first_sign = sp;
6365 else
6366 sp_prev->sn_next = sp;
6367 sp->sn_name = vim_strnsave(arg, (int)(p - arg));
6368
6369 /* If the name is a number use that for the typenr,
6370 * otherwise use a negative number. */
6371 if (VIM_ISDIGIT(*arg))
6372 sp->sn_typenr = atoi((char *)arg);
6373 else
6374 {
6375 sign_T *lp;
6376 int start = last_sign_typenr;
6377
6378 for (lp = first_sign; lp != NULL; lp = lp->sn_next)
6379 {
6380 if (lp->sn_typenr == last_sign_typenr)
6381 {
6382 --last_sign_typenr;
6383 if (last_sign_typenr == 0)
6384 last_sign_typenr = MAX_TYPENR;
6385 if (last_sign_typenr == start)
6386 {
6387 EMSG(_("E612: Too many signs defined"));
6388 return;
6389 }
6390 lp = first_sign;
6391 continue;
6392 }
6393 }
6394
6395 sp->sn_typenr = last_sign_typenr--;
6396 if (last_sign_typenr == 0)
6397 last_sign_typenr = MAX_TYPENR; /* wrap around */
6398 }
6399 }
6400
6401 /* set values for a defined sign. */
6402 for (;;)
6403 {
6404 arg = skipwhite(p);
6405 if (*arg == NUL)
6406 break;
6407 p = skiptowhite_esc(arg);
6408 if (STRNCMP(arg, "icon=", 5) == 0)
6409 {
6410 arg += 5;
6411 vim_free(sp->sn_icon);
6412 sp->sn_icon = vim_strnsave(arg, (int)(p - arg));
6413 backslash_halve(sp->sn_icon);
6414#ifdef FEAT_SIGN_ICONS
6415 if (gui.in_use)
6416 {
6417 out_flush();
6418 if (sp->sn_image != NULL)
6419 gui_mch_destroy_sign(sp->sn_image);
6420 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6421 }
6422#endif
6423 }
6424 else if (STRNCMP(arg, "text=", 5) == 0)
6425 {
6426 char_u *s;
6427 int cells;
6428 int len;
6429
6430 arg += 5;
6431#ifdef FEAT_MBYTE
6432 /* Count cells and check for non-printable chars */
6433 if (has_mbyte)
6434 {
6435 cells = 0;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00006436 for (s = arg; s < p; s += (*mb_ptr2len)(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437 {
6438 if (!vim_isprintc((*mb_ptr2char)(s)))
6439 break;
6440 cells += (*mb_ptr2cells)(s);
6441 }
6442 }
6443 else
6444#endif
6445 {
6446 for (s = arg; s < p; ++s)
6447 if (!vim_isprintc(*s))
6448 break;
6449 cells = s - arg;
6450 }
6451 /* Currently must be one or two display cells */
6452 if (s != p || cells < 1 || cells > 2)
6453 {
6454 *p = NUL;
6455 EMSG2(_("E239: Invalid sign text: %s"), arg);
6456 return;
6457 }
6458
6459 vim_free(sp->sn_text);
6460 /* Allocate one byte more if we need to pad up
6461 * with a space. */
6462 len = p - arg + ((cells == 1) ? 1 : 0);
6463 sp->sn_text = vim_strnsave(arg, len);
6464
6465 if (sp->sn_text != NULL && cells == 1)
6466 STRCPY(sp->sn_text + len - 1, " ");
6467 }
6468 else if (STRNCMP(arg, "linehl=", 7) == 0)
6469 {
6470 arg += 7;
6471 sp->sn_line_hl = syn_check_group(arg, (int)(p - arg));
6472 }
6473 else if (STRNCMP(arg, "texthl=", 7) == 0)
6474 {
6475 arg += 7;
6476 sp->sn_text_hl = syn_check_group(arg, (int)(p - arg));
6477 }
6478 else
6479 {
6480 EMSG2(_(e_invarg2), arg);
6481 return;
6482 }
6483 }
6484 }
6485 else if (sp == NULL)
6486 EMSG2(_("E155: Unknown sign: %s"), arg);
6487 else if (idx == SIGNCMD_LIST)
6488 /* ":sign list {name}" */
6489 sign_list_defined(sp);
6490 else
6491 {
6492 /* ":sign undefine {name}" */
6493 vim_free(sp->sn_name);
6494 vim_free(sp->sn_icon);
6495#ifdef FEAT_SIGN_ICONS
6496 if (sp->sn_image != NULL)
6497 {
6498 out_flush();
6499 gui_mch_destroy_sign(sp->sn_image);
6500 }
6501#endif
6502 vim_free(sp->sn_text);
6503 if (sp_prev == NULL)
6504 first_sign = sp->sn_next;
6505 else
6506 sp_prev->sn_next = sp->sn_next;
6507 vim_free(sp);
6508 }
6509 }
6510 }
6511 else
6512 {
6513 int id = -1;
6514 linenr_T lnum = -1;
6515 char_u *sign_name = NULL;
6516 char_u *arg1;
6517
6518 if (*arg == NUL)
6519 {
6520 if (idx == SIGNCMD_PLACE)
6521 {
6522 /* ":sign place": list placed signs in all buffers */
6523 sign_list_placed(NULL);
6524 }
6525 else if (idx == SIGNCMD_UNPLACE)
6526 {
6527 /* ":sign unplace": remove placed sign at cursor */
6528 id = buf_findsign_id(curwin->w_buffer, curwin->w_cursor.lnum);
6529 if (id > 0)
6530 {
6531 buf_delsign(curwin->w_buffer, id);
6532 update_debug_sign(curwin->w_buffer, curwin->w_cursor.lnum);
6533 }
6534 else
6535 EMSG(_("E159: Missing sign number"));
6536 }
6537 else
6538 EMSG(_(e_argreq));
6539 return;
6540 }
6541
6542 if (idx == SIGNCMD_UNPLACE && arg[0] == '*' && arg[1] == NUL)
6543 {
6544 /* ":sign unplace *": remove all placed signs */
6545 buf_delete_all_signs();
6546 return;
6547 }
6548
6549 /* first arg could be placed sign id */
6550 arg1 = arg;
6551 if (VIM_ISDIGIT(*arg))
6552 {
6553 id = getdigits(&arg);
6554 if (!vim_iswhite(*arg) && *arg != NUL)
6555 {
6556 id = -1;
6557 arg = arg1;
6558 }
6559 else
6560 {
6561 arg = skipwhite(arg);
6562 if (idx == SIGNCMD_UNPLACE && *arg == NUL)
6563 {
6564 /* ":sign unplace {id}": remove placed sign by number */
6565 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6566 if ((lnum = buf_delsign(buf, id)) != 0)
6567 update_debug_sign(buf, lnum);
6568 return;
6569 }
6570 }
6571 }
6572
6573 /*
6574 * Check for line={lnum} name={name} and file={fname} or buffer={nr}.
6575 * Leave "arg" pointing to {fname}.
6576 */
6577 for (;;)
6578 {
6579 if (STRNCMP(arg, "line=", 5) == 0)
6580 {
6581 arg += 5;
6582 lnum = atoi((char *)arg);
6583 arg = skiptowhite(arg);
6584 }
6585 else if (STRNCMP(arg, "name=", 5) == 0)
6586 {
6587 arg += 5;
6588 sign_name = arg;
6589 arg = skiptowhite(arg);
6590 if (*arg != NUL)
6591 *arg++ = NUL;
6592 }
6593 else if (STRNCMP(arg, "file=", 5) == 0)
6594 {
6595 arg += 5;
6596 buf = buflist_findname(arg);
6597 break;
6598 }
6599 else if (STRNCMP(arg, "buffer=", 7) == 0)
6600 {
6601 arg += 7;
6602 buf = buflist_findnr((int)getdigits(&arg));
6603 if (*skipwhite(arg) != NUL)
6604 EMSG(_(e_trailing));
6605 break;
6606 }
6607 else
6608 {
6609 EMSG(_(e_invarg));
6610 return;
6611 }
6612 arg = skipwhite(arg);
6613 }
6614
6615 if (buf == NULL)
6616 {
6617 EMSG2(_("E158: Invalid buffer name: %s"), arg);
6618 }
6619 else if (id <= 0)
6620 {
6621 if (lnum >= 0 || sign_name != NULL)
6622 EMSG(_(e_invarg));
6623 else
6624 /* ":sign place file={fname}": list placed signs in one file */
6625 sign_list_placed(buf);
6626 }
6627 else if (idx == SIGNCMD_JUMP)
6628 {
6629 /* ":sign jump {id} file={fname}" */
6630 if (lnum >= 0 || sign_name != NULL)
6631 EMSG(_(e_invarg));
6632 else if ((lnum = buf_findsign(buf, id)) > 0)
6633 { /* goto a sign ... */
6634 if (buf_jump_open_win(buf) != NULL)
6635 { /* ... in a current window */
6636 curwin->w_cursor.lnum = lnum;
6637 check_cursor_lnum();
6638 beginline(BL_WHITE);
6639 }
6640 else
6641 { /* ... not currently in a window */
6642 char_u *cmd;
6643
6644 cmd = alloc((unsigned)STRLEN(buf->b_fname) + 25);
6645 if (cmd == NULL)
6646 return;
6647 sprintf((char *)cmd, "e +%ld %s", (long)lnum, buf->b_fname);
6648 do_cmdline_cmd(cmd);
6649 vim_free(cmd);
6650 }
6651#ifdef FEAT_FOLDING
6652 foldOpenCursor();
6653#endif
6654 }
6655 else
6656 EMSGN(_("E157: Invalid sign ID: %ld"), id);
6657 }
6658 else if (idx == SIGNCMD_UNPLACE)
6659 {
6660 /* ":sign unplace {id} file={fname}" */
6661 if (lnum >= 0 || sign_name != NULL)
6662 EMSG(_(e_invarg));
6663 else
6664 {
6665 lnum = buf_delsign(buf, id);
6666 update_debug_sign(buf, lnum);
6667 }
6668 }
6669 /* idx == SIGNCMD_PLACE */
6670 else if (sign_name != NULL)
6671 {
6672 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6673 if (STRCMP(sp->sn_name, sign_name) == 0)
6674 break;
6675 if (sp == NULL)
6676 {
6677 EMSG2(_("E155: Unknown sign: %s"), sign_name);
6678 return;
6679 }
6680 if (lnum > 0)
6681 /* ":sign place {id} line={lnum} name={name} file={fname}":
6682 * place a sign */
6683 buf_addsign(buf, id, lnum, sp->sn_typenr);
6684 else
6685 /* ":sign place {id} file={fname}": change sign type */
6686 lnum = buf_change_sign_type(buf, id, sp->sn_typenr);
6687 update_debug_sign(buf, lnum);
6688 }
6689 else
6690 EMSG(_(e_invarg));
6691 }
6692}
6693
6694#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6695/*
6696 * Allocate the icons. Called when the GUI has started. Allows defining
6697 * signs before it starts.
6698 */
6699 void
6700sign_gui_started()
6701{
6702 sign_T *sp;
6703
6704 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6705 if (sp->sn_icon != NULL)
6706 sp->sn_image = gui_mch_register_sign(sp->sn_icon);
6707}
6708#endif
6709
6710/*
6711 * List one sign.
6712 */
6713 static void
6714sign_list_defined(sp)
6715 sign_T *sp;
6716{
6717 char_u *p;
6718
Bram Moolenaar555b2802005-05-19 21:08:39 +00006719 smsg((char_u *)"sign %s", sp->sn_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 if (sp->sn_icon != NULL)
6721 {
6722 MSG_PUTS(" icon=");
6723 msg_outtrans(sp->sn_icon);
6724#ifdef FEAT_SIGN_ICONS
6725 if (sp->sn_image == NULL)
6726 MSG_PUTS(_(" (NOT FOUND)"));
6727#else
6728 MSG_PUTS(_(" (not supported)"));
6729#endif
6730 }
6731 if (sp->sn_text != NULL)
6732 {
6733 MSG_PUTS(" text=");
6734 msg_outtrans(sp->sn_text);
6735 }
6736 if (sp->sn_line_hl > 0)
6737 {
6738 MSG_PUTS(" linehl=");
6739 p = get_highlight_name(NULL, sp->sn_line_hl - 1);
6740 if (p == NULL)
6741 MSG_PUTS("NONE");
6742 else
6743 msg_puts(p);
6744 }
6745 if (sp->sn_text_hl > 0)
6746 {
6747 MSG_PUTS(" texthl=");
6748 p = get_highlight_name(NULL, sp->sn_text_hl - 1);
6749 if (p == NULL)
6750 MSG_PUTS("NONE");
6751 else
6752 msg_puts(p);
6753 }
6754}
6755
6756/*
6757 * Get highlighting attribute for sign "typenr".
6758 * If "line" is TRUE: line highl, if FALSE: text highl.
6759 */
6760 int
6761sign_get_attr(typenr, line)
6762 int typenr;
6763 int line;
6764{
6765 sign_T *sp;
6766
6767 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6768 if (sp->sn_typenr == typenr)
6769 {
6770 if (line)
6771 {
6772 if (sp->sn_line_hl > 0)
6773 return syn_id2attr(sp->sn_line_hl);
6774 }
6775 else
6776 {
6777 if (sp->sn_text_hl > 0)
6778 return syn_id2attr(sp->sn_text_hl);
6779 }
6780 break;
6781 }
6782 return 0;
6783}
6784
6785/*
6786 * Get text mark for sign "typenr".
6787 * Returns NULL if there isn't one.
6788 */
6789 char_u *
6790sign_get_text(typenr)
6791 int typenr;
6792{
6793 sign_T *sp;
6794
6795 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6796 if (sp->sn_typenr == typenr)
6797 return sp->sn_text;
6798 return NULL;
6799}
6800
6801#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6802 void *
6803sign_get_image(typenr)
6804 int typenr; /* the attribute which may have a sign */
6805{
6806 sign_T *sp;
6807
6808 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6809 if (sp->sn_typenr == typenr)
6810 return sp->sn_image;
6811 return NULL;
6812}
6813#endif
6814
6815/*
6816 * Get the name of a sign by its typenr.
6817 */
6818 char_u *
6819sign_typenr2name(typenr)
6820 int typenr;
6821{
6822 sign_T *sp;
6823
6824 for (sp = first_sign; sp != NULL; sp = sp->sn_next)
6825 if (sp->sn_typenr == typenr)
6826 return sp->sn_name;
6827 return (char_u *)_("[Deleted]");
6828}
6829
6830#endif
6831
6832#if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
6833/*
6834 * ":drop"
6835 * Opens the first argument in a window. When there are two or more arguments
6836 * the argument list is redefined.
6837 */
6838 void
6839ex_drop(eap)
6840 exarg_T *eap;
6841{
6842 int split = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843 win_T *wp;
6844 buf_T *buf;
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006845# ifdef FEAT_WINDOWS
6846 tabpage_T *tp;
6847# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848
6849 /*
6850 * Check if the first argument is already being edited in a window. If
6851 * so, jump to that window.
6852 * We would actually need to check all arguments, but that's complicated
6853 * and mostly only one file is dropped.
6854 * This also ignores wildcards, since it is very unlikely the user is
6855 * editing a file name with a wildcard character.
6856 */
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006857 set_arglist(eap->arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006859# ifdef FEAT_WINDOWS
6860 if (cmdmod.tab)
6861 {
6862 /* ":tab drop file ...": open a tab for each argument that isn't
6863 * edited in a window yet. It's like ":tab all" but without closing
6864 * windows or tabs. */
6865 ex_all(eap);
6866 }
6867 else
6868# endif
6869 {
6870 /* ":drop file ...": Edit the first argument. Jump to an existing
6871 * window if possible, edit in current window if the current buffer
6872 * can be abandoned, otherwise open a new window. */
6873 buf = buflist_findnr(ARGLIST[0].ae_fnum);
6874
6875 FOR_ALL_TAB_WINDOWS(tp, wp)
6876 {
6877 if (wp->w_buffer == buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 {
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006879# ifdef FEAT_WINDOWS
6880 goto_tabpage_tp(tp);
6881 win_enter(wp, TRUE);
6882# ifdef FEAT_GUI_TABLINE
6883 if (gui_use_tabline())
6884 gui_mch_set_curtab(tabpage_index(curtab));
6885# endif
6886# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887 curwin->w_arg_idx = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 return;
6889 }
6890 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006892 /*
6893 * Check whether the current buffer is changed. If so, we will need
6894 * to split the current window or data could be lost.
6895 * Skip the check if the 'hidden' option is set, as in this case the
6896 * buffer won't be lost.
6897 */
6898 if (!P_HID(curbuf))
6899 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900# ifdef FEAT_WINDOWS
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006901 ++emsg_off;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902# endif
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006903 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904# ifdef FEAT_WINDOWS
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006905 --emsg_off;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906# else
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006907 if (split)
6908 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909# endif
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006910 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911
Bram Moolenaara5b6ad12006-03-11 21:36:59 +00006912 /* Fake a ":sfirst" or ":first" command edit the first argument. */
6913 if (split)
6914 {
6915 eap->cmdidx = CMD_sfirst;
6916 eap->cmd[0] = 's';
6917 }
6918 else
6919 eap->cmdidx = CMD_first;
6920 ex_rewind(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922}
6923#endif