blob: f04612d88656977dbe1098f7d0f6de2bd59bc821 [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 * fileio.c: read from and write to a file
12 */
13
14#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
15# include <io.h> /* for lseek(), must be before vim.h */
16#endif
17
18#if defined __EMX__
19# include <io.h> /* for mktemp(), CJW 1997-12-03 */
20#endif
21
22#include "vim.h"
23
24#ifdef HAVE_FCNTL_H
25# include <fcntl.h>
26#endif
27
28#ifdef __TANDEM
29# include <limits.h> /* for SSIZE_MAX */
30#endif
31
32#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
33# include <utime.h> /* for struct utimbuf */
34#endif
35
36#define BUFSIZE 8192 /* size of normal write buffer */
37#define SMBUFSIZE 256 /* size of emergency write buffer */
38
39#ifdef FEAT_CRYPT
40# define CRYPT_MAGIC "VimCrypt~01!" /* "01" is the version nr */
41# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
42#endif
43
44/* Is there any system that doesn't have access()? */
45#ifndef MACOS_CLASSIC /* Not available on MacOS 9 */
46# define USE_MCH_ACCESS
47#endif
48
49#ifdef FEAT_MBYTE
50static char_u *next_fenc __ARGS((char_u **pp));
51# ifdef FEAT_EVAL
52static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
53# endif
54#endif
55#ifdef FEAT_VIMINFO
56static void check_marks_read __ARGS((void));
57#endif
58#ifdef FEAT_CRYPT
59static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, long *filesizep, int newfile));
60#endif
61#ifdef UNIX
62static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
63#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000064static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000065static void msg_add_eol __ARGS((void));
66static int check_mtime __ARGS((buf_T *buf, struct stat *s));
67static int time_differs __ARGS((long t1, long t2));
68#ifdef FEAT_AUTOCMD
69static int apply_autocmds_exarg __ARGS((EVENT_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap));
70#endif
71
72#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
73# define HAS_BW_FLAGS
74# define FIO_LATIN1 0x01 /* convert Latin1 */
75# define FIO_UTF8 0x02 /* convert UTF-8 */
76# define FIO_UCS2 0x04 /* convert UCS-2 */
77# define FIO_UCS4 0x08 /* convert UCS-4 */
78# define FIO_UTF16 0x10 /* convert UTF-16 */
79# ifdef WIN3264
80# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
81# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
82# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
83# endif
84# ifdef MACOS_X
85# define FIO_MACROMAN 0x20 /* convert MacRoman */
86# endif
87# define FIO_ENDIAN_L 0x80 /* little endian */
88# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
89# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
90# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
91# define FIO_ALL -1 /* allow all formats */
92#endif
93
94/* When converting, a read() or write() may leave some bytes to be converted
95 * for the next call. The value is guessed... */
96#define CONV_RESTLEN 30
97
98/* We have to guess how much a sequence of bytes may expand when converting
99 * with iconv() to be able to allocate a buffer. */
100#define ICONV_MULT 8
101
102/*
103 * Structure to pass arguments from buf_write() to buf_write_bytes().
104 */
105struct bw_info
106{
107 int bw_fd; /* file descriptor */
108 char_u *bw_buf; /* buffer with data to be written */
109 int bw_len; /* lenght of data */
110#ifdef HAS_BW_FLAGS
111 int bw_flags; /* FIO_ flags */
112#endif
113#ifdef FEAT_MBYTE
114 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
115 int bw_restlen; /* nr of bytes in bw_rest[] */
116 int bw_first; /* first write call */
117 char_u *bw_conv_buf; /* buffer for writing converted chars */
118 int bw_conv_buflen; /* size of bw_conv_buf */
119 int bw_conv_error; /* set for conversion error */
120# ifdef USE_ICONV
121 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
122# endif
123#endif
124};
125
126static int buf_write_bytes __ARGS((struct bw_info *ip));
127
128#ifdef FEAT_MBYTE
129static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
130static int same_encoding __ARGS((char_u *a, char_u *b));
131static int get_fio_flags __ARGS((char_u *ptr));
132static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
133static int make_bom __ARGS((char_u *buf, char_u *name));
134# ifdef WIN3264
135static int get_win_fio_flags __ARGS((char_u *ptr));
136# endif
137# ifdef MACOS_X
138static int get_mac_fio_flags __ARGS((char_u *ptr));
139# endif
140#endif
141static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
142
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143 void
144filemess(buf, name, s, attr)
145 buf_T *buf;
146 char_u *name;
147 char_u *s;
148 int attr;
149{
150 int msg_scroll_save;
151
152 if (msg_silent != 0)
153 return;
154 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
155 /* If it's extremely long, truncate it. */
156 if (STRLEN(IObuff) > IOSIZE - 80)
157 IObuff[IOSIZE - 80] = NUL;
158 STRCAT(IObuff, s);
159 /*
160 * For the first message may have to start a new line.
161 * For further ones overwrite the previous one, reset msg_scroll before
162 * calling filemess().
163 */
164 msg_scroll_save = msg_scroll;
165 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
166 msg_scroll = FALSE;
167 if (!msg_scroll) /* wait a bit when overwriting an error msg */
168 check_for_delay(FALSE);
169 msg_start();
170 msg_scroll = msg_scroll_save;
171 msg_scrolled_ign = TRUE;
172 /* may truncate the message to avoid a hit-return prompt */
173 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
174 msg_clr_eos();
175 out_flush();
176 msg_scrolled_ign = FALSE;
177}
178
179/*
180 * Read lines from file "fname" into the buffer after line "from".
181 *
182 * 1. We allocate blocks with lalloc, as big as possible.
183 * 2. Each block is filled with characters from the file with a single read().
184 * 3. The lines are inserted in the buffer with ml_append().
185 *
186 * (caller must check that fname != NULL, unless READ_STDIN is used)
187 *
188 * "lines_to_skip" is the number of lines that must be skipped
189 * "lines_to_read" is the number of lines that are appended
190 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
191 *
192 * flags:
193 * READ_NEW starting to edit a new buffer
194 * READ_FILTER reading filter output
195 * READ_STDIN read from stdin instead of a file
196 * READ_BUFFER read from curbuf instead of a file (converting after reading
197 * stdin)
198 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
199 *
200 * return FAIL for failure, OK otherwise
201 */
202 int
203readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
204 char_u *fname;
205 char_u *sfname;
206 linenr_T from;
207 linenr_T lines_to_skip;
208 linenr_T lines_to_read;
209 exarg_T *eap; /* can be NULL! */
210 int flags;
211{
212 int fd = 0;
213 int newfile = (flags & READ_NEW);
214 int check_readonly;
215 int filtering = (flags & READ_FILTER);
216 int read_stdin = (flags & READ_STDIN);
217 int read_buffer = (flags & READ_BUFFER);
218 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
219 colnr_T read_buf_col = 0; /* next char to read from this line */
220 char_u c;
221 linenr_T lnum = from;
222 char_u *ptr = NULL; /* pointer into read buffer */
223 char_u *buffer = NULL; /* read buffer */
224 char_u *new_buffer = NULL; /* init to shut up gcc */
225 char_u *line_start = NULL; /* init to shut up gcc */
226 int wasempty; /* buffer was empty before reading */
227 colnr_T len;
228 long size = 0;
229 char_u *p;
230 long filesize = 0;
231 int skip_read = FALSE;
232#ifdef FEAT_CRYPT
233 char_u *cryptkey = NULL;
234#endif
235 int split = 0; /* number of split lines */
236#define UNKNOWN 0x0fffffff /* file size is unknown */
237 linenr_T linecnt;
238 int error = FALSE; /* errors encountered */
239 int ff_error = EOL_UNKNOWN; /* file format with errors */
240 long linerest = 0; /* remaining chars in line */
241#ifdef UNIX
242 int perm = 0;
243 int swap_mode = -1; /* protection bits for swap file */
244#else
245 int perm;
246#endif
247 int fileformat = 0; /* end-of-line format */
248 int keep_fileformat = FALSE;
249 struct stat st;
250 int file_readonly;
251 linenr_T skip_count = 0;
252 linenr_T read_count = 0;
253 int msg_save = msg_scroll;
254 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
255 * last read was missing the eol */
256 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
257 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
258 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
259 int file_rewind = FALSE;
260#ifdef FEAT_MBYTE
261 int can_retry;
262 int conv_error = FALSE; /* conversion error detected */
263 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
264 in destination encoding */
265 linenr_T illegal_byte = 0; /* line nr with illegal byte */
266 char_u *tmpname = NULL; /* name of 'charconvert' output file */
267 int fio_flags = 0;
268 char_u *fenc; /* fileencoding to use */
269 int fenc_alloced; /* fenc_next is in allocated memory */
270 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
271 int advance_fenc = FALSE;
272 long real_size = 0;
273# ifdef USE_ICONV
274 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
275# ifdef FEAT_EVAL
276 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
277 'charconvert' next */
278# endif
279# endif
280 int converted = FALSE; /* TRUE if conversion done */
281 int notconverted = FALSE; /* TRUE if conversion wanted but it
282 wasn't possible */
283 char_u conv_rest[CONV_RESTLEN];
284 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
285#endif
286
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288
289 /*
290 * If there is no file name yet, use the one for the read file.
291 * BF_NOTEDITED is set to reflect this.
292 * Don't do this for a read from a filter.
293 * Only do this when 'cpoptions' contains the 'f' flag.
294 */
295 if (curbuf->b_ffname == NULL
296 && !filtering
297 && fname != NULL
298 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
299 && !(flags & READ_DUMMY))
300 {
301 if (setfname(curbuf, fname, sfname, FALSE) == OK)
302 curbuf->b_flags |= BF_NOTEDITED;
303 }
304
Bram Moolenaardf177f62005-02-22 08:39:57 +0000305 /* After reading a file the cursor line changes but we don't want to
306 * display the line. */
307 ex_no_reprint = TRUE;
308
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309 /*
310 * For Unix: Use the short file name whenever possible.
311 * Avoids problems with networks and when directory names are changed.
312 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
313 * another directory, which we don't detect.
314 */
315 if (sfname == NULL)
316 sfname = fname;
317#if defined(UNIX) || defined(__EMX__)
318 fname = sfname;
319#endif
320
321#ifdef FEAT_AUTOCMD
322 /*
323 * The BufReadCmd and FileReadCmd events intercept the reading process by
324 * executing the associated commands instead.
325 */
326 if (!filtering && !read_stdin && !read_buffer)
327 {
328 pos_T pos;
329
330 pos = curbuf->b_op_start;
331
332 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
333 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
334 curbuf->b_op_start.col = 0;
335
336 if (newfile)
337 {
338 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
339 FALSE, curbuf, eap))
340#ifdef FEAT_EVAL
341 return aborting() ? FAIL : OK;
342#else
343 return OK;
344#endif
345 }
346 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
347 FALSE, NULL, eap))
348#ifdef FEAT_EVAL
349 return aborting() ? FAIL : OK;
350#else
351 return OK;
352#endif
353
354 curbuf->b_op_start = pos;
355 }
356#endif
357
358 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
359 msg_scroll = FALSE; /* overwrite previous file message */
360 else
361 msg_scroll = TRUE; /* don't overwrite previous file message */
362
363 /*
364 * If the name ends in a path separator, we can't open it. Check here,
365 * because reading the file may actually work, but then creating the swap
366 * file may destroy it! Reported on MS-DOS and Win 95.
367 * If the name is too long we might crash further on, quit here.
368 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000369 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000371 p = fname + STRLEN(fname);
372 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000373 {
374 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
375 msg_end();
376 msg_scroll = msg_save;
377 return FAIL;
378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 }
380
381#ifdef UNIX
382 /*
383 * On Unix it is possible to read a directory, so we have to
384 * check for it before the mch_open().
385 */
386 if (!read_stdin && !read_buffer)
387 {
388 perm = mch_getperm(fname);
389 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
390# ifdef S_ISFIFO
391 && !S_ISFIFO(perm) /* ... or fifo */
392# endif
393# ifdef S_ISSOCK
394 && !S_ISSOCK(perm) /* ... or socket */
395# endif
396 )
397 {
398 if (S_ISDIR(perm))
399 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
400 else
401 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
402 msg_end();
403 msg_scroll = msg_save;
404 return FAIL;
405 }
406 }
407#endif
408
409 /* set default 'fileformat' */
410 if (newfile)
411 {
412 if (eap != NULL && eap->force_ff != 0)
413 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
414 else if (*p_ffs != NUL)
415 set_fileformat(default_fileformat(), OPT_LOCAL);
416 }
417
418 /* set or reset 'binary' */
419 if (eap != NULL && eap->force_bin != 0)
420 {
421 int oldval = curbuf->b_p_bin;
422
423 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
424 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
425 }
426
427 /*
428 * When opening a new file we take the readonly flag from the file.
429 * Default is r/w, can be set to r/o below.
430 * Don't reset it when in readonly mode
431 * Only set/reset b_p_ro when BF_CHECK_RO is set.
432 */
433 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000434 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 curbuf->b_p_ro = FALSE;
436
437 if (newfile && !read_stdin && !read_buffer)
438 {
439 /* Remember time of file.
440 * For RISCOS, also remember the filetype.
441 */
442 if (mch_stat((char *)fname, &st) >= 0)
443 {
444 buf_store_time(curbuf, &st, fname);
445 curbuf->b_mtime_read = curbuf->b_mtime;
446
447#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
448 /* Read the filetype into the buffer local filetype option. */
449 mch_read_filetype(fname);
450#endif
451#ifdef UNIX
452 /*
453 * Use the protection bits of the original file for the swap file.
454 * This makes it possible for others to read the name of the
455 * edited file from the swapfile, but only if they can read the
456 * edited file.
457 * Remove the "write" and "execute" bits for group and others
458 * (they must not write the swapfile).
459 * Add the "read" and "write" bits for the user, otherwise we may
460 * not be able to write to the file ourselves.
461 * Setting the bits is done below, after creating the swap file.
462 */
463 swap_mode = (st.st_mode & 0644) | 0600;
464#endif
465#ifdef FEAT_CW_EDITOR
466 /* Get the FSSpec on MacOS
467 * TODO: Update it properly when the buffer name changes
468 */
469 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
470#endif
471#ifdef VMS
472 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000473 curbuf->b_fab_rat = st.st_fab_rat;
474 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475#endif
476 }
477 else
478 {
479 curbuf->b_mtime = 0;
480 curbuf->b_mtime_read = 0;
481 curbuf->b_orig_size = 0;
482 curbuf->b_orig_mode = 0;
483 }
484
485 /* Reset the "new file" flag. It will be set again below when the
486 * file doesn't exist. */
487 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
488 }
489
490/*
491 * for UNIX: check readonly with perm and mch_access()
492 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
493 * for MSDOS and Amiga: check readonly by trying to open the file for writing
494 */
495 file_readonly = FALSE;
496 if (read_stdin)
497 {
498#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
499 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
500 setmode(0, O_BINARY);
501#endif
502 }
503 else if (!read_buffer)
504 {
505#ifdef USE_MCH_ACCESS
506 if (
507# ifdef UNIX
508 !(perm & 0222) ||
509# endif
510 mch_access((char *)fname, W_OK))
511 file_readonly = TRUE;
512 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
513#else
514 if (!newfile
515 || readonlymode
516 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
517 {
518 file_readonly = TRUE;
519 /* try to open ro */
520 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
521 }
522#endif
523 }
524
525 if (fd < 0) /* cannot open at all */
526 {
527#ifndef UNIX
528 int isdir_f;
529#endif
530 msg_scroll = msg_save;
531#ifndef UNIX
532 /*
533 * On MSDOS and Amiga we can't open a directory, check here.
534 */
535 isdir_f = (mch_isdir(fname));
536 perm = mch_getperm(fname); /* check if the file exists */
537 if (isdir_f)
538 {
539 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
540 curbuf->b_p_ro = TRUE; /* must use "w!" now */
541 }
542 else
543#endif
544 if (newfile)
545 {
546 if (perm < 0)
547 {
548 /*
549 * Set the 'new-file' flag, so that when the file has
550 * been created by someone else, a ":w" will complain.
551 */
552 curbuf->b_flags |= BF_NEW;
553
554 /* Create a swap file now, so that other Vims are warned
555 * that we are editing this file. Don't do this for a
556 * "nofile" or "nowrite" buffer type. */
557#ifdef FEAT_QUICKFIX
558 if (!bt_dontwrite(curbuf))
559#endif
560 check_need_swap(newfile);
561 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
562#ifdef FEAT_VIMINFO
563 /* Even though this is a new file, it might have been
564 * edited before and deleted. Get the old marks. */
565 check_marks_read();
566#endif
567#ifdef FEAT_MBYTE
568 if (eap != NULL && eap->force_enc != 0)
569 {
570 /* set forced 'fileencoding' */
571 fenc = enc_canonize(eap->cmd + eap->force_enc);
572 if (fenc != NULL)
573 set_string_option_direct((char_u *)"fenc", -1,
574 fenc, OPT_FREE|OPT_LOCAL);
575 vim_free(fenc);
576 }
577#endif
578#ifdef FEAT_AUTOCMD
579 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
580 FALSE, curbuf, eap);
581#endif
582 /* remember the current fileformat */
583 save_file_ff(curbuf);
584
585#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
586 if (aborting()) /* autocmds may abort script processing */
587 return FAIL;
588#endif
589 return OK; /* a new file is not an error */
590 }
591 else
592 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000593 filemess(curbuf, sfname, (char_u *)(
594# ifdef EFBIG
595 (errno == EFBIG) ? _("[File too big]") :
596# endif
597 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 curbuf->b_p_ro = TRUE; /* must use "w!" now */
599 }
600 }
601
602 return FAIL;
603 }
604
605 /*
606 * Only set the 'ro' flag for readonly files the first time they are
607 * loaded. Help files always get readonly mode
608 */
609 if ((check_readonly && file_readonly) || curbuf->b_help)
610 curbuf->b_p_ro = TRUE;
611
612 if (newfile)
613 {
614 curbuf->b_p_eol = TRUE;
615 curbuf->b_start_eol = TRUE;
616#ifdef FEAT_MBYTE
617 curbuf->b_p_bomb = FALSE;
618#endif
619 }
620
621 /* Create a swap file now, so that other Vims are warned that we are
622 * editing this file.
623 * Don't do this for a "nofile" or "nowrite" buffer type. */
624#ifdef FEAT_QUICKFIX
625 if (!bt_dontwrite(curbuf))
626#endif
627 {
628 check_need_swap(newfile);
629#ifdef UNIX
630 /* Set swap file protection bits after creating it. */
631 if (swap_mode > 0 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
632 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
633#endif
634 }
635
636#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
637 /* If "Quit" selected at ATTENTION dialog, don't load the file */
638 if (swap_exists_action == SEA_QUIT)
639 {
640 if (!read_buffer && !read_stdin)
641 close(fd);
642 return FAIL;
643 }
644#endif
645
646 ++no_wait_return; /* don't wait for return yet */
647
648 /*
649 * Set '[ mark to the line above where the lines go (line 1 if zero).
650 */
651 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
652 curbuf->b_op_start.col = 0;
653
654#ifdef FEAT_AUTOCMD
655 if (!read_buffer)
656 {
657 int m = msg_scroll;
658 int n = msg_scrolled;
659 buf_T *old_curbuf = curbuf;
660
661 /*
662 * The file must be closed again, the autocommands may want to change
663 * the file before reading it.
664 */
665 if (!read_stdin)
666 close(fd); /* ignore errors */
667
668 /*
669 * The output from the autocommands should not overwrite anything and
670 * should not be overwritten: Set msg_scroll, restore its value if no
671 * output was done.
672 */
673 msg_scroll = TRUE;
674 if (filtering)
675 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
676 FALSE, curbuf, eap);
677 else if (read_stdin)
678 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
679 FALSE, curbuf, eap);
680 else if (newfile)
681 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
682 FALSE, curbuf, eap);
683 else
684 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
685 FALSE, NULL, eap);
686 if (msg_scrolled == n)
687 msg_scroll = m;
688
689#ifdef FEAT_EVAL
690 if (aborting()) /* autocmds may abort script processing */
691 {
692 --no_wait_return;
693 msg_scroll = msg_save;
694 curbuf->b_p_ro = TRUE; /* must use "w!" now */
695 return FAIL;
696 }
697#endif
698 /*
699 * Don't allow the autocommands to change the current buffer.
700 * Try to re-open the file.
701 */
702 if (!read_stdin && (curbuf != old_curbuf
703 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
704 {
705 --no_wait_return;
706 msg_scroll = msg_save;
707 if (fd < 0)
708 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
709 else
710 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
711 curbuf->b_p_ro = TRUE; /* must use "w!" now */
712 return FAIL;
713 }
714 }
715#endif /* FEAT_AUTOCMD */
716
717 /* Autocommands may add lines to the file, need to check if it is empty */
718 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
719
720 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
721 {
722 /*
723 * Show the user that we are busy reading the input. Sometimes this
724 * may take a while. When reading from stdin another program may
725 * still be running, don't move the cursor to the last line, unless
726 * always using the GUI.
727 */
728 if (read_stdin)
729 {
730#ifndef ALWAYS_USE_GUI
731 mch_msg(_("Vim: Reading from stdin...\n"));
732#endif
733#ifdef FEAT_GUI
734 /* Also write a message in the GUI window, if there is one. */
735 if (gui.in_use && !gui.dying && !gui.starting)
736 {
737 p = (char_u *)_("Reading from stdin...");
738 gui_write(p, (int)STRLEN(p));
739 }
740#endif
741 }
742 else if (!read_buffer)
743 filemess(curbuf, sfname, (char_u *)"", 0);
744 }
745
746 msg_scroll = FALSE; /* overwrite the file message */
747
748 /*
749 * Set linecnt now, before the "retry" caused by a wrong guess for
750 * fileformat, and after the autocommands, which may change them.
751 */
752 linecnt = curbuf->b_ml.ml_line_count;
753
754#ifdef FEAT_MBYTE
755 /*
756 * Decide which 'encoding' to use first.
757 */
758 if (eap != NULL && eap->force_enc != 0)
759 {
760 fenc = enc_canonize(eap->cmd + eap->force_enc);
761 fenc_alloced = TRUE;
762 }
763 else if (curbuf->b_p_bin)
764 {
765 fenc = (char_u *)""; /* binary: don't convert */
766 fenc_alloced = FALSE;
767 }
768 else if (curbuf->b_help)
769 {
770 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000771 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772
773 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
774 * fails it must be latin1.
775 * Always do this when 'encoding' is "utf-8". Otherwise only do
776 * this when needed to avoid [converted] remarks all the time.
777 * It is needed when the first line contains non-ASCII characters.
778 * That is only in *.??x files. */
779 fenc = (char_u *)"latin1";
780 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000781 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000783 fc = fname[STRLEN(fname) - 1];
784 if (TOLOWER_ASC(fc) == 'x')
785 {
786 /* Read the first line (and a bit more). Immediately rewind to
787 * the start of the file. If the read() fails "len" is -1. */
788 len = vim_read(fd, firstline, 80);
789 lseek(fd, (off_t)0L, SEEK_SET);
790 for (p = firstline; p < firstline + len; ++p)
791 if (*p >= 0x80)
792 {
793 c = TRUE;
794 break;
795 }
796 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000797 }
798
799 if (c)
800 {
801 fenc_next = fenc;
802 fenc = (char_u *)"utf-8";
803
804 /* When the file is utf-8 but a character doesn't fit in
805 * 'encoding' don't retry. In help text editing utf-8 bytes
806 * doesn't make sense. */
807 keep_dest_enc = TRUE;
808 }
809 fenc_alloced = FALSE;
810 }
811 else if (*p_fencs == NUL)
812 {
813 fenc = curbuf->b_p_fenc; /* use format from buffer */
814 fenc_alloced = FALSE;
815 }
816 else
817 {
818 fenc_next = p_fencs; /* try items in 'fileencodings' */
819 fenc = next_fenc(&fenc_next);
820 fenc_alloced = TRUE;
821 }
822#endif
823
824 /*
825 * Jump back here to retry reading the file in different ways.
826 * Reasons to retry:
827 * - encoding conversion failed: try another one from "fenc_next"
828 * - BOM detected and fenc was set, need to setup conversion
829 * - "fileformat" check failed: try another
830 *
831 * Variables set for special retry actions:
832 * "file_rewind" Rewind the file to start reading it again.
833 * "advance_fenc" Advance "fenc" using "fenc_next".
834 * "skip_read" Re-use already read bytes (BOM detected).
835 * "did_iconv" iconv() conversion failed, try 'charconvert'.
836 * "keep_fileformat" Don't reset "fileformat".
837 *
838 * Other status indicators:
839 * "tmpname" When != NULL did conversion with 'charconvert'.
840 * Output file has to be deleted afterwards.
841 * "iconv_fd" When != -1 did conversion with iconv().
842 */
843retry:
844
845 if (file_rewind)
846 {
847 if (read_buffer)
848 {
849 read_buf_lnum = 1;
850 read_buf_col = 0;
851 }
852 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
853 {
854 /* Can't rewind the file, give up. */
855 error = TRUE;
856 goto failed;
857 }
858 /* Delete the previously read lines. */
859 while (lnum > from)
860 ml_delete(lnum--, FALSE);
861 file_rewind = FALSE;
862#ifdef FEAT_MBYTE
863 if (newfile)
864 curbuf->b_p_bomb = FALSE;
865 conv_error = FALSE;
866#endif
867 }
868
869 /*
870 * When retrying with another "fenc" and the first time "fileformat"
871 * will be reset.
872 */
873 if (keep_fileformat)
874 keep_fileformat = FALSE;
875 else
876 {
877 if (eap != NULL && eap->force_ff != 0)
878 fileformat = get_fileformat_force(curbuf, eap);
879 else if (curbuf->b_p_bin)
880 fileformat = EOL_UNIX; /* binary: use Unix format */
881 else if (*p_ffs == NUL)
882 fileformat = get_fileformat(curbuf);/* use format from buffer */
883 else
884 fileformat = EOL_UNKNOWN; /* detect from file */
885 }
886
887#ifdef FEAT_MBYTE
888# ifdef USE_ICONV
889 if (iconv_fd != (iconv_t)-1)
890 {
891 /* aborted conversion with iconv(), close the descriptor */
892 iconv_close(iconv_fd);
893 iconv_fd = (iconv_t)-1;
894 }
895# endif
896
897 if (advance_fenc)
898 {
899 /*
900 * Try the next entry in 'fileencodings'.
901 */
902 advance_fenc = FALSE;
903
904 if (eap != NULL && eap->force_enc != 0)
905 {
906 /* Conversion given with "++cc=" wasn't possible, read
907 * without conversion. */
908 notconverted = TRUE;
909 conv_error = FALSE;
910 if (fenc_alloced)
911 vim_free(fenc);
912 fenc = (char_u *)"";
913 fenc_alloced = FALSE;
914 }
915 else
916 {
917 if (fenc_alloced)
918 vim_free(fenc);
919 if (fenc_next != NULL)
920 {
921 fenc = next_fenc(&fenc_next);
922 fenc_alloced = (fenc_next != NULL);
923 }
924 else
925 {
926 fenc = (char_u *)"";
927 fenc_alloced = FALSE;
928 }
929 }
930 if (tmpname != NULL)
931 {
932 mch_remove(tmpname); /* delete converted file */
933 vim_free(tmpname);
934 tmpname = NULL;
935 }
936 }
937
938 /*
939 * Conversion is required when the encoding of the file is different
940 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4 (requires
941 * conversion to UTF-8).
942 */
943 fio_flags = 0;
944 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
945 if (converted || enc_unicode != 0)
946 {
947
948 /* "ucs-bom" means we need to check the first bytes of the file
949 * for a BOM. */
950 if (STRCMP(fenc, ENC_UCSBOM) == 0)
951 fio_flags = FIO_UCSBOM;
952
953 /*
954 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
955 * done. This is handled below after read(). Prepare the
956 * fio_flags to avoid having to parse the string each time.
957 * Also check for Unicode to Latin1 conversion, because iconv()
958 * appears not to handle this correctly. This works just like
959 * conversion to UTF-8 except how the resulting character is put in
960 * the buffer.
961 */
962 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
963 fio_flags = get_fio_flags(fenc);
964
965# ifdef WIN3264
966 /*
967 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
968 * is handled with MultiByteToWideChar().
969 */
970 if (fio_flags == 0)
971 fio_flags = get_win_fio_flags(fenc);
972# endif
973
974# ifdef MACOS_X
975 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
976 if (fio_flags == 0)
977 fio_flags = get_mac_fio_flags(fenc);
978# endif
979
980# ifdef USE_ICONV
981 /*
982 * Try using iconv() if we can't convert internally.
983 */
984 if (fio_flags == 0
985# ifdef FEAT_EVAL
986 && !did_iconv
987# endif
988 )
989 iconv_fd = (iconv_t)my_iconv_open(
990 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
991# endif
992
993# ifdef FEAT_EVAL
994 /*
995 * Use the 'charconvert' expression when conversion is required
996 * and we can't do it internally or with iconv().
997 */
998 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
999# ifdef USE_ICONV
1000 && iconv_fd == (iconv_t)-1
1001# endif
1002 )
1003 {
1004# ifdef USE_ICONV
1005 did_iconv = FALSE;
1006# endif
1007 /* Skip conversion when it's already done (retry for wrong
1008 * "fileformat"). */
1009 if (tmpname == NULL)
1010 {
1011 tmpname = readfile_charconvert(fname, fenc, &fd);
1012 if (tmpname == NULL)
1013 {
1014 /* Conversion failed. Try another one. */
1015 advance_fenc = TRUE;
1016 if (fd < 0)
1017 {
1018 /* Re-opening the original file failed! */
1019 EMSG(_("E202: Conversion made file unreadable!"));
1020 error = TRUE;
1021 goto failed;
1022 }
1023 goto retry;
1024 }
1025 }
1026 }
1027 else
1028# endif
1029 {
1030 if (fio_flags == 0
1031# ifdef USE_ICONV
1032 && iconv_fd == (iconv_t)-1
1033# endif
1034 )
1035 {
1036 /* Conversion wanted but we can't.
1037 * Try the next conversion in 'fileencodings' */
1038 advance_fenc = TRUE;
1039 goto retry;
1040 }
1041 }
1042 }
1043
1044 /* Set can_retry when it's possible to rewind the file and try with
1045 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
1046 * stdin or "fenc" was specified with "++enc=". */
1047 can_retry = (*fenc != NUL && !read_stdin
1048 && (eap == NULL || eap->force_enc == 0));
1049#endif
1050
1051 if (!skip_read)
1052 {
1053 linerest = 0;
1054 filesize = 0;
1055 skip_count = lines_to_skip;
1056 read_count = lines_to_read;
1057#ifdef FEAT_MBYTE
1058 conv_restlen = 0;
1059#endif
1060 }
1061
1062 while (!error && !got_int)
1063 {
1064 /*
1065 * We allocate as much space for the file as we can get, plus
1066 * space for the old line plus room for one terminating NUL.
1067 * The amount is limited by the fact that read() only can read
1068 * upto max_unsigned characters (and other things).
1069 */
1070#if SIZEOF_INT <= 2
1071 if (linerest >= 0x7ff0)
1072 {
1073 ++split;
1074 *ptr = NL; /* split line by inserting a NL */
1075 size = 1;
1076 }
1077 else
1078#endif
1079 {
1080 if (!skip_read)
1081 {
1082#if SIZEOF_INT > 2
1083# ifdef __TANDEM
1084 size = SSIZE_MAX; /* use max I/O size, 52K */
1085# else
1086 size = 0x10000L; /* use buffer >= 64K */
1087# endif
1088#else
1089 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1090#endif
1091
1092 for ( ; size >= 10; size = (long_u)size >> 1)
1093 {
1094 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1095 FALSE)) != NULL)
1096 break;
1097 }
1098 if (new_buffer == NULL)
1099 {
1100 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1101 error = TRUE;
1102 break;
1103 }
1104 if (linerest) /* copy characters from the previous buffer */
1105 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1106 vim_free(buffer);
1107 buffer = new_buffer;
1108 ptr = buffer + linerest;
1109 line_start = buffer;
1110
1111#ifdef FEAT_MBYTE
1112 /* May need room to translate into.
1113 * For iconv() we don't really know the required space, use a
1114 * factor ICONV_MULT.
1115 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1116 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1117 * become up to 4 bytes, size must be multiple of 2
1118 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1119 * multiple of 2
1120 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1121 * multiple of 4 */
1122 real_size = size;
1123# ifdef USE_ICONV
1124 if (iconv_fd != (iconv_t)-1)
1125 size = size / ICONV_MULT;
1126 else
1127# endif
1128 if (fio_flags & FIO_LATIN1)
1129 size = size / 2;
1130 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1131 size = (size * 2 / 3) & ~1;
1132 else if (fio_flags & FIO_UCS4)
1133 size = (size * 2 / 3) & ~3;
1134 else if (fio_flags == FIO_UCSBOM)
1135 size = size / ICONV_MULT; /* worst case */
1136# ifdef WIN3264
1137 else if (fio_flags & FIO_CODEPAGE)
1138 size = size / ICONV_MULT; /* also worst case */
1139# endif
1140# ifdef MACOS_X
1141 else if (fio_flags & FIO_MACROMAN)
1142 size = size / ICONV_MULT; /* also worst case */
1143# endif
1144#endif
1145
1146#ifdef FEAT_MBYTE
1147 if (conv_restlen > 0)
1148 {
1149 /* Insert unconverted bytes from previous line. */
1150 mch_memmove(ptr, conv_rest, conv_restlen);
1151 ptr += conv_restlen;
1152 size -= conv_restlen;
1153 }
1154#endif
1155
1156 if (read_buffer)
1157 {
1158 /*
1159 * Read bytes from curbuf. Used for converting text read
1160 * from stdin.
1161 */
1162 if (read_buf_lnum > from)
1163 size = 0;
1164 else
1165 {
1166 int n, ni;
1167 long tlen;
1168
1169 tlen = 0;
1170 for (;;)
1171 {
1172 p = ml_get(read_buf_lnum) + read_buf_col;
1173 n = (int)STRLEN(p);
1174 if ((int)tlen + n + 1 > size)
1175 {
1176 /* Filled up to "size", append partial line.
1177 * Change NL to NUL to reverse the effect done
1178 * below. */
1179 n = size - tlen;
1180 for (ni = 0; ni < n; ++ni)
1181 {
1182 if (p[ni] == NL)
1183 ptr[tlen++] = NUL;
1184 else
1185 ptr[tlen++] = p[ni];
1186 }
1187 read_buf_col += n;
1188 break;
1189 }
1190 else
1191 {
1192 /* Append whole line and new-line. Change NL
1193 * to NUL to reverse the effect done below. */
1194 for (ni = 0; ni < n; ++ni)
1195 {
1196 if (p[ni] == NL)
1197 ptr[tlen++] = NUL;
1198 else
1199 ptr[tlen++] = p[ni];
1200 }
1201 ptr[tlen++] = NL;
1202 read_buf_col = 0;
1203 if (++read_buf_lnum > from)
1204 {
1205 /* When the last line didn't have an
1206 * end-of-line don't add it now either. */
1207 if (!curbuf->b_p_eol)
1208 --tlen;
1209 size = tlen;
1210 break;
1211 }
1212 }
1213 }
1214 }
1215 }
1216 else
1217 {
1218 /*
1219 * Read bytes from the file.
1220 */
1221 size = vim_read(fd, ptr, size);
1222 }
1223
1224 if (size <= 0)
1225 {
1226 if (size < 0) /* read error */
1227 error = TRUE;
1228#ifdef FEAT_MBYTE
1229 else if (conv_restlen > 0)
1230 /* some trailing bytes unconverted */
1231 conv_error = TRUE;
1232#endif
1233 }
1234
1235#ifdef FEAT_CRYPT
1236 /*
1237 * At start of file: Check for magic number of encryption.
1238 */
1239 if (filesize == 0)
1240 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1241 &filesize, newfile);
1242 /*
1243 * Decrypt the read bytes.
1244 */
1245 if (cryptkey != NULL && size > 0)
1246 for (p = ptr; p < ptr + size; ++p)
1247 ZDECODE(*p);
1248#endif
1249 }
1250 skip_read = FALSE;
1251
1252#ifdef FEAT_MBYTE
1253 /*
1254 * At start of file (or after crypt magic number): Check for BOM.
1255 * Also check for a BOM for other Unicode encodings, but not after
1256 * converting with 'charconvert' or when a BOM has already been
1257 * found.
1258 */
1259 if ((filesize == 0
1260# ifdef FEAT_CRYPT
1261 || (filesize == CRYPT_MAGIC_LEN && cryptkey != NULL)
1262# endif
1263 )
1264 && (fio_flags == FIO_UCSBOM
1265 || (!curbuf->b_p_bomb
1266 && tmpname == NULL
1267 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1268 {
1269 char_u *ccname;
1270 int blen;
1271
1272 /* no BOM detection in a short file or in binary mode */
1273 if (size < 2 || curbuf->b_p_bin)
1274 ccname = NULL;
1275 else
1276 ccname = check_for_bom(ptr, size, &blen,
1277 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1278 if (ccname != NULL)
1279 {
1280 /* Remove BOM from the text */
1281 filesize += blen;
1282 size -= blen;
1283 mch_memmove(ptr, ptr + blen, (size_t)size);
1284 if (newfile)
1285 curbuf->b_p_bomb = TRUE;
1286 }
1287
1288 if (fio_flags == FIO_UCSBOM)
1289 {
1290 if (ccname == NULL)
1291 {
1292 /* No BOM detected: retry with next encoding. */
1293 advance_fenc = TRUE;
1294 }
1295 else
1296 {
1297 /* BOM detected: set "fenc" and jump back */
1298 if (fenc_alloced)
1299 vim_free(fenc);
1300 fenc = ccname;
1301 fenc_alloced = FALSE;
1302 }
1303 /* retry reading without getting new bytes or rewinding */
1304 skip_read = TRUE;
1305 goto retry;
1306 }
1307 }
1308#endif
1309 /*
1310 * Break here for a read error or end-of-file.
1311 */
1312 if (size <= 0)
1313 break;
1314
1315#ifdef FEAT_MBYTE
1316
1317 /* Include not converted bytes. */
1318 ptr -= conv_restlen;
1319 size += conv_restlen;
1320 conv_restlen = 0;
1321
1322# ifdef USE_ICONV
1323 if (iconv_fd != (iconv_t)-1)
1324 {
1325 /*
1326 * Attempt conversion of the read bytes to 'encoding' using
1327 * iconv().
1328 */
1329 const char *fromp;
1330 char *top;
1331 size_t from_size;
1332 size_t to_size;
1333
1334 fromp = (char *)ptr;
1335 from_size = size;
1336 ptr += size;
1337 top = (char *)ptr;
1338 to_size = real_size - size;
1339
1340 /*
1341 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001342 * another conversion. Except for when there is no
1343 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001344 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001345 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1346 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001347 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1348 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001349 {
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001350 if (!keep_dest_enc && can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001351 goto rewind_retry;
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001352 if (!keep_dest_enc)
1353 conv_error = TRUE;
1354
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001355 /* Ignore a byte and try again. */
1356 ++fromp;
1357 --from_size;
1358 *top++ = '?';
1359 --to_size;
1360 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361
1362 if (from_size > 0)
1363 {
1364 /* Some remaining characters, keep them for the next
1365 * round. */
1366 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1367 conv_restlen = (int)from_size;
1368 }
1369
1370 /* move the linerest to before the converted characters */
1371 line_start = ptr - linerest;
1372 mch_memmove(line_start, buffer, (size_t)linerest);
1373 size = (long)((char_u *)top - ptr);
1374 }
1375# endif
1376
1377# ifdef WIN3264
1378 if (fio_flags & FIO_CODEPAGE)
1379 {
1380 /*
1381 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
1382 * a codepage, using standard MS-Windows functions.
1383 * 1. find out how many ucs-2 characters there are.
1384 * 2. convert from 'fileencoding' to ucs-2
1385 * 3. convert from ucs-2 to 'encoding'
1386 */
1387 char_u *ucsp;
1388 size_t from_size = size;
1389 int needed;
1390 char_u *p;
1391 int u8c;
1392
1393 /*
1394 * 1. find out how many ucs-2 characters there are.
1395 */
1396# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1397 if (FIO_GET_CP(fio_flags) == CP_UTF8)
1398 {
1399 int l, flen;
1400
1401 /* Handle CP_UTF8 ourselves to be able to handle trailing
1402 * bytes properly. First find out the number of
1403 * characters and check for trailing bytes. */
1404 needed = 0;
1405 p = ptr;
1406 for (flen = from_size; flen > 0; flen -= l)
1407 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001408 l = utf_ptr2len_len(p, flen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001409 if (l > flen) /* incomplete char */
1410 {
1411 if (l > CONV_RESTLEN)
1412 /* weird overlong byte sequence */
1413 goto rewind_retry;
1414 mch_memmove(conv_rest, p, flen);
1415 conv_restlen = flen;
1416 from_size -= flen;
1417 break;
1418 }
1419 if (l == 1 && *p >= 0x80) /* illegal byte */
1420 goto rewind_retry;
1421 ++needed;
1422 p += l;
1423 }
1424 }
1425 else
1426# endif
1427 {
1428 /* We can't tell if the last byte of an MBCS string is
1429 * valid and MultiByteToWideChar() returns zero if it
1430 * isn't. Try the whole string, and if that fails, bump
1431 * the last byte into conv_rest and try again. */
1432 needed = MultiByteToWideChar(FIO_GET_CP(fio_flags),
1433 MB_ERR_INVALID_CHARS, (LPCSTR)ptr, from_size,
1434 NULL, 0);
1435 if (needed == 0)
1436 {
1437 conv_rest[0] = ptr[from_size - 1];
1438 conv_restlen = 1;
1439 --from_size;
1440 needed = MultiByteToWideChar(FIO_GET_CP(fio_flags),
1441 MB_ERR_INVALID_CHARS, (LPCSTR)ptr, from_size,
1442 NULL, 0);
1443 }
1444
1445 /* If there really is a conversion error, try using another
1446 * conversion. */
1447 if (needed == 0)
1448 goto rewind_retry;
1449 }
1450
1451 /*
1452 * 2. convert from 'fileencoding' to ucs-2
1453 *
1454 * Put the result of conversion to UCS-2 at the end of the
1455 * buffer, then convert from UCS-2 to UTF-8 or "enc_codepage"
1456 * into the start of the buffer. If there is not enough space
1457 * just fail, there is probably something wrong.
1458 */
1459 ucsp = ptr + real_size - (needed * sizeof(WCHAR));
1460 if (ucsp < ptr + size)
1461 goto rewind_retry;
1462
1463# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1464 if (FIO_GET_CP(fio_flags) == CP_UTF8)
1465 {
1466 int l, flen;
1467
1468 /* Convert from utf-8 to ucs-2. */
1469 needed = 0;
1470 p = ptr;
1471 for (flen = from_size; flen > 0; flen -= l)
1472 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001473 l = utf_ptr2len_len(p, flen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474 u8c = utf_ptr2char(p);
1475 ucsp[needed * 2] = (u8c & 0xff);
1476 ucsp[needed * 2 + 1] = (u8c >> 8);
1477 ++needed;
1478 p += l;
1479 }
1480 }
1481 else
1482# endif
1483 needed = MultiByteToWideChar(FIO_GET_CP(fio_flags),
1484 MB_ERR_INVALID_CHARS, (LPCSTR)ptr,
1485 from_size, (LPWSTR)ucsp, needed);
1486
1487 /*
1488 * 3. convert from ucs-2 to 'encoding'
1489 */
1490 if (enc_utf8)
1491 {
1492 /* From UCS-2 to UTF-8. Cannot fail. */
1493 p = ptr;
1494 for (; needed > 0; --needed)
1495 {
1496 u8c = *ucsp++;
1497 u8c += (*ucsp++ << 8);
1498 p += utf_char2bytes(u8c, p);
1499 }
1500 size = p - ptr;
1501 }
1502 else
1503 {
1504 BOOL bad = FALSE;
1505
1506 /* From UCS-2 to "enc_codepage". If the conversion uses
1507 * the default character "?", the data doesn't fit in this
1508 * encoding, so fail (unless forced). */
1509 size = WideCharToMultiByte(enc_codepage, 0,
1510 (LPCWSTR)ucsp, needed,
1511 (LPSTR)ptr, real_size, "?", &bad);
1512 if (bad && !keep_dest_enc)
1513 goto rewind_retry;
1514 }
1515 }
1516 else
1517# endif
1518# ifdef MACOS_X
1519 if (fio_flags & FIO_MACROMAN)
1520 {
1521 /*
1522 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001523 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001524 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001525 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527 }
1528 else
1529# endif
1530 if (fio_flags != 0)
1531 {
1532 int u8c;
1533 char_u *dest;
1534 char_u *tail = NULL;
1535
1536 /*
1537 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1538 * "enc_utf8" not set: Convert Unicode to Latin1.
1539 * Go from end to start through the buffer, because the number
1540 * of bytes may increase.
1541 * "dest" points to after where the UTF-8 bytes go, "p" points
1542 * to after the next character to convert.
1543 */
1544 dest = ptr + real_size;
1545 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1546 {
1547 p = ptr + size;
1548 if (fio_flags == FIO_UTF8)
1549 {
1550 /* Check for a trailing incomplete UTF-8 sequence */
1551 tail = ptr + size - 1;
1552 while (tail > ptr && (*tail & 0xc0) == 0x80)
1553 --tail;
1554 if (tail + utf_byte2len(*tail) <= ptr + size)
1555 tail = NULL;
1556 else
1557 p = tail;
1558 }
1559 }
1560 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1561 {
1562 /* Check for a trailing byte */
1563 p = ptr + (size & ~1);
1564 if (size & 1)
1565 tail = p;
1566 if ((fio_flags & FIO_UTF16) && p > ptr)
1567 {
1568 /* Check for a trailing leading word */
1569 if (fio_flags & FIO_ENDIAN_L)
1570 {
1571 u8c = (*--p << 8);
1572 u8c += *--p;
1573 }
1574 else
1575 {
1576 u8c = *--p;
1577 u8c += (*--p << 8);
1578 }
1579 if (u8c >= 0xd800 && u8c <= 0xdbff)
1580 tail = p;
1581 else
1582 p += 2;
1583 }
1584 }
1585 else /* FIO_UCS4 */
1586 {
1587 /* Check for trailing 1, 2 or 3 bytes */
1588 p = ptr + (size & ~3);
1589 if (size & 3)
1590 tail = p;
1591 }
1592
1593 /* If there is a trailing incomplete sequence move it to
1594 * conv_rest[]. */
1595 if (tail != NULL)
1596 {
1597 conv_restlen = (int)((ptr + size) - tail);
1598 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1599 size -= conv_restlen;
1600 }
1601
1602
1603 while (p > ptr)
1604 {
1605 if (fio_flags & FIO_LATIN1)
1606 u8c = *--p;
1607 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1608 {
1609 if (fio_flags & FIO_ENDIAN_L)
1610 {
1611 u8c = (*--p << 8);
1612 u8c += *--p;
1613 }
1614 else
1615 {
1616 u8c = *--p;
1617 u8c += (*--p << 8);
1618 }
1619 if ((fio_flags & FIO_UTF16)
1620 && u8c >= 0xdc00 && u8c <= 0xdfff)
1621 {
1622 int u16c;
1623
1624 if (p == ptr)
1625 {
1626 /* Missing leading word. */
1627 if (can_retry)
1628 goto rewind_retry;
1629 conv_error = TRUE;
1630 }
1631
1632 /* found second word of double-word, get the first
1633 * word and compute the resulting character */
1634 if (fio_flags & FIO_ENDIAN_L)
1635 {
1636 u16c = (*--p << 8);
1637 u16c += *--p;
1638 }
1639 else
1640 {
1641 u16c = *--p;
1642 u16c += (*--p << 8);
1643 }
1644 /* Check if the word is indeed a leading word. */
1645 if (u16c < 0xd800 || u16c > 0xdbff)
1646 {
1647 if (can_retry)
1648 goto rewind_retry;
1649 conv_error = TRUE;
1650 }
1651 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1652 + (u8c & 0x3ff);
1653 }
1654 }
1655 else if (fio_flags & FIO_UCS4)
1656 {
1657 if (fio_flags & FIO_ENDIAN_L)
1658 {
1659 u8c = (*--p << 24);
1660 u8c += (*--p << 16);
1661 u8c += (*--p << 8);
1662 u8c += *--p;
1663 }
1664 else /* big endian */
1665 {
1666 u8c = *--p;
1667 u8c += (*--p << 8);
1668 u8c += (*--p << 16);
1669 u8c += (*--p << 24);
1670 }
1671 }
1672 else /* UTF-8 */
1673 {
1674 if (*--p < 0x80)
1675 u8c = *p;
1676 else
1677 {
1678 len = utf_head_off(ptr, p);
1679 if (len == 0)
1680 {
1681 /* Not a valid UTF-8 character, retry with
1682 * another fenc when possible, otherwise just
1683 * report the error. */
1684 if (can_retry)
1685 goto rewind_retry;
1686 conv_error = TRUE;
1687 }
1688 p -= len;
1689 u8c = utf_ptr2char(p);
1690 }
1691 }
1692 if (enc_utf8) /* produce UTF-8 */
1693 {
1694 dest -= utf_char2len(u8c);
1695 (void)utf_char2bytes(u8c, dest);
1696 }
1697 else /* produce Latin1 */
1698 {
1699 --dest;
1700 if (u8c >= 0x100)
1701 {
1702 /* character doesn't fit in latin1, retry with
1703 * another fenc when possible, otherwise just
1704 * report the error. */
1705 if (can_retry && !keep_dest_enc)
1706 goto rewind_retry;
1707 *dest = 0xBF;
1708 conv_error = TRUE;
1709 }
1710 else
1711 *dest = u8c;
1712 }
1713 }
1714
1715 /* move the linerest to before the converted characters */
1716 line_start = dest - linerest;
1717 mch_memmove(line_start, buffer, (size_t)linerest);
1718 size = (long)((ptr + real_size) - dest);
1719 ptr = dest;
1720 }
1721 else if (enc_utf8 && !conv_error && !curbuf->b_p_bin)
1722 {
1723 /* Reading UTF-8: Check if the bytes are valid UTF-8.
1724 * Need to start before "ptr" when part of the character was
1725 * read in the previous read() call. */
1726 for (p = ptr - utf_head_off(buffer, ptr); p < ptr + size; ++p)
1727 {
1728 if (*p >= 0x80)
1729 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001730 len = utf_ptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 /* A length of 1 means it's an illegal byte. Accept
1732 * an incomplete character at the end though, the next
1733 * read() will get the next bytes, we'll check it
1734 * then. */
1735 if (len == 1)
1736 {
1737 p += utf_byte2len(*p) - 1;
1738 break;
1739 }
1740 p += len - 1;
1741 }
1742 }
1743 if (p < ptr + size)
1744 {
1745 /* Detected a UTF-8 error. */
1746 if (can_retry)
1747 {
1748rewind_retry:
1749 /* Retry reading with another conversion. */
1750# if defined(FEAT_EVAL) && defined(USE_ICONV)
1751 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
1752 /* iconv() failed, try 'charconvert' */
1753 did_iconv = TRUE;
1754 else
1755# endif
1756 /* use next item from 'fileencodings' */
1757 advance_fenc = TRUE;
1758 file_rewind = TRUE;
1759 goto retry;
1760 }
1761
1762 /* There is no alternative fenc, just report the error. */
1763# ifdef USE_ICONV
1764 if (iconv_fd != (iconv_t)-1)
1765 conv_error = TRUE;
1766 else
1767# endif
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001768 if (illegal_byte == 0) /* Keep the first linenr */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 {
1770 char_u *s;
1771
1772 /* Estimate the line number. */
1773 illegal_byte = curbuf->b_ml.ml_line_count - linecnt + 1;
1774 for (s = ptr; s < p; ++s)
1775 if (*s == '\n')
1776 ++illegal_byte;
1777 }
1778 }
1779 }
1780#endif
1781
1782 /* count the number of characters (after conversion!) */
1783 filesize += size;
1784
1785 /*
1786 * when reading the first part of a file: guess EOL type
1787 */
1788 if (fileformat == EOL_UNKNOWN)
1789 {
1790 /* First try finding a NL, for Dos and Unix */
1791 if (try_dos || try_unix)
1792 {
1793 for (p = ptr; p < ptr + size; ++p)
1794 {
1795 if (*p == NL)
1796 {
1797 if (!try_unix
1798 || (try_dos && p > ptr && p[-1] == CAR))
1799 fileformat = EOL_DOS;
1800 else
1801 fileformat = EOL_UNIX;
1802 break;
1803 }
1804 }
1805
1806 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
1807 if (fileformat == EOL_UNIX && try_mac)
1808 {
1809 /* Need to reset the counters when retrying fenc. */
1810 try_mac = 1;
1811 try_unix = 1;
1812 for (; p >= ptr && *p != CAR; p--)
1813 ;
1814 if (p >= ptr)
1815 {
1816 for (p = ptr; p < ptr + size; ++p)
1817 {
1818 if (*p == NL)
1819 try_unix++;
1820 else if (*p == CAR)
1821 try_mac++;
1822 }
1823 if (try_mac > try_unix)
1824 fileformat = EOL_MAC;
1825 }
1826 }
1827 }
1828
1829 /* No NL found: may use Mac format */
1830 if (fileformat == EOL_UNKNOWN && try_mac)
1831 fileformat = EOL_MAC;
1832
1833 /* Still nothing found? Use first format in 'ffs' */
1834 if (fileformat == EOL_UNKNOWN)
1835 fileformat = default_fileformat();
1836
1837 /* if editing a new file: may set p_tx and p_ff */
1838 if (newfile)
1839 set_fileformat(fileformat, OPT_LOCAL);
1840 }
1841 }
1842
1843 /*
1844 * This loop is executed once for every character read.
1845 * Keep it fast!
1846 */
1847 if (fileformat == EOL_MAC)
1848 {
1849 --ptr;
1850 while (++ptr, --size >= 0)
1851 {
1852 /* catch most common case first */
1853 if ((c = *ptr) != NUL && c != CAR && c != NL)
1854 continue;
1855 if (c == NUL)
1856 *ptr = NL; /* NULs are replaced by newlines! */
1857 else if (c == NL)
1858 *ptr = CAR; /* NLs are replaced by CRs! */
1859 else
1860 {
1861 if (skip_count == 0)
1862 {
1863 *ptr = NUL; /* end of line */
1864 len = (colnr_T) (ptr - line_start + 1);
1865 if (ml_append(lnum, line_start, len, newfile) == FAIL)
1866 {
1867 error = TRUE;
1868 break;
1869 }
1870 ++lnum;
1871 if (--read_count == 0)
1872 {
1873 error = TRUE; /* break loop */
1874 line_start = ptr; /* nothing left to write */
1875 break;
1876 }
1877 }
1878 else
1879 --skip_count;
1880 line_start = ptr + 1;
1881 }
1882 }
1883 }
1884 else
1885 {
1886 --ptr;
1887 while (++ptr, --size >= 0)
1888 {
1889 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
1890 continue;
1891 if (c == NUL)
1892 *ptr = NL; /* NULs are replaced by newlines! */
1893 else
1894 {
1895 if (skip_count == 0)
1896 {
1897 *ptr = NUL; /* end of line */
1898 len = (colnr_T)(ptr - line_start + 1);
1899 if (fileformat == EOL_DOS)
1900 {
1901 if (ptr[-1] == CAR) /* remove CR */
1902 {
1903 ptr[-1] = NUL;
1904 --len;
1905 }
1906 /*
1907 * Reading in Dos format, but no CR-LF found!
1908 * When 'fileformats' includes "unix", delete all
1909 * the lines read so far and start all over again.
1910 * Otherwise give an error message later.
1911 */
1912 else if (ff_error != EOL_DOS)
1913 {
1914 if ( try_unix
1915 && !read_stdin
1916 && (read_buffer
1917 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
1918 {
1919 fileformat = EOL_UNIX;
1920 if (newfile)
1921 set_fileformat(EOL_UNIX, OPT_LOCAL);
1922 file_rewind = TRUE;
1923 keep_fileformat = TRUE;
1924 goto retry;
1925 }
1926 ff_error = EOL_DOS;
1927 }
1928 }
1929 if (ml_append(lnum, line_start, len, newfile) == FAIL)
1930 {
1931 error = TRUE;
1932 break;
1933 }
1934 ++lnum;
1935 if (--read_count == 0)
1936 {
1937 error = TRUE; /* break loop */
1938 line_start = ptr; /* nothing left to write */
1939 break;
1940 }
1941 }
1942 else
1943 --skip_count;
1944 line_start = ptr + 1;
1945 }
1946 }
1947 }
1948 linerest = (long)(ptr - line_start);
1949 ui_breakcheck();
1950 }
1951
1952failed:
1953 /* not an error, max. number of lines reached */
1954 if (error && read_count == 0)
1955 error = FALSE;
1956
1957 /*
1958 * If we get EOF in the middle of a line, note the fact and
1959 * complete the line ourselves.
1960 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
1961 */
1962 if (!error
1963 && !got_int
1964 && linerest != 0
1965 && !(!curbuf->b_p_bin
1966 && fileformat == EOL_DOS
1967 && *line_start == Ctrl_Z
1968 && ptr == line_start + 1))
1969 {
1970 if (newfile) /* remember for when writing */
1971 curbuf->b_p_eol = FALSE;
1972 *ptr = NUL;
1973 if (ml_append(lnum, line_start,
1974 (colnr_T)(ptr - line_start + 1), newfile) == FAIL)
1975 error = TRUE;
1976 else
1977 read_no_eol_lnum = ++lnum;
1978 }
1979
1980 if (newfile)
1981 save_file_ff(curbuf); /* remember the current file format */
1982
1983#ifdef FEAT_CRYPT
1984 if (cryptkey != curbuf->b_p_key)
1985 vim_free(cryptkey);
1986#endif
1987
1988#ifdef FEAT_MBYTE
1989 /* If editing a new file: set 'fenc' for the current buffer. */
1990 if (newfile)
1991 set_string_option_direct((char_u *)"fenc", -1, fenc,
1992 OPT_FREE|OPT_LOCAL);
1993 if (fenc_alloced)
1994 vim_free(fenc);
1995# ifdef USE_ICONV
1996 if (iconv_fd != (iconv_t)-1)
1997 {
1998 iconv_close(iconv_fd);
1999 iconv_fd = (iconv_t)-1;
2000 }
2001# endif
2002#endif
2003
2004 if (!read_buffer && !read_stdin)
2005 close(fd); /* errors are ignored */
2006 vim_free(buffer);
2007
2008#ifdef HAVE_DUP
2009 if (read_stdin)
2010 {
2011 /* Use stderr for stdin, makes shell commands work. */
2012 close(0);
2013 dup(2);
2014 }
2015#endif
2016
2017#ifdef FEAT_MBYTE
2018 if (tmpname != NULL)
2019 {
2020 mch_remove(tmpname); /* delete converted file */
2021 vim_free(tmpname);
2022 }
2023#endif
2024 --no_wait_return; /* may wait for return now */
2025
2026 /*
2027 * In recovery mode everything but autocommands is skipped.
2028 */
2029 if (!recoverymode)
2030 {
2031 /* need to delete the last line, which comes from the empty buffer */
2032 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2033 {
2034#ifdef FEAT_NETBEANS_INTG
2035 netbeansFireChanges = 0;
2036#endif
2037 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2038#ifdef FEAT_NETBEANS_INTG
2039 netbeansFireChanges = 1;
2040#endif
2041 --linecnt;
2042 }
2043 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2044 if (filesize == 0)
2045 linecnt = 0;
2046 if (newfile || read_buffer)
2047 redraw_curbuf_later(NOT_VALID);
2048 else if (linecnt) /* appended at least one line */
2049 appended_lines_mark(from, linecnt);
2050
2051#ifdef FEAT_DIFF
2052 /* After reading the text into the buffer the diff info needs to be
2053 * updated. */
2054 if ((newfile || read_buffer))
2055 diff_invalidate();
2056#endif
2057#ifndef ALWAYS_USE_GUI
2058 /*
2059 * If we were reading from the same terminal as where messages go,
2060 * the screen will have been messed up.
2061 * Switch on raw mode now and clear the screen.
2062 */
2063 if (read_stdin)
2064 {
2065 settmode(TMODE_RAW); /* set to raw mode */
2066 starttermcap();
2067 screenclear();
2068 }
2069#endif
2070
2071 if (got_int)
2072 {
2073 if (!(flags & READ_DUMMY))
2074 {
2075 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2076 if (newfile)
2077 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2078 }
2079 msg_scroll = msg_save;
2080#ifdef FEAT_VIMINFO
2081 check_marks_read();
2082#endif
2083 return OK; /* an interrupt isn't really an error */
2084 }
2085
2086 if (!filtering && !(flags & READ_DUMMY))
2087 {
2088 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2089 c = FALSE;
2090
2091#ifdef UNIX
2092# ifdef S_ISFIFO
2093 if (S_ISFIFO(perm)) /* fifo or socket */
2094 {
2095 STRCAT(IObuff, _("[fifo/socket]"));
2096 c = TRUE;
2097 }
2098# else
2099# ifdef S_IFIFO
2100 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2101 {
2102 STRCAT(IObuff, _("[fifo]"));
2103 c = TRUE;
2104 }
2105# endif
2106# ifdef S_IFSOCK
2107 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2108 {
2109 STRCAT(IObuff, _("[socket]"));
2110 c = TRUE;
2111 }
2112# endif
2113# endif
2114#endif
2115 if (curbuf->b_p_ro)
2116 {
2117 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2118 c = TRUE;
2119 }
2120 if (read_no_eol_lnum)
2121 {
2122 msg_add_eol();
2123 c = TRUE;
2124 }
2125 if (ff_error == EOL_DOS)
2126 {
2127 STRCAT(IObuff, _("[CR missing]"));
2128 c = TRUE;
2129 }
2130 if (ff_error == EOL_MAC)
2131 {
2132 STRCAT(IObuff, _("[NL found]"));
2133 c = TRUE;
2134 }
2135 if (split)
2136 {
2137 STRCAT(IObuff, _("[long lines split]"));
2138 c = TRUE;
2139 }
2140#ifdef FEAT_MBYTE
2141 if (notconverted)
2142 {
2143 STRCAT(IObuff, _("[NOT converted]"));
2144 c = TRUE;
2145 }
2146 else if (converted)
2147 {
2148 STRCAT(IObuff, _("[converted]"));
2149 c = TRUE;
2150 }
2151#endif
2152#ifdef FEAT_CRYPT
2153 if (cryptkey != NULL)
2154 {
2155 STRCAT(IObuff, _("[crypted]"));
2156 c = TRUE;
2157 }
2158#endif
2159#ifdef FEAT_MBYTE
2160 if (conv_error)
2161 {
2162 STRCAT(IObuff, _("[CONVERSION ERROR]"));
2163 c = TRUE;
2164 }
2165 else if (illegal_byte > 0)
2166 {
2167 sprintf((char *)IObuff + STRLEN(IObuff),
2168 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2169 c = TRUE;
2170 }
2171 else
2172#endif
2173 if (error)
2174 {
2175 STRCAT(IObuff, _("[READ ERRORS]"));
2176 c = TRUE;
2177 }
2178 if (msg_add_fileformat(fileformat))
2179 c = TRUE;
2180#ifdef FEAT_CRYPT
2181 if (cryptkey != NULL)
2182 msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN);
2183 else
2184#endif
2185 msg_add_lines(c, (long)linecnt, filesize);
2186
2187 vim_free(keep_msg);
2188 keep_msg = NULL;
2189 msg_scrolled_ign = TRUE;
2190#ifdef ALWAYS_USE_GUI
2191 /* Don't show the message when reading stdin, it would end up in a
2192 * message box (which might be shown when exiting!) */
2193 if (read_stdin || read_buffer)
2194 p = msg_may_trunc(FALSE, IObuff);
2195 else
2196#endif
2197 p = msg_trunc_attr(IObuff, FALSE, 0);
2198 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002199 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 {
2201 /* Need to repeat the message after redrawing when:
2202 * - When reading from stdin (the screen will be cleared next).
2203 * - When restart_edit is set (otherwise there will be a delay
2204 * before redrawing).
2205 * - When the screen was scrolled but there is no wait-return
2206 * prompt. */
2207 set_keep_msg(p);
2208 keep_msg_attr = 0;
2209 }
2210 msg_scrolled_ign = FALSE;
2211 }
2212
2213 /* with errors writing the file requires ":w!" */
2214 if (newfile && (error
2215#ifdef FEAT_MBYTE
2216 || conv_error
2217#endif
2218 ))
2219 curbuf->b_p_ro = TRUE;
2220
2221 u_clearline(); /* cannot use "U" command after adding lines */
2222
2223 /*
2224 * In Ex mode: cursor at last new line.
2225 * Otherwise: cursor at first new line.
2226 */
2227 if (exmode_active)
2228 curwin->w_cursor.lnum = from + linecnt;
2229 else
2230 curwin->w_cursor.lnum = from + 1;
2231 check_cursor_lnum();
2232 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2233
2234 /*
2235 * Set '[ and '] marks to the newly read lines.
2236 */
2237 curbuf->b_op_start.lnum = from + 1;
2238 curbuf->b_op_start.col = 0;
2239 curbuf->b_op_end.lnum = from + linecnt;
2240 curbuf->b_op_end.col = 0;
2241 }
2242 msg_scroll = msg_save;
2243
2244#ifdef FEAT_VIMINFO
2245 /*
2246 * Get the marks before executing autocommands, so they can be used there.
2247 */
2248 check_marks_read();
2249#endif
2250
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 /*
2252 * Trick: We remember if the last line of the read didn't have
2253 * an eol for when writing it again. This is required for
2254 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2255 */
2256 write_no_eol_lnum = read_no_eol_lnum;
2257
Bram Moolenaardf177f62005-02-22 08:39:57 +00002258#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 if (!read_stdin && !read_buffer)
2260 {
2261 int m = msg_scroll;
2262 int n = msg_scrolled;
2263
2264 /* Save the fileformat now, otherwise the buffer will be considered
2265 * modified if the format/encoding was automatically detected. */
2266 if (newfile)
2267 save_file_ff(curbuf);
2268
2269 /*
2270 * The output from the autocommands should not overwrite anything and
2271 * should not be overwritten: Set msg_scroll, restore its value if no
2272 * output was done.
2273 */
2274 msg_scroll = TRUE;
2275 if (filtering)
2276 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2277 FALSE, curbuf, eap);
2278 else if (newfile)
2279 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2280 FALSE, curbuf, eap);
2281 else
2282 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2283 FALSE, NULL, eap);
2284 if (msg_scrolled == n)
2285 msg_scroll = m;
2286#ifdef FEAT_EVAL
2287 if (aborting()) /* autocmds may abort script processing */
2288 return FAIL;
2289#endif
2290 }
2291#endif
2292
2293 if (recoverymode && error)
2294 return FAIL;
2295 return OK;
2296}
2297
2298/*
2299 * Fill "*eap" to force the 'fileencoding' and 'fileformat' to be equal to the
2300 * buffer "buf". Used for calling readfile().
2301 * Returns OK or FAIL.
2302 */
2303 int
2304prep_exarg(eap, buf)
2305 exarg_T *eap;
2306 buf_T *buf;
2307{
2308 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2309#ifdef FEAT_MBYTE
2310 + STRLEN(buf->b_p_fenc)
2311#endif
2312 + 15));
2313 if (eap->cmd == NULL)
2314 return FAIL;
2315
2316#ifdef FEAT_MBYTE
2317 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2318 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
2319#else
2320 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2321#endif
2322 eap->force_ff = 7;
2323 return OK;
2324}
2325
2326#ifdef FEAT_MBYTE
2327/*
2328 * Find next fileencoding to use from 'fileencodings'.
2329 * "pp" points to fenc_next. It's advanced to the next item.
2330 * When there are no more items, an empty string is returned and *pp is set to
2331 * NULL.
2332 * When *pp is not set to NULL, the result is in allocated memory.
2333 */
2334 static char_u *
2335next_fenc(pp)
2336 char_u **pp;
2337{
2338 char_u *p;
2339 char_u *r;
2340
2341 if (**pp == NUL)
2342 {
2343 *pp = NULL;
2344 return (char_u *)"";
2345 }
2346 p = vim_strchr(*pp, ',');
2347 if (p == NULL)
2348 {
2349 r = enc_canonize(*pp);
2350 *pp += STRLEN(*pp);
2351 }
2352 else
2353 {
2354 r = vim_strnsave(*pp, (int)(p - *pp));
2355 *pp = p + 1;
2356 if (r != NULL)
2357 {
2358 p = enc_canonize(r);
2359 vim_free(r);
2360 r = p;
2361 }
2362 }
2363 if (r == NULL) /* out of memory */
2364 {
2365 r = (char_u *)"";
2366 *pp = NULL;
2367 }
2368 return r;
2369}
2370
2371# ifdef FEAT_EVAL
2372/*
2373 * Convert a file with the 'charconvert' expression.
2374 * This closes the file which is to be read, converts it and opens the
2375 * resulting file for reading.
2376 * Returns name of the resulting converted file (the caller should delete it
2377 * after reading it).
2378 * Returns NULL if the conversion failed ("*fdp" is not set) .
2379 */
2380 static char_u *
2381readfile_charconvert(fname, fenc, fdp)
2382 char_u *fname; /* name of input file */
2383 char_u *fenc; /* converted from */
2384 int *fdp; /* in/out: file descriptor of file */
2385{
2386 char_u *tmpname;
2387 char_u *errmsg = NULL;
2388
2389 tmpname = vim_tempname('r');
2390 if (tmpname == NULL)
2391 errmsg = (char_u *)_("Can't find temp file for conversion");
2392 else
2393 {
2394 close(*fdp); /* close the input file, ignore errors */
2395 *fdp = -1;
2396 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2397 fname, tmpname) == FAIL)
2398 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2399 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2400 O_RDONLY | O_EXTRA, 0)) < 0)
2401 errmsg = (char_u *)_("can't read output of 'charconvert'");
2402 }
2403
2404 if (errmsg != NULL)
2405 {
2406 /* Don't use emsg(), it breaks mappings, the retry with
2407 * another type of conversion might still work. */
2408 MSG(errmsg);
2409 if (tmpname != NULL)
2410 {
2411 mch_remove(tmpname); /* delete converted file */
2412 vim_free(tmpname);
2413 tmpname = NULL;
2414 }
2415 }
2416
2417 /* If the input file is closed, open it (caller should check for error). */
2418 if (*fdp < 0)
2419 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2420
2421 return tmpname;
2422}
2423# endif
2424
2425#endif
2426
2427#ifdef FEAT_VIMINFO
2428/*
2429 * Read marks for the current buffer from the viminfo file, when we support
2430 * buffer marks and the buffer has a name.
2431 */
2432 static void
2433check_marks_read()
2434{
2435 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2436 && curbuf->b_ffname != NULL)
2437 read_viminfo(NULL, FALSE, TRUE, FALSE);
2438
2439 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2440 * the ' parameter after opening a buffer. */
2441 curbuf->b_marks_read = TRUE;
2442}
2443#endif
2444
2445#ifdef FEAT_CRYPT
2446/*
2447 * Check for magic number used for encryption.
2448 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2449 * *filesizep are updated.
2450 * Return the (new) encryption key, NULL for no encryption.
2451 */
2452 static char_u *
2453check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile)
2454 char_u *cryptkey; /* previous encryption key or NULL */
2455 char_u *ptr; /* pointer to read bytes */
2456 long *sizep; /* length of read bytes */
2457 long *filesizep; /* nr of bytes used from file */
2458 int newfile; /* editing a new buffer */
2459{
2460 if (*sizep >= CRYPT_MAGIC_LEN
2461 && STRNCMP(ptr, CRYPT_MAGIC, CRYPT_MAGIC_LEN) == 0)
2462 {
2463 if (cryptkey == NULL)
2464 {
2465 if (*curbuf->b_p_key)
2466 cryptkey = curbuf->b_p_key;
2467 else
2468 {
2469 /* When newfile is TRUE, store the typed key
2470 * in the 'key' option and don't free it. */
2471 cryptkey = get_crypt_key(newfile, FALSE);
2472 /* check if empty key entered */
2473 if (cryptkey != NULL && *cryptkey == NUL)
2474 {
2475 if (cryptkey != curbuf->b_p_key)
2476 vim_free(cryptkey);
2477 cryptkey = NULL;
2478 }
2479 }
2480 }
2481
2482 if (cryptkey != NULL)
2483 {
2484 crypt_init_keys(cryptkey);
2485
2486 /* Remove magic number from the text */
2487 *filesizep += CRYPT_MAGIC_LEN;
2488 *sizep -= CRYPT_MAGIC_LEN;
2489 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN, (size_t)*sizep);
2490 }
2491 }
2492 /* When starting to edit a new file which does not have
2493 * encryption, clear the 'key' option, except when
2494 * starting up (called with -x argument) */
2495 else if (newfile && *curbuf->b_p_key && !starting)
2496 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2497
2498 return cryptkey;
2499}
2500#endif
2501
2502#ifdef UNIX
2503 static void
2504set_file_time(fname, atime, mtime)
2505 char_u *fname;
2506 time_t atime; /* access time */
2507 time_t mtime; /* modification time */
2508{
2509# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2510 struct utimbuf buf;
2511
2512 buf.actime = atime;
2513 buf.modtime = mtime;
2514 (void)utime((char *)fname, &buf);
2515# else
2516# if defined(HAVE_UTIMES)
2517 struct timeval tvp[2];
2518
2519 tvp[0].tv_sec = atime;
2520 tvp[0].tv_usec = 0;
2521 tvp[1].tv_sec = mtime;
2522 tvp[1].tv_usec = 0;
2523# ifdef NeXT
2524 (void)utimes((char *)fname, tvp);
2525# else
2526 (void)utimes((char *)fname, (const struct timeval *)&tvp);
2527# endif
2528# endif
2529# endif
2530}
2531#endif /* UNIX */
2532
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002533#if defined(VMS) && !defined(MIN)
2534/* Older DECC compiler for VAX doesn't define MIN() */
2535# define MIN(a, b) ((a) < (b) ? (a) : (b))
2536#endif
2537
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538/*
2539 * buf_write() - write to file 'fname' lines 'start' through 'end'
2540 *
2541 * We do our own buffering here because fwrite() is so slow.
2542 *
2543 * If forceit is true, we don't care for errors when attempting backups (jw).
2544 * In case of an error everything possible is done to restore the original file.
2545 * But when forceit is TRUE, we risk loosing it.
2546 * When reset_changed is TRUE and start == 1 and end ==
2547 * curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
2548 *
2549 * This function must NOT use NameBuff (because it's called by autowrite()).
2550 *
2551 * return FAIL for failure, OK otherwise
2552 */
2553 int
2554buf_write(buf, fname, sfname, start, end, eap, append, forceit,
2555 reset_changed, filtering)
2556 buf_T *buf;
2557 char_u *fname;
2558 char_u *sfname;
2559 linenr_T start, end;
2560 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
2561 NULL! */
2562 int append;
2563 int forceit;
2564 int reset_changed;
2565 int filtering;
2566{
2567 int fd;
2568 char_u *backup = NULL;
2569 int backup_copy = FALSE; /* copy the original file? */
2570 int dobackup;
2571 char_u *ffname;
2572 char_u *wfname = NULL; /* name of file to write to */
2573 char_u *s;
2574 char_u *ptr;
2575 char_u c;
2576 int len;
2577 linenr_T lnum;
2578 long nchars;
2579 char_u *errmsg = NULL;
2580 char_u *errnum = NULL;
2581 char_u *buffer;
2582 char_u smallbuf[SMBUFSIZE];
2583 char_u *backup_ext;
2584 int bufsize;
2585 long perm; /* file permissions */
2586 int retval = OK;
2587 int newfile = FALSE; /* TRUE if file doesn't exist yet */
2588 int msg_save = msg_scroll;
2589 int overwriting; /* TRUE if writing over original */
2590 int no_eol = FALSE; /* no end-of-line written */
2591 int device = FALSE; /* writing to a device */
2592 struct stat st_old;
2593 int prev_got_int = got_int;
2594 int file_readonly = FALSE; /* overwritten file is read-only */
2595 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
2596#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
2597 int made_writable = FALSE; /* 'w' bit has been set */
2598#endif
2599 /* writing everything */
2600 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
2601#ifdef FEAT_AUTOCMD
2602 linenr_T old_line_count = buf->b_ml.ml_line_count;
2603#endif
2604 int attr;
2605 int fileformat;
2606 int write_bin;
2607 struct bw_info write_info; /* info for buf_write_bytes() */
2608#ifdef FEAT_MBYTE
2609 int converted = FALSE;
2610 int notconverted = FALSE;
2611 char_u *fenc; /* effective 'fileencoding' */
2612 char_u *fenc_tofree = NULL; /* allocated "fenc" */
2613#endif
2614#ifdef HAS_BW_FLAGS
2615 int wb_flags = 0;
2616#endif
2617#ifdef HAVE_ACL
2618 vim_acl_T acl = NULL; /* ACL copied from original file to
2619 backup or new file */
2620#endif
2621
2622 if (fname == NULL || *fname == NUL) /* safety check */
2623 return FAIL;
2624
2625 /*
2626 * Disallow writing from .exrc and .vimrc in current directory for
2627 * security reasons.
2628 */
2629 if (check_secure())
2630 return FAIL;
2631
2632 /* Avoid a crash for a long name. */
2633 if (STRLEN(fname) >= MAXPATHL)
2634 {
2635 EMSG(_(e_longname));
2636 return FAIL;
2637 }
2638
2639#ifdef FEAT_MBYTE
2640 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
2641 write_info.bw_conv_buf = NULL;
2642 write_info.bw_conv_error = FALSE;
2643 write_info.bw_restlen = 0;
2644# ifdef USE_ICONV
2645 write_info.bw_iconv_fd = (iconv_t)-1;
2646# endif
2647#endif
2648
Bram Moolenaardf177f62005-02-22 08:39:57 +00002649 /* After writing a file changedtick changes but we don't want to display
2650 * the line. */
2651 ex_no_reprint = TRUE;
2652
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 /*
2654 * If there is no file name yet, use the one for the written file.
2655 * BF_NOTEDITED is set to reflect this (in case the write fails).
2656 * Don't do this when the write is for a filter command.
2657 * Only do this when 'cpoptions' contains the 'f' flag.
2658 */
2659 if (reset_changed
2660 && whole
2661 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002662#ifdef FEAT_QUICKFIX
2663 && !bt_nofile(buf)
2664#endif
2665 && buf->b_ffname == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 && !filtering
2667 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
2668 {
2669#ifdef FEAT_AUTOCMD
2670 /* It's like the unnamed buffer is deleted.... */
2671 if (curbuf->b_p_bl)
2672 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
2673 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
2674#ifdef FEAT_EVAL
2675 if (aborting()) /* autocmds may abort script processing */
2676 return FAIL;
2677#endif
2678#endif
2679 if (setfname(curbuf, fname, sfname, FALSE) == OK)
2680 curbuf->b_flags |= BF_NOTEDITED;
2681#ifdef FEAT_AUTOCMD
2682 /* ....and a new named one is created */
2683 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
2684 if (curbuf->b_p_bl)
2685 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
2686#endif
2687 }
2688
2689 if (sfname == NULL)
2690 sfname = fname;
2691 /*
2692 * For Unix: Use the short file name whenever possible.
2693 * Avoids problems with networks and when directory names are changed.
2694 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
2695 * another directory, which we don't detect
2696 */
2697 ffname = fname; /* remember full fname */
2698#ifdef UNIX
2699 fname = sfname;
2700#endif
2701
2702 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
2703 overwriting = TRUE;
2704 else
2705 overwriting = FALSE;
2706
2707 if (exiting)
2708 settmode(TMODE_COOK); /* when exiting allow typahead now */
2709
2710 ++no_wait_return; /* don't wait for return yet */
2711
2712 /*
2713 * Set '[ and '] marks to the lines to be written.
2714 */
2715 buf->b_op_start.lnum = start;
2716 buf->b_op_start.col = 0;
2717 buf->b_op_end.lnum = end;
2718 buf->b_op_end.col = 0;
2719
2720#ifdef FEAT_AUTOCMD
2721 {
2722 aco_save_T aco;
2723 int buf_ffname = FALSE;
2724 int buf_sfname = FALSE;
2725 int buf_fname_f = FALSE;
2726 int buf_fname_s = FALSE;
2727 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002728 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00002729 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730
2731 /*
2732 * Apply PRE aucocommands.
2733 * Set curbuf to the buffer to be written.
2734 * Careful: The autocommands may call buf_write() recursively!
2735 */
2736 if (ffname == buf->b_ffname)
2737 buf_ffname = TRUE;
2738 if (sfname == buf->b_sfname)
2739 buf_sfname = TRUE;
2740 if (fname == buf->b_ffname)
2741 buf_fname_f = TRUE;
2742 if (fname == buf->b_sfname)
2743 buf_fname_s = TRUE;
2744
2745 /* set curwin/curbuf to buf and save a few things */
2746 aucmd_prepbuf(&aco, buf);
2747
2748 if (append)
2749 {
2750 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
2751 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002752 {
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00002753 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002754 nofile_err = TRUE;
2755 else
2756 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759 }
2760 else if (filtering)
2761 {
2762 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
2763 NULL, sfname, FALSE, curbuf, eap);
2764 }
2765 else if (reset_changed && whole)
2766 {
2767 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
2768 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002769 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002770 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002771 nofile_err = TRUE;
2772 else
2773 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 }
2777 else
2778 {
2779 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
2780 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002781 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002782 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002783 nofile_err = TRUE;
2784 else
2785 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002787 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 }
2789
2790 /* restore curwin/curbuf and a few other things */
2791 aucmd_restbuf(&aco);
2792
2793 /*
2794 * In three situations we return here and don't write the file:
2795 * 1. the autocommands deleted or unloaded the buffer.
2796 * 2. The autocommands abort script processing.
2797 * 3. If one of the "Cmd" autocommands was executed.
2798 */
2799 if (!buf_valid(buf))
2800 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00002801 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00002802 || did_cmd || nofile_err
2803#ifdef FEAT_EVAL
2804 || aborting()
2805#endif
2806 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 {
2808 --no_wait_return;
2809 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002810 if (nofile_err)
2811 EMSG(_("E676: No matching autocommands for acwrite buffer"));
2812
Bram Moolenaar1e015462005-09-25 22:16:38 +00002813 if (nofile_err
2814#ifdef FEAT_EVAL
2815 || aborting()
2816#endif
2817 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 /* An aborting error, interrupt or exception in the
2819 * autocommands. */
2820 return FAIL;
2821 if (did_cmd)
2822 {
2823 if (buf == NULL)
2824 /* The buffer was deleted. We assume it was written
2825 * (can't retry anyway). */
2826 return OK;
2827 if (overwriting)
2828 {
2829 /* Assume the buffer was written, update the timestamp. */
2830 ml_timestamp(buf);
2831 buf->b_flags &= ~BF_WRITE_MASK;
2832 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002833 if (reset_changed && buf->b_changed
2834 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 /* Buffer still changed, the autocommands didn't work
2836 * properly. */
2837 return FAIL;
2838 return OK;
2839 }
2840#ifdef FEAT_EVAL
2841 if (!aborting())
2842#endif
2843 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
2844 return FAIL;
2845 }
2846
2847 /*
2848 * The autocommands may have changed the number of lines in the file.
2849 * When writing the whole file, adjust the end.
2850 * When writing part of the file, assume that the autocommands only
2851 * changed the number of lines that are to be written (tricky!).
2852 */
2853 if (buf->b_ml.ml_line_count != old_line_count)
2854 {
2855 if (whole) /* write all */
2856 end = buf->b_ml.ml_line_count;
2857 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
2858 end += buf->b_ml.ml_line_count - old_line_count;
2859 else /* less lines */
2860 {
2861 end -= old_line_count - buf->b_ml.ml_line_count;
2862 if (end < start)
2863 {
2864 --no_wait_return;
2865 msg_scroll = msg_save;
2866 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
2867 return FAIL;
2868 }
2869 }
2870 }
2871
2872 /*
2873 * The autocommands may have changed the name of the buffer, which may
2874 * be kept in fname, ffname and sfname.
2875 */
2876 if (buf_ffname)
2877 ffname = buf->b_ffname;
2878 if (buf_sfname)
2879 sfname = buf->b_sfname;
2880 if (buf_fname_f)
2881 fname = buf->b_ffname;
2882 if (buf_fname_s)
2883 fname = buf->b_sfname;
2884 }
2885#endif
2886
2887#ifdef FEAT_NETBEANS_INTG
2888 if (usingNetbeans && isNetbeansBuffer(buf))
2889 {
2890 if (whole)
2891 {
2892 /*
2893 * b_changed can be 0 after an undo, but we still need to write
2894 * the buffer to NetBeans.
2895 */
2896 if (buf->b_changed || isNetbeansModified(buf))
2897 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00002898 --no_wait_return; /* may wait for return now */
2899 msg_scroll = msg_save;
2900 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 return retval;
2902 }
2903 else
2904 {
2905 errnum = (char_u *)"E656: ";
2906 errmsg = (char_u *)_("NetBeans dissallows writes of unmodified buffers");
2907 buffer = NULL;
2908 goto fail;
2909 }
2910 }
2911 else
2912 {
2913 errnum = (char_u *)"E657: ";
2914 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
2915 buffer = NULL;
2916 goto fail;
2917 }
2918 }
2919#endif
2920
2921 if (shortmess(SHM_OVER) && !exiting)
2922 msg_scroll = FALSE; /* overwrite previous file message */
2923 else
2924 msg_scroll = TRUE; /* don't overwrite previous file message */
2925 if (!filtering)
2926 filemess(buf,
2927#ifndef UNIX
2928 sfname,
2929#else
2930 fname,
2931#endif
2932 (char_u *)"", 0); /* show that we are busy */
2933 msg_scroll = FALSE; /* always overwrite the file message now */
2934
2935 buffer = alloc(BUFSIZE);
2936 if (buffer == NULL) /* can't allocate big buffer, use small
2937 * one (to be able to write when out of
2938 * memory) */
2939 {
2940 buffer = smallbuf;
2941 bufsize = SMBUFSIZE;
2942 }
2943 else
2944 bufsize = BUFSIZE;
2945
2946 /*
2947 * Get information about original file (if there is one).
2948 */
2949#if defined(UNIX) && !defined(ARCHIE)
2950 st_old.st_dev = st_old.st_ino = 0;
2951 perm = -1;
2952 if (mch_stat((char *)fname, &st_old) < 0)
2953 newfile = TRUE;
2954 else
2955 {
2956 perm = st_old.st_mode;
2957 if (!S_ISREG(st_old.st_mode)) /* not a file */
2958 {
2959 if (S_ISDIR(st_old.st_mode))
2960 {
2961 errnum = (char_u *)"E502: ";
2962 errmsg = (char_u *)_("is a directory");
2963 goto fail;
2964 }
2965 if (mch_nodetype(fname) != NODE_WRITABLE)
2966 {
2967 errnum = (char_u *)"E503: ";
2968 errmsg = (char_u *)_("is not a file or writable device");
2969 goto fail;
2970 }
2971 /* It's a device of some kind (or a fifo) which we can write to
2972 * but for which we can't make a backup. */
2973 device = TRUE;
2974 newfile = TRUE;
2975 perm = -1;
2976 }
2977 }
2978#else /* !UNIX */
2979 /*
2980 * Check for a writable device name.
2981 */
2982 c = mch_nodetype(fname);
2983 if (c == NODE_OTHER)
2984 {
2985 errnum = (char_u *)"E503: ";
2986 errmsg = (char_u *)_("is not a file or writable device");
2987 goto fail;
2988 }
2989 if (c == NODE_WRITABLE)
2990 {
2991 device = TRUE;
2992 newfile = TRUE;
2993 perm = -1;
2994 }
2995 else
2996 {
2997 perm = mch_getperm(fname);
2998 if (perm < 0)
2999 newfile = TRUE;
3000 else if (mch_isdir(fname))
3001 {
3002 errnum = (char_u *)"E502: ";
3003 errmsg = (char_u *)_("is a directory");
3004 goto fail;
3005 }
3006 if (overwriting)
3007 (void)mch_stat((char *)fname, &st_old);
3008 }
3009#endif /* !UNIX */
3010
3011 if (!device && !newfile)
3012 {
3013 /*
3014 * Check if the file is really writable (when renaming the file to
3015 * make a backup we won't discover it later).
3016 */
3017 file_readonly = (
3018# ifdef USE_MCH_ACCESS
3019# ifdef UNIX
3020 (perm & 0222) == 0 ||
3021# endif
3022 mch_access((char *)fname, W_OK)
3023# else
3024 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3025 ? TRUE : (close(fd), FALSE)
3026# endif
3027 );
3028 if (!forceit && file_readonly)
3029 {
3030 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3031 {
3032 errnum = (char_u *)"E504: ";
3033 errmsg = (char_u *)_(err_readonly);
3034 }
3035 else
3036 {
3037 errnum = (char_u *)"E505: ";
3038 errmsg = (char_u *)_("is read-only (add ! to override)");
3039 }
3040 goto fail;
3041 }
3042
3043 /*
3044 * Check if the timestamp hasn't changed since reading the file.
3045 */
3046 if (overwriting)
3047 {
3048 retval = check_mtime(buf, &st_old);
3049 if (retval == FAIL)
3050 goto fail;
3051 }
3052 }
3053
3054#ifdef HAVE_ACL
3055 /*
3056 * For systems that support ACL: get the ACL from the original file.
3057 */
3058 if (!newfile)
3059 acl = mch_get_acl(fname);
3060#endif
3061
3062 /*
3063 * If 'backupskip' is not empty, don't make a backup for some files.
3064 */
3065 dobackup = (p_wb || p_bk || *p_pm != NUL);
3066#ifdef FEAT_WILDIGN
3067 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3068 dobackup = FALSE;
3069#endif
3070
3071 /*
3072 * Save the value of got_int and reset it. We don't want a previous
3073 * interruption cancel writing, only hitting CTRL-C while writing should
3074 * abort it.
3075 */
3076 prev_got_int = got_int;
3077 got_int = FALSE;
3078
3079 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3080 buf->b_saving = TRUE;
3081
3082 /*
3083 * If we are not appending or filtering, the file exists, and the
3084 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3085 * When 'patchmode' is set also make a backup when appending.
3086 *
3087 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3088 * off. This helps when editing large files on almost-full disks.
3089 */
3090 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3091 {
3092#if defined(UNIX) || defined(WIN32)
3093 struct stat st;
3094#endif
3095
3096 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3097 backup_copy = TRUE;
3098#if defined(UNIX) || defined(WIN32)
3099 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3100 {
3101 int i;
3102
3103# ifdef UNIX
3104 /*
3105 * Don't rename the file when:
3106 * - it's a hard link
3107 * - it's a symbolic link
3108 * - we don't have write permission in the directory
3109 * - we can't set the owner/group of the new file
3110 */
3111 if (st_old.st_nlink > 1
3112 || mch_lstat((char *)fname, &st) < 0
3113 || st.st_dev != st_old.st_dev
3114 || st.st_ino != st_old.st_ino)
3115 backup_copy = TRUE;
3116 else
3117# endif
3118 {
3119 /*
3120 * Check if we can create a file and set the owner/group to
3121 * the ones from the original file.
3122 * First find a file name that doesn't exist yet (use some
3123 * arbitrary numbers).
3124 */
3125 STRCPY(IObuff, fname);
3126 for (i = 4913; ; i += 123)
3127 {
3128 sprintf((char *)gettail(IObuff), "%d", i);
3129 if (mch_stat((char *)IObuff, &st) < 0)
3130 break;
3131 }
3132 fd = mch_open((char *)IObuff, O_CREAT|O_WRONLY|O_EXCL, perm);
3133 close(fd);
3134 if (fd < 0) /* can't write in directory */
3135 backup_copy = TRUE;
3136 else
3137 {
3138# ifdef UNIX
3139 chown((char *)IObuff, st_old.st_uid, st_old.st_gid);
3140 (void)mch_setperm(IObuff, perm);
3141 if (mch_stat((char *)IObuff, &st) < 0
3142 || st.st_uid != st_old.st_uid
3143 || st.st_gid != st_old.st_gid
3144 || st.st_mode != perm)
3145 backup_copy = TRUE;
3146# endif
3147 mch_remove(IObuff);
3148 }
3149 }
3150 }
3151
3152# ifdef UNIX
3153 /*
3154 * Break symlinks and/or hardlinks if we've been asked to.
3155 */
3156 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3157 {
3158 int lstat_res;
3159
3160 lstat_res = mch_lstat((char *)fname, &st);
3161
3162 /* Symlinks. */
3163 if ((bkc_flags & BKC_BREAKSYMLINK)
3164 && lstat_res == 0
3165 && st.st_ino != st_old.st_ino)
3166 backup_copy = FALSE;
3167
3168 /* Hardlinks. */
3169 if ((bkc_flags & BKC_BREAKHARDLINK)
3170 && st_old.st_nlink > 1
3171 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3172 backup_copy = FALSE;
3173 }
3174#endif
3175
3176#endif
3177
3178 /* make sure we have a valid backup extension to use */
3179 if (*p_bex == NUL)
3180 {
3181#ifdef RISCOS
3182 backup_ext = (char_u *)"/bak";
3183#else
3184 backup_ext = (char_u *)".bak";
3185#endif
3186 }
3187 else
3188 backup_ext = p_bex;
3189
3190 if (backup_copy
3191 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3192 {
3193 int bfd;
3194 char_u *copybuf, *wp;
3195 int some_error = FALSE;
3196 struct stat st_new;
3197 char_u *dirp;
3198 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003199#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 int did_set_shortname;
3201#endif
3202
3203 copybuf = alloc(BUFSIZE + 1);
3204 if (copybuf == NULL)
3205 {
3206 some_error = TRUE; /* out of memory */
3207 goto nobackup;
3208 }
3209
3210 /*
3211 * Try to make the backup in each directory in the 'bdir' option.
3212 *
3213 * Unix semantics has it, that we may have a writable file,
3214 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3215 * - the directory is not writable,
3216 * - the file may be a symbolic link,
3217 * - the file may belong to another user/group, etc.
3218 *
3219 * For these reasons, the existing writable file must be truncated
3220 * and reused. Creation of a backup COPY will be attempted.
3221 */
3222 dirp = p_bdir;
3223 while (*dirp)
3224 {
3225#ifdef UNIX
3226 st_new.st_ino = 0;
3227 st_new.st_dev = 0;
3228 st_new.st_gid = 0;
3229#endif
3230
3231 /*
3232 * Isolate one directory name, using an entry in 'bdir'.
3233 */
3234 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3235 rootname = get_file_in_dir(fname, copybuf);
3236 if (rootname == NULL)
3237 {
3238 some_error = TRUE; /* out of memory */
3239 goto nobackup;
3240 }
3241
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003242#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 did_set_shortname = FALSE;
3244#endif
3245
3246 /*
3247 * May try twice if 'shortname' not set.
3248 */
3249 for (;;)
3250 {
3251 /*
3252 * Make backup file name.
3253 */
3254 backup = buf_modname(
3255#ifdef SHORT_FNAME
3256 TRUE,
3257#else
3258 (buf->b_p_sn || buf->b_shortname),
3259#endif
3260 rootname, backup_ext, FALSE);
3261 if (backup == NULL)
3262 {
3263 vim_free(rootname);
3264 some_error = TRUE; /* out of memory */
3265 goto nobackup;
3266 }
3267
3268 /*
3269 * Check if backup file already exists.
3270 */
3271 if (mch_stat((char *)backup, &st_new) >= 0)
3272 {
3273#ifdef UNIX
3274 /*
3275 * Check if backup file is same as original file.
3276 * May happen when modname() gave the same file back.
3277 * E.g. silly link, or file name-length reached.
3278 * If we don't check here, we either ruin the file
3279 * when copying or erase it after writing. jw.
3280 */
3281 if (st_new.st_dev == st_old.st_dev
3282 && st_new.st_ino == st_old.st_ino)
3283 {
3284 vim_free(backup);
3285 backup = NULL; /* no backup file to delete */
3286# ifndef SHORT_FNAME
3287 /*
3288 * may try again with 'shortname' set
3289 */
3290 if (!(buf->b_shortname || buf->b_p_sn))
3291 {
3292 buf->b_shortname = TRUE;
3293 did_set_shortname = TRUE;
3294 continue;
3295 }
3296 /* setting shortname didn't help */
3297 if (did_set_shortname)
3298 buf->b_shortname = FALSE;
3299# endif
3300 break;
3301 }
3302#endif
3303
3304 /*
3305 * If we are not going to keep the backup file, don't
3306 * delete an existing one, try to use another name.
3307 * Change one character, just before the extension.
3308 */
3309 if (!p_bk)
3310 {
3311 wp = backup + STRLEN(backup) - 1
3312 - STRLEN(backup_ext);
3313 if (wp < backup) /* empty file name ??? */
3314 wp = backup;
3315 *wp = 'z';
3316 while (*wp > 'a'
3317 && mch_stat((char *)backup, &st_new) >= 0)
3318 --*wp;
3319 /* They all exist??? Must be something wrong. */
3320 if (*wp == 'a')
3321 {
3322 vim_free(backup);
3323 backup = NULL;
3324 }
3325 }
3326 }
3327 break;
3328 }
3329 vim_free(rootname);
3330
3331 /*
3332 * Try to create the backup file
3333 */
3334 if (backup != NULL)
3335 {
3336 /* remove old backup, if present */
3337 mch_remove(backup);
3338 /* Open with O_EXCL to avoid the file being created while
3339 * we were sleeping (symlink hacker attack?) */
3340 bfd = mch_open((char *)backup,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003341 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL, perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342 if (bfd < 0)
3343 {
3344 vim_free(backup);
3345 backup = NULL;
3346 }
3347 else
3348 {
3349 /* set file protection same as original file, but
3350 * strip s-bit */
3351 (void)mch_setperm(backup, perm & 0777);
3352
3353#ifdef UNIX
3354 /*
3355 * Try to set the group of the backup same as the
3356 * original file. If this fails, set the protection
3357 * bits for the group same as the protection bits for
3358 * others.
3359 */
3360 if (st_new.st_gid != st_old.st_gid &&
3361# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
3362 fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
3363# else
3364 chown((char *)backup, (uid_t)-1, st_old.st_gid) != 0
3365# endif
3366 )
3367 mch_setperm(backup,
3368 (perm & 0707) | ((perm & 07) << 3));
3369#endif
3370
3371 /*
3372 * copy the file.
3373 */
3374 write_info.bw_fd = bfd;
3375 write_info.bw_buf = copybuf;
3376#ifdef HAS_BW_FLAGS
3377 write_info.bw_flags = FIO_NOCONVERT;
3378#endif
3379 while ((write_info.bw_len = vim_read(fd, copybuf,
3380 BUFSIZE)) > 0)
3381 {
3382 if (buf_write_bytes(&write_info) == FAIL)
3383 {
3384 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3385 break;
3386 }
3387 ui_breakcheck();
3388 if (got_int)
3389 {
3390 errmsg = (char_u *)_(e_interr);
3391 break;
3392 }
3393 }
3394
3395 if (close(bfd) < 0 && errmsg == NULL)
3396 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3397 if (write_info.bw_len < 0)
3398 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3399#ifdef UNIX
3400 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3401#endif
3402#ifdef HAVE_ACL
3403 mch_set_acl(backup, acl);
3404#endif
3405 break;
3406 }
3407 }
3408 }
3409 nobackup:
3410 close(fd); /* ignore errors for closing read file */
3411 vim_free(copybuf);
3412
3413 if (backup == NULL && errmsg == NULL)
3414 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3415 /* ignore errors when forceit is TRUE */
3416 if ((some_error || errmsg != NULL) && !forceit)
3417 {
3418 retval = FAIL;
3419 goto fail;
3420 }
3421 errmsg = NULL;
3422 }
3423 else
3424 {
3425 char_u *dirp;
3426 char_u *p;
3427 char_u *rootname;
3428
3429 /*
3430 * Make a backup by renaming the original file.
3431 */
3432 /*
3433 * If 'cpoptions' includes the "W" flag, we don't want to
3434 * overwrite a read-only file. But rename may be possible
3435 * anyway, thus we need an extra check here.
3436 */
3437 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3438 {
3439 errnum = (char_u *)"E504: ";
3440 errmsg = (char_u *)_(err_readonly);
3441 goto fail;
3442 }
3443
3444 /*
3445 *
3446 * Form the backup file name - change path/fo.o.h to
3447 * path/fo.o.h.bak Try all directories in 'backupdir', first one
3448 * that works is used.
3449 */
3450 dirp = p_bdir;
3451 while (*dirp)
3452 {
3453 /*
3454 * Isolate one directory name and make the backup file name.
3455 */
3456 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
3457 rootname = get_file_in_dir(fname, IObuff);
3458 if (rootname == NULL)
3459 backup = NULL;
3460 else
3461 {
3462 backup = buf_modname(
3463#ifdef SHORT_FNAME
3464 TRUE,
3465#else
3466 (buf->b_p_sn || buf->b_shortname),
3467#endif
3468 rootname, backup_ext, FALSE);
3469 vim_free(rootname);
3470 }
3471
3472 if (backup != NULL)
3473 {
3474 /*
3475 * If we are not going to keep the backup file, don't
3476 * delete an existing one, try to use another name.
3477 * Change one character, just before the extension.
3478 */
3479 if (!p_bk && mch_getperm(backup) >= 0)
3480 {
3481 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
3482 if (p < backup) /* empty file name ??? */
3483 p = backup;
3484 *p = 'z';
3485 while (*p > 'a' && mch_getperm(backup) >= 0)
3486 --*p;
3487 /* They all exist??? Must be something wrong! */
3488 if (*p == 'a')
3489 {
3490 vim_free(backup);
3491 backup = NULL;
3492 }
3493 }
3494 }
3495 if (backup != NULL)
3496 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003498 * Delete any existing backup and move the current version
3499 * to the backup. For safety, we don't remove the backup
3500 * until the write has finished successfully. And if the
3501 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502 */
3503 /*
3504 * If the renaming of the original file to the backup file
3505 * works, quit here.
3506 */
3507 if (vim_rename(fname, backup) == 0)
3508 break;
3509
3510 vim_free(backup); /* don't do the rename below */
3511 backup = NULL;
3512 }
3513 }
3514 if (backup == NULL && !forceit)
3515 {
3516 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
3517 goto fail;
3518 }
3519 }
3520 }
3521
3522#if defined(UNIX) && !defined(ARCHIE)
3523 /* When using ":w!" and the file was read-only: make it writable */
3524 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
3525 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
3526 {
3527 perm |= 0200;
3528 (void)mch_setperm(fname, perm);
3529 made_writable = TRUE;
3530 }
3531#endif
3532
3533 /* When using ":w!" and writing to the current file, readonly makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003534 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
3535 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 {
3537 buf->b_p_ro = FALSE;
3538#ifdef FEAT_TITLE
3539 need_maketitle = TRUE; /* set window title later */
3540#endif
3541#ifdef FEAT_WINDOWS
3542 status_redraw_all(); /* redraw status lines later */
3543#endif
3544 }
3545
3546 if (end > buf->b_ml.ml_line_count)
3547 end = buf->b_ml.ml_line_count;
3548 if (buf->b_ml.ml_flags & ML_EMPTY)
3549 start = end + 1;
3550
3551 /*
3552 * If the original file is being overwritten, there is a small chance that
3553 * we crash in the middle of writing. Therefore the file is preserved now.
3554 * This makes all block numbers positive so that recovery does not need
3555 * the original file.
3556 * Don't do this if there is a backup file and we are exiting.
3557 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003558 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 && !(exiting && backup != NULL))
3560 {
3561 ml_preserve(buf, FALSE);
3562 if (got_int)
3563 {
3564 errmsg = (char_u *)_(e_interr);
3565 goto restore_backup;
3566 }
3567 }
3568
3569#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
3570 /*
3571 * Before risking to lose the original file verify if there's
3572 * a resource fork to preserve, and if cannot be done warn
3573 * the users. This happens when overwriting without backups.
3574 */
3575 if (backup == NULL && overwriting && !append)
3576 if (mch_has_resource_fork(fname))
3577 {
3578 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
3579 goto restore_backup;
3580 }
3581#endif
3582
3583#ifdef VMS
3584 vms_remove_version(fname); /* remove version */
3585#endif
3586 /* Default: write the the file directly. May write to a temp file for
3587 * multi-byte conversion. */
3588 wfname = fname;
3589
3590#ifdef FEAT_MBYTE
3591 /* Check for forced 'fileencoding' from "++opt=val" argument. */
3592 if (eap != NULL && eap->force_enc != 0)
3593 {
3594 fenc = eap->cmd + eap->force_enc;
3595 fenc = enc_canonize(fenc);
3596 fenc_tofree = fenc;
3597 }
3598 else
3599 fenc = buf->b_p_fenc;
3600
3601 /*
3602 * The file needs to be converted when 'fileencoding' is set and
3603 * 'fileencoding' differs from 'encoding'.
3604 */
3605 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
3606
3607 /*
3608 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
3609 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
3610 * Prepare the flags for it and allocate bw_conv_buf when needed.
3611 */
3612 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
3613 {
3614 wb_flags = get_fio_flags(fenc);
3615 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
3616 {
3617 /* Need to allocate a buffer to translate into. */
3618 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
3619 write_info.bw_conv_buflen = bufsize * 2;
3620 else /* FIO_UCS4 */
3621 write_info.bw_conv_buflen = bufsize * 4;
3622 write_info.bw_conv_buf
3623 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3624 if (write_info.bw_conv_buf == NULL)
3625 end = 0;
3626 }
3627 }
3628
3629# ifdef WIN3264
3630 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
3631 {
3632 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
3633 write_info.bw_conv_buflen = bufsize * 4;
3634 write_info.bw_conv_buf
3635 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3636 if (write_info.bw_conv_buf == NULL)
3637 end = 0;
3638 }
3639# endif
3640
3641# ifdef MACOS_X
3642 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
3643 {
3644 write_info.bw_conv_buflen = bufsize * 3;
3645 write_info.bw_conv_buf
3646 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3647 if (write_info.bw_conv_buf == NULL)
3648 end = 0;
3649 }
3650# endif
3651
3652# if defined(FEAT_EVAL) || defined(USE_ICONV)
3653 if (converted && wb_flags == 0)
3654 {
3655# ifdef USE_ICONV
3656 /*
3657 * Use iconv() conversion when conversion is needed and it's not done
3658 * internally.
3659 */
3660 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
3661 enc_utf8 ? (char_u *)"utf-8" : p_enc);
3662 if (write_info.bw_iconv_fd != (iconv_t)-1)
3663 {
3664 /* We're going to use iconv(), allocate a buffer to convert in. */
3665 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
3666 write_info.bw_conv_buf
3667 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3668 if (write_info.bw_conv_buf == NULL)
3669 end = 0;
3670 write_info.bw_first = TRUE;
3671 }
3672# ifdef FEAT_EVAL
3673 else
3674# endif
3675# endif
3676
3677# ifdef FEAT_EVAL
3678 /*
3679 * When the file needs to be converted with 'charconvert' after
3680 * writing, write to a temp file instead and let the conversion
3681 * overwrite the original file.
3682 */
3683 if (*p_ccv != NUL)
3684 {
3685 wfname = vim_tempname('w');
3686 if (wfname == NULL) /* Can't write without a tempfile! */
3687 {
3688 errmsg = (char_u *)_("E214: Can't find temp file for writing");
3689 goto restore_backup;
3690 }
3691 }
3692# endif
3693 }
3694# endif
3695 if (converted && wb_flags == 0
3696# ifdef USE_ICONV
3697 && write_info.bw_iconv_fd == (iconv_t)-1
3698# endif
3699# ifdef FEAT_EVAL
3700 && wfname == fname
3701# endif
3702 )
3703 {
3704 if (!forceit)
3705 {
3706 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
3707 goto restore_backup;
3708 }
3709 notconverted = TRUE;
3710 }
3711#endif
3712
3713 /*
3714 * Open the file "wfname" for writing.
3715 * We may try to open the file twice: If we can't write to the
3716 * file and forceit is TRUE we delete the existing file and try to create
3717 * a new one. If this still fails we may have lost the original file!
3718 * (this may happen when the user reached his quotum for number of files).
3719 * Appending will fail if the file does not exist and forceit is FALSE.
3720 */
3721 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
3722 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
3723 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00003724 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725 {
3726 /*
3727 * A forced write will try to create a new file if the old one is
3728 * still readonly. This may also happen when the directory is
3729 * read-only. In that case the mch_remove() will fail.
3730 */
3731 if (errmsg == NULL)
3732 {
3733#ifdef UNIX
3734 struct stat st;
3735
3736 /* Don't delete the file when it's a hard or symbolic link. */
3737 if ((!newfile && st_old.st_nlink > 1)
3738 || (mch_lstat((char *)fname, &st) == 0
3739 && (st.st_dev != st_old.st_dev
3740 || st.st_ino != st_old.st_ino)))
3741 errmsg = (char_u *)_("E166: Can't open linked file for writing");
3742 else
3743#endif
3744 {
3745 errmsg = (char_u *)_("E212: Can't open file for writing");
3746 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
3747 && perm >= 0)
3748 {
3749#ifdef UNIX
3750 /* we write to the file, thus it should be marked
3751 writable after all */
3752 if (!(perm & 0200))
3753 made_writable = TRUE;
3754 perm |= 0200;
3755 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
3756 perm &= 0777;
3757#endif
3758 if (!append) /* don't remove when appending */
3759 mch_remove(wfname);
3760 continue;
3761 }
3762 }
3763 }
3764
3765restore_backup:
3766 {
3767 struct stat st;
3768
3769 /*
3770 * If we failed to open the file, we don't need a backup. Throw it
3771 * away. If we moved or removed the original file try to put the
3772 * backup in its place.
3773 */
3774 if (backup != NULL && wfname == fname)
3775 {
3776 if (backup_copy)
3777 {
3778 /*
3779 * There is a small chance that we removed the original,
3780 * try to move the copy in its place.
3781 * This may not work if the vim_rename() fails.
3782 * In that case we leave the copy around.
3783 */
3784 /* If file does not exist, put the copy in its place */
3785 if (mch_stat((char *)fname, &st) < 0)
3786 vim_rename(backup, fname);
3787 /* if original file does exist throw away the copy */
3788 if (mch_stat((char *)fname, &st) >= 0)
3789 mch_remove(backup);
3790 }
3791 else
3792 {
3793 /* try to put the original file back */
3794 vim_rename(backup, fname);
3795 }
3796 }
3797
3798 /* if original file no longer exists give an extra warning */
3799 if (!newfile && mch_stat((char *)fname, &st) < 0)
3800 end = 0;
3801 }
3802
3803#ifdef FEAT_MBYTE
3804 if (wfname != fname)
3805 vim_free(wfname);
3806#endif
3807 goto fail;
3808 }
3809 errmsg = NULL;
3810
3811#if defined(MACOS_CLASSIC) || defined(WIN3264)
3812 /* TODO: Is it need for MACOS_X? (Dany) */
3813 /*
3814 * On macintosh copy the original files attributes (i.e. the backup)
3815 * This is done in order to preserve the ressource fork and the
3816 * Finder attribute (label, comments, custom icons, file creatore)
3817 */
3818 if (backup != NULL && overwriting && !append)
3819 {
3820 if (backup_copy)
3821 (void)mch_copy_file_attribute(wfname, backup);
3822 else
3823 (void)mch_copy_file_attribute(backup, wfname);
3824 }
3825
3826 if (!overwriting && !append)
3827 {
3828 if (buf->b_ffname != NULL)
3829 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
3830 /* Should copy ressource fork */
3831 }
3832#endif
3833
3834 write_info.bw_fd = fd;
3835
3836#ifdef FEAT_CRYPT
3837 if (*buf->b_p_key && !filtering)
3838 {
3839 crypt_init_keys(buf->b_p_key);
3840 /* Write magic number, so that Vim knows that this file is encrypted
3841 * when reading it again. This also undergoes utf-8 to ucs-2/4
3842 * conversion when needed. */
3843 write_info.bw_buf = (char_u *)CRYPT_MAGIC;
3844 write_info.bw_len = CRYPT_MAGIC_LEN;
3845 write_info.bw_flags = FIO_NOCONVERT;
3846 if (buf_write_bytes(&write_info) == FAIL)
3847 end = 0;
3848 wb_flags |= FIO_ENCRYPTED;
3849 }
3850#endif
3851
3852 write_info.bw_buf = buffer;
3853 nchars = 0;
3854
3855 /* use "++bin", "++nobin" or 'binary' */
3856 if (eap != NULL && eap->force_bin != 0)
3857 write_bin = (eap->force_bin == FORCE_BIN);
3858 else
3859 write_bin = buf->b_p_bin;
3860
3861#ifdef FEAT_MBYTE
3862 /*
3863 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003864 * Skip it when appending and the file already existed, the BOM only makes
3865 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003867 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 {
3869 write_info.bw_len = make_bom(buffer, fenc);
3870 if (write_info.bw_len > 0)
3871 {
3872 /* don't convert, do encryption */
3873 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
3874 if (buf_write_bytes(&write_info) == FAIL)
3875 end = 0;
3876 else
3877 nchars += write_info.bw_len;
3878 }
3879 }
3880#endif
3881
3882 write_info.bw_len = bufsize;
3883#ifdef HAS_BW_FLAGS
3884 write_info.bw_flags = wb_flags;
3885#endif
3886 fileformat = get_fileformat_force(buf, eap);
3887 s = buffer;
3888 len = 0;
3889 for (lnum = start; lnum <= end; ++lnum)
3890 {
3891 /*
3892 * The next while loop is done once for each character written.
3893 * Keep it fast!
3894 */
3895 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
3896 while ((c = *++ptr) != NUL)
3897 {
3898 if (c == NL)
3899 *s = NUL; /* replace newlines with NULs */
3900 else if (c == CAR && fileformat == EOL_MAC)
3901 *s = NL; /* Mac: replace CRs with NLs */
3902 else
3903 *s = c;
3904 ++s;
3905 if (++len != bufsize)
3906 continue;
3907 if (buf_write_bytes(&write_info) == FAIL)
3908 {
3909 end = 0; /* write error: break loop */
3910 break;
3911 }
3912 nchars += bufsize;
3913 s = buffer;
3914 len = 0;
3915 }
3916 /* write failed or last line has no EOL: stop here */
3917 if (end == 0
3918 || (lnum == end
3919 && write_bin
3920 && (lnum == write_no_eol_lnum
3921 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
3922 {
3923 ++lnum; /* written the line, count it */
3924 no_eol = TRUE;
3925 break;
3926 }
3927 if (fileformat == EOL_UNIX)
3928 *s++ = NL;
3929 else
3930 {
3931 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
3932 if (fileformat == EOL_DOS) /* write CR-NL */
3933 {
3934 if (++len == bufsize)
3935 {
3936 if (buf_write_bytes(&write_info) == FAIL)
3937 {
3938 end = 0; /* write error: break loop */
3939 break;
3940 }
3941 nchars += bufsize;
3942 s = buffer;
3943 len = 0;
3944 }
3945 *s++ = NL;
3946 }
3947 }
3948 if (++len == bufsize && end)
3949 {
3950 if (buf_write_bytes(&write_info) == FAIL)
3951 {
3952 end = 0; /* write error: break loop */
3953 break;
3954 }
3955 nchars += bufsize;
3956 s = buffer;
3957 len = 0;
3958
3959 ui_breakcheck();
3960 if (got_int)
3961 {
3962 end = 0; /* Interrupted, break loop */
3963 break;
3964 }
3965 }
3966#ifdef VMS
3967 /*
3968 * On VMS there is a problem: newlines get added when writing blocks
3969 * at a time. Fix it by writing a line at a time.
3970 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003971 * Explanation: VAX/DECC RTL insists that records in some RMS
3972 * structures end with a newline (carriage return) character, and if
3973 * they don't it adds one.
3974 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975 */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003976 if ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003977 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003978 int b2write;
3979
3980 buf->b_fab_mrs = (buf->b_fab_mrs == 0
3981 ? MIN(4096, bufsize)
3982 : MIN(buf->b_fab_mrs, bufsize));
3983
3984 b2write = len;
3985 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003987 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
3988 if (buf_write_bytes(&write_info) == FAIL)
3989 {
3990 end = 0;
3991 break;
3992 }
3993 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 }
3995 write_info.bw_len = bufsize;
3996 nchars += len;
3997 s = buffer;
3998 len = 0;
3999 }
4000#endif
4001 }
4002 if (len > 0 && end > 0)
4003 {
4004 write_info.bw_len = len;
4005 if (buf_write_bytes(&write_info) == FAIL)
4006 end = 0; /* write error */
4007 nchars += len;
4008 }
4009
4010#if defined(UNIX) && defined(HAVE_FSYNC)
4011 /* On many journalling file systems there is a bug that causes both the
4012 * original and the backup file to be lost when halting the system right
4013 * after writing the file. That's because only the meta-data is
4014 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004015 * been written to disk and we don't lose it.
4016 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004017 * (could be a pipe).
4018 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4019 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020 {
4021 errmsg = (char_u *)_("E667: Fsync failed");
4022 end = 0;
4023 }
4024#endif
4025
4026 if (close(fd) != 0)
4027 {
4028 errmsg = (char_u *)_("E512: Close failed");
4029 end = 0;
4030 }
4031
4032#ifdef UNIX
4033 if (made_writable)
4034 perm &= ~0200; /* reset 'w' bit for security reasons */
4035#endif
4036 if (perm >= 0) /* set perm. of new file same as old file */
4037 (void)mch_setperm(wfname, perm);
4038#ifdef RISCOS
4039 if (!append && !filtering)
4040 /* Set the filetype after writing the file. */
4041 mch_set_filetype(wfname, buf->b_p_oft);
4042#endif
4043#ifdef HAVE_ACL
4044 /* Probably need to set the ACL before changing the user (can't set the
4045 * ACL on a file the user doesn't own). */
4046 if (!backup_copy)
4047 mch_set_acl(wfname, acl);
4048#endif
4049
4050#ifdef UNIX
4051 /* When creating a new file, set its owner/group to that of the original
4052 * file. Get the new device and inode number. */
4053 if (backup != NULL && !backup_copy)
4054 {
4055 struct stat st;
4056
4057 /* don't change the owner when it's already OK, some systems remove
4058 * permission or ACL stuff */
4059 if (mch_stat((char *)wfname, &st) < 0
4060 || st.st_uid != st_old.st_uid
4061 || st.st_gid != st_old.st_gid)
4062 {
4063 chown((char *)wfname, st_old.st_uid, st_old.st_gid);
4064 if (perm >= 0) /* set permission again, may have changed */
4065 (void)mch_setperm(wfname, perm);
4066 }
4067 buf_setino(buf);
4068 }
4069#endif
4070
4071
4072#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4073 if (wfname != fname)
4074 {
4075 /*
4076 * The file was written to a temp file, now it needs to be converted
4077 * with 'charconvert' to (overwrite) the output file.
4078 */
4079 if (end != 0)
4080 {
4081 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4082 wfname, fname) == FAIL)
4083 {
4084 write_info.bw_conv_error = TRUE;
4085 end = 0;
4086 }
4087 }
4088 mch_remove(wfname);
4089 vim_free(wfname);
4090 }
4091#endif
4092
4093 if (end == 0)
4094 {
4095 if (errmsg == NULL)
4096 {
4097#ifdef FEAT_MBYTE
4098 if (write_info.bw_conv_error)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004099 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 else
4101#endif
4102 if (got_int)
4103 errmsg = (char_u *)_(e_interr);
4104 else
4105 errmsg = (char_u *)_("E514: write error (file system full?)");
4106 }
4107
4108 /*
4109 * If we have a backup file, try to put it in place of the new file,
4110 * because the new file is probably corrupt. This avoids loosing the
4111 * original file when trying to make a backup when writing the file a
4112 * second time.
4113 * When "backup_copy" is set we need to copy the backup over the new
4114 * file. Otherwise rename the backup file.
4115 * If this is OK, don't give the extra warning message.
4116 */
4117 if (backup != NULL)
4118 {
4119 if (backup_copy)
4120 {
4121 /* This may take a while, if we were interrupted let the user
4122 * know we got the message. */
4123 if (got_int)
4124 {
4125 MSG(_(e_interr));
4126 out_flush();
4127 }
4128 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4129 {
4130 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004131 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4132 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 {
4134 /* copy the file. */
4135 write_info.bw_buf = smallbuf;
4136#ifdef HAS_BW_FLAGS
4137 write_info.bw_flags = FIO_NOCONVERT;
4138#endif
4139 while ((write_info.bw_len = vim_read(fd, smallbuf,
4140 SMBUFSIZE)) > 0)
4141 if (buf_write_bytes(&write_info) == FAIL)
4142 break;
4143
4144 if (close(write_info.bw_fd) >= 0
4145 && write_info.bw_len == 0)
4146 end = 1; /* success */
4147 }
4148 close(fd); /* ignore errors for closing read file */
4149 }
4150 }
4151 else
4152 {
4153 if (vim_rename(backup, fname) == 0)
4154 end = 1;
4155 }
4156 }
4157 goto fail;
4158 }
4159
4160 lnum -= start; /* compute number of written lines */
4161 --no_wait_return; /* may wait for return now */
4162
4163#if !(defined(UNIX) || defined(VMS))
4164 fname = sfname; /* use shortname now, for the messages */
4165#endif
4166 if (!filtering)
4167 {
4168 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4169 c = FALSE;
4170#ifdef FEAT_MBYTE
4171 if (write_info.bw_conv_error)
4172 {
4173 STRCAT(IObuff, _(" CONVERSION ERROR"));
4174 c = TRUE;
4175 }
4176 else if (notconverted)
4177 {
4178 STRCAT(IObuff, _("[NOT converted]"));
4179 c = TRUE;
4180 }
4181 else if (converted)
4182 {
4183 STRCAT(IObuff, _("[converted]"));
4184 c = TRUE;
4185 }
4186#endif
4187 if (device)
4188 {
4189 STRCAT(IObuff, _("[Device]"));
4190 c = TRUE;
4191 }
4192 else if (newfile)
4193 {
4194 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4195 c = TRUE;
4196 }
4197 if (no_eol)
4198 {
4199 msg_add_eol();
4200 c = TRUE;
4201 }
4202 /* may add [unix/dos/mac] */
4203 if (msg_add_fileformat(fileformat))
4204 c = TRUE;
4205#ifdef FEAT_CRYPT
4206 if (wb_flags & FIO_ENCRYPTED)
4207 {
4208 STRCAT(IObuff, _("[crypted]"));
4209 c = TRUE;
4210 }
4211#endif
4212 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4213 if (!shortmess(SHM_WRITE))
4214 {
4215 if (append)
4216 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4217 else
4218 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4219 }
4220
4221 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0));
4222 keep_msg_attr = 0;
4223 }
4224
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004225 /* When written everything correctly: reset 'modified'. Unless not
4226 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 if (reset_changed && whole
4228#ifdef FEAT_MBYTE
4229 && !write_info.bw_conv_error
4230#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004231 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4232 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233 {
4234 unchanged(buf, TRUE);
4235 u_unchanged(buf);
4236 }
4237
4238 /*
4239 * If written to the current file, update the timestamp of the swap file
4240 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4241 */
4242 if (overwriting)
4243 {
4244 ml_timestamp(buf);
4245 buf->b_flags &= ~BF_WRITE_MASK;
4246 }
4247
4248 /*
4249 * If we kept a backup until now, and we are in patch mode, then we make
4250 * the backup file our 'original' file.
4251 */
4252 if (*p_pm && dobackup)
4253 {
4254 char *org = (char *)buf_modname(
4255#ifdef SHORT_FNAME
4256 TRUE,
4257#else
4258 (buf->b_p_sn || buf->b_shortname),
4259#endif
4260 fname, p_pm, FALSE);
4261
4262 if (backup != NULL)
4263 {
4264 struct stat st;
4265
4266 /*
4267 * If the original file does not exist yet
4268 * the current backup file becomes the original file
4269 */
4270 if (org == NULL)
4271 EMSG(_("E205: Patchmode: can't save original file"));
4272 else if (mch_stat(org, &st) < 0)
4273 {
4274 vim_rename(backup, (char_u *)org);
4275 vim_free(backup); /* don't delete the file */
4276 backup = NULL;
4277#ifdef UNIX
4278 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4279#endif
4280 }
4281 }
4282 /*
4283 * If there is no backup file, remember that a (new) file was
4284 * created.
4285 */
4286 else
4287 {
4288 int empty_fd;
4289
4290 if (org == NULL
4291 || (empty_fd = mch_open(org, O_CREAT | O_EXTRA | O_EXCL,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004292 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 EMSG(_("E206: patchmode: can't touch empty original file"));
4294 else
4295 close(empty_fd);
4296 }
4297 if (org != NULL)
4298 {
4299 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4300 vim_free(org);
4301 }
4302 }
4303
4304 /*
4305 * Remove the backup unless 'backup' option is set
4306 */
4307 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4308 EMSG(_("E207: Can't delete backup file"));
4309
4310#ifdef FEAT_SUN_WORKSHOP
4311 if (usingSunWorkShop)
4312 workshop_file_saved((char *) ffname);
4313#endif
4314
4315 goto nofail;
4316
4317 /*
4318 * Finish up. We get here either after failure or success.
4319 */
4320fail:
4321 --no_wait_return; /* may wait for return now */
4322nofail:
4323
4324 /* Done saving, we accept changed buffer warnings again */
4325 buf->b_saving = FALSE;
4326
4327 vim_free(backup);
4328 if (buffer != smallbuf)
4329 vim_free(buffer);
4330#ifdef FEAT_MBYTE
4331 vim_free(fenc_tofree);
4332 vim_free(write_info.bw_conv_buf);
4333# ifdef USE_ICONV
4334 if (write_info.bw_iconv_fd != (iconv_t)-1)
4335 {
4336 iconv_close(write_info.bw_iconv_fd);
4337 write_info.bw_iconv_fd = (iconv_t)-1;
4338 }
4339# endif
4340#endif
4341#ifdef HAVE_ACL
4342 mch_free_acl(acl);
4343#endif
4344
4345 if (errmsg != NULL)
4346 {
4347 int numlen = errnum != NULL ? STRLEN(errnum) : 0;
4348
4349 attr = hl_attr(HLF_E); /* set highlight for error messages */
4350 msg_add_fname(buf,
4351#ifndef UNIX
4352 sfname
4353#else
4354 fname
4355#endif
4356 ); /* put file name in IObuff with quotes */
4357 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
4358 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
4359 /* If the error message has the form "is ...", put the error number in
4360 * front of the file name. */
4361 if (errnum != NULL)
4362 {
4363 mch_memmove(IObuff + numlen, IObuff, STRLEN(IObuff) + 1);
4364 mch_memmove(IObuff, errnum, (size_t)numlen);
4365 }
4366 STRCAT(IObuff, errmsg);
4367 emsg(IObuff);
4368
4369 retval = FAIL;
4370 if (end == 0)
4371 {
4372 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
4373 attr | MSG_HIST);
4374 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
4375 attr | MSG_HIST);
4376
4377 /* Update the timestamp to avoid an "overwrite changed file"
4378 * prompt when writing again. */
4379 if (mch_stat((char *)fname, &st_old) >= 0)
4380 {
4381 buf_store_time(buf, &st_old, fname);
4382 buf->b_mtime_read = buf->b_mtime;
4383 }
4384 }
4385 }
4386 msg_scroll = msg_save;
4387
4388#ifdef FEAT_AUTOCMD
4389#ifdef FEAT_EVAL
4390 if (!should_abort(retval))
4391#else
4392 if (!got_int)
4393#endif
4394 {
4395 aco_save_T aco;
4396
4397 write_no_eol_lnum = 0; /* in case it was set by the previous read */
4398
4399 /*
4400 * Apply POST autocommands.
4401 * Careful: The autocommands may call buf_write() recursively!
4402 */
4403 aucmd_prepbuf(&aco, buf);
4404
4405 if (append)
4406 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
4407 FALSE, curbuf, eap);
4408 else if (filtering)
4409 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
4410 FALSE, curbuf, eap);
4411 else if (reset_changed && whole)
4412 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
4413 FALSE, curbuf, eap);
4414 else
4415 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
4416 FALSE, curbuf, eap);
4417
4418 /* restore curwin/curbuf and a few other things */
4419 aucmd_restbuf(&aco);
4420
4421#ifdef FEAT_EVAL
4422 if (aborting()) /* autocmds may abort script processing */
4423 retval = FALSE;
4424#endif
4425 }
4426#endif
4427
4428 got_int |= prev_got_int;
4429
4430#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4431 /* Update machine specific information. */
4432 mch_post_buffer_write(buf);
4433#endif
4434 return retval;
4435}
4436
4437/*
4438 * Put file name into IObuff with quotes.
4439 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004440 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441msg_add_fname(buf, fname)
4442 buf_T *buf;
4443 char_u *fname;
4444{
4445 if (fname == NULL)
4446 fname = (char_u *)"-stdin-";
4447 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
4448 IObuff[0] = '"';
4449 STRCAT(IObuff, "\" ");
4450}
4451
4452/*
4453 * Append message for text mode to IObuff.
4454 * Return TRUE if something appended.
4455 */
4456 static int
4457msg_add_fileformat(eol_type)
4458 int eol_type;
4459{
4460#ifndef USE_CRNL
4461 if (eol_type == EOL_DOS)
4462 {
4463 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
4464 return TRUE;
4465 }
4466#endif
4467#ifndef USE_CR
4468 if (eol_type == EOL_MAC)
4469 {
4470 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
4471 return TRUE;
4472 }
4473#endif
4474#if defined(USE_CRNL) || defined(USE_CR)
4475 if (eol_type == EOL_UNIX)
4476 {
4477 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
4478 return TRUE;
4479 }
4480#endif
4481 return FALSE;
4482}
4483
4484/*
4485 * Append line and character count to IObuff.
4486 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004487 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488msg_add_lines(insert_space, lnum, nchars)
4489 int insert_space;
4490 long lnum;
4491 long nchars;
4492{
4493 char_u *p;
4494
4495 p = IObuff + STRLEN(IObuff);
4496
4497 if (insert_space)
4498 *p++ = ' ';
4499 if (shortmess(SHM_LINES))
4500 sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
4501 else
4502 {
4503 if (lnum == 1)
4504 STRCPY(p, _("1 line, "));
4505 else
4506 sprintf((char *)p, _("%ld lines, "), lnum);
4507 p += STRLEN(p);
4508 if (nchars == 1)
4509 STRCPY(p, _("1 character"));
4510 else
4511 sprintf((char *)p, _("%ld characters"), nchars);
4512 }
4513}
4514
4515/*
4516 * Append message for missing line separator to IObuff.
4517 */
4518 static void
4519msg_add_eol()
4520{
4521 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
4522}
4523
4524/*
4525 * Check modification time of file, before writing to it.
4526 * The size isn't checked, because using a tool like "gzip" takes care of
4527 * using the same timestamp but can't set the size.
4528 */
4529 static int
4530check_mtime(buf, st)
4531 buf_T *buf;
4532 struct stat *st;
4533{
4534 if (buf->b_mtime_read != 0
4535 && time_differs((long)st->st_mtime, buf->b_mtime_read))
4536 {
4537 msg_scroll = TRUE; /* don't overwrite messages here */
4538 msg_silent = 0; /* must give this prompt */
4539 /* don't use emsg() here, don't want to flush the buffers */
4540 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
4541 hl_attr(HLF_E));
4542 if (ask_yesno((char_u *)_("Do you really want to write to it"),
4543 TRUE) == 'n')
4544 return FAIL;
4545 msg_scroll = FALSE; /* always overwrite the file message now */
4546 }
4547 return OK;
4548}
4549
4550 static int
4551time_differs(t1, t2)
4552 long t1, t2;
4553{
4554#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
4555 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
4556 * the seconds. Since the roundoff is done when flushing the inode, the
4557 * time may change unexpectedly by one second!!! */
4558 return (t1 - t2 > 1 || t2 - t1 > 1);
4559#else
4560 return (t1 != t2);
4561#endif
4562}
4563
4564/*
4565 * Call write() to write a number of bytes to the file.
4566 * Also handles encryption and 'encoding' conversion.
4567 *
4568 * Return FAIL for failure, OK otherwise.
4569 */
4570 static int
4571buf_write_bytes(ip)
4572 struct bw_info *ip;
4573{
4574 int wlen;
4575 char_u *buf = ip->bw_buf; /* data to write */
4576 int len = ip->bw_len; /* length of data */
4577#ifdef HAS_BW_FLAGS
4578 int flags = ip->bw_flags; /* extra flags */
4579#endif
4580
4581#ifdef FEAT_MBYTE
4582 /*
4583 * Skip conversion when writing the crypt magic number or the BOM.
4584 */
4585 if (!(flags & FIO_NOCONVERT))
4586 {
4587 char_u *p;
4588 unsigned c;
4589 int n;
4590
4591 if (flags & FIO_UTF8)
4592 {
4593 /*
4594 * Convert latin1 in the buffer to UTF-8 in the file.
4595 */
4596 p = ip->bw_conv_buf; /* translate to buffer */
4597 for (wlen = 0; wlen < len; ++wlen)
4598 p += utf_char2bytes(buf[wlen], p);
4599 buf = ip->bw_conv_buf;
4600 len = (int)(p - ip->bw_conv_buf);
4601 }
4602 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
4603 {
4604 /*
4605 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
4606 * Latin1 chars in the file.
4607 */
4608 if (flags & FIO_LATIN1)
4609 p = buf; /* translate in-place (can only get shorter) */
4610 else
4611 p = ip->bw_conv_buf; /* translate to buffer */
4612 for (wlen = 0; wlen < len; wlen += n)
4613 {
4614 if (wlen == 0 && ip->bw_restlen != 0)
4615 {
4616 int l;
4617
4618 /* Use remainder of previous call. Append the start of
4619 * buf[] to get a full sequence. Might still be too
4620 * short! */
4621 l = CONV_RESTLEN - ip->bw_restlen;
4622 if (l > len)
4623 l = len;
4624 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004625 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 if (n > ip->bw_restlen + len)
4627 {
4628 /* We have an incomplete byte sequence at the end to
4629 * be written. We can't convert it without the
4630 * remaining bytes. Keep them for the next call. */
4631 if (ip->bw_restlen + len > CONV_RESTLEN)
4632 return FAIL;
4633 ip->bw_restlen += len;
4634 break;
4635 }
4636 if (n > 1)
4637 c = utf_ptr2char(ip->bw_rest);
4638 else
4639 c = ip->bw_rest[0];
4640 if (n >= ip->bw_restlen)
4641 {
4642 n -= ip->bw_restlen;
4643 ip->bw_restlen = 0;
4644 }
4645 else
4646 {
4647 ip->bw_restlen -= n;
4648 mch_memmove(ip->bw_rest, ip->bw_rest + n,
4649 (size_t)ip->bw_restlen);
4650 n = 0;
4651 }
4652 }
4653 else
4654 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004655 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 if (n > len - wlen)
4657 {
4658 /* We have an incomplete byte sequence at the end to
4659 * be written. We can't convert it without the
4660 * remaining bytes. Keep them for the next call. */
4661 if (len - wlen > CONV_RESTLEN)
4662 return FAIL;
4663 ip->bw_restlen = len - wlen;
4664 mch_memmove(ip->bw_rest, buf + wlen,
4665 (size_t)ip->bw_restlen);
4666 break;
4667 }
4668 if (n > 1)
4669 c = utf_ptr2char(buf + wlen);
4670 else
4671 c = buf[wlen];
4672 }
4673
4674 ip->bw_conv_error |= ucs2bytes(c, &p, flags);
4675 }
4676 if (flags & FIO_LATIN1)
4677 len = (int)(p - buf);
4678 else
4679 {
4680 buf = ip->bw_conv_buf;
4681 len = (int)(p - ip->bw_conv_buf);
4682 }
4683 }
4684
4685# ifdef WIN3264
4686 else if (flags & FIO_CODEPAGE)
4687 {
4688 /*
4689 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
4690 * codepage.
4691 */
4692 char_u *from;
4693 size_t fromlen;
4694 char_u *to;
4695 int u8c;
4696 BOOL bad = FALSE;
4697 int needed;
4698
4699 if (ip->bw_restlen > 0)
4700 {
4701 /* Need to concatenate the remainder of the previous call and
4702 * the bytes of the current call. Use the end of the
4703 * conversion buffer for this. */
4704 fromlen = len + ip->bw_restlen;
4705 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
4706 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
4707 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
4708 }
4709 else
4710 {
4711 from = buf;
4712 fromlen = len;
4713 }
4714
4715 to = ip->bw_conv_buf;
4716 if (enc_utf8)
4717 {
4718 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
4719 * The buffer has been allocated to be big enough. */
4720 while (fromlen > 0)
4721 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004722 n = utf_ptr2len_len(from, fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 if (n > (int)fromlen) /* incomplete byte sequence */
4724 break;
4725 u8c = utf_ptr2char(from);
4726 *to++ = (u8c & 0xff);
4727 *to++ = (u8c >> 8);
4728 fromlen -= n;
4729 from += n;
4730 }
4731
4732 /* Copy remainder to ip->bw_rest[] to be used for the next
4733 * call. */
4734 if (fromlen > CONV_RESTLEN)
4735 {
4736 /* weird overlong sequence */
4737 ip->bw_conv_error = TRUE;
4738 return FAIL;
4739 }
4740 mch_memmove(ip->bw_rest, from, fromlen);
4741 ip->bw_restlen = fromlen;
4742 }
4743 else
4744 {
4745 /* Convert from enc_codepage to UCS-2, to the start of the
4746 * buffer. The buffer has been allocated to be big enough. */
4747 ip->bw_restlen = 0;
4748 needed = MultiByteToWideChar(enc_codepage,
4749 MB_ERR_INVALID_CHARS, (LPCSTR)from, fromlen,
4750 NULL, 0);
4751 if (needed == 0)
4752 {
4753 /* When conversion fails there may be a trailing byte. */
4754 needed = MultiByteToWideChar(enc_codepage,
4755 MB_ERR_INVALID_CHARS, (LPCSTR)from, fromlen - 1,
4756 NULL, 0);
4757 if (needed == 0)
4758 {
4759 /* Conversion doesn't work. */
4760 ip->bw_conv_error = TRUE;
4761 return FAIL;
4762 }
4763 /* Save the trailing byte for the next call. */
4764 ip->bw_rest[0] = from[fromlen - 1];
4765 ip->bw_restlen = 1;
4766 }
4767 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
4768 (LPCSTR)from, fromlen - ip->bw_restlen,
4769 (LPWSTR)to, needed);
4770 if (needed == 0)
4771 {
4772 /* Safety check: Conversion doesn't work. */
4773 ip->bw_conv_error = TRUE;
4774 return FAIL;
4775 }
4776 to += needed * 2;
4777 }
4778
4779 fromlen = to - ip->bw_conv_buf;
4780 buf = to;
4781# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
4782 if (FIO_GET_CP(flags) == CP_UTF8)
4783 {
4784 /* Convert from UCS-2 to UTF-8, using the remainder of the
4785 * conversion buffer. Fails when out of space. */
4786 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
4787 {
4788 u8c = *from++;
4789 u8c += (*from++ << 8);
4790 to += utf_char2bytes(u8c, to);
4791 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
4792 {
4793 ip->bw_conv_error = TRUE;
4794 return FAIL;
4795 }
4796 }
4797 len = to - buf;
4798 }
4799 else
4800#endif
4801 {
4802 /* Convert from UCS-2 to the codepage, using the remainder of
4803 * the conversion buffer. If the conversion uses the default
4804 * character "0", the data doesn't fit in this encoding, so
4805 * fail. */
4806 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
4807 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
4808 (LPSTR)to, ip->bw_conv_buflen - fromlen, 0, &bad);
4809 if (bad)
4810 {
4811 ip->bw_conv_error = TRUE;
4812 return FAIL;
4813 }
4814 }
4815 }
4816# endif
4817
4818# ifdef MACOS_X
4819 else if (flags & FIO_MACROMAN)
4820 {
4821 /*
4822 * Convert UTF-8 or latin1 to Apple MacRoman.
4823 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 char_u *from;
4825 size_t fromlen;
4826
4827 if (ip->bw_restlen > 0)
4828 {
4829 /* Need to concatenate the remainder of the previous call and
4830 * the bytes of the current call. Use the end of the
4831 * conversion buffer for this. */
4832 fromlen = len + ip->bw_restlen;
4833 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
4834 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
4835 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
4836 }
4837 else
4838 {
4839 from = buf;
4840 fromlen = len;
4841 }
4842
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00004843 if (enc2macroman(from, fromlen,
4844 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
4845 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846 {
4847 ip->bw_conv_error = TRUE;
4848 return FAIL;
4849 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 }
4852# endif
4853
4854# ifdef USE_ICONV
4855 if (ip->bw_iconv_fd != (iconv_t)-1)
4856 {
4857 const char *from;
4858 size_t fromlen;
4859 char *to;
4860 size_t tolen;
4861
4862 /* Convert with iconv(). */
4863 if (ip->bw_restlen > 0)
4864 {
4865 /* Need to concatenate the remainder of the previous call and
4866 * the bytes of the current call. Use the end of the
4867 * conversion buffer for this. */
4868 fromlen = len + ip->bw_restlen;
4869 from = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
4870 mch_memmove((void *)from, ip->bw_rest, (size_t)ip->bw_restlen);
4871 mch_memmove((void *)(from + ip->bw_restlen), buf, (size_t)len);
4872 tolen = ip->bw_conv_buflen - fromlen;
4873 }
4874 else
4875 {
4876 from = (const char *)buf;
4877 fromlen = len;
4878 tolen = ip->bw_conv_buflen;
4879 }
4880 to = (char *)ip->bw_conv_buf;
4881
4882 if (ip->bw_first)
4883 {
4884 size_t save_len = tolen;
4885
4886 /* output the initial shift state sequence */
4887 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
4888
4889 /* There is a bug in iconv() on Linux (which appears to be
4890 * wide-spread) which sets "to" to NULL and messes up "tolen".
4891 */
4892 if (to == NULL)
4893 {
4894 to = (char *)ip->bw_conv_buf;
4895 tolen = save_len;
4896 }
4897 ip->bw_first = FALSE;
4898 }
4899
4900 /*
4901 * If iconv() has an error or there is not enough room, fail.
4902 */
4903 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
4904 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
4905 || fromlen > CONV_RESTLEN)
4906 {
4907 ip->bw_conv_error = TRUE;
4908 return FAIL;
4909 }
4910
4911 /* copy remainder to ip->bw_rest[] to be used for the next call. */
4912 if (fromlen > 0)
4913 mch_memmove(ip->bw_rest, (void *)from, fromlen);
4914 ip->bw_restlen = (int)fromlen;
4915
4916 buf = ip->bw_conv_buf;
4917 len = (int)((char_u *)to - ip->bw_conv_buf);
4918 }
4919# endif
4920 }
4921#endif /* FEAT_MBYTE */
4922
4923#ifdef FEAT_CRYPT
4924 if (flags & FIO_ENCRYPTED) /* encrypt the data */
4925 {
4926 int ztemp, t, i;
4927
4928 for (i = 0; i < len; i++)
4929 {
4930 ztemp = buf[i];
4931 buf[i] = ZENCODE(ztemp, t);
4932 }
4933 }
4934#endif
4935
4936 /* Repeat the write(), it may be interrupted by a signal. */
4937 while (len)
4938 {
4939 wlen = vim_write(ip->bw_fd, buf, len);
4940 if (wlen <= 0) /* error! */
4941 return FAIL;
4942 len -= wlen;
4943 buf += wlen;
4944 }
4945 return OK;
4946}
4947
4948#ifdef FEAT_MBYTE
4949/*
4950 * Convert a Unicode character to bytes.
4951 */
4952 static int
4953ucs2bytes(c, pp, flags)
4954 unsigned c; /* in: character */
4955 char_u **pp; /* in/out: pointer to result */
4956 int flags; /* FIO_ flags */
4957{
4958 char_u *p = *pp;
4959 int error = FALSE;
4960 int cc;
4961
4962
4963 if (flags & FIO_UCS4)
4964 {
4965 if (flags & FIO_ENDIAN_L)
4966 {
4967 *p++ = c;
4968 *p++ = (c >> 8);
4969 *p++ = (c >> 16);
4970 *p++ = (c >> 24);
4971 }
4972 else
4973 {
4974 *p++ = (c >> 24);
4975 *p++ = (c >> 16);
4976 *p++ = (c >> 8);
4977 *p++ = c;
4978 }
4979 }
4980 else if (flags & (FIO_UCS2 | FIO_UTF16))
4981 {
4982 if (c >= 0x10000)
4983 {
4984 if (flags & FIO_UTF16)
4985 {
4986 /* Make two words, ten bits of the character in each. First
4987 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
4988 c -= 0x10000;
4989 if (c >= 0x100000)
4990 error = TRUE;
4991 cc = ((c >> 10) & 0x3ff) + 0xd800;
4992 if (flags & FIO_ENDIAN_L)
4993 {
4994 *p++ = cc;
4995 *p++ = ((unsigned)cc >> 8);
4996 }
4997 else
4998 {
4999 *p++ = ((unsigned)cc >> 8);
5000 *p++ = cc;
5001 }
5002 c = (c & 0x3ff) + 0xdc00;
5003 }
5004 else
5005 error = TRUE;
5006 }
5007 if (flags & FIO_ENDIAN_L)
5008 {
5009 *p++ = c;
5010 *p++ = (c >> 8);
5011 }
5012 else
5013 {
5014 *p++ = (c >> 8);
5015 *p++ = c;
5016 }
5017 }
5018 else /* Latin1 */
5019 {
5020 if (c >= 0x100)
5021 {
5022 error = TRUE;
5023 *p++ = 0xBF;
5024 }
5025 else
5026 *p++ = c;
5027 }
5028
5029 *pp = p;
5030 return error;
5031}
5032
5033/*
5034 * Return TRUE if "a" and "b" are the same 'encoding'.
5035 * Ignores difference between "ansi" and "latin1", "ucs-4" and "ucs-4be", etc.
5036 */
5037 static int
5038same_encoding(a, b)
5039 char_u *a;
5040 char_u *b;
5041{
5042 int f;
5043
5044 if (STRCMP(a, b) == 0)
5045 return TRUE;
5046 f = get_fio_flags(a);
5047 return (f != 0 && get_fio_flags(b) == f);
5048}
5049
5050/*
5051 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5052 * internal conversion.
5053 * if "ptr" is an empty string, use 'encoding'.
5054 */
5055 static int
5056get_fio_flags(ptr)
5057 char_u *ptr;
5058{
5059 int prop;
5060
5061 if (*ptr == NUL)
5062 ptr = p_enc;
5063
5064 prop = enc_canon_props(ptr);
5065 if (prop & ENC_UNICODE)
5066 {
5067 if (prop & ENC_2BYTE)
5068 {
5069 if (prop & ENC_ENDIAN_L)
5070 return FIO_UCS2 | FIO_ENDIAN_L;
5071 return FIO_UCS2;
5072 }
5073 if (prop & ENC_4BYTE)
5074 {
5075 if (prop & ENC_ENDIAN_L)
5076 return FIO_UCS4 | FIO_ENDIAN_L;
5077 return FIO_UCS4;
5078 }
5079 if (prop & ENC_2WORD)
5080 {
5081 if (prop & ENC_ENDIAN_L)
5082 return FIO_UTF16 | FIO_ENDIAN_L;
5083 return FIO_UTF16;
5084 }
5085 return FIO_UTF8;
5086 }
5087 if (prop & ENC_LATIN1)
5088 return FIO_LATIN1;
5089 /* must be ENC_DBCS, requires iconv() */
5090 return 0;
5091}
5092
5093#ifdef WIN3264
5094/*
5095 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5096 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5097 * Used for conversion between 'encoding' and 'fileencoding'.
5098 */
5099 static int
5100get_win_fio_flags(ptr)
5101 char_u *ptr;
5102{
5103 int cp;
5104
5105 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5106 if (!enc_utf8 && enc_codepage <= 0)
5107 return 0;
5108
5109 cp = encname2codepage(ptr);
5110 if (cp == 0)
5111 {
5112# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5113 if (STRCMP(ptr, "utf-8") == 0)
5114 cp = CP_UTF8;
5115 else
5116# endif
5117 return 0;
5118 }
5119 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5120}
5121#endif
5122
5123#ifdef MACOS_X
5124/*
5125 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5126 * needed for the internal conversion to/from utf-8 or latin1.
5127 */
5128 static int
5129get_mac_fio_flags(ptr)
5130 char_u *ptr;
5131{
5132 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5133 && (enc_canon_props(ptr) & ENC_MACROMAN))
5134 return FIO_MACROMAN;
5135 return 0;
5136}
5137#endif
5138
5139/*
5140 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5141 * "size" must be at least 2.
5142 * Return the name of the encoding and set "*lenp" to the length.
5143 * Returns NULL when no BOM found.
5144 */
5145 static char_u *
5146check_for_bom(p, size, lenp, flags)
5147 char_u *p;
5148 long size;
5149 int *lenp;
5150 int flags;
5151{
5152 char *name = NULL;
5153 int len = 2;
5154
5155 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
5156 && (flags == FIO_ALL || flags == 0))
5157 {
5158 name = "utf-8"; /* EF BB BF */
5159 len = 3;
5160 }
5161 else if (p[0] == 0xff && p[1] == 0xfe)
5162 {
5163 if (size >= 4 && p[2] == 0 && p[3] == 0
5164 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5165 {
5166 name = "ucs-4le"; /* FF FE 00 00 */
5167 len = 4;
5168 }
5169 else if (flags == FIO_ALL || flags == (FIO_UCS2 | FIO_ENDIAN_L))
5170 name = "ucs-2le"; /* FF FE */
5171 else if (flags == (FIO_UTF16 | FIO_ENDIAN_L))
5172 name = "utf-16le"; /* FF FE */
5173 }
5174 else if (p[0] == 0xfe && p[1] == 0xff
5175 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5176 {
5177 if (flags == FIO_UTF16)
5178 name = "utf-16"; /* FE FF */
5179 else
5180 name = "ucs-2"; /* FE FF */
5181 }
5182 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5183 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5184 {
5185 name = "ucs-4"; /* 00 00 FE FF */
5186 len = 4;
5187 }
5188
5189 *lenp = len;
5190 return (char_u *)name;
5191}
5192
5193/*
5194 * Generate a BOM in "buf[4]" for encoding "name".
5195 * Return the length of the BOM (zero when no BOM).
5196 */
5197 static int
5198make_bom(buf, name)
5199 char_u *buf;
5200 char_u *name;
5201{
5202 int flags;
5203 char_u *p;
5204
5205 flags = get_fio_flags(name);
5206
5207 /* Can't put a BOM in a non-Unicode file. */
5208 if (flags == FIO_LATIN1 || flags == 0)
5209 return 0;
5210
5211 if (flags == FIO_UTF8) /* UTF-8 */
5212 {
5213 buf[0] = 0xef;
5214 buf[1] = 0xbb;
5215 buf[2] = 0xbf;
5216 return 3;
5217 }
5218 p = buf;
5219 (void)ucs2bytes(0xfeff, &p, flags);
5220 return (int)(p - buf);
5221}
5222#endif
5223
5224/*
5225 * Try to find a shortname by comparing the fullname with the current
5226 * directory.
5227 * Returns NULL if not shorter name possible, pointer into "full_path"
5228 * otherwise.
5229 */
5230 char_u *
5231shorten_fname(full_path, dir_name)
5232 char_u *full_path;
5233 char_u *dir_name;
5234{
5235 int len;
5236 char_u *p;
5237
5238 if (full_path == NULL)
5239 return NULL;
5240 len = (int)STRLEN(dir_name);
5241 if (fnamencmp(dir_name, full_path, len) == 0)
5242 {
5243 p = full_path + len;
5244#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5245 /*
5246 * MSDOS: when a file is in the root directory, dir_name will end in a
5247 * slash, since C: by itself does not define a specific dir. In this
5248 * case p may already be correct. <negri>
5249 */
5250 if (!((len > 2) && (*(p - 2) == ':')))
5251#endif
5252 {
5253 if (vim_ispathsep(*p))
5254 ++p;
5255#ifndef VMS /* the path separator is always part of the path */
5256 else
5257 p = NULL;
5258#endif
5259 }
5260 }
5261#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5262 /*
5263 * When using a file in the current drive, remove the drive name:
5264 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
5265 * a floppy from "A:\dir" to "B:\dir".
5266 */
5267 else if (len > 3
5268 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
5269 && full_path[1] == ':'
5270 && vim_ispathsep(full_path[2]))
5271 p = full_path + 2;
5272#endif
5273 else
5274 p = NULL;
5275 return p;
5276}
5277
5278/*
5279 * Shorten filenames for all buffers.
5280 * When "force" is TRUE: Use full path from now on for files currently being
5281 * edited, both for file name and swap file name. Try to shorten the file
5282 * names a bit, if safe to do so.
5283 * When "force" is FALSE: Only try to shorten absolute file names.
5284 * For buffers that have buftype "nofile" or "scratch": never change the file
5285 * name.
5286 */
5287 void
5288shorten_fnames(force)
5289 int force;
5290{
5291 char_u dirname[MAXPATHL];
5292 buf_T *buf;
5293 char_u *p;
5294
5295 mch_dirname(dirname, MAXPATHL);
5296 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5297 {
5298 if (buf->b_fname != NULL
5299#ifdef FEAT_QUICKFIX
5300 && !bt_nofile(buf)
5301#endif
5302 && !path_with_url(buf->b_fname)
5303 && (force
5304 || buf->b_sfname == NULL
5305 || mch_isFullName(buf->b_sfname)))
5306 {
5307 vim_free(buf->b_sfname);
5308 buf->b_sfname = NULL;
5309 p = shorten_fname(buf->b_ffname, dirname);
5310 if (p != NULL)
5311 {
5312 buf->b_sfname = vim_strsave(p);
5313 buf->b_fname = buf->b_sfname;
5314 }
5315 if (p == NULL || buf->b_fname == NULL)
5316 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005318
5319 /* Always make the swap file name a full path, a "nofile" buffer may
5320 * also have a swap file. */
5321 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 }
5323#ifdef FEAT_WINDOWS
5324 status_redraw_all();
5325#endif
5326}
5327
5328#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
5329 || defined(FEAT_GUI_MSWIN) \
5330 || defined(FEAT_GUI_MAC) \
5331 || defined(PROTO)
5332/*
5333 * Shorten all filenames in "fnames[count]" by current directory.
5334 */
5335 void
5336shorten_filenames(fnames, count)
5337 char_u **fnames;
5338 int count;
5339{
5340 int i;
5341 char_u dirname[MAXPATHL];
5342 char_u *p;
5343
5344 if (fnames == NULL || count < 1)
5345 return;
5346 mch_dirname(dirname, sizeof(dirname));
5347 for (i = 0; i < count; ++i)
5348 {
5349 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
5350 {
5351 /* shorten_fname() returns pointer in given "fnames[i]". If free
5352 * "fnames[i]" first, "p" becomes invalid. So we need to copy
5353 * "p" first then free fnames[i]. */
5354 p = vim_strsave(p);
5355 vim_free(fnames[i]);
5356 fnames[i] = p;
5357 }
5358 }
5359}
5360#endif
5361
5362/*
5363 * add extention to file name - change path/fo.o.h to path/fo.o.h.ext or
5364 * fo_o_h.ext for MSDOS or when shortname option set.
5365 *
5366 * Assumed that fname is a valid name found in the filesystem we assure that
5367 * the return value is a different name and ends in 'ext'.
5368 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
5369 * characters otherwise.
5370 * Space for the returned name is allocated, must be freed later.
5371 * Returns NULL when out of memory.
5372 */
5373 char_u *
5374modname(fname, ext, prepend_dot)
5375 char_u *fname, *ext;
5376 int prepend_dot; /* may prepend a '.' to file name */
5377{
5378 return buf_modname(
5379#ifdef SHORT_FNAME
5380 TRUE,
5381#else
5382 (curbuf->b_p_sn || curbuf->b_shortname),
5383#endif
5384 fname, ext, prepend_dot);
5385}
5386
5387 char_u *
5388buf_modname(shortname, fname, ext, prepend_dot)
5389 int shortname; /* use 8.3 file name */
5390 char_u *fname, *ext;
5391 int prepend_dot; /* may prepend a '.' to file name */
5392{
5393 char_u *retval;
5394 char_u *s;
5395 char_u *e;
5396 char_u *ptr;
5397 int fnamelen, extlen;
5398
5399 extlen = (int)STRLEN(ext);
5400
5401 /*
5402 * If there is no file name we must get the name of the current directory
5403 * (we need the full path in case :cd is used).
5404 */
5405 if (fname == NULL || *fname == NUL)
5406 {
5407 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
5408 if (retval == NULL)
5409 return NULL;
5410 if (mch_dirname(retval, MAXPATHL) == FAIL ||
5411 (fnamelen = (int)STRLEN(retval)) == 0)
5412 {
5413 vim_free(retval);
5414 return NULL;
5415 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005416 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417 {
5418 retval[fnamelen++] = PATHSEP;
5419 retval[fnamelen] = NUL;
5420 }
5421#ifndef SHORT_FNAME
5422 prepend_dot = FALSE; /* nothing to prepend a dot to */
5423#endif
5424 }
5425 else
5426 {
5427 fnamelen = (int)STRLEN(fname);
5428 retval = alloc((unsigned)(fnamelen + extlen + 3));
5429 if (retval == NULL)
5430 return NULL;
5431 STRCPY(retval, fname);
5432#ifdef VMS
5433 vms_remove_version(retval); /* we do not need versions here */
5434#endif
5435 }
5436
5437 /*
5438 * search backwards until we hit a '/', '\' or ':' replacing all '.'
5439 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
5440 * Then truncate what is after the '/', '\' or ':' to 8 characters for
5441 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
5442 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005443 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 {
5445#ifndef RISCOS
5446 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005447# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005449# else
5450# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005452# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005453# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454 )
5455 if (*ptr == '.') /* replace '.' by '_' */
5456 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005457#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005459 {
5460 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005462 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005464
5465 /* the file name has at most BASENAMELEN characters. */
5466#ifndef SHORT_FNAME
5467 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
5468 ptr[BASENAMELEN] = '\0';
5469#endif
5470
5471 s = ptr + STRLEN(ptr);
5472
5473 /*
5474 * For 8.3 file names we may have to reduce the length.
5475 */
5476#ifdef USE_LONG_FNAME
5477 if (!USE_LONG_FNAME || shortname)
5478#else
5479# ifndef SHORT_FNAME
5480 if (shortname)
5481# endif
5482#endif
5483 {
5484 /*
5485 * If there is no file name, or the file name ends in '/', and the
5486 * extension starts with '.', put a '_' before the dot, because just
5487 * ".ext" is invalid.
5488 */
5489 if (fname == NULL || *fname == NUL
5490 || vim_ispathsep(fname[STRLEN(fname) - 1]))
5491 {
5492#ifdef RISCOS
5493 if (*ext == '/')
5494#else
5495 if (*ext == '.')
5496#endif
5497 *s++ = '_';
5498 }
5499 /*
5500 * If the extension starts with '.', truncate the base name at 8
5501 * characters
5502 */
5503#ifdef RISCOS
5504 /* We normally use '/', but swap files are '_' */
5505 else if (*ext == '/' || *ext == '_')
5506#else
5507 else if (*ext == '.')
5508#endif
5509 {
5510 if (s - ptr > (size_t)8)
5511 {
5512 s = ptr + 8;
5513 *s = '\0';
5514 }
5515 }
5516 /*
5517 * If the extension doesn't start with '.', and the file name
5518 * doesn't have an extension yet, append a '.'
5519 */
5520#ifdef RISCOS
5521 else if ((e = vim_strchr(ptr, '/')) == NULL)
5522 *s++ = '/';
5523#else
5524 else if ((e = vim_strchr(ptr, '.')) == NULL)
5525 *s++ = '.';
5526#endif
5527 /*
5528 * If the extension doesn't start with '.', and there already is an
5529 * extension, it may need to be tructated
5530 */
5531 else if ((int)STRLEN(e) + extlen > 4)
5532 s = e + 4 - extlen;
5533 }
5534#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
5535 /*
5536 * If there is no file name, and the extension starts with '.', put a
5537 * '_' before the dot, because just ".ext" may be invalid if it's on a
5538 * FAT partition, and on HPFS it doesn't matter.
5539 */
5540 else if ((fname == NULL || *fname == NUL) && *ext == '.')
5541 *s++ = '_';
5542#endif
5543
5544 /*
5545 * Append the extention.
5546 * ext can start with '.' and cannot exceed 3 more characters.
5547 */
5548 STRCPY(s, ext);
5549
5550#ifndef SHORT_FNAME
5551 /*
5552 * Prepend the dot.
5553 */
5554 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
5555#ifdef RISCOS
5556 '/'
5557#else
5558 '.'
5559#endif
5560#ifdef USE_LONG_FNAME
5561 && USE_LONG_FNAME
5562#endif
5563 )
5564 {
5565 mch_memmove(e + 1, e, STRLEN(e) + 1);
5566#ifdef RISCOS
5567 *e = '/';
5568#else
5569 *e = '.';
5570#endif
5571 }
5572#endif
5573
5574 /*
5575 * Check that, after appending the extension, the file name is really
5576 * different.
5577 */
5578 if (fname != NULL && STRCMP(fname, retval) == 0)
5579 {
5580 /* we search for a character that can be replaced by '_' */
5581 while (--s >= ptr)
5582 {
5583 if (*s != '_')
5584 {
5585 *s = '_';
5586 break;
5587 }
5588 }
5589 if (s < ptr) /* fname was "________.<ext>", how tricky! */
5590 *ptr = 'v';
5591 }
5592 return retval;
5593}
5594
5595/*
5596 * Like fgets(), but if the file line is too long, it is truncated and the
5597 * rest of the line is thrown away. Returns TRUE for end-of-file.
5598 */
5599 int
5600vim_fgets(buf, size, fp)
5601 char_u *buf;
5602 int size;
5603 FILE *fp;
5604{
5605 char *eof;
5606#define FGETS_SIZE 200
5607 char tbuf[FGETS_SIZE];
5608
5609 buf[size - 2] = NUL;
5610#ifdef USE_CR
5611 eof = fgets_cr((char *)buf, size, fp);
5612#else
5613 eof = fgets((char *)buf, size, fp);
5614#endif
5615 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
5616 {
5617 buf[size - 1] = NUL; /* Truncate the line */
5618
5619 /* Now throw away the rest of the line: */
5620 do
5621 {
5622 tbuf[FGETS_SIZE - 2] = NUL;
5623#ifdef USE_CR
5624 fgets_cr((char *)tbuf, FGETS_SIZE, fp);
5625#else
5626 fgets((char *)tbuf, FGETS_SIZE, fp);
5627#endif
5628 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
5629 }
5630 return (eof == NULL);
5631}
5632
5633#if defined(USE_CR) || defined(PROTO)
5634/*
5635 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
5636 * Returns TRUE for end-of-file.
5637 * Only used for the Mac, because it's much slower than vim_fgets().
5638 */
5639 int
5640tag_fgets(buf, size, fp)
5641 char_u *buf;
5642 int size;
5643 FILE *fp;
5644{
5645 int i = 0;
5646 int c;
5647 int eof = FALSE;
5648
5649 for (;;)
5650 {
5651 c = fgetc(fp);
5652 if (c == EOF)
5653 {
5654 eof = TRUE;
5655 break;
5656 }
5657 if (c == '\r')
5658 {
5659 /* Always store a NL for end-of-line. */
5660 if (i < size - 1)
5661 buf[i++] = '\n';
5662 c = fgetc(fp);
5663 if (c != '\n') /* Macintosh format: single CR. */
5664 ungetc(c, fp);
5665 break;
5666 }
5667 if (i < size - 1)
5668 buf[i++] = c;
5669 if (c == '\n')
5670 break;
5671 }
5672 buf[i] = NUL;
5673 return eof;
5674}
5675#endif
5676
5677/*
5678 * rename() only works if both files are on the same file system, this
5679 * function will (attempts to?) copy the file across if rename fails -- webb
5680 * Return -1 for failure, 0 for success.
5681 */
5682 int
5683vim_rename(from, to)
5684 char_u *from;
5685 char_u *to;
5686{
5687 int fd_in;
5688 int fd_out;
5689 int n;
5690 char *errmsg = NULL;
5691 char *buffer;
5692#ifdef AMIGA
5693 BPTR flock;
5694#endif
5695 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005696 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00005697#ifdef HAVE_ACL
5698 vim_acl_T acl; /* ACL from original file */
5699#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700
5701 /*
5702 * When the names are identical, there is nothing to do.
5703 */
5704 if (fnamecmp(from, to) == 0)
5705 return 0;
5706
5707 /*
5708 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
5709 */
5710 if (mch_stat((char *)from, &st) < 0)
5711 return -1;
5712
5713 /*
5714 * Delete the "to" file, this is required on some systems to make the
5715 * mch_rename() work, on other systems it makes sure that we don't have
5716 * two files when the mch_rename() fails.
5717 */
5718
5719#ifdef AMIGA
5720 /*
5721 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
5722 * that the name of the "to" file is the same as the "from" file, even
5723 * though the names are different. To avoid the chance of accidently
5724 * deleting the "from" file (horror!) we lock it during the remove.
5725 *
5726 * When used for making a backup before writing the file: This should not
5727 * happen with ":w", because startscript() should detect this problem and
5728 * set buf->b_shortname, causing modname() to return a correct ".bak" file
5729 * name. This problem does exist with ":w filename", but then the
5730 * original file will be somewhere else so the backup isn't really
5731 * important. If autoscripting is off the rename may fail.
5732 */
5733 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
5734#endif
5735 mch_remove(to);
5736#ifdef AMIGA
5737 if (flock)
5738 UnLock(flock);
5739#endif
5740
5741 /*
5742 * First try a normal rename, return if it works.
5743 */
5744 if (mch_rename((char *)from, (char *)to) == 0)
5745 return 0;
5746
5747 /*
5748 * Rename() failed, try copying the file.
5749 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005750 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00005751#ifdef HAVE_ACL
5752 /* For systems that support ACL: get the ACL from the original file. */
5753 acl = mch_get_acl(from);
5754#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
5756 if (fd_in == -1)
5757 return -1;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005758
5759 /* Create the new file with same permissions as the original. */
5760 fd_out = mch_open((char *)to, O_CREAT|O_EXCL|O_WRONLY|O_EXTRA, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 if (fd_out == -1)
5762 {
5763 close(fd_in);
5764 return -1;
5765 }
5766
5767 buffer = (char *)alloc(BUFSIZE);
5768 if (buffer == NULL)
5769 {
5770 close(fd_in);
5771 close(fd_out);
5772 return -1;
5773 }
5774
5775 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
5776 if (vim_write(fd_out, buffer, n) != n)
5777 {
5778 errmsg = _("E208: Error writing to \"%s\"");
5779 break;
5780 }
5781
5782 vim_free(buffer);
5783 close(fd_in);
5784 if (close(fd_out) < 0)
5785 errmsg = _("E209: Error closing \"%s\"");
5786 if (n < 0)
5787 {
5788 errmsg = _("E210: Error reading \"%s\"");
5789 to = from;
5790 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005791 mch_setperm(to, perm);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00005792#ifdef HAVE_ACL
5793 mch_set_acl(to, acl);
5794#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 if (errmsg != NULL)
5796 {
5797 EMSG2(errmsg, to);
5798 return -1;
5799 }
5800 mch_remove(from);
5801 return 0;
5802}
5803
5804static int already_warned = FALSE;
5805
5806/*
5807 * Check if any not hidden buffer has been changed.
5808 * Postpone the check if there are characters in the stuff buffer, a global
5809 * command is being executed, a mapping is being executed or an autocommand is
5810 * busy.
5811 * Returns TRUE if some message was written (screen should be redrawn and
5812 * cursor positioned).
5813 */
5814 int
5815check_timestamps(focus)
5816 int focus; /* called for GUI focus event */
5817{
5818 buf_T *buf;
5819 int didit = 0;
5820 int n;
5821
5822 /* Don't check timestamps while system() or another low-level function may
5823 * cause us to lose and gain focus. */
5824 if (no_check_timestamps > 0)
5825 return FALSE;
5826
5827 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
5828 * event and we would keep on checking if the file is steadily growing.
5829 * Do check again after typing something. */
5830 if (focus && did_check_timestamps)
5831 {
5832 need_check_timestamps = TRUE;
5833 return FALSE;
5834 }
5835
5836 if (!stuff_empty() || global_busy || !typebuf_typed()
5837#ifdef FEAT_AUTOCMD
5838 || autocmd_busy
5839#endif
5840 )
5841 need_check_timestamps = TRUE; /* check later */
5842 else
5843 {
5844 ++no_wait_return;
5845 did_check_timestamps = TRUE;
5846 already_warned = FALSE;
5847 for (buf = firstbuf; buf != NULL; )
5848 {
5849 /* Only check buffers in a window. */
5850 if (buf->b_nwindows > 0)
5851 {
5852 n = buf_check_timestamp(buf, focus);
5853 if (didit < n)
5854 didit = n;
5855 if (n > 0 && !buf_valid(buf))
5856 {
5857 /* Autocommands have removed the buffer, start at the
5858 * first one again. */
5859 buf = firstbuf;
5860 continue;
5861 }
5862 }
5863 buf = buf->b_next;
5864 }
5865 --no_wait_return;
5866 need_check_timestamps = FALSE;
5867 if (need_wait_return && didit == 2)
5868 {
5869 /* make sure msg isn't overwritten */
5870 msg_puts((char_u *)"\n");
5871 out_flush();
5872 }
5873 }
5874 return didit;
5875}
5876
5877/*
5878 * Move all the lines from buffer "frombuf" to buffer "tobuf".
5879 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
5880 * empty.
5881 */
5882 static int
5883move_lines(frombuf, tobuf)
5884 buf_T *frombuf;
5885 buf_T *tobuf;
5886{
5887 buf_T *tbuf = curbuf;
5888 int retval = OK;
5889 linenr_T lnum;
5890 char_u *p;
5891
5892 /* Copy the lines in "frombuf" to "tobuf". */
5893 curbuf = tobuf;
5894 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
5895 {
5896 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
5897 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
5898 {
5899 vim_free(p);
5900 retval = FAIL;
5901 break;
5902 }
5903 vim_free(p);
5904 }
5905
5906 /* Delete all the lines in "frombuf". */
5907 if (retval != FAIL)
5908 {
5909 curbuf = frombuf;
5910 while (!bufempty())
5911 if (ml_delete(curbuf->b_ml.ml_line_count, FALSE) == FAIL)
5912 {
5913 /* Oops! We could try putting back the saved lines, but that
5914 * might fail again... */
5915 retval = FAIL;
5916 break;
5917 }
5918 }
5919
5920 curbuf = tbuf;
5921 return retval;
5922}
5923
5924/*
5925 * Check if buffer "buf" has been changed.
5926 * Also check if the file for a new buffer unexpectedly appeared.
5927 * return 1 if a changed buffer was found.
5928 * return 2 if a message has been displayed.
5929 * return 0 otherwise.
5930 */
5931/*ARGSUSED*/
5932 int
5933buf_check_timestamp(buf, focus)
5934 buf_T *buf;
5935 int focus; /* called for GUI focus event */
5936{
5937 struct stat st;
5938 int stat_res;
5939 int retval = 0;
5940 char_u *path;
5941 char_u *tbuf;
5942 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00005943 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 int helpmesg = FALSE;
5945 int reload = FALSE;
5946#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
5947 int can_reload = FALSE;
5948#endif
5949 size_t orig_size = buf->b_orig_size;
5950 int orig_mode = buf->b_orig_mode;
5951#ifdef FEAT_GUI
5952 int save_mouse_correct = need_mouse_correct;
5953#endif
5954#ifdef FEAT_AUTOCMD
5955 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00005956 int n;
5957 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00005959 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960
5961 /* If there is no file name, the buffer is not loaded, 'buftype' is
5962 * set, we are in the middle of a save or being called recursively: ignore
5963 * this buffer. */
5964 if (buf->b_ffname == NULL
5965 || buf->b_ml.ml_mfp == NULL
5966#if defined(FEAT_QUICKFIX)
5967 || *buf->b_p_bt != NUL
5968#endif
5969 || buf->b_saving
5970#ifdef FEAT_AUTOCMD
5971 || busy
5972#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00005973#ifdef FEAT_NETBEANS_INTG
5974 || isNetbeansBuffer(buf)
5975#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005976 )
5977 return 0;
5978
5979 if ( !(buf->b_flags & BF_NOTEDITED)
5980 && buf->b_mtime != 0
5981 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
5982 || time_differs((long)st.st_mtime, buf->b_mtime)
5983#ifdef HAVE_ST_MODE
5984 || (int)st.st_mode != buf->b_orig_mode
5985#else
5986 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
5987#endif
5988 ))
5989 {
5990 retval = 1;
5991
5992 /* set b_mtime to stop further warnings */
5993 if (stat_res < 0)
5994 {
5995 buf->b_mtime = 0;
5996 buf->b_orig_size = 0;
5997 buf->b_orig_mode = 0;
5998 }
5999 else
6000 buf_store_time(buf, &st, buf->b_ffname);
6001
6002 /* Don't do anything for a directory. Might contain the file
6003 * explorer. */
6004 if (mch_isdir(buf->b_fname))
6005 ;
6006
6007 /*
6008 * If 'autoread' is set, the buffer has no changes and the file still
6009 * exists, reload the buffer. Use the buffer-local option value if it
6010 * was set, the global option value otherwise.
6011 */
6012 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6013 && !bufIsChanged(buf) && stat_res >= 0)
6014 reload = TRUE;
6015 else
6016 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006017 if (stat_res < 0)
6018 reason = "deleted";
6019 else if (bufIsChanged(buf))
6020 reason = "conflict";
6021 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6022 reason = "changed";
6023 else if (orig_mode != buf->b_orig_mode)
6024 reason = "mode";
6025 else
6026 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006028#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029 /*
6030 * Only give the warning if there are no FileChangedShell
6031 * autocommands.
6032 * Avoid being called recursively by setting "busy".
6033 */
6034 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006035# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006036 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6037 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006038# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6040 buf->b_fname, buf->b_fname, FALSE, buf);
6041 busy = FALSE;
6042 if (n)
6043 {
6044 if (!buf_valid(buf))
6045 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006046# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006047 s = get_vim_var_str(VV_FCS_CHOICE);
6048 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6049 reload = TRUE;
6050 else if (STRCMP(s, "ask") == 0)
6051 n = FALSE;
6052 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006053# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006054 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006056 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057#endif
6058 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006059 if (*reason == 'd')
6060 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061 else
6062 {
6063 helpmesg = TRUE;
6064#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6065 can_reload = TRUE;
6066#endif
6067 /*
6068 * Check if the file contents really changed to avoid
6069 * giving a warning when only the timestamp was set (e.g.,
6070 * checked out of CVS). Always warn when the buffer was
6071 * changed.
6072 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006073 if (reason[2] == 'n')
6074 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006076 mesg2 = _("See \":help W12\" for more info.");
6077 }
6078 else if (reason[1] == 'h')
6079 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006081 mesg2 = _("See \":help W11\" for more info.");
6082 }
6083 else if (*reason == 'm')
6084 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006086 mesg2 = _("See \":help W16\" for more info.");
6087 }
6088 /* Else: only timestamp changed, ignored */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089 }
6090 }
6091 }
6092
6093 }
6094 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6095 && vim_fexists(buf->b_ffname))
6096 {
6097 retval = 1;
6098 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6099 buf->b_flags |= BF_NEW_W;
6100#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6101 can_reload = TRUE;
6102#endif
6103 }
6104
6105 if (mesg != NULL)
6106 {
6107 path = home_replace_save(buf, buf->b_fname);
6108 if (path != NULL)
6109 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006110 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111 mesg2 = "";
6112 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6113 + STRLEN(mesg2) + 2));
6114 sprintf((char *)tbuf, mesg, path);
6115#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6116 if (can_reload)
6117 {
6118 if (*mesg2 != NUL)
6119 {
6120 STRCAT(tbuf, "\n");
6121 STRCAT(tbuf, mesg2);
6122 }
6123 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6124 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6125 reload = TRUE;
6126 }
6127 else
6128#endif
6129 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6130 {
6131 if (*mesg2 != NUL)
6132 {
6133 STRCAT(tbuf, "; ");
6134 STRCAT(tbuf, mesg2);
6135 }
6136 EMSG(tbuf);
6137 retval = 2;
6138 }
6139 else
6140 {
Bram Moolenaared203462004-06-16 11:19:22 +00006141# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006143# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144 {
6145 msg_start();
6146 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6147 if (*mesg2 != NUL)
6148 msg_puts_attr((char_u *)mesg2,
6149 hl_attr(HLF_W) + MSG_HIST);
6150 msg_clr_eos();
6151 (void)msg_end();
6152 if (emsg_silent == 0)
6153 {
6154 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00006155# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00006157# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158 /* give the user some time to think about it */
6159 ui_delay(1000L, TRUE);
6160
6161 /* don't redraw and erase the message */
6162 redraw_cmdline = FALSE;
6163 }
6164 }
6165 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 }
6167
6168 vim_free(path);
6169 vim_free(tbuf);
6170 }
6171 }
6172
6173 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006174 /* Reload the buffer. */
6175 buf_reload(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176
6177#ifdef FEAT_GUI
6178 /* restore this in case an autocommand has set it; it would break
6179 * 'mousefocus' */
6180 need_mouse_correct = save_mouse_correct;
6181#endif
6182
6183 return retval;
6184}
6185
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006186/*
6187 * Reload a buffer that is already loaded.
6188 * Used when the file was changed outside of Vim.
6189 */
6190 void
6191buf_reload(buf)
6192 buf_T *buf;
6193{
6194 exarg_T ea;
6195 pos_T old_cursor;
6196 linenr_T old_topline;
6197 int old_ro = buf->b_p_ro;
6198 int orig_mode = buf->b_orig_mode;
6199 buf_T *savebuf;
6200 int saved = OK;
6201#ifdef FEAT_AUTOCMD
6202 aco_save_T aco;
6203
6204 /* set curwin/curbuf for "buf" and save some things */
6205 aucmd_prepbuf(&aco, buf);
6206#else
6207 buf_T *save_curbuf = curbuf;
6208
6209 curbuf = buf;
6210 curwin->w_buffer = buf;
6211#endif
6212
6213 /* We only want to read the text from the file, not reset the syntax
6214 * highlighting, clear marks, diff status, etc. Force the fileformat
6215 * and encoding to be the same. */
6216 if (prep_exarg(&ea, buf) == OK)
6217 {
6218 old_cursor = curwin->w_cursor;
6219 old_topline = curwin->w_topline;
6220
6221 /*
6222 * To behave like when a new file is edited (matters for
6223 * BufReadPost autocommands) we first need to delete the current
6224 * buffer contents. But if reading the file fails we should keep
6225 * the old contents. Can't use memory only, the file might be
6226 * too big. Use a hidden buffer to move the buffer contents to.
6227 */
6228 if (bufempty())
6229 savebuf = NULL;
6230 else
6231 {
6232 /* Allocate a buffer without putting it in the buffer list. */
6233 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
6234 if (savebuf != NULL)
6235 {
6236 /* Open the memline. */
6237 curbuf = savebuf;
6238 curwin->w_buffer = savebuf;
6239 saved = ml_open();
6240 curbuf = buf;
6241 curwin->w_buffer = buf;
6242 }
6243 if (savebuf == NULL || saved == FAIL
6244 || move_lines(buf, savebuf) == FAIL)
6245 {
6246 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
6247 buf->b_fname);
6248 saved = FAIL;
6249 }
6250 }
6251
6252 if (saved == OK)
6253 {
6254 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
6255#ifdef FEAT_AUTOCMD
6256 keep_filetype = TRUE; /* don't detect 'filetype' */
6257#endif
6258 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
6259 (linenr_T)0,
6260 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
6261 {
6262#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6263 if (!aborting())
6264#endif
6265 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
6266 if (savebuf != NULL)
6267 {
6268 /* Put the text back from the save buffer. First
6269 * delete any lines that readfile() added. */
6270 while (!bufempty())
6271 if (ml_delete(curbuf->b_ml.ml_line_count, FALSE)
6272 == FAIL)
6273 break;
6274 (void)move_lines(savebuf, buf);
6275 }
6276 }
6277 else
6278 {
6279 /* Mark the buffer as unmodified and free undo info. */
6280 unchanged(buf, TRUE);
6281 u_blockfree(buf);
6282 u_clearall(buf);
6283 }
6284 }
6285 vim_free(ea.cmd);
6286
6287 if (savebuf != NULL)
6288 wipe_buffer(savebuf, FALSE);
6289
6290#ifdef FEAT_DIFF
6291 /* Invalidate diff info if necessary. */
6292 diff_invalidate();
6293#endif
6294
6295 /* Restore the topline and cursor position and check it (lines may
6296 * have been removed). */
6297 if (old_topline > curbuf->b_ml.ml_line_count)
6298 curwin->w_topline = curbuf->b_ml.ml_line_count;
6299 else
6300 curwin->w_topline = old_topline;
6301 curwin->w_cursor = old_cursor;
6302 check_cursor();
6303 update_topline();
6304#ifdef FEAT_AUTOCMD
6305 keep_filetype = FALSE;
6306#endif
6307#ifdef FEAT_FOLDING
6308 {
6309 win_T *wp;
6310
6311 /* Update folds unless they are defined manually. */
6312 FOR_ALL_WINDOWS(wp)
6313 if (wp->w_buffer == curwin->w_buffer
6314 && !foldmethodIsManual(wp))
6315 foldUpdateAll(wp);
6316 }
6317#endif
6318 /* If the mode didn't change and 'readonly' was set, keep the old
6319 * value; the user probably used the ":view" command. But don't
6320 * reset it, might have had a read error. */
6321 if (orig_mode == curbuf->b_orig_mode)
6322 curbuf->b_p_ro |= old_ro;
6323 }
6324
6325#ifdef FEAT_AUTOCMD
6326 /* restore curwin/curbuf and a few other things */
6327 aucmd_restbuf(&aco);
6328 /* Careful: autocommands may have made "buf" invalid! */
6329#else
6330 curwin->w_buffer = save_curbuf;
6331 curbuf = save_curbuf;
6332#endif
6333}
6334
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335/*ARGSUSED*/
6336 void
6337buf_store_time(buf, st, fname)
6338 buf_T *buf;
6339 struct stat *st;
6340 char_u *fname;
6341{
6342 buf->b_mtime = (long)st->st_mtime;
6343 buf->b_orig_size = (size_t)st->st_size;
6344#ifdef HAVE_ST_MODE
6345 buf->b_orig_mode = (int)st->st_mode;
6346#else
6347 buf->b_orig_mode = mch_getperm(fname);
6348#endif
6349}
6350
6351/*
6352 * Adjust the line with missing eol, used for the next write.
6353 * Used for do_filter(), when the input lines for the filter are deleted.
6354 */
6355 void
6356write_lnum_adjust(offset)
6357 linenr_T offset;
6358{
Bram Moolenaardf177f62005-02-22 08:39:57 +00006359 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 write_no_eol_lnum += offset;
6361}
6362
6363#if defined(TEMPDIRNAMES) || defined(PROTO)
6364static long temp_count = 0; /* Temp filename counter. */
6365
6366/*
6367 * Delete the temp directory and all files it contains.
6368 */
6369 void
6370vim_deltempdir()
6371{
6372 char_u **files;
6373 int file_count;
6374 int i;
6375
6376 if (vim_tempdir != NULL)
6377 {
6378 sprintf((char *)NameBuff, "%s*", vim_tempdir);
6379 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
6380 EW_DIR|EW_FILE|EW_SILENT) == OK)
6381 {
6382 for (i = 0; i < file_count; ++i)
6383 mch_remove(files[i]);
6384 FreeWild(file_count, files);
6385 }
6386 gettail(NameBuff)[-1] = NUL;
6387 (void)mch_rmdir(NameBuff);
6388
6389 vim_free(vim_tempdir);
6390 vim_tempdir = NULL;
6391 }
6392}
6393#endif
6394
6395/*
6396 * vim_tempname(): Return a unique name that can be used for a temp file.
6397 *
6398 * The temp file is NOT created.
6399 *
6400 * The returned pointer is to allocated memory.
6401 * The returned pointer is NULL if no valid name was found.
6402 */
6403/*ARGSUSED*/
6404 char_u *
6405vim_tempname(extra_char)
6406 int extra_char; /* character to use in the name instead of '?' */
6407{
6408#ifdef USE_TMPNAM
6409 char_u itmp[L_tmpnam]; /* use tmpnam() */
6410#else
6411 char_u itmp[TEMPNAMELEN];
6412#endif
6413
6414#ifdef TEMPDIRNAMES
6415 static char *(tempdirs[]) = {TEMPDIRNAMES};
6416 int i;
6417 long nr;
6418 long off;
6419# ifndef EEXIST
6420 struct stat st;
6421# endif
6422
6423 /*
6424 * This will create a directory for private use by this instance of Vim.
6425 * This is done once, and the same directory is used for all temp files.
6426 * This method avoids security problems because of symlink attacks et al.
6427 * It's also a bit faster, because we only need to check for an existing
6428 * file when creating the directory and not for each temp file.
6429 */
6430 if (vim_tempdir == NULL)
6431 {
6432 /*
6433 * Try the entries in TEMPDIRNAMES to create the temp directory.
6434 */
6435 for (i = 0; i < sizeof(tempdirs) / sizeof(char *); ++i)
6436 {
6437 /* expand $TMP, leave room for "/v1100000/999999999" */
6438 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
6439 if (mch_isdir(itmp)) /* directory exists */
6440 {
6441# ifdef __EMX__
6442 /* If $TMP contains a forward slash (perhaps using bash or
6443 * tcsh), don't add a backslash, use a forward slash!
6444 * Adding 2 backslashes didn't work. */
6445 if (vim_strchr(itmp, '/') != NULL)
6446 STRCAT(itmp, "/");
6447 else
6448# endif
6449 add_pathsep(itmp);
6450
6451 /* Get an arbitrary number of up to 6 digits. When it's
6452 * unlikely that it already exists it will be faster,
6453 * otherwise it doesn't matter. The use of mkdir() avoids any
6454 * security problems because of the predictable number. */
6455 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
6456
6457 /* Try up to 10000 different values until we find a name that
6458 * doesn't exist. */
6459 for (off = 0; off < 10000L; ++off)
6460 {
6461 int r;
6462#if defined(UNIX) || defined(VMS)
6463 mode_t umask_save;
6464#endif
6465
6466 sprintf((char *)itmp + STRLEN(itmp), "v%ld", nr + off);
6467# ifndef EEXIST
6468 /* If mkdir() does not set errno to EEXIST, check for
6469 * existing file here. There is a race condition then,
6470 * although it's fail-safe. */
6471 if (mch_stat((char *)itmp, &st) >= 0)
6472 continue;
6473# endif
6474#if defined(UNIX) || defined(VMS)
6475 /* Make sure the umask doesn't remove the executable bit.
6476 * "repl" has been reported to use "177". */
6477 umask_save = umask(077);
6478#endif
6479 r = vim_mkdir(itmp, 0700);
6480#if defined(UNIX) || defined(VMS)
6481 (void)umask(umask_save);
6482#endif
6483 if (r == 0)
6484 {
6485 char_u *buf;
6486
6487 /* Directory was created, use this name.
6488 * Expand to full path; When using the current
6489 * directory a ":cd" would confuse us. */
6490 buf = alloc((unsigned)MAXPATHL + 1);
6491 if (buf != NULL)
6492 {
6493 if (vim_FullName(itmp, buf, MAXPATHL, FALSE)
6494 == FAIL)
6495 STRCPY(buf, itmp);
6496# ifdef __EMX__
6497 if (vim_strchr(buf, '/') != NULL)
6498 STRCAT(buf, "/");
6499 else
6500# endif
6501 add_pathsep(buf);
6502 vim_tempdir = vim_strsave(buf);
6503 vim_free(buf);
6504 }
6505 break;
6506 }
6507# ifdef EEXIST
6508 /* If the mkdir() didn't fail because the file/dir exists,
6509 * we probably can't create any dir here, try another
6510 * place. */
6511 if (errno != EEXIST)
6512# endif
6513 break;
6514 }
6515 if (vim_tempdir != NULL)
6516 break;
6517 }
6518 }
6519 }
6520
6521 if (vim_tempdir != NULL)
6522 {
6523 /* There is no need to check if the file exists, because we own the
6524 * directory and nobody else creates a file in it. */
6525 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
6526 return vim_strsave(itmp);
6527 }
6528
6529 return NULL;
6530
6531#else /* TEMPDIRNAMES */
6532
6533# ifdef WIN3264
6534 char szTempFile[_MAX_PATH + 1];
6535 char buf4[4];
6536 char_u *retval;
6537 char_u *p;
6538
6539 STRCPY(itmp, "");
6540 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
6541 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
6542 strcpy(buf4, "VIM");
6543 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
6544 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
6545 return NULL;
6546 /* GetTempFileName() will create the file, we don't want that */
6547 (void)DeleteFile(itmp);
6548
6549 /* Backslashes in a temp file name cause problems when filtering with
6550 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
6551 * didn't set 'shellslash'. */
6552 retval = vim_strsave(itmp);
6553 if (*p_shcf == '-' || p_ssl)
6554 for (p = retval; *p; ++p)
6555 if (*p == '\\')
6556 *p = '/';
6557 return retval;
6558
6559# else /* WIN3264 */
6560
6561# ifdef USE_TMPNAM
6562 /* tmpnam() will make its own name */
6563 if (*tmpnam((char *)itmp) == NUL)
6564 return NULL;
6565# else
6566 char_u *p;
6567
6568# ifdef VMS_TEMPNAM
6569 /* mktemp() is not working on VMS. It seems to be
6570 * a do-nothing function. Therefore we use tempnam().
6571 */
6572 sprintf((char *)itmp, "VIM%c", extra_char);
6573 p = (char_u *)tempnam("tmp:", (char *)itmp);
6574 if (p != NULL)
6575 {
6576 /* VMS will use '.LOG' if we don't explicitly specify an extension,
6577 * and VIM will then be unable to find the file later */
6578 STRCPY(itmp, p);
6579 STRCAT(itmp, ".txt");
6580 free(p);
6581 }
6582 else
6583 return NULL;
6584# else
6585 STRCPY(itmp, TEMPNAME);
6586 if ((p = vim_strchr(itmp, '?')) != NULL)
6587 *p = extra_char;
6588 if (mktemp((char *)itmp) == NULL)
6589 return NULL;
6590# endif
6591# endif
6592
6593 return vim_strsave(itmp);
6594# endif /* WIN3264 */
6595#endif /* TEMPDIRNAMES */
6596}
6597
6598#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
6599/*
6600 * Convert all backslashes in fname to forward slashes in-place.
6601 */
6602 void
6603forward_slash(fname)
6604 char_u *fname;
6605{
6606 char_u *p;
6607
6608 for (p = fname; *p != NUL; ++p)
6609# ifdef FEAT_MBYTE
6610 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00006611 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 ++p;
6613 else
6614# endif
6615 if (*p == '\\')
6616 *p = '/';
6617}
6618#endif
6619
6620
6621/*
6622 * Code for automatic commands.
6623 *
6624 * Only included when "FEAT_AUTOCMD" has been defined.
6625 */
6626
6627#if defined(FEAT_AUTOCMD) || defined(PROTO)
6628
6629/*
6630 * The autocommands are stored in a list for each event.
6631 * Autocommands for the same pattern, that are consecutive, are joined
6632 * together, to avoid having to match the pattern too often.
6633 * The result is an array of Autopat lists, which point to AutoCmd lists:
6634 *
6635 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
6636 * Autopat.cmds Autopat.cmds
6637 * | |
6638 * V V
6639 * AutoCmd.next AutoCmd.next
6640 * | |
6641 * V V
6642 * AutoCmd.next NULL
6643 * |
6644 * V
6645 * NULL
6646 *
6647 * first_autopat[1] --> Autopat.next --> NULL
6648 * Autopat.cmds
6649 * |
6650 * V
6651 * AutoCmd.next
6652 * |
6653 * V
6654 * NULL
6655 * etc.
6656 *
6657 * The order of AutoCmds is important, this is the order in which they were
6658 * defined and will have to be executed.
6659 */
6660typedef struct AutoCmd
6661{
6662 char_u *cmd; /* The command to be executed (NULL
6663 when command has been removed) */
6664 char nested; /* If autocommands nest here */
6665 char last; /* last command in list */
6666#ifdef FEAT_EVAL
6667 scid_T scriptID; /* script ID where defined */
6668#endif
6669 struct AutoCmd *next; /* Next AutoCmd in list */
6670} AutoCmd;
6671
6672typedef struct AutoPat
6673{
6674 int group; /* group ID */
6675 char_u *pat; /* pattern as typed (NULL when pattern
6676 has been removed) */
6677 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00006678 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 char allow_dirs; /* Pattern may match whole path */
6680 char last; /* last pattern for apply_autocmds() */
6681 AutoCmd *cmds; /* list of commands to do */
6682 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006683 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684} AutoPat;
6685
6686static struct event_name
6687{
6688 char *name; /* event name */
6689 EVENT_T event; /* event number */
6690} event_names[] =
6691{
6692 {"BufAdd", EVENT_BUFADD},
6693 {"BufCreate", EVENT_BUFADD},
6694 {"BufDelete", EVENT_BUFDELETE},
6695 {"BufEnter", EVENT_BUFENTER},
6696 {"BufFilePost", EVENT_BUFFILEPOST},
6697 {"BufFilePre", EVENT_BUFFILEPRE},
6698 {"BufHidden", EVENT_BUFHIDDEN},
6699 {"BufLeave", EVENT_BUFLEAVE},
6700 {"BufNew", EVENT_BUFNEW},
6701 {"BufNewFile", EVENT_BUFNEWFILE},
6702 {"BufRead", EVENT_BUFREADPOST},
6703 {"BufReadCmd", EVENT_BUFREADCMD},
6704 {"BufReadPost", EVENT_BUFREADPOST},
6705 {"BufReadPre", EVENT_BUFREADPRE},
6706 {"BufUnload", EVENT_BUFUNLOAD},
6707 {"BufWinEnter", EVENT_BUFWINENTER},
6708 {"BufWinLeave", EVENT_BUFWINLEAVE},
6709 {"BufWipeout", EVENT_BUFWIPEOUT},
6710 {"BufWrite", EVENT_BUFWRITEPRE},
6711 {"BufWritePost", EVENT_BUFWRITEPOST},
6712 {"BufWritePre", EVENT_BUFWRITEPRE},
6713 {"BufWriteCmd", EVENT_BUFWRITECMD},
6714 {"CmdwinEnter", EVENT_CMDWINENTER},
6715 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006716 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717 {"EncodingChanged", EVENT_ENCODINGCHANGED},
6718 {"FileEncoding", EVENT_ENCODINGCHANGED},
6719 {"CursorHold", EVENT_CURSORHOLD},
6720 {"FileAppendPost", EVENT_FILEAPPENDPOST},
6721 {"FileAppendPre", EVENT_FILEAPPENDPRE},
6722 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
6723 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
6724 {"FileChangedRO", EVENT_FILECHANGEDRO},
6725 {"FileReadPost", EVENT_FILEREADPOST},
6726 {"FileReadPre", EVENT_FILEREADPRE},
6727 {"FileReadCmd", EVENT_FILEREADCMD},
6728 {"FileType", EVENT_FILETYPE},
6729 {"FileWritePost", EVENT_FILEWRITEPOST},
6730 {"FileWritePre", EVENT_FILEWRITEPRE},
6731 {"FileWriteCmd", EVENT_FILEWRITECMD},
6732 {"FilterReadPost", EVENT_FILTERREADPOST},
6733 {"FilterReadPre", EVENT_FILTERREADPRE},
6734 {"FilterWritePost", EVENT_FILTERWRITEPOST},
6735 {"FilterWritePre", EVENT_FILTERWRITEPRE},
6736 {"FocusGained", EVENT_FOCUSGAINED},
6737 {"FocusLost", EVENT_FOCUSLOST},
6738 {"FuncUndefined", EVENT_FUNCUNDEFINED},
6739 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar843ee412004-06-30 16:16:41 +00006740 {"InsertChange", EVENT_INSERTCHANGE},
6741 {"InsertEnter", EVENT_INSERTENTER},
6742 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00006743 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00006744 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
6745 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 {"RemoteReply", EVENT_REMOTEREPLY},
6747 {"StdinReadPost", EVENT_STDINREADPOST},
6748 {"StdinReadPre", EVENT_STDINREADPRE},
6749 {"Syntax", EVENT_SYNTAX},
6750 {"TermChanged", EVENT_TERMCHANGED},
6751 {"TermResponse", EVENT_TERMRESPONSE},
6752 {"User", EVENT_USER},
6753 {"VimEnter", EVENT_VIMENTER},
6754 {"VimLeave", EVENT_VIMLEAVE},
6755 {"VimLeavePre", EVENT_VIMLEAVEPRE},
6756 {"WinEnter", EVENT_WINENTER},
6757 {"WinLeave", EVENT_WINLEAVE},
6758 {NULL, (EVENT_T)0}
6759};
6760
6761static AutoPat *first_autopat[NUM_EVENTS] =
6762{
6763 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6764 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6765 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6766 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00006767 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6768 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769};
6770
6771/*
6772 * struct used to keep status while executing autocommands for an event.
6773 */
6774typedef struct AutoPatCmd
6775{
6776 AutoPat *curpat; /* next AutoPat to examine */
6777 AutoCmd *nextcmd; /* next AutoCmd to execute */
6778 int group; /* group being used */
6779 char_u *fname; /* fname to match with */
6780 char_u *sfname; /* sfname to match with */
6781 char_u *tail; /* tail of fname */
6782 EVENT_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006783 int arg_bufnr; /* initially equal to <abuf>, set to zero when
6784 buf is deleted */
6785 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786} AutoPatCmd;
6787
Bram Moolenaard6f676d2005-06-01 21:51:55 +00006788static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006789
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790/*
6791 * augroups stores a list of autocmd group names.
6792 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00006793static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
6795
6796/*
6797 * The ID of the current group. Group 0 is the default one.
6798 */
6799#define AUGROUP_DEFAULT -1 /* default autocmd group */
6800#define AUGROUP_ERROR -2 /* errornouse autocmd group */
6801#define AUGROUP_ALL -3 /* all autocmd groups */
6802static int current_augroup = AUGROUP_DEFAULT;
6803
6804static int au_need_clean = FALSE; /* need to delete marked patterns */
6805
6806static void show_autocmd __ARGS((AutoPat *ap, EVENT_T event));
6807static void au_remove_pat __ARGS((AutoPat *ap));
6808static void au_remove_cmds __ARGS((AutoPat *ap));
6809static void au_cleanup __ARGS((void));
6810static int au_new_group __ARGS((char_u *name));
6811static void au_del_group __ARGS((char_u *name));
6812static int au_find_group __ARGS((char_u *name));
6813static EVENT_T event_name2nr __ARGS((char_u *start, char_u **end));
6814static char_u *event_nr2name __ARGS((EVENT_T event));
6815static char_u *find_end_event __ARGS((char_u *arg, int have_group));
6816static int event_ignored __ARGS((EVENT_T event));
6817static int au_get_grouparg __ARGS((char_u **argp));
6818static int do_autocmd_event __ARGS((EVENT_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
6819static char_u *getnextac __ARGS((int c, void *cookie, int indent));
6820static int apply_autocmds_group __ARGS((EVENT_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap));
6821static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
6822
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006823
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824static EVENT_T last_event;
6825static int last_group;
6826
6827/*
6828 * Show the autocommands for one AutoPat.
6829 */
6830 static void
6831show_autocmd(ap, event)
6832 AutoPat *ap;
6833 EVENT_T event;
6834{
6835 AutoCmd *ac;
6836
6837 /* Check for "got_int" (here and at various places below), which is set
6838 * when "q" has been hit for the "--more--" prompt */
6839 if (got_int)
6840 return;
6841 if (ap->pat == NULL) /* pattern has been removed */
6842 return;
6843
6844 msg_putchar('\n');
6845 if (got_int)
6846 return;
6847 if (event != last_event || ap->group != last_group)
6848 {
6849 if (ap->group != AUGROUP_DEFAULT)
6850 {
6851 if (AUGROUP_NAME(ap->group) == NULL)
6852 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
6853 else
6854 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
6855 msg_puts((char_u *)" ");
6856 }
6857 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
6858 last_event = event;
6859 last_group = ap->group;
6860 msg_putchar('\n');
6861 if (got_int)
6862 return;
6863 }
6864 msg_col = 4;
6865 msg_outtrans(ap->pat);
6866
6867 for (ac = ap->cmds; ac != NULL; ac = ac->next)
6868 {
6869 if (ac->cmd != NULL) /* skip removed commands */
6870 {
6871 if (msg_col >= 14)
6872 msg_putchar('\n');
6873 msg_col = 14;
6874 if (got_int)
6875 return;
6876 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00006877#ifdef FEAT_EVAL
6878 if (p_verbose > 0)
6879 last_set_msg(ac->scriptID);
6880#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 if (got_int)
6882 return;
6883 if (ac->next != NULL)
6884 {
6885 msg_putchar('\n');
6886 if (got_int)
6887 return;
6888 }
6889 }
6890 }
6891}
6892
6893/*
6894 * Mark an autocommand pattern for deletion.
6895 */
6896 static void
6897au_remove_pat(ap)
6898 AutoPat *ap;
6899{
6900 vim_free(ap->pat);
6901 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006902 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 au_need_clean = TRUE;
6904}
6905
6906/*
6907 * Mark all commands for a pattern for deletion.
6908 */
6909 static void
6910au_remove_cmds(ap)
6911 AutoPat *ap;
6912{
6913 AutoCmd *ac;
6914
6915 for (ac = ap->cmds; ac != NULL; ac = ac->next)
6916 {
6917 vim_free(ac->cmd);
6918 ac->cmd = NULL;
6919 }
6920 au_need_clean = TRUE;
6921}
6922
6923/*
6924 * Cleanup autocommands and patterns that have been deleted.
6925 * This is only done when not executing autocommands.
6926 */
6927 static void
6928au_cleanup()
6929{
6930 AutoPat *ap, **prev_ap;
6931 AutoCmd *ac, **prev_ac;
6932 EVENT_T event;
6933
6934 if (autocmd_busy || !au_need_clean)
6935 return;
6936
6937 /* loop over all events */
6938 for (event = (EVENT_T)0; (int)event < (int)NUM_EVENTS;
6939 event = (EVENT_T)((int)event + 1))
6940 {
6941 /* loop over all autocommand patterns */
6942 prev_ap = &(first_autopat[(int)event]);
6943 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
6944 {
6945 /* loop over all commands for this pattern */
6946 prev_ac = &(ap->cmds);
6947 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
6948 {
6949 /* remove the command if the pattern is to be deleted or when
6950 * the command has been marked for deletion */
6951 if (ap->pat == NULL || ac->cmd == NULL)
6952 {
6953 *prev_ac = ac->next;
6954 vim_free(ac->cmd);
6955 vim_free(ac);
6956 }
6957 else
6958 prev_ac = &(ac->next);
6959 }
6960
6961 /* remove the pattern if it has been marked for deletion */
6962 if (ap->pat == NULL)
6963 {
6964 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00006965 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 vim_free(ap);
6967 }
6968 else
6969 prev_ap = &(ap->next);
6970 }
6971 }
6972
6973 au_need_clean = FALSE;
6974}
6975
6976/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006977 * Called when buffer is freed, to remove/invalidate related buffer-local
6978 * autocmds.
6979 */
6980 void
6981aubuflocal_remove(buf)
6982 buf_T *buf;
6983{
6984 AutoPat *ap;
6985 EVENT_T event;
6986 AutoPatCmd *apc;
6987
6988 /* invalidate currently executing autocommands */
6989 for (apc = active_apc_list; apc; apc = apc->next)
6990 if (buf->b_fnum == apc->arg_bufnr)
6991 apc->arg_bufnr = 0;
6992
6993 /* invalidate buflocals looping through events */
6994 for (event = (EVENT_T)0; (int)event < (int)NUM_EVENTS;
6995 event = (EVENT_T)((int)event + 1))
6996 /* loop over all autocommand patterns */
6997 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
6998 if (ap->buflocal_nr == buf->b_fnum)
6999 {
7000 au_remove_pat(ap);
7001 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007002 {
7003 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007004 smsg((char_u *)
7005 _("auto-removing autocommand: %s <buffer=%d>"),
7006 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007007 verbose_leave();
7008 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007009 }
7010 au_cleanup();
7011}
7012
7013/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 * Add an autocmd group name.
7015 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7016 */
7017 static int
7018au_new_group(name)
7019 char_u *name;
7020{
7021 int i;
7022
7023 i = au_find_group(name);
7024 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7025 {
7026 /* First try using a free entry. */
7027 for (i = 0; i < augroups.ga_len; ++i)
7028 if (AUGROUP_NAME(i) == NULL)
7029 break;
7030 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7031 return AUGROUP_ERROR;
7032
7033 AUGROUP_NAME(i) = vim_strsave(name);
7034 if (AUGROUP_NAME(i) == NULL)
7035 return AUGROUP_ERROR;
7036 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 }
7039
7040 return i;
7041}
7042
7043 static void
7044au_del_group(name)
7045 char_u *name;
7046{
7047 int i;
7048
7049 i = au_find_group(name);
7050 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7051 EMSG2(_("E367: No such group: \"%s\""), name);
7052 else
7053 {
7054 vim_free(AUGROUP_NAME(i));
7055 AUGROUP_NAME(i) = NULL;
7056 }
7057}
7058
7059/*
7060 * Find the ID of an autocmd group name.
7061 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7062 */
7063 static int
7064au_find_group(name)
7065 char_u *name;
7066{
7067 int i;
7068
7069 for (i = 0; i < augroups.ga_len; ++i)
7070 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7071 return i;
7072 return AUGROUP_ERROR;
7073}
7074
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007075#if defined(FEAT_BROWSE) || defined(PROTO)
7076/*
7077 * Return TRUE if augroup "name" exists.
7078 */
7079 int
7080au_has_group(name)
7081 char_u *name;
7082{
7083 return au_find_group(name) != AUGROUP_ERROR;
7084}
7085#endif
7086
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087/*
7088 * ":augroup {name}".
7089 */
7090 void
7091do_augroup(arg, del_group)
7092 char_u *arg;
7093 int del_group;
7094{
7095 int i;
7096
7097 if (del_group)
7098 {
7099 if (*arg == NUL)
7100 EMSG(_(e_argreq));
7101 else
7102 au_del_group(arg);
7103 }
7104 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
7105 current_augroup = AUGROUP_DEFAULT;
7106 else if (*arg) /* ":aug xxx": switch to group xxx */
7107 {
7108 i = au_new_group(arg);
7109 if (i != AUGROUP_ERROR)
7110 current_augroup = i;
7111 }
7112 else /* ":aug": list the group names */
7113 {
7114 msg_start();
7115 for (i = 0; i < augroups.ga_len; ++i)
7116 {
7117 if (AUGROUP_NAME(i) != NULL)
7118 {
7119 msg_puts(AUGROUP_NAME(i));
7120 msg_puts((char_u *)" ");
7121 }
7122 }
7123 msg_clr_eos();
7124 msg_end();
7125 }
7126}
7127
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007128#if defined(EXITFREE) || defined(PROTO)
7129 void
7130free_all_autocmds()
7131{
7132 for (current_augroup = -1; current_augroup < augroups.ga_len;
7133 ++current_augroup)
7134 do_autocmd((char_u *)"", TRUE);
7135 ga_clear_strings(&augroups);
7136}
7137#endif
7138
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139/*
7140 * Return the event number for event name "start".
7141 * Return NUM_EVENTS if the event name was not found.
7142 * Return a pointer to the next event name in "end".
7143 */
7144 static EVENT_T
7145event_name2nr(start, end)
7146 char_u *start;
7147 char_u **end;
7148{
7149 char_u *p;
7150 int i;
7151 int len;
7152
7153 /* the event name ends with end of line, a blank or a comma */
7154 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
7155 ;
7156 for (i = 0; event_names[i].name != NULL; ++i)
7157 {
7158 len = (int)STRLEN(event_names[i].name);
7159 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
7160 break;
7161 }
7162 if (*p == ',')
7163 ++p;
7164 *end = p;
7165 if (event_names[i].name == NULL)
7166 return NUM_EVENTS;
7167 return event_names[i].event;
7168}
7169
7170/*
7171 * Return the name for event "event".
7172 */
7173 static char_u *
7174event_nr2name(event)
7175 EVENT_T event;
7176{
7177 int i;
7178
7179 for (i = 0; event_names[i].name != NULL; ++i)
7180 if (event_names[i].event == event)
7181 return (char_u *)event_names[i].name;
7182 return (char_u *)"Unknown";
7183}
7184
7185/*
7186 * Scan over the events. "*" stands for all events.
7187 */
7188 static char_u *
7189find_end_event(arg, have_group)
7190 char_u *arg;
7191 int have_group; /* TRUE when group name was found */
7192{
7193 char_u *pat;
7194 char_u *p;
7195
7196 if (*arg == '*')
7197 {
7198 if (arg[1] && !vim_iswhite(arg[1]))
7199 {
7200 EMSG2(_("E215: Illegal character after *: %s"), arg);
7201 return NULL;
7202 }
7203 pat = arg + 1;
7204 }
7205 else
7206 {
7207 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
7208 {
7209 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
7210 {
7211 if (have_group)
7212 EMSG2(_("E216: No such event: %s"), pat);
7213 else
7214 EMSG2(_("E216: No such group or event: %s"), pat);
7215 return NULL;
7216 }
7217 }
7218 }
7219 return pat;
7220}
7221
7222/*
7223 * Return TRUE if "event" is included in 'eventignore'.
7224 */
7225 static int
7226event_ignored(event)
7227 EVENT_T event;
7228{
7229 char_u *p = p_ei;
7230
7231 if (STRICMP(p_ei, "all") == 0)
7232 return TRUE;
7233
7234 while (*p)
7235 if (event_name2nr(p, &p) == event)
7236 return TRUE;
7237
7238 return FALSE;
7239}
7240
7241/*
7242 * Return OK when the contents of p_ei is valid, FAIL otherwise.
7243 */
7244 int
7245check_ei()
7246{
7247 char_u *p = p_ei;
7248
7249 if (STRICMP(p_ei, "all") == 0)
7250 return OK;
7251
7252 while (*p)
7253 if (event_name2nr(p, &p) == NUM_EVENTS)
7254 return FAIL;
7255
7256 return OK;
7257}
7258
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007259# if defined(FEAT_SYN_HL) || defined(PROTO)
7260
7261/*
7262 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
7263 * buffer loaded into the window. "what" must start with a comma.
7264 * Returns the old value of 'eventignore' in allocated memory.
7265 */
7266 char_u *
7267au_event_disable(what)
7268 char *what;
7269{
7270 char_u *new_ei;
7271 char_u *save_ei;
7272
7273 save_ei = vim_strsave(p_ei);
7274 if (save_ei != NULL)
7275 {
7276 new_ei = vim_strnsave(p_ei, (int)STRLEN(p_ei) + 8);
7277 if (new_ei != NULL)
7278 {
7279 STRCAT(new_ei, what);
7280 set_string_option_direct((char_u *)"ei", -1, new_ei, OPT_FREE);
7281 vim_free(new_ei);
7282 }
7283 }
7284 return save_ei;
7285}
7286
7287 void
7288au_event_restore(old_ei)
7289 char_u *old_ei;
7290{
7291 if (old_ei != NULL)
7292 {
7293 set_string_option_direct((char_u *)"ei", -1, old_ei, OPT_FREE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007294 vim_free(old_ei);
7295 }
7296}
7297# endif /* FEAT_SYN_HL */
7298
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299/*
7300 * do_autocmd() -- implements the :autocmd command. Can be used in the
7301 * following ways:
7302 *
7303 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
7304 * will be automatically executed for <event>
7305 * when editing a file matching <pat>, in
7306 * the current group.
7307 * :autocmd <event> <pat> Show the auto-commands associated with
7308 * <event> and <pat>.
7309 * :autocmd <event> Show the auto-commands associated with
7310 * <event>.
7311 * :autocmd Show all auto-commands.
7312 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
7313 * <event> and <pat>, and add the command
7314 * <cmd>, for the current group.
7315 * :autocmd! <event> <pat> Remove all auto-commands associated with
7316 * <event> and <pat> for the current group.
7317 * :autocmd! <event> Remove all auto-commands associated with
7318 * <event> for the current group.
7319 * :autocmd! Remove ALL auto-commands for the current
7320 * group.
7321 *
7322 * Multiple events and patterns may be given separated by commas. Here are
7323 * some examples:
7324 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
7325 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
7326 *
7327 * :autocmd * *.c show all autocommands for *.c files.
7328 */
7329 void
7330do_autocmd(arg, forceit)
7331 char_u *arg;
7332 int forceit;
7333{
7334 char_u *pat;
7335 char_u *envpat = NULL;
7336 char_u *cmd;
7337 EVENT_T event;
7338 int need_free = FALSE;
7339 int nested = FALSE;
7340 int group;
7341
7342 /*
7343 * Check for a legal group name. If not, use AUGROUP_ALL.
7344 */
7345 group = au_get_grouparg(&arg);
7346 if (arg == NULL) /* out of memory */
7347 return;
7348
7349 /*
7350 * Scan over the events.
7351 * If we find an illegal name, return here, don't do anything.
7352 */
7353 pat = find_end_event(arg, group != AUGROUP_ALL);
7354 if (pat == NULL)
7355 return;
7356
7357 /*
7358 * Scan over the pattern. Put a NUL at the end.
7359 */
7360 pat = skipwhite(pat);
7361 cmd = pat;
7362 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
7363 cmd++;
7364 if (*cmd)
7365 *cmd++ = NUL;
7366
7367 /* Expand environment variables in the pattern. Set 'shellslash', we want
7368 * forward slashes here. */
7369 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
7370 {
7371#ifdef BACKSLASH_IN_FILENAME
7372 int p_ssl_save = p_ssl;
7373
7374 p_ssl = TRUE;
7375#endif
7376 envpat = expand_env_save(pat);
7377#ifdef BACKSLASH_IN_FILENAME
7378 p_ssl = p_ssl_save;
7379#endif
7380 if (envpat != NULL)
7381 pat = envpat;
7382 }
7383
7384 /*
7385 * Check for "nested" flag.
7386 */
7387 cmd = skipwhite(cmd);
7388 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
7389 {
7390 nested = TRUE;
7391 cmd = skipwhite(cmd + 6);
7392 }
7393
7394 /*
7395 * Find the start of the commands.
7396 * Expand <sfile> in it.
7397 */
7398 if (*cmd != NUL)
7399 {
7400 cmd = expand_sfile(cmd);
7401 if (cmd == NULL) /* some error */
7402 return;
7403 need_free = TRUE;
7404 }
7405
7406 /*
7407 * Print header when showing autocommands.
7408 */
7409 if (!forceit && *cmd == NUL)
7410 {
7411 /* Highlight title */
7412 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
7413 }
7414
7415 /*
7416 * Loop over the events.
7417 */
7418 last_event = (EVENT_T)-1; /* for listing the event name */
7419 last_group = AUGROUP_ERROR; /* for listing the group name */
7420 if (*arg == '*' || *arg == NUL)
7421 {
7422 for (event = (EVENT_T)0; (int)event < (int)NUM_EVENTS;
7423 event = (EVENT_T)((int)event + 1))
7424 if (do_autocmd_event(event, pat,
7425 nested, cmd, forceit, group) == FAIL)
7426 break;
7427 }
7428 else
7429 {
7430 while (*arg && !vim_iswhite(*arg))
7431 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
7432 nested, cmd, forceit, group) == FAIL)
7433 break;
7434 }
7435
7436 if (need_free)
7437 vim_free(cmd);
7438 vim_free(envpat);
7439}
7440
7441/*
7442 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
7443 * The "argp" argument is advanced to the following argument.
7444 *
7445 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
7446 */
7447 static int
7448au_get_grouparg(argp)
7449 char_u **argp;
7450{
7451 char_u *group_name;
7452 char_u *p;
7453 char_u *arg = *argp;
7454 int group = AUGROUP_ALL;
7455
7456 p = skiptowhite(arg);
7457 if (p > arg)
7458 {
7459 group_name = vim_strnsave(arg, (int)(p - arg));
7460 if (group_name == NULL) /* out of memory */
7461 return AUGROUP_ERROR;
7462 group = au_find_group(group_name);
7463 if (group == AUGROUP_ERROR)
7464 group = AUGROUP_ALL; /* no match, use all groups */
7465 else
7466 *argp = skipwhite(p); /* match, skip over group name */
7467 vim_free(group_name);
7468 }
7469 return group;
7470}
7471
7472/*
7473 * do_autocmd() for one event.
7474 * If *pat == NUL do for all patterns.
7475 * If *cmd == NUL show entries.
7476 * If forceit == TRUE delete entries.
7477 * If group is not AUGROUP_ALL, only use this group.
7478 */
7479 static int
7480do_autocmd_event(event, pat, nested, cmd, forceit, group)
7481 EVENT_T event;
7482 char_u *pat;
7483 int nested;
7484 char_u *cmd;
7485 int forceit;
7486 int group;
7487{
7488 AutoPat *ap;
7489 AutoPat **prev_ap;
7490 AutoCmd *ac;
7491 AutoCmd **prev_ac;
7492 int brace_level;
7493 char_u *endpat;
7494 int findgroup;
7495 int allgroups;
7496 int patlen;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007497 int is_buflocal;
7498 int buflocal_nr;
7499 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500
7501 if (group == AUGROUP_ALL)
7502 findgroup = current_augroup;
7503 else
7504 findgroup = group;
7505 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
7506
7507 /*
7508 * Show or delete all patterns for an event.
7509 */
7510 if (*pat == NUL)
7511 {
7512 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7513 {
7514 if (forceit) /* delete the AutoPat, if it's in the current group */
7515 {
7516 if (ap->group == findgroup)
7517 au_remove_pat(ap);
7518 }
7519 else if (group == AUGROUP_ALL || ap->group == group)
7520 show_autocmd(ap, event);
7521 }
7522 }
7523
7524 /*
7525 * Loop through all the specified patterns.
7526 */
7527 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
7528 {
7529 /*
7530 * Find end of the pattern.
7531 * Watch out for a comma in braces, like "*.\{obj,o\}".
7532 */
7533 brace_level = 0;
7534 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
7535 || endpat[-1] == '\\'); ++endpat)
7536 {
7537 if (*endpat == '{')
7538 brace_level++;
7539 else if (*endpat == '}')
7540 brace_level--;
7541 }
7542 if (pat == endpat) /* ignore single comma */
7543 continue;
7544 patlen = (int)(endpat - pat);
7545
7546 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007547 * detect special <buflocal[=X]> buffer-local patterns
7548 */
7549 is_buflocal = FALSE;
7550 buflocal_nr = 0;
7551
7552 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
7553 && pat[patlen - 1] == '>')
7554 {
7555 /* Error will be printed only for addition. printing and removing
7556 * will proceed silently. */
7557 is_buflocal = TRUE;
7558 if (patlen == 8)
7559 buflocal_nr = curbuf->b_fnum;
7560 else if (patlen > 9 && pat[7] == '=')
7561 {
7562 /* <buffer=abuf> */
7563 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
7564 buflocal_nr = autocmd_bufnr;
7565 /* <buffer=123> */
7566 else if (skipdigits(pat + 8) == pat + patlen - 1)
7567 buflocal_nr = atoi((char *)pat + 8);
7568 }
7569 }
7570
7571 if (is_buflocal)
7572 {
7573 /* normalize pat into standard "<buffer>#N" form */
7574 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
7575 pat = buflocal_pat; /* can modify pat and patlen */
7576 patlen = STRLEN(buflocal_pat); /* but not endpat */
7577 }
7578
7579 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007580 * Find AutoPat entries with this pattern.
7581 */
7582 prev_ap = &first_autopat[(int)event];
7583 while ((ap = *prev_ap) != NULL)
7584 {
7585 if (ap->pat != NULL)
7586 {
7587 /* Accept a pattern when:
7588 * - a group was specified and it's that group, or a group was
7589 * not specified and it's the current group, or a group was
7590 * not specified and we are listing
7591 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007592 * - the pattern matches.
7593 * For <buffer[=X]>, this condition works because we normalize
7594 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595 */
7596 if ((allgroups || ap->group == findgroup)
7597 && ap->patlen == patlen
7598 && STRNCMP(pat, ap->pat, patlen) == 0)
7599 {
7600 /*
7601 * Remove existing autocommands.
7602 * If adding any new autocmd's for this AutoPat, don't
7603 * delete the pattern from the autopat list, append to
7604 * this list.
7605 */
7606 if (forceit)
7607 {
7608 if (*cmd != NUL && ap->next == NULL)
7609 {
7610 au_remove_cmds(ap);
7611 break;
7612 }
7613 au_remove_pat(ap);
7614 }
7615
7616 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007617 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00007618 */
7619 else if (*cmd == NUL)
7620 show_autocmd(ap, event);
7621
7622 /*
7623 * Add autocmd to this autopat, if it's the last one.
7624 */
7625 else if (ap->next == NULL)
7626 break;
7627 }
7628 }
7629 prev_ap = &ap->next;
7630 }
7631
7632 /*
7633 * Add a new command.
7634 */
7635 if (*cmd != NUL)
7636 {
7637 /*
7638 * If the pattern we want to add a command to does appear at the
7639 * end of the list (or not is not in the list at all), add the
7640 * pattern at the end of the list.
7641 */
7642 if (ap == NULL)
7643 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007644 /* refuse to add buffer-local ap if buffer number is invalid */
7645 if (is_buflocal && (buflocal_nr == 0
7646 || buflist_findnr(buflocal_nr) == NULL))
7647 {
7648 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
7649 buflocal_nr);
7650 return FAIL;
7651 }
7652
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
7654 if (ap == NULL)
7655 return FAIL;
7656 ap->pat = vim_strnsave(pat, patlen);
7657 ap->patlen = patlen;
7658 if (ap->pat == NULL)
7659 {
7660 vim_free(ap);
7661 return FAIL;
7662 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007663
7664 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007666 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007667 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007668 }
7669 else
7670 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00007671 char_u *reg_pat;
7672
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007673 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007674 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007675 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00007676 if (reg_pat != NULL)
7677 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007678 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00007679 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007680 {
7681 vim_free(ap->pat);
7682 vim_free(ap);
7683 return FAIL;
7684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685 }
7686 ap->cmds = NULL;
7687 *prev_ap = ap;
7688 ap->next = NULL;
7689 if (group == AUGROUP_ALL)
7690 ap->group = current_augroup;
7691 else
7692 ap->group = group;
7693 }
7694
7695 /*
7696 * Add the autocmd at the end of the AutoCmd list.
7697 */
7698 prev_ac = &(ap->cmds);
7699 while ((ac = *prev_ac) != NULL)
7700 prev_ac = &ac->next;
7701 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
7702 if (ac == NULL)
7703 return FAIL;
7704 ac->cmd = vim_strsave(cmd);
7705#ifdef FEAT_EVAL
7706 ac->scriptID = current_SID;
7707#endif
7708 if (ac->cmd == NULL)
7709 {
7710 vim_free(ac);
7711 return FAIL;
7712 }
7713 ac->next = NULL;
7714 *prev_ac = ac;
7715 ac->nested = nested;
7716 }
7717 }
7718
7719 au_cleanup(); /* may really delete removed patterns/commands now */
7720 return OK;
7721}
7722
7723/*
7724 * Implementation of ":doautocmd [group] event [fname]".
7725 * Return OK for success, FAIL for failure;
7726 */
7727 int
7728do_doautocmd(arg, do_msg)
7729 char_u *arg;
7730 int do_msg; /* give message for no matching autocmds? */
7731{
7732 char_u *fname;
7733 int nothing_done = TRUE;
7734 int group;
7735
7736 /*
7737 * Check for a legal group name. If not, use AUGROUP_ALL.
7738 */
7739 group = au_get_grouparg(&arg);
7740 if (arg == NULL) /* out of memory */
7741 return FAIL;
7742
7743 if (*arg == '*')
7744 {
7745 EMSG(_("E217: Can't execute autocommands for ALL events"));
7746 return FAIL;
7747 }
7748
7749 /*
7750 * Scan over the events.
7751 * If we find an illegal name, return here, don't do anything.
7752 */
7753 fname = find_end_event(arg, group != AUGROUP_ALL);
7754 if (fname == NULL)
7755 return FAIL;
7756
7757 fname = skipwhite(fname);
7758
7759 /*
7760 * Loop over the events.
7761 */
7762 while (*arg && !vim_iswhite(*arg))
7763 if (apply_autocmds_group(event_name2nr(arg, &arg),
7764 fname, NULL, TRUE, group, curbuf, NULL))
7765 nothing_done = FALSE;
7766
7767 if (nothing_done && do_msg)
7768 MSG(_("No matching autocommands"));
7769
7770#ifdef FEAT_EVAL
7771 return aborting() ? FAIL : OK;
7772#else
7773 return OK;
7774#endif
7775}
7776
7777/*
7778 * ":doautoall": execute autocommands for each loaded buffer.
7779 */
7780 void
7781ex_doautoall(eap)
7782 exarg_T *eap;
7783{
7784 int retval;
7785 aco_save_T aco;
7786 buf_T *buf;
7787
7788 /*
7789 * This is a bit tricky: For some commands curwin->w_buffer needs to be
7790 * equal to curbuf, but for some buffers there may not be a window.
7791 * So we change the buffer for the current window for a moment. This
7792 * gives problems when the autocommands make changes to the list of
7793 * buffers or windows...
7794 */
7795 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7796 {
7797 if (curbuf->b_ml.ml_mfp != NULL)
7798 {
7799 /* find a window for this buffer and save some values */
7800 aucmd_prepbuf(&aco, buf);
7801
7802 /* execute the autocommands for this buffer */
7803 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00007804 do_modelines(FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805
7806 /* restore the current window */
7807 aucmd_restbuf(&aco);
7808
7809 /* stop if there is some error or buffer was deleted */
7810 if (retval == FAIL || !buf_valid(buf))
7811 break;
7812 }
7813 }
7814
7815 check_cursor(); /* just in case lines got deleted */
7816}
7817
7818/*
7819 * Prepare for executing autocommands for (hidden) buffer "buf".
7820 * Search a window for the current buffer. Save the cursor position and
7821 * screen offset.
7822 * Set "curbuf" and "curwin" to match "buf".
7823 */
7824 void
7825aucmd_prepbuf(aco, buf)
7826 aco_save_T *aco; /* structure to save values in */
7827 buf_T *buf; /* new curbuf */
7828{
7829 win_T *win;
7830
7831 aco->new_curbuf = buf;
7832
7833 /* Find a window that is for the new buffer */
7834 if (buf == curbuf) /* be quick when buf is curbuf */
7835 win = curwin;
7836 else
7837#ifdef FEAT_WINDOWS
7838 for (win = firstwin; win != NULL; win = win->w_next)
7839 if (win->w_buffer == buf)
7840 break;
7841#else
7842 win = NULL;
7843#endif
7844
7845 /*
7846 * Prefer to use an existing window for the buffer, it has the least side
7847 * effects (esp. if "buf" is curbuf).
7848 * Otherwise, use curwin for "buf". It might make some items in the
7849 * window invalid. At least save the cursor and topline.
7850 */
7851 if (win != NULL)
7852 {
7853 /* there is a window for "buf", make it the curwin */
7854 aco->save_curwin = curwin;
7855 curwin = win;
7856 aco->save_buf = win->w_buffer;
7857 aco->new_curwin = win;
7858 }
7859 else
7860 {
7861 /* there is no window for "buf", use curwin */
7862 aco->save_curwin = NULL;
7863 aco->save_buf = curbuf;
7864 --curbuf->b_nwindows;
7865 curwin->w_buffer = buf;
7866 ++buf->b_nwindows;
7867
7868 /* save cursor and topline, set them to safe values */
7869 aco->save_cursor = curwin->w_cursor;
7870 curwin->w_cursor.lnum = 1;
7871 curwin->w_cursor.col = 0;
7872 aco->save_topline = curwin->w_topline;
7873 curwin->w_topline = 1;
7874#ifdef FEAT_DIFF
7875 aco->save_topfill = curwin->w_topfill;
7876 curwin->w_topfill = 0;
7877#endif
7878 }
7879
7880 curbuf = buf;
7881}
7882
7883/*
7884 * Cleanup after executing autocommands for a (hidden) buffer.
7885 * Restore the window as it was (if possible).
7886 */
7887 void
7888aucmd_restbuf(aco)
7889 aco_save_T *aco; /* structure holding saved values */
7890{
7891 if (aco->save_curwin != NULL)
7892 {
7893 /* restore curwin */
7894#ifdef FEAT_WINDOWS
7895 if (win_valid(aco->save_curwin))
7896#endif
7897 {
7898 /* restore the buffer which was previously edited by curwin, if
7899 * it's still the same window and it's valid */
7900 if (curwin == aco->new_curwin
7901 && buf_valid(aco->save_buf)
7902 && aco->save_buf->b_ml.ml_mfp != NULL)
7903 {
7904 --curbuf->b_nwindows;
7905 curbuf = aco->save_buf;
7906 curwin->w_buffer = curbuf;
7907 ++curbuf->b_nwindows;
7908 }
7909
7910 curwin = aco->save_curwin;
7911 curbuf = curwin->w_buffer;
7912 }
7913 }
7914 else
7915 {
7916 /* restore buffer for curwin if it still exists and is loaded */
7917 if (buf_valid(aco->save_buf) && aco->save_buf->b_ml.ml_mfp != NULL)
7918 {
7919 --curbuf->b_nwindows;
7920 curbuf = aco->save_buf;
7921 curwin->w_buffer = curbuf;
7922 ++curbuf->b_nwindows;
7923 curwin->w_cursor = aco->save_cursor;
7924 check_cursor();
7925 /* check topline < line_count, in case lines got deleted */
7926 if (aco->save_topline <= curbuf->b_ml.ml_line_count)
7927 {
7928 curwin->w_topline = aco->save_topline;
7929#ifdef FEAT_DIFF
7930 curwin->w_topfill = aco->save_topfill;
7931#endif
7932 }
7933 else
7934 {
7935 curwin->w_topline = curbuf->b_ml.ml_line_count;
7936#ifdef FEAT_DIFF
7937 curwin->w_topfill = 0;
7938#endif
7939 }
7940 }
7941 }
7942}
7943
7944static int autocmd_nested = FALSE;
7945
7946/*
7947 * Execute autocommands for "event" and file name "fname".
7948 * Return TRUE if some commands were executed.
7949 */
7950 int
7951apply_autocmds(event, fname, fname_io, force, buf)
7952 EVENT_T event;
7953 char_u *fname; /* NULL or empty means use actual file name */
7954 char_u *fname_io; /* fname to use for <afile> on cmdline */
7955 int force; /* when TRUE, ignore autocmd_busy */
7956 buf_T *buf; /* buffer for <abuf> */
7957{
7958 return apply_autocmds_group(event, fname, fname_io, force,
7959 AUGROUP_ALL, buf, NULL);
7960}
7961
7962/*
7963 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
7964 * setting v:filearg.
7965 */
7966 static int
7967apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
7968 EVENT_T event;
7969 char_u *fname;
7970 char_u *fname_io;
7971 int force;
7972 buf_T *buf;
7973 exarg_T *eap;
7974{
7975 return apply_autocmds_group(event, fname, fname_io, force,
7976 AUGROUP_ALL, buf, eap);
7977}
7978
7979/*
7980 * Like apply_autocmds(), but handles the caller's retval. If the script
7981 * processing is being aborted or if retval is FAIL when inside a try
7982 * conditional, no autocommands are executed. If otherwise the autocommands
7983 * cause the script to be aborted, retval is set to FAIL.
7984 */
7985 int
7986apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
7987 EVENT_T event;
7988 char_u *fname; /* NULL or empty means use actual file name */
7989 char_u *fname_io; /* fname to use for <afile> on cmdline */
7990 int force; /* when TRUE, ignore autocmd_busy */
7991 buf_T *buf; /* buffer for <abuf> */
7992 int *retval; /* pointer to caller's retval */
7993{
7994 int did_cmd;
7995
Bram Moolenaar1e015462005-09-25 22:16:38 +00007996#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997 if (should_abort(*retval))
7998 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00007999#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008000
8001 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8002 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008003 if (did_cmd
8004#ifdef FEAT_EVAL
8005 && aborting()
8006#endif
8007 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008008 *retval = FAIL;
8009 return did_cmd;
8010}
8011
8012#if defined(FEAT_AUTOCMD) || defined(PROTO)
8013 int
8014has_cursorhold()
8015{
8016 return (first_autopat[(int)EVENT_CURSORHOLD] != NULL);
8017}
8018#endif
8019
8020 static int
8021apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
8022 EVENT_T event;
8023 char_u *fname; /* NULL or empty means use actual file name */
8024 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
8025 use fname */
8026 int force; /* when TRUE, ignore autocmd_busy */
8027 int group; /* group ID, or AUGROUP_ALL */
8028 buf_T *buf; /* buffer for <abuf> */
8029 exarg_T *eap; /* command arguments */
8030{
8031 char_u *sfname = NULL; /* short file name */
8032 char_u *tail;
8033 int save_changed;
8034 buf_T *old_curbuf;
8035 int retval = FALSE;
8036 char_u *save_sourcing_name;
8037 linenr_T save_sourcing_lnum;
8038 char_u *save_autocmd_fname;
8039 int save_autocmd_bufnr;
8040 char_u *save_autocmd_match;
8041 int save_autocmd_busy;
8042 int save_autocmd_nested;
8043 static int nesting = 0;
8044 AutoPatCmd patcmd;
8045 AutoPat *ap;
8046#ifdef FEAT_EVAL
8047 scid_T save_current_SID;
8048 void *save_funccalp;
8049 char_u *save_cmdarg;
8050 long save_cmdbang;
8051#endif
8052 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00008053#ifdef FEAT_PROFILE
8054 proftime_T wait_time;
8055#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008056
8057 /*
8058 * Quickly return if there are no autocommands for this event or
8059 * autocommands are blocked.
8060 */
8061 if (first_autopat[(int)event] == NULL || autocmd_block > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008062 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008063
8064 /*
8065 * When autocommands are busy, new autocommands are only executed when
8066 * explicitly enabled with the "nested" flag.
8067 */
8068 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008069 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008070
8071#ifdef FEAT_EVAL
8072 /*
8073 * Quickly return when immdediately aborting on error, or when an interrupt
8074 * occurred or an exception was thrown but not caught.
8075 */
8076 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008077 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008078#endif
8079
8080 /*
8081 * FileChangedShell never nests, because it can create an endless loop.
8082 */
8083 if (filechangeshell_busy && event == EVENT_FILECHANGEDSHELL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008084 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008085
8086 /*
8087 * Ignore events in 'eventignore'.
8088 */
8089 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008090 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008091
8092 /*
8093 * Allow nesting of autocommands, but restrict the depth, because it's
8094 * possible to create an endless loop.
8095 */
8096 if (nesting == 10)
8097 {
8098 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008099 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008100 }
8101
8102 /*
8103 * Check if these autocommands are disabled. Used when doing ":all" or
8104 * ":ball".
8105 */
8106 if ( (autocmd_no_enter
8107 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
8108 || (autocmd_no_leave
8109 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008110 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008111
8112 /*
8113 * Save the autocmd_* variables and info about the current buffer.
8114 */
8115 save_autocmd_fname = autocmd_fname;
8116 save_autocmd_bufnr = autocmd_bufnr;
8117 save_autocmd_match = autocmd_match;
8118 save_autocmd_busy = autocmd_busy;
8119 save_autocmd_nested = autocmd_nested;
8120 save_changed = curbuf->b_changed;
8121 old_curbuf = curbuf;
8122
8123 /*
8124 * Set the file name to be used for <afile>.
8125 */
8126 if (fname_io == NULL)
8127 {
8128 if (fname != NULL && *fname != NUL)
8129 autocmd_fname = fname;
8130 else if (buf != NULL)
8131 autocmd_fname = buf->b_fname;
8132 else
8133 autocmd_fname = NULL;
8134 }
8135 else
8136 autocmd_fname = fname_io;
8137
8138 /*
8139 * Set the buffer number to be used for <abuf>.
8140 */
8141 if (buf == NULL)
8142 autocmd_bufnr = 0;
8143 else
8144 autocmd_bufnr = buf->b_fnum;
8145
8146 /*
8147 * When the file name is NULL or empty, use the file name of buffer "buf".
8148 * Always use the full path of the file name to match with, in case
8149 * "allow_dirs" is set.
8150 */
8151 if (fname == NULL || *fname == NUL)
8152 {
8153 if (buf == NULL)
8154 fname = NULL;
8155 else
8156 {
8157#ifdef FEAT_SYN_HL
8158 if (event == EVENT_SYNTAX)
8159 fname = buf->b_p_syn;
8160 else
8161#endif
8162 if (event == EVENT_FILETYPE)
8163 fname = buf->b_p_ft;
8164 else
8165 {
8166 if (buf->b_sfname != NULL)
8167 sfname = vim_strsave(buf->b_sfname);
8168 fname = buf->b_ffname;
8169 }
8170 }
8171 if (fname == NULL)
8172 fname = (char_u *)"";
8173 fname = vim_strsave(fname); /* make a copy, so we can change it */
8174 }
8175 else
8176 {
8177 sfname = vim_strsave(fname);
Bram Moolenaar7c626922005-02-07 22:01:03 +00008178 /* Don't try expanding FileType, Syntax, WindowID or QuickFixCmd* */
8179 if (event == EVENT_FILETYPE
8180 || event == EVENT_SYNTAX
8181 || event == EVENT_REMOTEREPLY
8182 || event == EVENT_QUICKFIXCMDPRE
8183 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008184 fname = vim_strsave(fname);
8185 else
8186 fname = FullName_save(fname, FALSE);
8187 }
8188 if (fname == NULL) /* out of memory */
8189 {
8190 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008191 retval = FALSE;
8192 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008193 }
8194
8195#ifdef BACKSLASH_IN_FILENAME
8196 /*
8197 * Replace all backslashes with forward slashes. This makes the
8198 * autocommand patterns portable between Unix and MS-DOS.
8199 */
8200 if (sfname != NULL)
8201 forward_slash(sfname);
8202 forward_slash(fname);
8203#endif
8204
8205#ifdef VMS
8206 /* remove version for correct match */
8207 if (sfname != NULL)
8208 vms_remove_version(sfname);
8209 vms_remove_version(fname);
8210#endif
8211
8212 /*
8213 * Set the name to be used for <amatch>.
8214 */
8215 autocmd_match = fname;
8216
8217
8218 /* Don't redraw while doing auto commands. */
8219 ++RedrawingDisabled;
8220 save_sourcing_name = sourcing_name;
8221 sourcing_name = NULL; /* don't free this one */
8222 save_sourcing_lnum = sourcing_lnum;
8223 sourcing_lnum = 0; /* no line number here */
8224
8225#ifdef FEAT_EVAL
8226 save_current_SID = current_SID;
8227
Bram Moolenaar05159a02005-02-26 23:04:13 +00008228# ifdef FEAT_PROFILE
8229 if (do_profiling)
8230 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
8231# endif
8232
Bram Moolenaar071d4272004-06-13 20:20:40 +00008233 /* Don't use local function variables, if called from a function */
8234 save_funccalp = save_funccal();
8235#endif
8236
8237 /*
8238 * When starting to execute autocommands, save the search patterns.
8239 */
8240 if (!autocmd_busy)
8241 {
8242 save_search_patterns();
8243 saveRedobuff();
8244 did_filetype = keep_filetype;
8245 }
8246
8247 /*
8248 * Note that we are applying autocmds. Some commands need to know.
8249 */
8250 autocmd_busy = TRUE;
8251 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
8252 ++nesting; /* see matching decrement below */
8253
8254 /* Remember that FileType was triggered. Used for did_filetype(). */
8255 if (event == EVENT_FILETYPE)
8256 did_filetype = TRUE;
8257
8258 tail = gettail(fname);
8259
8260 /* Find first autocommand that matches */
8261 patcmd.curpat = first_autopat[(int)event];
8262 patcmd.nextcmd = NULL;
8263 patcmd.group = group;
8264 patcmd.fname = fname;
8265 patcmd.sfname = sfname;
8266 patcmd.tail = tail;
8267 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008268 patcmd.arg_bufnr = autocmd_bufnr;
8269 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008270 auto_next_pat(&patcmd, FALSE);
8271
8272 /* found one, start executing the autocommands */
8273 if (patcmd.curpat != NULL)
8274 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008275 /* add to active_apc_list */
8276 patcmd.next = active_apc_list;
8277 active_apc_list = &patcmd;
8278
Bram Moolenaar071d4272004-06-13 20:20:40 +00008279#ifdef FEAT_EVAL
8280 /* set v:cmdarg (only when there is a matching pattern) */
8281 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
8282 if (eap != NULL)
8283 {
8284 save_cmdarg = set_cmdarg(eap, NULL);
8285 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
8286 }
8287 else
8288 save_cmdarg = NULL; /* avoid gcc warning */
8289#endif
8290 retval = TRUE;
8291 /* mark the last pattern, to avoid an endless loop when more patterns
8292 * are added when executing autocommands */
8293 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
8294 ap->last = FALSE;
8295 ap->last = TRUE;
8296 check_lnums(TRUE); /* make sure cursor and topline are valid */
8297 do_cmdline(NULL, getnextac, (void *)&patcmd,
8298 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
8299#ifdef FEAT_EVAL
8300 if (eap != NULL)
8301 {
8302 (void)set_cmdarg(NULL, save_cmdarg);
8303 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
8304 }
8305#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008306 /* delete from active_apc_list */
8307 if (active_apc_list == &patcmd) /* just in case */
8308 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309 }
8310
8311 --RedrawingDisabled;
8312 autocmd_busy = save_autocmd_busy;
8313 filechangeshell_busy = FALSE;
8314 autocmd_nested = save_autocmd_nested;
8315 vim_free(sourcing_name);
8316 sourcing_name = save_sourcing_name;
8317 sourcing_lnum = save_sourcing_lnum;
8318 autocmd_fname = save_autocmd_fname;
8319 autocmd_bufnr = save_autocmd_bufnr;
8320 autocmd_match = save_autocmd_match;
8321#ifdef FEAT_EVAL
8322 current_SID = save_current_SID;
8323 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00008324# ifdef FEAT_PROFILE
8325 if (do_profiling)
8326 prof_child_exit(&wait_time);
8327# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328#endif
8329 vim_free(fname);
8330 vim_free(sfname);
8331 --nesting; /* see matching increment above */
8332
8333 /*
8334 * When stopping to execute autocommands, restore the search patterns and
8335 * the redo buffer.
8336 */
8337 if (!autocmd_busy)
8338 {
8339 restore_search_patterns();
8340 restoreRedobuff();
8341 did_filetype = FALSE;
8342 }
8343
8344 /*
8345 * Some events don't set or reset the Changed flag.
8346 * Check if still in the same buffer!
8347 */
8348 if (curbuf == old_curbuf
8349 && (event == EVENT_BUFREADPOST
8350 || event == EVENT_BUFWRITEPOST
8351 || event == EVENT_FILEAPPENDPOST
8352 || event == EVENT_VIMLEAVE
8353 || event == EVENT_VIMLEAVEPRE))
8354 {
8355#ifdef FEAT_TITLE
8356 if (curbuf->b_changed != save_changed)
8357 need_maketitle = TRUE;
8358#endif
8359 curbuf->b_changed = save_changed;
8360 }
8361
8362 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008363
8364BYPASS_AU:
8365 /* When wiping out a buffer make sure all its buffer-local autocommands
8366 * are deleted. */
8367 if (event == EVENT_BUFWIPEOUT && buf != NULL)
8368 aubuflocal_remove(buf);
8369
Bram Moolenaar071d4272004-06-13 20:20:40 +00008370 return retval;
8371}
8372
8373/*
8374 * Find next autocommand pattern that matches.
8375 */
8376 static void
8377auto_next_pat(apc, stop_at_last)
8378 AutoPatCmd *apc;
8379 int stop_at_last; /* stop when 'last' flag is set */
8380{
8381 AutoPat *ap;
8382 AutoCmd *cp;
8383 char_u *name;
8384 char *s;
8385
8386 vim_free(sourcing_name);
8387 sourcing_name = NULL;
8388
8389 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
8390 {
8391 apc->curpat = NULL;
8392
8393 /* only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008394 * the group matches. For buffer-local autocommands only check the
8395 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008396 if (ap->pat != NULL && ap->cmds != NULL
8397 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
8398 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008399 /* execution-condition */
8400 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00008401 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
8402 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008403 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008404 {
8405 name = event_nr2name(apc->event);
8406 s = _("%s Auto commands for \"%s\"");
8407 sourcing_name = alloc((unsigned)(STRLEN(s)
8408 + STRLEN(name) + ap->patlen + 1));
8409 if (sourcing_name != NULL)
8410 {
8411 sprintf((char *)sourcing_name, s,
8412 (char *)name, (char *)ap->pat);
8413 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008414 {
8415 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00008416 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008417 verbose_leave();
8418 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008419 }
8420
8421 apc->curpat = ap;
8422 apc->nextcmd = ap->cmds;
8423 /* mark last command */
8424 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
8425 cp->last = FALSE;
8426 cp->last = TRUE;
8427 }
8428 line_breakcheck();
8429 if (apc->curpat != NULL) /* found a match */
8430 break;
8431 }
8432 if (stop_at_last && ap->last)
8433 break;
8434 }
8435}
8436
8437/*
8438 * Get next autocommand command.
8439 * Called by do_cmdline() to get the next line for ":if".
8440 * Returns allocated string, or NULL for end of autocommands.
8441 */
8442/* ARGSUSED */
8443 static char_u *
8444getnextac(c, cookie, indent)
8445 int c; /* not used */
8446 void *cookie;
8447 int indent; /* not used */
8448{
8449 AutoPatCmd *acp = (AutoPatCmd *)cookie;
8450 char_u *retval;
8451 AutoCmd *ac;
8452
8453 /* Can be called again after returning the last line. */
8454 if (acp->curpat == NULL)
8455 return NULL;
8456
8457 /* repeat until we find an autocommand to execute */
8458 for (;;)
8459 {
8460 /* skip removed commands */
8461 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
8462 if (acp->nextcmd->last)
8463 acp->nextcmd = NULL;
8464 else
8465 acp->nextcmd = acp->nextcmd->next;
8466
8467 if (acp->nextcmd != NULL)
8468 break;
8469
8470 /* at end of commands, find next pattern that matches */
8471 if (acp->curpat->last)
8472 acp->curpat = NULL;
8473 else
8474 acp->curpat = acp->curpat->next;
8475 if (acp->curpat != NULL)
8476 auto_next_pat(acp, TRUE);
8477 if (acp->curpat == NULL)
8478 return NULL;
8479 }
8480
8481 ac = acp->nextcmd;
8482
8483 if (p_verbose >= 9)
8484 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008485 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00008486 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008487 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008488 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00008489 }
8490 retval = vim_strsave(ac->cmd);
8491 autocmd_nested = ac->nested;
8492#ifdef FEAT_EVAL
8493 current_SID = ac->scriptID;
8494#endif
8495 if (ac->last)
8496 acp->nextcmd = NULL;
8497 else
8498 acp->nextcmd = ac->next;
8499 return retval;
8500}
8501
8502/*
8503 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008504 * To account for buffer-local autocommands, function needs to know
8505 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008506 */
8507 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008508has_autocmd(event, sfname, buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008509 EVENT_T event;
8510 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008511 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008512{
8513 AutoPat *ap;
8514 char_u *fname;
8515 char_u *tail = gettail(sfname);
8516 int retval = FALSE;
8517
8518 fname = FullName_save(sfname, FALSE);
8519 if (fname == NULL)
8520 return FALSE;
8521
8522#ifdef BACKSLASH_IN_FILENAME
8523 /*
8524 * Replace all backslashes with forward slashes. This makes the
8525 * autocommand patterns portable between Unix and MS-DOS.
8526 */
8527 sfname = vim_strsave(sfname);
8528 if (sfname != NULL)
8529 forward_slash(sfname);
8530 forward_slash(fname);
8531#endif
8532
8533 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8534 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008535 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00008536 ? match_file_pat(NULL, ap->reg_prog,
8537 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008538 : buf != NULL && ap->buflocal_nr == buf->b_fnum
8539 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 {
8541 retval = TRUE;
8542 break;
8543 }
8544
8545 vim_free(fname);
8546#ifdef BACKSLASH_IN_FILENAME
8547 vim_free(sfname);
8548#endif
8549
8550 return retval;
8551}
8552
8553#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
8554/*
8555 * Function given to ExpandGeneric() to obtain the list of autocommand group
8556 * names.
8557 */
8558/*ARGSUSED*/
8559 char_u *
8560get_augroup_name(xp, idx)
8561 expand_T *xp;
8562 int idx;
8563{
8564 if (idx == augroups.ga_len) /* add "END" add the end */
8565 return (char_u *)"END";
8566 if (idx >= augroups.ga_len) /* end of list */
8567 return NULL;
8568 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
8569 return (char_u *)"";
8570 return AUGROUP_NAME(idx); /* return a name */
8571}
8572
8573static int include_groups = FALSE;
8574
8575 char_u *
8576set_context_in_autocmd(xp, arg, doautocmd)
8577 expand_T *xp;
8578 char_u *arg;
8579 int doautocmd; /* TRUE for :doautocmd, FALSE for :autocmd */
8580{
8581 char_u *p;
8582 int group;
8583
8584 /* check for a group name, skip it if present */
8585 include_groups = FALSE;
8586 p = arg;
8587 group = au_get_grouparg(&arg);
8588 if (group == AUGROUP_ERROR)
8589 return NULL;
8590 /* If there only is a group name that's what we expand. */
8591 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
8592 {
8593 arg = p;
8594 group = AUGROUP_ALL;
8595 }
8596
8597 /* skip over event name */
8598 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
8599 if (*p == ',')
8600 arg = p + 1;
8601 if (*p == NUL)
8602 {
8603 if (group == AUGROUP_ALL)
8604 include_groups = TRUE;
8605 xp->xp_context = EXPAND_EVENTS; /* expand event name */
8606 xp->xp_pattern = arg;
8607 return NULL;
8608 }
8609
8610 /* skip over pattern */
8611 arg = skipwhite(p);
8612 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
8613 arg++;
8614 if (*arg)
8615 return arg; /* expand (next) command */
8616
8617 if (doautocmd)
8618 xp->xp_context = EXPAND_FILES; /* expand file names */
8619 else
8620 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
8621 return NULL;
8622}
8623
8624/*
8625 * Function given to ExpandGeneric() to obtain the list of event names.
8626 */
8627/*ARGSUSED*/
8628 char_u *
8629get_event_name(xp, idx)
8630 expand_T *xp;
8631 int idx;
8632{
8633 if (idx < augroups.ga_len) /* First list group names, if wanted */
8634 {
8635 if (!include_groups || AUGROUP_NAME(idx) == NULL)
8636 return (char_u *)""; /* skip deleted entries */
8637 return AUGROUP_NAME(idx); /* return a name */
8638 }
8639 return (char_u *)event_names[idx - augroups.ga_len].name;
8640}
8641
8642#endif /* FEAT_CMDL_COMPL */
8643
8644/*
8645 * Return TRUE if an autocommand is defined for "event" and "pattern".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008646 * "pattern" can be NULL to accept any pattern. Buffer-local patterns
8647 * <buffer> or <buffer=N> are accepted.
8648 * Used for exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00008649 */
8650 int
8651au_exists(name, name_end, pattern)
8652 char_u *name;
8653 char_u *name_end;
8654 char_u *pattern;
8655{
8656 char_u *event_name;
8657 char_u *p;
8658 EVENT_T event;
8659 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008660 buf_T *buflocal_buf = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008661
8662 /* find the index (enum) for the event name */
8663 event_name = vim_strnsave(name, (int)(name_end - name));
8664 if (event_name == NULL)
8665 return FALSE;
8666 event = event_name2nr(event_name, &p);
8667 vim_free(event_name);
8668
8669 /* return FALSE if the event name is not recognized */
8670 if (event == NUM_EVENTS) /* unknown event name */
8671 return FALSE;
8672
8673 /* Find the first autocommand for this event.
8674 * If there isn't any, return FALSE;
8675 * If there is one and no pattern given, return TRUE; */
8676 ap = first_autopat[(int)event];
8677 if (ap == NULL)
8678 return FALSE;
8679 if (pattern == NULL)
8680 return TRUE;
8681
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008682 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
8683 /* for pattern "<buffer=N>, fnamecmp() will work fine */
8684 if (STRICMP(pattern, "<buffer>") == 0)
8685 buflocal_buf = curbuf;
8686
Bram Moolenaar071d4272004-06-13 20:20:40 +00008687 /* Check if there is an autocommand with the given pattern. */
8688 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008689 /* only use a pattern when it has not been removed and has commands. */
8690 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008691 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008692 && (buflocal_buf == NULL
8693 ? fnamecmp(ap->pat, pattern) == 0
8694 : ap->buflocal_nr == buflocal_buf->b_fnum))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008695 return TRUE;
8696
8697 return FALSE;
8698}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008699
Bram Moolenaar071d4272004-06-13 20:20:40 +00008700#endif /* FEAT_AUTOCMD */
8701
8702#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
8703/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00008704 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
8705 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
8706 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008707 * Used for autocommands and 'wildignore'.
8708 * Returns TRUE if there is a match, FALSE otherwise.
8709 */
8710 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00008711match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008712 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00008713 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008714 char_u *fname; /* full path of file name */
8715 char_u *sfname; /* short file name or NULL */
8716 char_u *tail; /* tail of path */
8717 int allow_dirs; /* allow matching with dir */
8718{
8719 regmatch_T regmatch;
8720 int result = FALSE;
8721#ifdef FEAT_OSFILETYPE
8722 int no_pattern = FALSE; /* TRUE if check is filetype only */
8723 char_u *type_start;
8724 char_u c;
8725 int match = FALSE;
8726#endif
8727
8728#ifdef CASE_INSENSITIVE_FILENAME
8729 regmatch.rm_ic = TRUE; /* Always ignore case */
8730#else
8731 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
8732#endif
8733#ifdef FEAT_OSFILETYPE
8734 if (*pattern == '<')
8735 {
8736 /* There is a filetype condition specified with this pattern.
8737 * Check the filetype matches first. If not, don't bother with the
8738 * pattern (set regprog to NULL).
8739 * Always use magic for the regexp.
8740 */
8741
8742 for (type_start = pattern + 1; (c = *pattern); pattern++)
8743 {
8744 if ((c == ';' || c == '>') && match == FALSE)
8745 {
8746 *pattern = NUL; /* Terminate the string */
8747 match = mch_check_filetype(fname, type_start);
8748 *pattern = c; /* Restore the terminator */
8749 type_start = pattern + 1;
8750 }
8751 if (c == '>')
8752 break;
8753 }
8754
8755 /* (c should never be NUL, but check anyway) */
8756 if (match == FALSE || c == NUL)
8757 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
8758 else if (*pattern == NUL)
8759 {
8760 regmatch.regprog = NULL; /* Vim will try to free regprog later */
8761 no_pattern = TRUE; /* Always matches - don't check pat. */
8762 }
8763 else
8764 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
8765 }
8766 else
8767#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00008768 {
8769 if (prog != NULL)
8770 regmatch.regprog = prog;
8771 else
8772 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
8773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008774
8775 /*
8776 * Try for a match with the pattern with:
8777 * 1. the full file name, when the pattern has a '/'.
8778 * 2. the short file name, when the pattern has a '/'.
8779 * 3. the tail of the file name, when the pattern has no '/'.
8780 */
8781 if (
8782#ifdef FEAT_OSFILETYPE
8783 /* If the check is for a filetype only and we don't care
8784 * about the path then skip all the regexp stuff.
8785 */
8786 no_pattern ||
8787#endif
8788 (regmatch.regprog != NULL
8789 && ((allow_dirs
8790 && (vim_regexec(&regmatch, fname, (colnr_T)0)
8791 || (sfname != NULL
8792 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
8793 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
8794 result = TRUE;
8795
Bram Moolenaar748bf032005-02-02 23:04:36 +00008796 if (prog == NULL)
8797 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008798 return result;
8799}
8800#endif
8801
8802#if defined(FEAT_WILDIGN) || defined(PROTO)
8803/*
8804 * Return TRUE if a file matches with a pattern in "list".
8805 * "list" is a comma-separated list of patterns, like 'wildignore'.
8806 * "sfname" is the short file name or NULL, "ffname" the long file name.
8807 */
8808 int
8809match_file_list(list, sfname, ffname)
8810 char_u *list;
8811 char_u *sfname;
8812 char_u *ffname;
8813{
8814 char_u buf[100];
8815 char_u *tail;
8816 char_u *regpat;
8817 char allow_dirs;
8818 int match;
8819 char_u *p;
8820
8821 tail = gettail(sfname);
8822
8823 /* try all patterns in 'wildignore' */
8824 p = list;
8825 while (*p)
8826 {
8827 copy_option_part(&p, buf, 100, ",");
8828 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
8829 if (regpat == NULL)
8830 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008831 match = match_file_pat(regpat, NULL, ffname, sfname,
8832 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008833 vim_free(regpat);
8834 if (match)
8835 return TRUE;
8836 }
8837 return FALSE;
8838}
8839#endif
8840
8841/*
8842 * Convert the given pattern "pat" which has shell style wildcards in it, into
8843 * a regular expression, and return the result in allocated memory. If there
8844 * is a directory path separator to be matched, then TRUE is put in
8845 * allow_dirs, otherwise FALSE is put there -- webb.
8846 * Handle backslashes before special characters, like "\*" and "\ ".
8847 *
8848 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
8849 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
8850 *
8851 * Returns NULL when out of memory.
8852 */
8853/*ARGSUSED*/
8854 char_u *
8855file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
8856 char_u *pat;
8857 char_u *pat_end; /* first char after pattern or NULL */
8858 char *allow_dirs; /* Result passed back out in here */
8859 int no_bslash; /* Don't use a backward slash as pathsep */
8860{
8861 int size;
8862 char_u *endp;
8863 char_u *reg_pat;
8864 char_u *p;
8865 int i;
8866 int nested = 0;
8867 int add_dollar = TRUE;
8868#ifdef FEAT_OSFILETYPE
8869 int check_length = 0;
8870#endif
8871
8872 if (allow_dirs != NULL)
8873 *allow_dirs = FALSE;
8874 if (pat_end == NULL)
8875 pat_end = pat + STRLEN(pat);
8876
8877#ifdef FEAT_OSFILETYPE
8878 /* Find out how much of the string is the filetype check */
8879 if (*pat == '<')
8880 {
8881 /* Count chars until the next '>' */
8882 for (p = pat + 1; p < pat_end && *p != '>'; p++)
8883 ;
8884 if (p < pat_end)
8885 {
8886 /* Pattern is of the form <.*>.* */
8887 check_length = p - pat + 1;
8888 if (p + 1 >= pat_end)
8889 {
8890 /* The 'pattern' is a filetype check ONLY */
8891 reg_pat = (char_u *)alloc(check_length + 1);
8892 if (reg_pat != NULL)
8893 {
8894 mch_memmove(reg_pat, pat, (size_t)check_length);
8895 reg_pat[check_length] = NUL;
8896 }
8897 return reg_pat;
8898 }
8899 }
8900 /* else: there was no closing '>' - assume it was a normal pattern */
8901
8902 }
8903 pat += check_length;
8904 size = 2 + check_length;
8905#else
8906 size = 2; /* '^' at start, '$' at end */
8907#endif
8908
8909 for (p = pat; p < pat_end; p++)
8910 {
8911 switch (*p)
8912 {
8913 case '*':
8914 case '.':
8915 case ',':
8916 case '{':
8917 case '}':
8918 case '~':
8919 size += 2; /* extra backslash */
8920 break;
8921#ifdef BACKSLASH_IN_FILENAME
8922 case '\\':
8923 case '/':
8924 size += 4; /* could become "[\/]" */
8925 break;
8926#endif
8927 default:
8928 size++;
8929# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008930 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931 {
8932 ++p;
8933 ++size;
8934 }
8935# endif
8936 break;
8937 }
8938 }
8939 reg_pat = alloc(size + 1);
8940 if (reg_pat == NULL)
8941 return NULL;
8942
8943#ifdef FEAT_OSFILETYPE
8944 /* Copy the type check in to the start. */
8945 if (check_length)
8946 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
8947 i = check_length;
8948#else
8949 i = 0;
8950#endif
8951
8952 if (pat[0] == '*')
8953 while (pat[0] == '*' && pat < pat_end - 1)
8954 pat++;
8955 else
8956 reg_pat[i++] = '^';
8957 endp = pat_end - 1;
8958 if (*endp == '*')
8959 {
8960 while (endp - pat > 0 && *endp == '*')
8961 endp--;
8962 add_dollar = FALSE;
8963 }
8964 for (p = pat; *p && nested >= 0 && p <= endp; p++)
8965 {
8966 switch (*p)
8967 {
8968 case '*':
8969 reg_pat[i++] = '.';
8970 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +00008971 while (p[1] == '*') /* "**" matches like "*" */
8972 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008973 break;
8974 case '.':
8975#ifdef RISCOS
8976 if (allow_dirs != NULL)
8977 *allow_dirs = TRUE;
8978 /* FALLTHROUGH */
8979#endif
8980 case '~':
8981 reg_pat[i++] = '\\';
8982 reg_pat[i++] = *p;
8983 break;
8984 case '?':
8985#ifdef RISCOS
8986 case '#':
8987#endif
8988 reg_pat[i++] = '.';
8989 break;
8990 case '\\':
8991 if (p[1] == NUL)
8992 break;
8993#ifdef BACKSLASH_IN_FILENAME
8994 if (!no_bslash)
8995 {
8996 /* translate:
8997 * "\x" to "\\x" e.g., "dir\file"
8998 * "\*" to "\\.*" e.g., "dir\*.c"
8999 * "\?" to "\\." e.g., "dir\??.c"
9000 * "\+" to "\+" e.g., "fileX\+.c"
9001 */
9002 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
9003 && p[1] != '+')
9004 {
9005 reg_pat[i++] = '[';
9006 reg_pat[i++] = '\\';
9007 reg_pat[i++] = '/';
9008 reg_pat[i++] = ']';
9009 if (allow_dirs != NULL)
9010 *allow_dirs = TRUE;
9011 break;
9012 }
9013 }
9014#endif
9015 if (*++p == '?'
9016#ifdef BACKSLASH_IN_FILENAME
9017 && no_bslash
9018#endif
9019 )
9020 reg_pat[i++] = '?';
9021 else
9022 if (*p == ',')
9023 reg_pat[i++] = ',';
9024 else
9025 {
9026 if (allow_dirs != NULL && vim_ispathsep(*p)
9027#ifdef BACKSLASH_IN_FILENAME
9028 && (!no_bslash || *p != '\\')
9029#endif
9030 )
9031 *allow_dirs = TRUE;
9032 reg_pat[i++] = '\\';
9033 reg_pat[i++] = *p;
9034 }
9035 break;
9036#ifdef BACKSLASH_IN_FILENAME
9037 case '/':
9038 reg_pat[i++] = '[';
9039 reg_pat[i++] = '\\';
9040 reg_pat[i++] = '/';
9041 reg_pat[i++] = ']';
9042 if (allow_dirs != NULL)
9043 *allow_dirs = TRUE;
9044 break;
9045#endif
9046 case '{':
9047 reg_pat[i++] = '\\';
9048 reg_pat[i++] = '(';
9049 nested++;
9050 break;
9051 case '}':
9052 reg_pat[i++] = '\\';
9053 reg_pat[i++] = ')';
9054 --nested;
9055 break;
9056 case ',':
9057 if (nested)
9058 {
9059 reg_pat[i++] = '\\';
9060 reg_pat[i++] = '|';
9061 }
9062 else
9063 reg_pat[i++] = ',';
9064 break;
9065 default:
9066# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009067 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068 reg_pat[i++] = *p++;
9069 else
9070# endif
9071 if (allow_dirs != NULL && vim_ispathsep(*p))
9072 *allow_dirs = TRUE;
9073 reg_pat[i++] = *p;
9074 break;
9075 }
9076 }
9077 if (add_dollar)
9078 reg_pat[i++] = '$';
9079 reg_pat[i] = NUL;
9080 if (nested != 0)
9081 {
9082 if (nested < 0)
9083 EMSG(_("E219: Missing {."));
9084 else
9085 EMSG(_("E220: Missing }."));
9086 vim_free(reg_pat);
9087 reg_pat = NULL;
9088 }
9089 return reg_pat;
9090}