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