blob: 2704d88b93adfa0d7ff945595943a45179c69cd7 [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)
Bram Moolenaar362e1a32006-03-06 23:29:24 +000015# include "vimio.h" /* for lseek(), must be before vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +000016#endif
17
18#if defined __EMX__
Bram Moolenaar362e1a32006-03-06 23:29:24 +000019# include "vimio.h" /* for mktemp(), CJW 1997-12-03 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000020#endif
21
22#include "vim.h"
23
Bram Moolenaar071d4272004-06-13 20:20:40 +000024#ifdef __TANDEM
25# include <limits.h> /* for SSIZE_MAX */
26#endif
27
28#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
29# include <utime.h> /* for struct utimbuf */
30#endif
31
32#define BUFSIZE 8192 /* size of normal write buffer */
33#define SMBUFSIZE 256 /* size of emergency write buffer */
34
35#ifdef FEAT_CRYPT
36# define CRYPT_MAGIC "VimCrypt~01!" /* "01" is the version nr */
37# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
38#endif
39
40/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000041#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000042
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000043#if defined(sun) && defined(S_ISCHR)
44# define OPEN_CHR_FILES
45static int is_dev_fd_file(char_u *fname);
46#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#ifdef FEAT_MBYTE
48static char_u *next_fenc __ARGS((char_u **pp));
49# ifdef FEAT_EVAL
50static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
51# endif
52#endif
53#ifdef FEAT_VIMINFO
54static void check_marks_read __ARGS((void));
55#endif
56#ifdef FEAT_CRYPT
57static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, long *filesizep, int newfile));
58#endif
59#ifdef UNIX
60static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
61#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000062static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000063static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000064static void msg_add_eol __ARGS((void));
65static int check_mtime __ARGS((buf_T *buf, struct stat *s));
66static int time_differs __ARGS((long t1, long t2));
67#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000068static int apply_autocmds_exarg __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap));
Bram Moolenaar70836c82006-02-20 21:28:49 +000069static int au_find_group __ARGS((char_u *name));
70
71# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000072# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000073# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000074#endif
75
76#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
77# define HAS_BW_FLAGS
78# define FIO_LATIN1 0x01 /* convert Latin1 */
79# define FIO_UTF8 0x02 /* convert UTF-8 */
80# define FIO_UCS2 0x04 /* convert UCS-2 */
81# define FIO_UCS4 0x08 /* convert UCS-4 */
82# define FIO_UTF16 0x10 /* convert UTF-16 */
83# ifdef WIN3264
84# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
85# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
86# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
87# endif
88# ifdef MACOS_X
89# define FIO_MACROMAN 0x20 /* convert MacRoman */
90# endif
91# define FIO_ENDIAN_L 0x80 /* little endian */
92# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
93# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
94# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
95# define FIO_ALL -1 /* allow all formats */
96#endif
97
98/* When converting, a read() or write() may leave some bytes to be converted
99 * for the next call. The value is guessed... */
100#define CONV_RESTLEN 30
101
102/* We have to guess how much a sequence of bytes may expand when converting
103 * with iconv() to be able to allocate a buffer. */
104#define ICONV_MULT 8
105
106/*
107 * Structure to pass arguments from buf_write() to buf_write_bytes().
108 */
109struct bw_info
110{
111 int bw_fd; /* file descriptor */
112 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000113 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114#ifdef HAS_BW_FLAGS
115 int bw_flags; /* FIO_ flags */
116#endif
117#ifdef FEAT_MBYTE
118 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
119 int bw_restlen; /* nr of bytes in bw_rest[] */
120 int bw_first; /* first write call */
121 char_u *bw_conv_buf; /* buffer for writing converted chars */
122 int bw_conv_buflen; /* size of bw_conv_buf */
123 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000124 linenr_T bw_conv_error_lnum; /* first line with error or zero */
125 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000126# ifdef USE_ICONV
127 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
128# endif
129#endif
130};
131
132static int buf_write_bytes __ARGS((struct bw_info *ip));
133
134#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000135static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
137static int same_encoding __ARGS((char_u *a, char_u *b));
138static int get_fio_flags __ARGS((char_u *ptr));
139static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
140static int make_bom __ARGS((char_u *buf, char_u *name));
141# ifdef WIN3264
142static int get_win_fio_flags __ARGS((char_u *ptr));
143# endif
144# ifdef MACOS_X
145static int get_mac_fio_flags __ARGS((char_u *ptr));
146# endif
147#endif
148static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000149#ifdef FEAT_AUTOCMD
150static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
151#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000152
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153 void
154filemess(buf, name, s, attr)
155 buf_T *buf;
156 char_u *name;
157 char_u *s;
158 int attr;
159{
160 int msg_scroll_save;
161
162 if (msg_silent != 0)
163 return;
164 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
165 /* If it's extremely long, truncate it. */
166 if (STRLEN(IObuff) > IOSIZE - 80)
167 IObuff[IOSIZE - 80] = NUL;
168 STRCAT(IObuff, s);
169 /*
170 * For the first message may have to start a new line.
171 * For further ones overwrite the previous one, reset msg_scroll before
172 * calling filemess().
173 */
174 msg_scroll_save = msg_scroll;
175 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
176 msg_scroll = FALSE;
177 if (!msg_scroll) /* wait a bit when overwriting an error msg */
178 check_for_delay(FALSE);
179 msg_start();
180 msg_scroll = msg_scroll_save;
181 msg_scrolled_ign = TRUE;
182 /* may truncate the message to avoid a hit-return prompt */
183 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
184 msg_clr_eos();
185 out_flush();
186 msg_scrolled_ign = FALSE;
187}
188
189/*
190 * Read lines from file "fname" into the buffer after line "from".
191 *
192 * 1. We allocate blocks with lalloc, as big as possible.
193 * 2. Each block is filled with characters from the file with a single read().
194 * 3. The lines are inserted in the buffer with ml_append().
195 *
196 * (caller must check that fname != NULL, unless READ_STDIN is used)
197 *
198 * "lines_to_skip" is the number of lines that must be skipped
199 * "lines_to_read" is the number of lines that are appended
200 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
201 *
202 * flags:
203 * READ_NEW starting to edit a new buffer
204 * READ_FILTER reading filter output
205 * READ_STDIN read from stdin instead of a file
206 * READ_BUFFER read from curbuf instead of a file (converting after reading
207 * stdin)
208 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
209 *
210 * return FAIL for failure, OK otherwise
211 */
212 int
213readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
214 char_u *fname;
215 char_u *sfname;
216 linenr_T from;
217 linenr_T lines_to_skip;
218 linenr_T lines_to_read;
219 exarg_T *eap; /* can be NULL! */
220 int flags;
221{
222 int fd = 0;
223 int newfile = (flags & READ_NEW);
224 int check_readonly;
225 int filtering = (flags & READ_FILTER);
226 int read_stdin = (flags & READ_STDIN);
227 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000228 int set_options = newfile || read_buffer
229 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
231 colnr_T read_buf_col = 0; /* next char to read from this line */
232 char_u c;
233 linenr_T lnum = from;
234 char_u *ptr = NULL; /* pointer into read buffer */
235 char_u *buffer = NULL; /* read buffer */
236 char_u *new_buffer = NULL; /* init to shut up gcc */
237 char_u *line_start = NULL; /* init to shut up gcc */
238 int wasempty; /* buffer was empty before reading */
239 colnr_T len;
240 long size = 0;
241 char_u *p;
242 long filesize = 0;
243 int skip_read = FALSE;
244#ifdef FEAT_CRYPT
245 char_u *cryptkey = NULL;
246#endif
247 int split = 0; /* number of split lines */
248#define UNKNOWN 0x0fffffff /* file size is unknown */
249 linenr_T linecnt;
250 int error = FALSE; /* errors encountered */
251 int ff_error = EOL_UNKNOWN; /* file format with errors */
252 long linerest = 0; /* remaining chars in line */
253#ifdef UNIX
254 int perm = 0;
255 int swap_mode = -1; /* protection bits for swap file */
256#else
257 int perm;
258#endif
259 int fileformat = 0; /* end-of-line format */
260 int keep_fileformat = FALSE;
261 struct stat st;
262 int file_readonly;
263 linenr_T skip_count = 0;
264 linenr_T read_count = 0;
265 int msg_save = msg_scroll;
266 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
267 * last read was missing the eol */
268 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
269 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
270 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
271 int file_rewind = FALSE;
272#ifdef FEAT_MBYTE
273 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000274 linenr_T conv_error = 0; /* line nr with conversion error */
275 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
277 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000278 int bad_char_behavior = BAD_REPLACE;
279 /* BAD_KEEP, BAD_DROP or character to
280 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000281 char_u *tmpname = NULL; /* name of 'charconvert' output file */
282 int fio_flags = 0;
283 char_u *fenc; /* fileencoding to use */
284 int fenc_alloced; /* fenc_next is in allocated memory */
285 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
286 int advance_fenc = FALSE;
287 long real_size = 0;
288# ifdef USE_ICONV
289 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
290# ifdef FEAT_EVAL
291 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
292 'charconvert' next */
293# endif
294# endif
295 int converted = FALSE; /* TRUE if conversion done */
296 int notconverted = FALSE; /* TRUE if conversion wanted but it
297 wasn't possible */
298 char_u conv_rest[CONV_RESTLEN];
299 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
300#endif
301
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000302#ifdef FEAT_AUTOCMD
303 /* Remember the initial values of curbuf, curbuf->b_ffname and
304 * curbuf->b_fname to detect whether they are altered as a result of
305 * executing nasty autocommands. Also check if "fname" and "sfname"
306 * point to one of these values. */
307 buf_T *old_curbuf = curbuf;
308 char_u *old_b_ffname = curbuf->b_ffname;
309 char_u *old_b_fname = curbuf->b_fname;
310 int using_b_ffname = (fname == curbuf->b_ffname)
311 || (sfname == curbuf->b_ffname);
312 int using_b_fname = (fname == curbuf->b_fname)
313 || (sfname == curbuf->b_fname);
314#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316
317 /*
318 * If there is no file name yet, use the one for the read file.
319 * BF_NOTEDITED is set to reflect this.
320 * Don't do this for a read from a filter.
321 * Only do this when 'cpoptions' contains the 'f' flag.
322 */
323 if (curbuf->b_ffname == NULL
324 && !filtering
325 && fname != NULL
326 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
327 && !(flags & READ_DUMMY))
328 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000329 if (set_rw_fname(fname, sfname) == FAIL)
330 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 }
332
Bram Moolenaardf177f62005-02-22 08:39:57 +0000333 /* After reading a file the cursor line changes but we don't want to
334 * display the line. */
335 ex_no_reprint = TRUE;
336
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000337 /* don't display the file info for another buffer now */
338 need_fileinfo = FALSE;
339
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 /*
341 * For Unix: Use the short file name whenever possible.
342 * Avoids problems with networks and when directory names are changed.
343 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
344 * another directory, which we don't detect.
345 */
346 if (sfname == NULL)
347 sfname = fname;
348#if defined(UNIX) || defined(__EMX__)
349 fname = sfname;
350#endif
351
352#ifdef FEAT_AUTOCMD
353 /*
354 * The BufReadCmd and FileReadCmd events intercept the reading process by
355 * executing the associated commands instead.
356 */
357 if (!filtering && !read_stdin && !read_buffer)
358 {
359 pos_T pos;
360
361 pos = curbuf->b_op_start;
362
363 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
364 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
365 curbuf->b_op_start.col = 0;
366
367 if (newfile)
368 {
369 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
370 FALSE, curbuf, eap))
371#ifdef FEAT_EVAL
372 return aborting() ? FAIL : OK;
373#else
374 return OK;
375#endif
376 }
377 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
378 FALSE, NULL, eap))
379#ifdef FEAT_EVAL
380 return aborting() ? FAIL : OK;
381#else
382 return OK;
383#endif
384
385 curbuf->b_op_start = pos;
386 }
387#endif
388
389 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
390 msg_scroll = FALSE; /* overwrite previous file message */
391 else
392 msg_scroll = TRUE; /* don't overwrite previous file message */
393
394 /*
395 * If the name ends in a path separator, we can't open it. Check here,
396 * because reading the file may actually work, but then creating the swap
397 * file may destroy it! Reported on MS-DOS and Win 95.
398 * If the name is too long we might crash further on, quit here.
399 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000400 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000402 p = fname + STRLEN(fname);
403 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000404 {
405 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
406 msg_end();
407 msg_scroll = msg_save;
408 return FAIL;
409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410 }
411
412#ifdef UNIX
413 /*
414 * On Unix it is possible to read a directory, so we have to
415 * check for it before the mch_open().
416 */
417 if (!read_stdin && !read_buffer)
418 {
419 perm = mch_getperm(fname);
420 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
421# ifdef S_ISFIFO
422 && !S_ISFIFO(perm) /* ... or fifo */
423# endif
424# ifdef S_ISSOCK
425 && !S_ISSOCK(perm) /* ... or socket */
426# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000427# ifdef OPEN_CHR_FILES
428 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
429 /* ... or a character special file named /dev/fd/<n> */
430# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000431 )
432 {
433 if (S_ISDIR(perm))
434 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
435 else
436 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
437 msg_end();
438 msg_scroll = msg_save;
439 return FAIL;
440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000442# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
443 /*
444 * MS-Windows allows opening a device, but we will probably get stuck
445 * trying to read it.
446 */
447 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
448 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000449 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000450 msg_end();
451 msg_scroll = msg_save;
452 return FAIL;
453 }
454# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000455 }
456#endif
457
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000459 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 {
461 if (eap != NULL && eap->force_ff != 0)
462 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
463 else if (*p_ffs != NUL)
464 set_fileformat(default_fileformat(), OPT_LOCAL);
465 }
466
467 /* set or reset 'binary' */
468 if (eap != NULL && eap->force_bin != 0)
469 {
470 int oldval = curbuf->b_p_bin;
471
472 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
473 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
474 }
475
476 /*
477 * When opening a new file we take the readonly flag from the file.
478 * Default is r/w, can be set to r/o below.
479 * Don't reset it when in readonly mode
480 * Only set/reset b_p_ro when BF_CHECK_RO is set.
481 */
482 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000483 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 curbuf->b_p_ro = FALSE;
485
486 if (newfile && !read_stdin && !read_buffer)
487 {
488 /* Remember time of file.
489 * For RISCOS, also remember the filetype.
490 */
491 if (mch_stat((char *)fname, &st) >= 0)
492 {
493 buf_store_time(curbuf, &st, fname);
494 curbuf->b_mtime_read = curbuf->b_mtime;
495
496#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
497 /* Read the filetype into the buffer local filetype option. */
498 mch_read_filetype(fname);
499#endif
500#ifdef UNIX
501 /*
502 * Use the protection bits of the original file for the swap file.
503 * This makes it possible for others to read the name of the
504 * edited file from the swapfile, but only if they can read the
505 * edited file.
506 * Remove the "write" and "execute" bits for group and others
507 * (they must not write the swapfile).
508 * Add the "read" and "write" bits for the user, otherwise we may
509 * not be able to write to the file ourselves.
510 * Setting the bits is done below, after creating the swap file.
511 */
512 swap_mode = (st.st_mode & 0644) | 0600;
513#endif
514#ifdef FEAT_CW_EDITOR
515 /* Get the FSSpec on MacOS
516 * TODO: Update it properly when the buffer name changes
517 */
518 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
519#endif
520#ifdef VMS
521 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000522 curbuf->b_fab_rat = st.st_fab_rat;
523 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524#endif
525 }
526 else
527 {
528 curbuf->b_mtime = 0;
529 curbuf->b_mtime_read = 0;
530 curbuf->b_orig_size = 0;
531 curbuf->b_orig_mode = 0;
532 }
533
534 /* Reset the "new file" flag. It will be set again below when the
535 * file doesn't exist. */
536 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
537 }
538
539/*
540 * for UNIX: check readonly with perm and mch_access()
541 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
542 * for MSDOS and Amiga: check readonly by trying to open the file for writing
543 */
544 file_readonly = FALSE;
545 if (read_stdin)
546 {
547#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
548 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
549 setmode(0, O_BINARY);
550#endif
551 }
552 else if (!read_buffer)
553 {
554#ifdef USE_MCH_ACCESS
555 if (
556# ifdef UNIX
557 !(perm & 0222) ||
558# endif
559 mch_access((char *)fname, W_OK))
560 file_readonly = TRUE;
561 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
562#else
563 if (!newfile
564 || readonlymode
565 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
566 {
567 file_readonly = TRUE;
568 /* try to open ro */
569 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
570 }
571#endif
572 }
573
574 if (fd < 0) /* cannot open at all */
575 {
576#ifndef UNIX
577 int isdir_f;
578#endif
579 msg_scroll = msg_save;
580#ifndef UNIX
581 /*
582 * On MSDOS and Amiga we can't open a directory, check here.
583 */
584 isdir_f = (mch_isdir(fname));
585 perm = mch_getperm(fname); /* check if the file exists */
586 if (isdir_f)
587 {
588 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
589 curbuf->b_p_ro = TRUE; /* must use "w!" now */
590 }
591 else
592#endif
593 if (newfile)
594 {
595 if (perm < 0)
596 {
597 /*
598 * Set the 'new-file' flag, so that when the file has
599 * been created by someone else, a ":w" will complain.
600 */
601 curbuf->b_flags |= BF_NEW;
602
603 /* Create a swap file now, so that other Vims are warned
604 * that we are editing this file. Don't do this for a
605 * "nofile" or "nowrite" buffer type. */
606#ifdef FEAT_QUICKFIX
607 if (!bt_dontwrite(curbuf))
608#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000609 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000611#ifdef FEAT_AUTOCMD
612 /* SwapExists autocommand may mess things up */
613 if (curbuf != old_curbuf
614 || (using_b_ffname
615 && (old_b_ffname != curbuf->b_ffname))
616 || (using_b_fname
617 && (old_b_fname != curbuf->b_fname)))
618 {
619 EMSG(_(e_auchangedbuf));
620 return FAIL;
621 }
622#endif
623 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000624 if (dir_of_file_exists(fname))
625 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
626 else
627 filemess(curbuf, sfname,
628 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629#ifdef FEAT_VIMINFO
630 /* Even though this is a new file, it might have been
631 * edited before and deleted. Get the old marks. */
632 check_marks_read();
633#endif
634#ifdef FEAT_MBYTE
635 if (eap != NULL && eap->force_enc != 0)
636 {
637 /* set forced 'fileencoding' */
638 fenc = enc_canonize(eap->cmd + eap->force_enc);
639 if (fenc != NULL)
640 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000641 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642 vim_free(fenc);
643 }
644#endif
645#ifdef FEAT_AUTOCMD
646 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
647 FALSE, curbuf, eap);
648#endif
649 /* remember the current fileformat */
650 save_file_ff(curbuf);
651
652#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
653 if (aborting()) /* autocmds may abort script processing */
654 return FAIL;
655#endif
656 return OK; /* a new file is not an error */
657 }
658 else
659 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000660 filemess(curbuf, sfname, (char_u *)(
661# ifdef EFBIG
662 (errno == EFBIG) ? _("[File too big]") :
663# endif
664 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 curbuf->b_p_ro = TRUE; /* must use "w!" now */
666 }
667 }
668
669 return FAIL;
670 }
671
672 /*
673 * Only set the 'ro' flag for readonly files the first time they are
674 * loaded. Help files always get readonly mode
675 */
676 if ((check_readonly && file_readonly) || curbuf->b_help)
677 curbuf->b_p_ro = TRUE;
678
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000679 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000681 /* Don't change 'eol' if reading from buffer as it will already be
682 * correctly set when reading stdin. */
683 if (!read_buffer)
684 {
685 curbuf->b_p_eol = TRUE;
686 curbuf->b_start_eol = TRUE;
687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688#ifdef FEAT_MBYTE
689 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000690 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691#endif
692 }
693
694 /* Create a swap file now, so that other Vims are warned that we are
695 * editing this file.
696 * Don't do this for a "nofile" or "nowrite" buffer type. */
697#ifdef FEAT_QUICKFIX
698 if (!bt_dontwrite(curbuf))
699#endif
700 {
701 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000702#ifdef FEAT_AUTOCMD
703 if (!read_stdin && (curbuf != old_curbuf
704 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
705 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
706 {
707 EMSG(_(e_auchangedbuf));
708 if (!read_buffer)
709 close(fd);
710 return FAIL;
711 }
712#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713#ifdef UNIX
714 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000715 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
716 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
718#endif
719 }
720
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000721#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 /* If "Quit" selected at ATTENTION dialog, don't load the file */
723 if (swap_exists_action == SEA_QUIT)
724 {
725 if (!read_buffer && !read_stdin)
726 close(fd);
727 return FAIL;
728 }
729#endif
730
731 ++no_wait_return; /* don't wait for return yet */
732
733 /*
734 * Set '[ mark to the line above where the lines go (line 1 if zero).
735 */
736 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
737 curbuf->b_op_start.col = 0;
738
739#ifdef FEAT_AUTOCMD
740 if (!read_buffer)
741 {
742 int m = msg_scroll;
743 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744
745 /*
746 * The file must be closed again, the autocommands may want to change
747 * the file before reading it.
748 */
749 if (!read_stdin)
750 close(fd); /* ignore errors */
751
752 /*
753 * The output from the autocommands should not overwrite anything and
754 * should not be overwritten: Set msg_scroll, restore its value if no
755 * output was done.
756 */
757 msg_scroll = TRUE;
758 if (filtering)
759 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
760 FALSE, curbuf, eap);
761 else if (read_stdin)
762 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
763 FALSE, curbuf, eap);
764 else if (newfile)
765 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
766 FALSE, curbuf, eap);
767 else
768 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
769 FALSE, NULL, eap);
770 if (msg_scrolled == n)
771 msg_scroll = m;
772
773#ifdef FEAT_EVAL
774 if (aborting()) /* autocmds may abort script processing */
775 {
776 --no_wait_return;
777 msg_scroll = msg_save;
778 curbuf->b_p_ro = TRUE; /* must use "w!" now */
779 return FAIL;
780 }
781#endif
782 /*
783 * Don't allow the autocommands to change the current buffer.
784 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000785 *
786 * Don't allow the autocommands to change the buffer name either
787 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000788 */
789 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000790 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
791 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
793 {
794 --no_wait_return;
795 msg_scroll = msg_save;
796 if (fd < 0)
797 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
798 else
799 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
800 curbuf->b_p_ro = TRUE; /* must use "w!" now */
801 return FAIL;
802 }
803 }
804#endif /* FEAT_AUTOCMD */
805
806 /* Autocommands may add lines to the file, need to check if it is empty */
807 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
808
809 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
810 {
811 /*
812 * Show the user that we are busy reading the input. Sometimes this
813 * may take a while. When reading from stdin another program may
814 * still be running, don't move the cursor to the last line, unless
815 * always using the GUI.
816 */
817 if (read_stdin)
818 {
819#ifndef ALWAYS_USE_GUI
820 mch_msg(_("Vim: Reading from stdin...\n"));
821#endif
822#ifdef FEAT_GUI
823 /* Also write a message in the GUI window, if there is one. */
824 if (gui.in_use && !gui.dying && !gui.starting)
825 {
826 p = (char_u *)_("Reading from stdin...");
827 gui_write(p, (int)STRLEN(p));
828 }
829#endif
830 }
831 else if (!read_buffer)
832 filemess(curbuf, sfname, (char_u *)"", 0);
833 }
834
835 msg_scroll = FALSE; /* overwrite the file message */
836
837 /*
838 * Set linecnt now, before the "retry" caused by a wrong guess for
839 * fileformat, and after the autocommands, which may change them.
840 */
841 linecnt = curbuf->b_ml.ml_line_count;
842
843#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000844 /* "++bad=" argument. */
845 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000846 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000847 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000848 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000849 curbuf->b_bad_char = eap->bad_char;
850 }
851 else
852 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000853
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000855 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856 */
857 if (eap != NULL && eap->force_enc != 0)
858 {
859 fenc = enc_canonize(eap->cmd + eap->force_enc);
860 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000861 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 }
863 else if (curbuf->b_p_bin)
864 {
865 fenc = (char_u *)""; /* binary: don't convert */
866 fenc_alloced = FALSE;
867 }
868 else if (curbuf->b_help)
869 {
870 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000871 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872
873 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
874 * fails it must be latin1.
875 * Always do this when 'encoding' is "utf-8". Otherwise only do
876 * this when needed to avoid [converted] remarks all the time.
877 * It is needed when the first line contains non-ASCII characters.
878 * That is only in *.??x files. */
879 fenc = (char_u *)"latin1";
880 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000881 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000883 fc = fname[STRLEN(fname) - 1];
884 if (TOLOWER_ASC(fc) == 'x')
885 {
886 /* Read the first line (and a bit more). Immediately rewind to
887 * the start of the file. If the read() fails "len" is -1. */
888 len = vim_read(fd, firstline, 80);
889 lseek(fd, (off_t)0L, SEEK_SET);
890 for (p = firstline; p < firstline + len; ++p)
891 if (*p >= 0x80)
892 {
893 c = TRUE;
894 break;
895 }
896 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897 }
898
899 if (c)
900 {
901 fenc_next = fenc;
902 fenc = (char_u *)"utf-8";
903
904 /* When the file is utf-8 but a character doesn't fit in
905 * 'encoding' don't retry. In help text editing utf-8 bytes
906 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000907 if (!enc_utf8)
908 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 }
910 fenc_alloced = FALSE;
911 }
912 else if (*p_fencs == NUL)
913 {
914 fenc = curbuf->b_p_fenc; /* use format from buffer */
915 fenc_alloced = FALSE;
916 }
917 else
918 {
919 fenc_next = p_fencs; /* try items in 'fileencodings' */
920 fenc = next_fenc(&fenc_next);
921 fenc_alloced = TRUE;
922 }
923#endif
924
925 /*
926 * Jump back here to retry reading the file in different ways.
927 * Reasons to retry:
928 * - encoding conversion failed: try another one from "fenc_next"
929 * - BOM detected and fenc was set, need to setup conversion
930 * - "fileformat" check failed: try another
931 *
932 * Variables set for special retry actions:
933 * "file_rewind" Rewind the file to start reading it again.
934 * "advance_fenc" Advance "fenc" using "fenc_next".
935 * "skip_read" Re-use already read bytes (BOM detected).
936 * "did_iconv" iconv() conversion failed, try 'charconvert'.
937 * "keep_fileformat" Don't reset "fileformat".
938 *
939 * Other status indicators:
940 * "tmpname" When != NULL did conversion with 'charconvert'.
941 * Output file has to be deleted afterwards.
942 * "iconv_fd" When != -1 did conversion with iconv().
943 */
944retry:
945
946 if (file_rewind)
947 {
948 if (read_buffer)
949 {
950 read_buf_lnum = 1;
951 read_buf_col = 0;
952 }
953 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
954 {
955 /* Can't rewind the file, give up. */
956 error = TRUE;
957 goto failed;
958 }
959 /* Delete the previously read lines. */
960 while (lnum > from)
961 ml_delete(lnum--, FALSE);
962 file_rewind = FALSE;
963#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000964 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000965 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000967 curbuf->b_start_bomb = FALSE;
968 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000969 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970#endif
971 }
972
973 /*
974 * When retrying with another "fenc" and the first time "fileformat"
975 * will be reset.
976 */
977 if (keep_fileformat)
978 keep_fileformat = FALSE;
979 else
980 {
981 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000982 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000984 try_unix = try_dos = try_mac = FALSE;
985 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986 else if (curbuf->b_p_bin)
987 fileformat = EOL_UNIX; /* binary: use Unix format */
988 else if (*p_ffs == NUL)
989 fileformat = get_fileformat(curbuf);/* use format from buffer */
990 else
991 fileformat = EOL_UNKNOWN; /* detect from file */
992 }
993
994#ifdef FEAT_MBYTE
995# ifdef USE_ICONV
996 if (iconv_fd != (iconv_t)-1)
997 {
998 /* aborted conversion with iconv(), close the descriptor */
999 iconv_close(iconv_fd);
1000 iconv_fd = (iconv_t)-1;
1001 }
1002# endif
1003
1004 if (advance_fenc)
1005 {
1006 /*
1007 * Try the next entry in 'fileencodings'.
1008 */
1009 advance_fenc = FALSE;
1010
1011 if (eap != NULL && eap->force_enc != 0)
1012 {
1013 /* Conversion given with "++cc=" wasn't possible, read
1014 * without conversion. */
1015 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001016 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 if (fenc_alloced)
1018 vim_free(fenc);
1019 fenc = (char_u *)"";
1020 fenc_alloced = FALSE;
1021 }
1022 else
1023 {
1024 if (fenc_alloced)
1025 vim_free(fenc);
1026 if (fenc_next != NULL)
1027 {
1028 fenc = next_fenc(&fenc_next);
1029 fenc_alloced = (fenc_next != NULL);
1030 }
1031 else
1032 {
1033 fenc = (char_u *)"";
1034 fenc_alloced = FALSE;
1035 }
1036 }
1037 if (tmpname != NULL)
1038 {
1039 mch_remove(tmpname); /* delete converted file */
1040 vim_free(tmpname);
1041 tmpname = NULL;
1042 }
1043 }
1044
1045 /*
1046 * Conversion is required when the encoding of the file is different
1047 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4 (requires
1048 * conversion to UTF-8).
1049 */
1050 fio_flags = 0;
1051 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
1052 if (converted || enc_unicode != 0)
1053 {
1054
1055 /* "ucs-bom" means we need to check the first bytes of the file
1056 * for a BOM. */
1057 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1058 fio_flags = FIO_UCSBOM;
1059
1060 /*
1061 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1062 * done. This is handled below after read(). Prepare the
1063 * fio_flags to avoid having to parse the string each time.
1064 * Also check for Unicode to Latin1 conversion, because iconv()
1065 * appears not to handle this correctly. This works just like
1066 * conversion to UTF-8 except how the resulting character is put in
1067 * the buffer.
1068 */
1069 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1070 fio_flags = get_fio_flags(fenc);
1071
1072# ifdef WIN3264
1073 /*
1074 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1075 * is handled with MultiByteToWideChar().
1076 */
1077 if (fio_flags == 0)
1078 fio_flags = get_win_fio_flags(fenc);
1079# endif
1080
1081# ifdef MACOS_X
1082 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1083 if (fio_flags == 0)
1084 fio_flags = get_mac_fio_flags(fenc);
1085# endif
1086
1087# ifdef USE_ICONV
1088 /*
1089 * Try using iconv() if we can't convert internally.
1090 */
1091 if (fio_flags == 0
1092# ifdef FEAT_EVAL
1093 && !did_iconv
1094# endif
1095 )
1096 iconv_fd = (iconv_t)my_iconv_open(
1097 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1098# endif
1099
1100# ifdef FEAT_EVAL
1101 /*
1102 * Use the 'charconvert' expression when conversion is required
1103 * and we can't do it internally or with iconv().
1104 */
1105 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1106# ifdef USE_ICONV
1107 && iconv_fd == (iconv_t)-1
1108# endif
1109 )
1110 {
1111# ifdef USE_ICONV
1112 did_iconv = FALSE;
1113# endif
1114 /* Skip conversion when it's already done (retry for wrong
1115 * "fileformat"). */
1116 if (tmpname == NULL)
1117 {
1118 tmpname = readfile_charconvert(fname, fenc, &fd);
1119 if (tmpname == NULL)
1120 {
1121 /* Conversion failed. Try another one. */
1122 advance_fenc = TRUE;
1123 if (fd < 0)
1124 {
1125 /* Re-opening the original file failed! */
1126 EMSG(_("E202: Conversion made file unreadable!"));
1127 error = TRUE;
1128 goto failed;
1129 }
1130 goto retry;
1131 }
1132 }
1133 }
1134 else
1135# endif
1136 {
1137 if (fio_flags == 0
1138# ifdef USE_ICONV
1139 && iconv_fd == (iconv_t)-1
1140# endif
1141 )
1142 {
1143 /* Conversion wanted but we can't.
1144 * Try the next conversion in 'fileencodings' */
1145 advance_fenc = TRUE;
1146 goto retry;
1147 }
1148 }
1149 }
1150
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001151 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001153 * stdin or fixed at a specific encoding. */
1154 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155#endif
1156
1157 if (!skip_read)
1158 {
1159 linerest = 0;
1160 filesize = 0;
1161 skip_count = lines_to_skip;
1162 read_count = lines_to_read;
1163#ifdef FEAT_MBYTE
1164 conv_restlen = 0;
1165#endif
1166 }
1167
1168 while (!error && !got_int)
1169 {
1170 /*
1171 * We allocate as much space for the file as we can get, plus
1172 * space for the old line plus room for one terminating NUL.
1173 * The amount is limited by the fact that read() only can read
1174 * upto max_unsigned characters (and other things).
1175 */
1176#if SIZEOF_INT <= 2
1177 if (linerest >= 0x7ff0)
1178 {
1179 ++split;
1180 *ptr = NL; /* split line by inserting a NL */
1181 size = 1;
1182 }
1183 else
1184#endif
1185 {
1186 if (!skip_read)
1187 {
1188#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001189# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190 size = SSIZE_MAX; /* use max I/O size, 52K */
1191# else
1192 size = 0x10000L; /* use buffer >= 64K */
1193# endif
1194#else
1195 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1196#endif
1197
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001198 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199 {
1200 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1201 FALSE)) != NULL)
1202 break;
1203 }
1204 if (new_buffer == NULL)
1205 {
1206 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1207 error = TRUE;
1208 break;
1209 }
1210 if (linerest) /* copy characters from the previous buffer */
1211 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1212 vim_free(buffer);
1213 buffer = new_buffer;
1214 ptr = buffer + linerest;
1215 line_start = buffer;
1216
1217#ifdef FEAT_MBYTE
1218 /* May need room to translate into.
1219 * For iconv() we don't really know the required space, use a
1220 * factor ICONV_MULT.
1221 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1222 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1223 * become up to 4 bytes, size must be multiple of 2
1224 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1225 * multiple of 2
1226 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1227 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001228 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229# ifdef USE_ICONV
1230 if (iconv_fd != (iconv_t)-1)
1231 size = size / ICONV_MULT;
1232 else
1233# endif
1234 if (fio_flags & FIO_LATIN1)
1235 size = size / 2;
1236 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1237 size = (size * 2 / 3) & ~1;
1238 else if (fio_flags & FIO_UCS4)
1239 size = (size * 2 / 3) & ~3;
1240 else if (fio_flags == FIO_UCSBOM)
1241 size = size / ICONV_MULT; /* worst case */
1242# ifdef WIN3264
1243 else if (fio_flags & FIO_CODEPAGE)
1244 size = size / ICONV_MULT; /* also worst case */
1245# endif
1246# ifdef MACOS_X
1247 else if (fio_flags & FIO_MACROMAN)
1248 size = size / ICONV_MULT; /* also worst case */
1249# endif
1250#endif
1251
1252#ifdef FEAT_MBYTE
1253 if (conv_restlen > 0)
1254 {
1255 /* Insert unconverted bytes from previous line. */
1256 mch_memmove(ptr, conv_rest, conv_restlen);
1257 ptr += conv_restlen;
1258 size -= conv_restlen;
1259 }
1260#endif
1261
1262 if (read_buffer)
1263 {
1264 /*
1265 * Read bytes from curbuf. Used for converting text read
1266 * from stdin.
1267 */
1268 if (read_buf_lnum > from)
1269 size = 0;
1270 else
1271 {
1272 int n, ni;
1273 long tlen;
1274
1275 tlen = 0;
1276 for (;;)
1277 {
1278 p = ml_get(read_buf_lnum) + read_buf_col;
1279 n = (int)STRLEN(p);
1280 if ((int)tlen + n + 1 > size)
1281 {
1282 /* Filled up to "size", append partial line.
1283 * Change NL to NUL to reverse the effect done
1284 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001285 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 for (ni = 0; ni < n; ++ni)
1287 {
1288 if (p[ni] == NL)
1289 ptr[tlen++] = NUL;
1290 else
1291 ptr[tlen++] = p[ni];
1292 }
1293 read_buf_col += n;
1294 break;
1295 }
1296 else
1297 {
1298 /* Append whole line and new-line. Change NL
1299 * to NUL to reverse the effect done below. */
1300 for (ni = 0; ni < n; ++ni)
1301 {
1302 if (p[ni] == NL)
1303 ptr[tlen++] = NUL;
1304 else
1305 ptr[tlen++] = p[ni];
1306 }
1307 ptr[tlen++] = NL;
1308 read_buf_col = 0;
1309 if (++read_buf_lnum > from)
1310 {
1311 /* When the last line didn't have an
1312 * end-of-line don't add it now either. */
1313 if (!curbuf->b_p_eol)
1314 --tlen;
1315 size = tlen;
1316 break;
1317 }
1318 }
1319 }
1320 }
1321 }
1322 else
1323 {
1324 /*
1325 * Read bytes from the file.
1326 */
1327 size = vim_read(fd, ptr, size);
1328 }
1329
1330 if (size <= 0)
1331 {
1332 if (size < 0) /* read error */
1333 error = TRUE;
1334#ifdef FEAT_MBYTE
1335 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001336 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001337 /*
1338 * Reached end-of-file but some trailing bytes could
1339 * not be converted. Truncated file?
1340 */
1341
1342 /* When we did a conversion report an error. */
1343 if (fio_flags != 0
1344# ifdef USE_ICONV
1345 || iconv_fd != (iconv_t)-1
1346# endif
1347 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001348 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001349 if (conv_error == 0)
1350 conv_error = curbuf->b_ml.ml_line_count
1351 - linecnt + 1;
1352 }
1353 /* Remember the first linenr with an illegal byte */
1354 else if (illegal_byte == 0)
1355 illegal_byte = curbuf->b_ml.ml_line_count
1356 - linecnt + 1;
1357 if (bad_char_behavior == BAD_DROP)
1358 {
1359 *(ptr - conv_restlen) = NUL;
1360 conv_restlen = 0;
1361 }
1362 else
1363 {
1364 /* Replace the trailing bytes with the replacement
1365 * character if we were converting; if we weren't,
1366 * leave the UTF8 checking code to do it, as it
1367 * works slightly differently. */
1368 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1369# ifdef USE_ICONV
1370 || iconv_fd != (iconv_t)-1
1371# endif
1372 ))
1373 {
1374 while (conv_restlen > 0)
1375 {
1376 *(--ptr) = bad_char_behavior;
1377 --conv_restlen;
1378 }
1379 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001380 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001381# ifdef USE_ICONV
1382 if (iconv_fd != (iconv_t)-1)
1383 {
1384 iconv_close(iconv_fd);
1385 iconv_fd = (iconv_t)-1;
1386 }
1387# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001388 }
1389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390#endif
1391 }
1392
1393#ifdef FEAT_CRYPT
1394 /*
1395 * At start of file: Check for magic number of encryption.
1396 */
1397 if (filesize == 0)
1398 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1399 &filesize, newfile);
1400 /*
1401 * Decrypt the read bytes.
1402 */
1403 if (cryptkey != NULL && size > 0)
1404 for (p = ptr; p < ptr + size; ++p)
1405 ZDECODE(*p);
1406#endif
1407 }
1408 skip_read = FALSE;
1409
1410#ifdef FEAT_MBYTE
1411 /*
1412 * At start of file (or after crypt magic number): Check for BOM.
1413 * Also check for a BOM for other Unicode encodings, but not after
1414 * converting with 'charconvert' or when a BOM has already been
1415 * found.
1416 */
1417 if ((filesize == 0
1418# ifdef FEAT_CRYPT
1419 || (filesize == CRYPT_MAGIC_LEN && cryptkey != NULL)
1420# endif
1421 )
1422 && (fio_flags == FIO_UCSBOM
1423 || (!curbuf->b_p_bomb
1424 && tmpname == NULL
1425 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1426 {
1427 char_u *ccname;
1428 int blen;
1429
1430 /* no BOM detection in a short file or in binary mode */
1431 if (size < 2 || curbuf->b_p_bin)
1432 ccname = NULL;
1433 else
1434 ccname = check_for_bom(ptr, size, &blen,
1435 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1436 if (ccname != NULL)
1437 {
1438 /* Remove BOM from the text */
1439 filesize += blen;
1440 size -= blen;
1441 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001442 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001443 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001445 curbuf->b_start_bomb = TRUE;
1446 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 }
1448
1449 if (fio_flags == FIO_UCSBOM)
1450 {
1451 if (ccname == NULL)
1452 {
1453 /* No BOM detected: retry with next encoding. */
1454 advance_fenc = TRUE;
1455 }
1456 else
1457 {
1458 /* BOM detected: set "fenc" and jump back */
1459 if (fenc_alloced)
1460 vim_free(fenc);
1461 fenc = ccname;
1462 fenc_alloced = FALSE;
1463 }
1464 /* retry reading without getting new bytes or rewinding */
1465 skip_read = TRUE;
1466 goto retry;
1467 }
1468 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001469
1470 /* Include not converted bytes. */
1471 ptr -= conv_restlen;
1472 size += conv_restlen;
1473 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474#endif
1475 /*
1476 * Break here for a read error or end-of-file.
1477 */
1478 if (size <= 0)
1479 break;
1480
1481#ifdef FEAT_MBYTE
1482
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483# ifdef USE_ICONV
1484 if (iconv_fd != (iconv_t)-1)
1485 {
1486 /*
1487 * Attempt conversion of the read bytes to 'encoding' using
1488 * iconv().
1489 */
1490 const char *fromp;
1491 char *top;
1492 size_t from_size;
1493 size_t to_size;
1494
1495 fromp = (char *)ptr;
1496 from_size = size;
1497 ptr += size;
1498 top = (char *)ptr;
1499 to_size = real_size - size;
1500
1501 /*
1502 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001503 * another conversion. Except for when there is no
1504 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001506 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1507 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1509 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001510 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001511 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001512 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001513 if (conv_error == 0)
1514 conv_error = readfile_linenr(linecnt,
1515 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001516
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001517 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001518 ++fromp;
1519 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001520 if (bad_char_behavior == BAD_KEEP)
1521 {
1522 *top++ = *(fromp - 1);
1523 --to_size;
1524 }
1525 else if (bad_char_behavior != BAD_DROP)
1526 {
1527 *top++ = bad_char_behavior;
1528 --to_size;
1529 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531
1532 if (from_size > 0)
1533 {
1534 /* Some remaining characters, keep them for the next
1535 * round. */
1536 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1537 conv_restlen = (int)from_size;
1538 }
1539
1540 /* move the linerest to before the converted characters */
1541 line_start = ptr - linerest;
1542 mch_memmove(line_start, buffer, (size_t)linerest);
1543 size = (long)((char_u *)top - ptr);
1544 }
1545# endif
1546
1547# ifdef WIN3264
1548 if (fio_flags & FIO_CODEPAGE)
1549 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001550 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001551 WCHAR ucs2buf[3];
1552 int ucs2len;
1553 int codepage = FIO_GET_CP(fio_flags);
1554 int bytelen;
1555 int found_bad;
1556 char replstr[2];
1557
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558 /*
1559 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001560 * a codepage, using standard MS-Windows functions. This
1561 * requires two steps:
1562 * 1. convert from 'fileencoding' to ucs-2
1563 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001565 * Because there may be illegal bytes AND an incomplete byte
1566 * sequence at the end, we may have to do the conversion one
1567 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001570 /* Replacement string for WideCharToMultiByte(). */
1571 if (bad_char_behavior > 0)
1572 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001574 replstr[0] = '?';
1575 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576
1577 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001578 * Move the bytes to the end of the buffer, so that we have
1579 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001581 src = ptr + real_size - size;
1582 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001584 /*
1585 * Do the conversion.
1586 */
1587 dst = ptr;
1588 size = size;
1589 while (size > 0)
1590 {
1591 found_bad = FALSE;
1592
1593# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1594 if (codepage == CP_UTF8)
1595 {
1596 /* Handle CP_UTF8 input ourselves to be able to handle
1597 * trailing bytes properly.
1598 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001599 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001600 if (bytelen > size)
1601 {
1602 /* Only got some bytes of a character. Normally
1603 * it's put in "conv_rest", but if it's too long
1604 * deal with it as if they were illegal bytes. */
1605 if (bytelen <= CONV_RESTLEN)
1606 break;
1607
1608 /* weird overlong byte sequence */
1609 bytelen = size;
1610 found_bad = TRUE;
1611 }
1612 else
1613 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001614 int u8c = utf_ptr2char(src);
1615
Bram Moolenaar86e01082005-12-29 22:45:34 +00001616 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001617 found_bad = TRUE;
1618 ucs2buf[0] = u8c;
1619 ucs2len = 1;
1620 }
1621 }
1622 else
1623# endif
1624 {
1625 /* We don't know how long the byte sequence is, try
1626 * from one to three bytes. */
1627 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1628 ++bytelen)
1629 {
1630 ucs2len = MultiByteToWideChar(codepage,
1631 MB_ERR_INVALID_CHARS,
1632 (LPCSTR)src, bytelen,
1633 ucs2buf, 3);
1634 if (ucs2len > 0)
1635 break;
1636 }
1637 if (ucs2len == 0)
1638 {
1639 /* If we have only one byte then it's probably an
1640 * incomplete byte sequence. Otherwise discard
1641 * one byte as a bad character. */
1642 if (size == 1)
1643 break;
1644 found_bad = TRUE;
1645 bytelen = 1;
1646 }
1647 }
1648
1649 if (!found_bad)
1650 {
1651 int i;
1652
1653 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1654 if (enc_utf8)
1655 {
1656 /* From UCS-2 to UTF-8. Cannot fail. */
1657 for (i = 0; i < ucs2len; ++i)
1658 dst += utf_char2bytes(ucs2buf[i], dst);
1659 }
1660 else
1661 {
1662 BOOL bad = FALSE;
1663 int dstlen;
1664
1665 /* From UCS-2 to "enc_codepage". If the
1666 * conversion uses the default character "?",
1667 * the data doesn't fit in this encoding. */
1668 dstlen = WideCharToMultiByte(enc_codepage, 0,
1669 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001670 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001671 replstr, &bad);
1672 if (bad)
1673 found_bad = TRUE;
1674 else
1675 dst += dstlen;
1676 }
1677 }
1678
1679 if (found_bad)
1680 {
1681 /* Deal with bytes we can't convert. */
1682 if (can_retry)
1683 goto rewind_retry;
1684 if (conv_error == 0)
1685 conv_error = readfile_linenr(linecnt, ptr, dst);
1686 if (bad_char_behavior != BAD_DROP)
1687 {
1688 if (bad_char_behavior == BAD_KEEP)
1689 {
1690 mch_memmove(dst, src, bytelen);
1691 dst += bytelen;
1692 }
1693 else
1694 *dst++ = bad_char_behavior;
1695 }
1696 }
1697
1698 src += bytelen;
1699 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001701
1702 if (size > 0)
1703 {
1704 /* An incomplete byte sequence remaining. */
1705 mch_memmove(conv_rest, src, size);
1706 conv_restlen = size;
1707 }
1708
1709 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001710 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 }
1712 else
1713# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001714# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 if (fio_flags & FIO_MACROMAN)
1716 {
1717 /*
1718 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001719 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001721 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 }
1724 else
1725# endif
1726 if (fio_flags != 0)
1727 {
1728 int u8c;
1729 char_u *dest;
1730 char_u *tail = NULL;
1731
1732 /*
1733 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1734 * "enc_utf8" not set: Convert Unicode to Latin1.
1735 * Go from end to start through the buffer, because the number
1736 * of bytes may increase.
1737 * "dest" points to after where the UTF-8 bytes go, "p" points
1738 * to after the next character to convert.
1739 */
1740 dest = ptr + real_size;
1741 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1742 {
1743 p = ptr + size;
1744 if (fio_flags == FIO_UTF8)
1745 {
1746 /* Check for a trailing incomplete UTF-8 sequence */
1747 tail = ptr + size - 1;
1748 while (tail > ptr && (*tail & 0xc0) == 0x80)
1749 --tail;
1750 if (tail + utf_byte2len(*tail) <= ptr + size)
1751 tail = NULL;
1752 else
1753 p = tail;
1754 }
1755 }
1756 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1757 {
1758 /* Check for a trailing byte */
1759 p = ptr + (size & ~1);
1760 if (size & 1)
1761 tail = p;
1762 if ((fio_flags & FIO_UTF16) && p > ptr)
1763 {
1764 /* Check for a trailing leading word */
1765 if (fio_flags & FIO_ENDIAN_L)
1766 {
1767 u8c = (*--p << 8);
1768 u8c += *--p;
1769 }
1770 else
1771 {
1772 u8c = *--p;
1773 u8c += (*--p << 8);
1774 }
1775 if (u8c >= 0xd800 && u8c <= 0xdbff)
1776 tail = p;
1777 else
1778 p += 2;
1779 }
1780 }
1781 else /* FIO_UCS4 */
1782 {
1783 /* Check for trailing 1, 2 or 3 bytes */
1784 p = ptr + (size & ~3);
1785 if (size & 3)
1786 tail = p;
1787 }
1788
1789 /* If there is a trailing incomplete sequence move it to
1790 * conv_rest[]. */
1791 if (tail != NULL)
1792 {
1793 conv_restlen = (int)((ptr + size) - tail);
1794 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1795 size -= conv_restlen;
1796 }
1797
1798
1799 while (p > ptr)
1800 {
1801 if (fio_flags & FIO_LATIN1)
1802 u8c = *--p;
1803 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1804 {
1805 if (fio_flags & FIO_ENDIAN_L)
1806 {
1807 u8c = (*--p << 8);
1808 u8c += *--p;
1809 }
1810 else
1811 {
1812 u8c = *--p;
1813 u8c += (*--p << 8);
1814 }
1815 if ((fio_flags & FIO_UTF16)
1816 && u8c >= 0xdc00 && u8c <= 0xdfff)
1817 {
1818 int u16c;
1819
1820 if (p == ptr)
1821 {
1822 /* Missing leading word. */
1823 if (can_retry)
1824 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001825 if (conv_error == 0)
1826 conv_error = readfile_linenr(linecnt,
1827 ptr, p);
1828 if (bad_char_behavior == BAD_DROP)
1829 continue;
1830 if (bad_char_behavior != BAD_KEEP)
1831 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 }
1833
1834 /* found second word of double-word, get the first
1835 * word and compute the resulting character */
1836 if (fio_flags & FIO_ENDIAN_L)
1837 {
1838 u16c = (*--p << 8);
1839 u16c += *--p;
1840 }
1841 else
1842 {
1843 u16c = *--p;
1844 u16c += (*--p << 8);
1845 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001846 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1847 + (u8c & 0x3ff);
1848
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849 /* Check if the word is indeed a leading word. */
1850 if (u16c < 0xd800 || u16c > 0xdbff)
1851 {
1852 if (can_retry)
1853 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001854 if (conv_error == 0)
1855 conv_error = readfile_linenr(linecnt,
1856 ptr, p);
1857 if (bad_char_behavior == BAD_DROP)
1858 continue;
1859 if (bad_char_behavior != BAD_KEEP)
1860 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 }
1863 }
1864 else if (fio_flags & FIO_UCS4)
1865 {
1866 if (fio_flags & FIO_ENDIAN_L)
1867 {
1868 u8c = (*--p << 24);
1869 u8c += (*--p << 16);
1870 u8c += (*--p << 8);
1871 u8c += *--p;
1872 }
1873 else /* big endian */
1874 {
1875 u8c = *--p;
1876 u8c += (*--p << 8);
1877 u8c += (*--p << 16);
1878 u8c += (*--p << 24);
1879 }
1880 }
1881 else /* UTF-8 */
1882 {
1883 if (*--p < 0x80)
1884 u8c = *p;
1885 else
1886 {
1887 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001888 p -= len;
1889 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 if (len == 0)
1891 {
1892 /* Not a valid UTF-8 character, retry with
1893 * another fenc when possible, otherwise just
1894 * report the error. */
1895 if (can_retry)
1896 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001897 if (conv_error == 0)
1898 conv_error = readfile_linenr(linecnt,
1899 ptr, p);
1900 if (bad_char_behavior == BAD_DROP)
1901 continue;
1902 if (bad_char_behavior != BAD_KEEP)
1903 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 }
1906 }
1907 if (enc_utf8) /* produce UTF-8 */
1908 {
1909 dest -= utf_char2len(u8c);
1910 (void)utf_char2bytes(u8c, dest);
1911 }
1912 else /* produce Latin1 */
1913 {
1914 --dest;
1915 if (u8c >= 0x100)
1916 {
1917 /* character doesn't fit in latin1, retry with
1918 * another fenc when possible, otherwise just
1919 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001920 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001922 if (conv_error == 0)
1923 conv_error = readfile_linenr(linecnt, ptr, p);
1924 if (bad_char_behavior == BAD_DROP)
1925 ++dest;
1926 else if (bad_char_behavior == BAD_KEEP)
1927 *dest = u8c;
1928 else if (eap != NULL && eap->bad_char != 0)
1929 *dest = bad_char_behavior;
1930 else
1931 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 }
1933 else
1934 *dest = u8c;
1935 }
1936 }
1937
1938 /* move the linerest to before the converted characters */
1939 line_start = dest - linerest;
1940 mch_memmove(line_start, buffer, (size_t)linerest);
1941 size = (long)((ptr + real_size) - dest);
1942 ptr = dest;
1943 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001944 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001946 int incomplete_tail = FALSE;
1947
1948 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1949 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001951 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001952 int l;
1953
1954 if (todo <= 0)
1955 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 if (*p >= 0x80)
1957 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 /* A length of 1 means it's an illegal byte. Accept
1959 * an incomplete character at the end though, the next
1960 * read() will get the next bytes, we'll check it
1961 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001962 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001963 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001965 /* Avoid retrying with a different encoding when
1966 * a truncated file is more likely, or attempting
1967 * to read the rest of an incomplete sequence when
1968 * we have already done so. */
1969 if (p > ptr || filesize > 0)
1970 incomplete_tail = TRUE;
1971 /* Incomplete byte sequence, move it to conv_rest[]
1972 * and try to read the rest of it, unless we've
1973 * already done so. */
1974 if (p > ptr)
1975 {
1976 conv_restlen = todo;
1977 mch_memmove(conv_rest, p, conv_restlen);
1978 size -= conv_restlen;
1979 break;
1980 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001982 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001983 {
1984 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00001985 * do that, unless at EOF where a truncated
1986 * file is more likely than a conversion error. */
1987 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001988 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001989# ifdef USE_ICONV
1990 /* When we did a conversion report an error. */
1991 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
1992 conv_error = readfile_linenr(linecnt, ptr, p);
1993# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001994 /* Remember the first linenr with an illegal byte */
1995 if (conv_error == 0 && illegal_byte == 0)
1996 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001997
1998 /* Drop, keep or replace the bad byte. */
1999 if (bad_char_behavior == BAD_DROP)
2000 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002001 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002002 --p;
2003 --size;
2004 }
2005 else if (bad_char_behavior != BAD_KEEP)
2006 *p = bad_char_behavior;
2007 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002008 else
2009 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 }
2011 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002012 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 {
2014 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002016 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002018 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2019 /* iconv() failed, try 'charconvert' */
2020 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 else
2022# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002023 /* use next item from 'fileencodings' */
2024 advance_fenc = TRUE;
2025 file_rewind = TRUE;
2026 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027 }
2028 }
2029#endif
2030
2031 /* count the number of characters (after conversion!) */
2032 filesize += size;
2033
2034 /*
2035 * when reading the first part of a file: guess EOL type
2036 */
2037 if (fileformat == EOL_UNKNOWN)
2038 {
2039 /* First try finding a NL, for Dos and Unix */
2040 if (try_dos || try_unix)
2041 {
2042 for (p = ptr; p < ptr + size; ++p)
2043 {
2044 if (*p == NL)
2045 {
2046 if (!try_unix
2047 || (try_dos && p > ptr && p[-1] == CAR))
2048 fileformat = EOL_DOS;
2049 else
2050 fileformat = EOL_UNIX;
2051 break;
2052 }
2053 }
2054
2055 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2056 if (fileformat == EOL_UNIX && try_mac)
2057 {
2058 /* Need to reset the counters when retrying fenc. */
2059 try_mac = 1;
2060 try_unix = 1;
2061 for (; p >= ptr && *p != CAR; p--)
2062 ;
2063 if (p >= ptr)
2064 {
2065 for (p = ptr; p < ptr + size; ++p)
2066 {
2067 if (*p == NL)
2068 try_unix++;
2069 else if (*p == CAR)
2070 try_mac++;
2071 }
2072 if (try_mac > try_unix)
2073 fileformat = EOL_MAC;
2074 }
2075 }
2076 }
2077
2078 /* No NL found: may use Mac format */
2079 if (fileformat == EOL_UNKNOWN && try_mac)
2080 fileformat = EOL_MAC;
2081
2082 /* Still nothing found? Use first format in 'ffs' */
2083 if (fileformat == EOL_UNKNOWN)
2084 fileformat = default_fileformat();
2085
2086 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002087 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088 set_fileformat(fileformat, OPT_LOCAL);
2089 }
2090 }
2091
2092 /*
2093 * This loop is executed once for every character read.
2094 * Keep it fast!
2095 */
2096 if (fileformat == EOL_MAC)
2097 {
2098 --ptr;
2099 while (++ptr, --size >= 0)
2100 {
2101 /* catch most common case first */
2102 if ((c = *ptr) != NUL && c != CAR && c != NL)
2103 continue;
2104 if (c == NUL)
2105 *ptr = NL; /* NULs are replaced by newlines! */
2106 else if (c == NL)
2107 *ptr = CAR; /* NLs are replaced by CRs! */
2108 else
2109 {
2110 if (skip_count == 0)
2111 {
2112 *ptr = NUL; /* end of line */
2113 len = (colnr_T) (ptr - line_start + 1);
2114 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2115 {
2116 error = TRUE;
2117 break;
2118 }
2119 ++lnum;
2120 if (--read_count == 0)
2121 {
2122 error = TRUE; /* break loop */
2123 line_start = ptr; /* nothing left to write */
2124 break;
2125 }
2126 }
2127 else
2128 --skip_count;
2129 line_start = ptr + 1;
2130 }
2131 }
2132 }
2133 else
2134 {
2135 --ptr;
2136 while (++ptr, --size >= 0)
2137 {
2138 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2139 continue;
2140 if (c == NUL)
2141 *ptr = NL; /* NULs are replaced by newlines! */
2142 else
2143 {
2144 if (skip_count == 0)
2145 {
2146 *ptr = NUL; /* end of line */
2147 len = (colnr_T)(ptr - line_start + 1);
2148 if (fileformat == EOL_DOS)
2149 {
2150 if (ptr[-1] == CAR) /* remove CR */
2151 {
2152 ptr[-1] = NUL;
2153 --len;
2154 }
2155 /*
2156 * Reading in Dos format, but no CR-LF found!
2157 * When 'fileformats' includes "unix", delete all
2158 * the lines read so far and start all over again.
2159 * Otherwise give an error message later.
2160 */
2161 else if (ff_error != EOL_DOS)
2162 {
2163 if ( try_unix
2164 && !read_stdin
2165 && (read_buffer
2166 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2167 {
2168 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002169 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170 set_fileformat(EOL_UNIX, OPT_LOCAL);
2171 file_rewind = TRUE;
2172 keep_fileformat = TRUE;
2173 goto retry;
2174 }
2175 ff_error = EOL_DOS;
2176 }
2177 }
2178 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2179 {
2180 error = TRUE;
2181 break;
2182 }
2183 ++lnum;
2184 if (--read_count == 0)
2185 {
2186 error = TRUE; /* break loop */
2187 line_start = ptr; /* nothing left to write */
2188 break;
2189 }
2190 }
2191 else
2192 --skip_count;
2193 line_start = ptr + 1;
2194 }
2195 }
2196 }
2197 linerest = (long)(ptr - line_start);
2198 ui_breakcheck();
2199 }
2200
2201failed:
2202 /* not an error, max. number of lines reached */
2203 if (error && read_count == 0)
2204 error = FALSE;
2205
2206 /*
2207 * If we get EOF in the middle of a line, note the fact and
2208 * complete the line ourselves.
2209 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2210 */
2211 if (!error
2212 && !got_int
2213 && linerest != 0
2214 && !(!curbuf->b_p_bin
2215 && fileformat == EOL_DOS
2216 && *line_start == Ctrl_Z
2217 && ptr == line_start + 1))
2218 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002219 /* remember for when writing */
2220 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221 curbuf->b_p_eol = FALSE;
2222 *ptr = NUL;
2223 if (ml_append(lnum, line_start,
2224 (colnr_T)(ptr - line_start + 1), newfile) == FAIL)
2225 error = TRUE;
2226 else
2227 read_no_eol_lnum = ++lnum;
2228 }
2229
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002230 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 save_file_ff(curbuf); /* remember the current file format */
2232
2233#ifdef FEAT_CRYPT
2234 if (cryptkey != curbuf->b_p_key)
2235 vim_free(cryptkey);
2236#endif
2237
2238#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002239 /* If editing a new file: set 'fenc' for the current buffer.
2240 * Also for ":read ++edit file". */
2241 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002243 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 if (fenc_alloced)
2245 vim_free(fenc);
2246# ifdef USE_ICONV
2247 if (iconv_fd != (iconv_t)-1)
2248 {
2249 iconv_close(iconv_fd);
2250 iconv_fd = (iconv_t)-1;
2251 }
2252# endif
2253#endif
2254
2255 if (!read_buffer && !read_stdin)
2256 close(fd); /* errors are ignored */
2257 vim_free(buffer);
2258
2259#ifdef HAVE_DUP
2260 if (read_stdin)
2261 {
2262 /* Use stderr for stdin, makes shell commands work. */
2263 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002264 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 }
2266#endif
2267
2268#ifdef FEAT_MBYTE
2269 if (tmpname != NULL)
2270 {
2271 mch_remove(tmpname); /* delete converted file */
2272 vim_free(tmpname);
2273 }
2274#endif
2275 --no_wait_return; /* may wait for return now */
2276
2277 /*
2278 * In recovery mode everything but autocommands is skipped.
2279 */
2280 if (!recoverymode)
2281 {
2282 /* need to delete the last line, which comes from the empty buffer */
2283 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2284 {
2285#ifdef FEAT_NETBEANS_INTG
2286 netbeansFireChanges = 0;
2287#endif
2288 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2289#ifdef FEAT_NETBEANS_INTG
2290 netbeansFireChanges = 1;
2291#endif
2292 --linecnt;
2293 }
2294 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2295 if (filesize == 0)
2296 linecnt = 0;
2297 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002298 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002300#ifdef FEAT_DIFF
2301 /* After reading the text into the buffer the diff info needs to
2302 * be updated. */
2303 diff_invalidate(curbuf);
2304#endif
2305#ifdef FEAT_FOLDING
2306 /* All folds in the window are invalid now. Mark them for update
2307 * before triggering autocommands. */
2308 foldUpdateAll(curwin);
2309#endif
2310 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311 else if (linecnt) /* appended at least one line */
2312 appended_lines_mark(from, linecnt);
2313
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314#ifndef ALWAYS_USE_GUI
2315 /*
2316 * If we were reading from the same terminal as where messages go,
2317 * the screen will have been messed up.
2318 * Switch on raw mode now and clear the screen.
2319 */
2320 if (read_stdin)
2321 {
2322 settmode(TMODE_RAW); /* set to raw mode */
2323 starttermcap();
2324 screenclear();
2325 }
2326#endif
2327
2328 if (got_int)
2329 {
2330 if (!(flags & READ_DUMMY))
2331 {
2332 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2333 if (newfile)
2334 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2335 }
2336 msg_scroll = msg_save;
2337#ifdef FEAT_VIMINFO
2338 check_marks_read();
2339#endif
2340 return OK; /* an interrupt isn't really an error */
2341 }
2342
2343 if (!filtering && !(flags & READ_DUMMY))
2344 {
2345 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2346 c = FALSE;
2347
2348#ifdef UNIX
2349# ifdef S_ISFIFO
2350 if (S_ISFIFO(perm)) /* fifo or socket */
2351 {
2352 STRCAT(IObuff, _("[fifo/socket]"));
2353 c = TRUE;
2354 }
2355# else
2356# ifdef S_IFIFO
2357 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2358 {
2359 STRCAT(IObuff, _("[fifo]"));
2360 c = TRUE;
2361 }
2362# endif
2363# ifdef S_IFSOCK
2364 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2365 {
2366 STRCAT(IObuff, _("[socket]"));
2367 c = TRUE;
2368 }
2369# endif
2370# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002371# ifdef OPEN_CHR_FILES
2372 if (S_ISCHR(perm)) /* or character special */
2373 {
2374 STRCAT(IObuff, _("[character special]"));
2375 c = TRUE;
2376 }
2377# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378#endif
2379 if (curbuf->b_p_ro)
2380 {
2381 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2382 c = TRUE;
2383 }
2384 if (read_no_eol_lnum)
2385 {
2386 msg_add_eol();
2387 c = TRUE;
2388 }
2389 if (ff_error == EOL_DOS)
2390 {
2391 STRCAT(IObuff, _("[CR missing]"));
2392 c = TRUE;
2393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 if (split)
2395 {
2396 STRCAT(IObuff, _("[long lines split]"));
2397 c = TRUE;
2398 }
2399#ifdef FEAT_MBYTE
2400 if (notconverted)
2401 {
2402 STRCAT(IObuff, _("[NOT converted]"));
2403 c = TRUE;
2404 }
2405 else if (converted)
2406 {
2407 STRCAT(IObuff, _("[converted]"));
2408 c = TRUE;
2409 }
2410#endif
2411#ifdef FEAT_CRYPT
2412 if (cryptkey != NULL)
2413 {
2414 STRCAT(IObuff, _("[crypted]"));
2415 c = TRUE;
2416 }
2417#endif
2418#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002419 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002421 sprintf((char *)IObuff + STRLEN(IObuff),
2422 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 c = TRUE;
2424 }
2425 else if (illegal_byte > 0)
2426 {
2427 sprintf((char *)IObuff + STRLEN(IObuff),
2428 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2429 c = TRUE;
2430 }
2431 else
2432#endif
2433 if (error)
2434 {
2435 STRCAT(IObuff, _("[READ ERRORS]"));
2436 c = TRUE;
2437 }
2438 if (msg_add_fileformat(fileformat))
2439 c = TRUE;
2440#ifdef FEAT_CRYPT
2441 if (cryptkey != NULL)
2442 msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN);
2443 else
2444#endif
2445 msg_add_lines(c, (long)linecnt, filesize);
2446
2447 vim_free(keep_msg);
2448 keep_msg = NULL;
2449 msg_scrolled_ign = TRUE;
2450#ifdef ALWAYS_USE_GUI
2451 /* Don't show the message when reading stdin, it would end up in a
2452 * message box (which might be shown when exiting!) */
2453 if (read_stdin || read_buffer)
2454 p = msg_may_trunc(FALSE, IObuff);
2455 else
2456#endif
2457 p = msg_trunc_attr(IObuff, FALSE, 0);
2458 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002459 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 /* Need to repeat the message after redrawing when:
2461 * - When reading from stdin (the screen will be cleared next).
2462 * - When restart_edit is set (otherwise there will be a delay
2463 * before redrawing).
2464 * - When the screen was scrolled but there is no wait-return
2465 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002466 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 msg_scrolled_ign = FALSE;
2468 }
2469
2470 /* with errors writing the file requires ":w!" */
2471 if (newfile && (error
2472#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002473 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002474 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475#endif
2476 ))
2477 curbuf->b_p_ro = TRUE;
2478
2479 u_clearline(); /* cannot use "U" command after adding lines */
2480
2481 /*
2482 * In Ex mode: cursor at last new line.
2483 * Otherwise: cursor at first new line.
2484 */
2485 if (exmode_active)
2486 curwin->w_cursor.lnum = from + linecnt;
2487 else
2488 curwin->w_cursor.lnum = from + 1;
2489 check_cursor_lnum();
2490 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2491
2492 /*
2493 * Set '[ and '] marks to the newly read lines.
2494 */
2495 curbuf->b_op_start.lnum = from + 1;
2496 curbuf->b_op_start.col = 0;
2497 curbuf->b_op_end.lnum = from + linecnt;
2498 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002499
2500#ifdef WIN32
2501 /*
2502 * Work around a weird problem: When a file has two links (only
2503 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002504 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002505 * It's correct again after reading the file, thus reset the timestamp
2506 * here.
2507 */
2508 if (newfile && !read_stdin && !read_buffer
2509 && mch_stat((char *)fname, &st) >= 0)
2510 {
2511 buf_store_time(curbuf, &st, fname);
2512 curbuf->b_mtime_read = curbuf->b_mtime;
2513 }
2514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 }
2516 msg_scroll = msg_save;
2517
2518#ifdef FEAT_VIMINFO
2519 /*
2520 * Get the marks before executing autocommands, so they can be used there.
2521 */
2522 check_marks_read();
2523#endif
2524
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 /*
2526 * Trick: We remember if the last line of the read didn't have
2527 * an eol for when writing it again. This is required for
2528 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2529 */
2530 write_no_eol_lnum = read_no_eol_lnum;
2531
Bram Moolenaardf177f62005-02-22 08:39:57 +00002532#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 if (!read_stdin && !read_buffer)
2534 {
2535 int m = msg_scroll;
2536 int n = msg_scrolled;
2537
2538 /* Save the fileformat now, otherwise the buffer will be considered
2539 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002540 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 save_file_ff(curbuf);
2542
2543 /*
2544 * The output from the autocommands should not overwrite anything and
2545 * should not be overwritten: Set msg_scroll, restore its value if no
2546 * output was done.
2547 */
2548 msg_scroll = TRUE;
2549 if (filtering)
2550 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2551 FALSE, curbuf, eap);
2552 else if (newfile)
2553 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2554 FALSE, curbuf, eap);
2555 else
2556 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2557 FALSE, NULL, eap);
2558 if (msg_scrolled == n)
2559 msg_scroll = m;
2560#ifdef FEAT_EVAL
2561 if (aborting()) /* autocmds may abort script processing */
2562 return FAIL;
2563#endif
2564 }
2565#endif
2566
2567 if (recoverymode && error)
2568 return FAIL;
2569 return OK;
2570}
2571
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002572#ifdef OPEN_CHR_FILES
2573/*
2574 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2575 * which is the name of files used for process substitution output by
2576 * some shells on some operating systems, e.g., bash on SunOS.
2577 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2578 */
2579 static int
2580is_dev_fd_file(fname)
2581 char_u *fname;
2582{
2583 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2584 && VIM_ISDIGIT(fname[8])
2585 && *skipdigits(fname + 9) == NUL
2586 && (fname[9] != NUL
2587 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2588}
2589#endif
2590
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002591#ifdef FEAT_MBYTE
2592
2593/*
2594 * From the current line count and characters read after that, estimate the
2595 * line number where we are now.
2596 * Used for error messages that include a line number.
2597 */
2598 static linenr_T
2599readfile_linenr(linecnt, p, endp)
2600 linenr_T linecnt; /* line count before reading more bytes */
2601 char_u *p; /* start of more bytes read */
2602 char_u *endp; /* end of more bytes read */
2603{
2604 char_u *s;
2605 linenr_T lnum;
2606
2607 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2608 for (s = p; s < endp; ++s)
2609 if (*s == '\n')
2610 ++lnum;
2611 return lnum;
2612}
2613#endif
2614
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002616 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2617 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 * Returns OK or FAIL.
2619 */
2620 int
2621prep_exarg(eap, buf)
2622 exarg_T *eap;
2623 buf_T *buf;
2624{
2625 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2626#ifdef FEAT_MBYTE
2627 + STRLEN(buf->b_p_fenc)
2628#endif
2629 + 15));
2630 if (eap->cmd == NULL)
2631 return FAIL;
2632
2633#ifdef FEAT_MBYTE
2634 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2635 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002636 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637#else
2638 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2639#endif
2640 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002641
2642 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002643 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002644 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645 return OK;
2646}
2647
2648#ifdef FEAT_MBYTE
2649/*
2650 * Find next fileencoding to use from 'fileencodings'.
2651 * "pp" points to fenc_next. It's advanced to the next item.
2652 * When there are no more items, an empty string is returned and *pp is set to
2653 * NULL.
2654 * When *pp is not set to NULL, the result is in allocated memory.
2655 */
2656 static char_u *
2657next_fenc(pp)
2658 char_u **pp;
2659{
2660 char_u *p;
2661 char_u *r;
2662
2663 if (**pp == NUL)
2664 {
2665 *pp = NULL;
2666 return (char_u *)"";
2667 }
2668 p = vim_strchr(*pp, ',');
2669 if (p == NULL)
2670 {
2671 r = enc_canonize(*pp);
2672 *pp += STRLEN(*pp);
2673 }
2674 else
2675 {
2676 r = vim_strnsave(*pp, (int)(p - *pp));
2677 *pp = p + 1;
2678 if (r != NULL)
2679 {
2680 p = enc_canonize(r);
2681 vim_free(r);
2682 r = p;
2683 }
2684 }
2685 if (r == NULL) /* out of memory */
2686 {
2687 r = (char_u *)"";
2688 *pp = NULL;
2689 }
2690 return r;
2691}
2692
2693# ifdef FEAT_EVAL
2694/*
2695 * Convert a file with the 'charconvert' expression.
2696 * This closes the file which is to be read, converts it and opens the
2697 * resulting file for reading.
2698 * Returns name of the resulting converted file (the caller should delete it
2699 * after reading it).
2700 * Returns NULL if the conversion failed ("*fdp" is not set) .
2701 */
2702 static char_u *
2703readfile_charconvert(fname, fenc, fdp)
2704 char_u *fname; /* name of input file */
2705 char_u *fenc; /* converted from */
2706 int *fdp; /* in/out: file descriptor of file */
2707{
2708 char_u *tmpname;
2709 char_u *errmsg = NULL;
2710
2711 tmpname = vim_tempname('r');
2712 if (tmpname == NULL)
2713 errmsg = (char_u *)_("Can't find temp file for conversion");
2714 else
2715 {
2716 close(*fdp); /* close the input file, ignore errors */
2717 *fdp = -1;
2718 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2719 fname, tmpname) == FAIL)
2720 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2721 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2722 O_RDONLY | O_EXTRA, 0)) < 0)
2723 errmsg = (char_u *)_("can't read output of 'charconvert'");
2724 }
2725
2726 if (errmsg != NULL)
2727 {
2728 /* Don't use emsg(), it breaks mappings, the retry with
2729 * another type of conversion might still work. */
2730 MSG(errmsg);
2731 if (tmpname != NULL)
2732 {
2733 mch_remove(tmpname); /* delete converted file */
2734 vim_free(tmpname);
2735 tmpname = NULL;
2736 }
2737 }
2738
2739 /* If the input file is closed, open it (caller should check for error). */
2740 if (*fdp < 0)
2741 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2742
2743 return tmpname;
2744}
2745# endif
2746
2747#endif
2748
2749#ifdef FEAT_VIMINFO
2750/*
2751 * Read marks for the current buffer from the viminfo file, when we support
2752 * buffer marks and the buffer has a name.
2753 */
2754 static void
2755check_marks_read()
2756{
2757 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2758 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002759 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760
2761 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2762 * the ' parameter after opening a buffer. */
2763 curbuf->b_marks_read = TRUE;
2764}
2765#endif
2766
2767#ifdef FEAT_CRYPT
2768/*
2769 * Check for magic number used for encryption.
2770 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2771 * *filesizep are updated.
2772 * Return the (new) encryption key, NULL for no encryption.
2773 */
2774 static char_u *
2775check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile)
2776 char_u *cryptkey; /* previous encryption key or NULL */
2777 char_u *ptr; /* pointer to read bytes */
2778 long *sizep; /* length of read bytes */
2779 long *filesizep; /* nr of bytes used from file */
2780 int newfile; /* editing a new buffer */
2781{
2782 if (*sizep >= CRYPT_MAGIC_LEN
2783 && STRNCMP(ptr, CRYPT_MAGIC, CRYPT_MAGIC_LEN) == 0)
2784 {
2785 if (cryptkey == NULL)
2786 {
2787 if (*curbuf->b_p_key)
2788 cryptkey = curbuf->b_p_key;
2789 else
2790 {
2791 /* When newfile is TRUE, store the typed key
2792 * in the 'key' option and don't free it. */
2793 cryptkey = get_crypt_key(newfile, FALSE);
2794 /* check if empty key entered */
2795 if (cryptkey != NULL && *cryptkey == NUL)
2796 {
2797 if (cryptkey != curbuf->b_p_key)
2798 vim_free(cryptkey);
2799 cryptkey = NULL;
2800 }
2801 }
2802 }
2803
2804 if (cryptkey != NULL)
2805 {
2806 crypt_init_keys(cryptkey);
2807
2808 /* Remove magic number from the text */
2809 *filesizep += CRYPT_MAGIC_LEN;
2810 *sizep -= CRYPT_MAGIC_LEN;
2811 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN, (size_t)*sizep);
2812 }
2813 }
2814 /* When starting to edit a new file which does not have
2815 * encryption, clear the 'key' option, except when
2816 * starting up (called with -x argument) */
2817 else if (newfile && *curbuf->b_p_key && !starting)
2818 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2819
2820 return cryptkey;
2821}
2822#endif
2823
2824#ifdef UNIX
2825 static void
2826set_file_time(fname, atime, mtime)
2827 char_u *fname;
2828 time_t atime; /* access time */
2829 time_t mtime; /* modification time */
2830{
2831# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2832 struct utimbuf buf;
2833
2834 buf.actime = atime;
2835 buf.modtime = mtime;
2836 (void)utime((char *)fname, &buf);
2837# else
2838# if defined(HAVE_UTIMES)
2839 struct timeval tvp[2];
2840
2841 tvp[0].tv_sec = atime;
2842 tvp[0].tv_usec = 0;
2843 tvp[1].tv_sec = mtime;
2844 tvp[1].tv_usec = 0;
2845# ifdef NeXT
2846 (void)utimes((char *)fname, tvp);
2847# else
2848 (void)utimes((char *)fname, (const struct timeval *)&tvp);
2849# endif
2850# endif
2851# endif
2852}
2853#endif /* UNIX */
2854
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002855#if defined(VMS) && !defined(MIN)
2856/* Older DECC compiler for VAX doesn't define MIN() */
2857# define MIN(a, b) ((a) < (b) ? (a) : (b))
2858#endif
2859
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00002861 * Return TRUE if a file appears to be read-only from the file permissions.
2862 */
2863 int
2864check_file_readonly(fname, perm)
2865 char_u *fname; /* full path to file */
2866 int perm; /* known permissions on file */
2867{
2868#ifndef USE_MCH_ACCESS
2869 int fd = 0;
2870#endif
2871
2872 return (
2873#ifdef USE_MCH_ACCESS
2874# ifdef UNIX
2875 (perm & 0222) == 0 ||
2876# endif
2877 mch_access((char *)fname, W_OK)
2878#else
2879 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
2880 ? TRUE : (close(fd), FALSE)
2881#endif
2882 );
2883}
2884
2885
2886/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00002887 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888 *
2889 * We do our own buffering here because fwrite() is so slow.
2890 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00002891 * If "forceit" is true, we don't care for errors when attempting backups.
2892 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00002893 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00002894 *
2895 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
2896 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 *
2898 * This function must NOT use NameBuff (because it's called by autowrite()).
2899 *
2900 * return FAIL for failure, OK otherwise
2901 */
2902 int
2903buf_write(buf, fname, sfname, start, end, eap, append, forceit,
2904 reset_changed, filtering)
2905 buf_T *buf;
2906 char_u *fname;
2907 char_u *sfname;
2908 linenr_T start, end;
2909 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
2910 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00002911 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 int forceit;
2913 int reset_changed;
2914 int filtering;
2915{
2916 int fd;
2917 char_u *backup = NULL;
2918 int backup_copy = FALSE; /* copy the original file? */
2919 int dobackup;
2920 char_u *ffname;
2921 char_u *wfname = NULL; /* name of file to write to */
2922 char_u *s;
2923 char_u *ptr;
2924 char_u c;
2925 int len;
2926 linenr_T lnum;
2927 long nchars;
2928 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00002929 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 char_u *errnum = NULL;
2931 char_u *buffer;
2932 char_u smallbuf[SMBUFSIZE];
2933 char_u *backup_ext;
2934 int bufsize;
2935 long perm; /* file permissions */
2936 int retval = OK;
2937 int newfile = FALSE; /* TRUE if file doesn't exist yet */
2938 int msg_save = msg_scroll;
2939 int overwriting; /* TRUE if writing over original */
2940 int no_eol = FALSE; /* no end-of-line written */
2941 int device = FALSE; /* writing to a device */
2942 struct stat st_old;
2943 int prev_got_int = got_int;
2944 int file_readonly = FALSE; /* overwritten file is read-only */
2945 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
2946#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
2947 int made_writable = FALSE; /* 'w' bit has been set */
2948#endif
2949 /* writing everything */
2950 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
2951#ifdef FEAT_AUTOCMD
2952 linenr_T old_line_count = buf->b_ml.ml_line_count;
2953#endif
2954 int attr;
2955 int fileformat;
2956 int write_bin;
2957 struct bw_info write_info; /* info for buf_write_bytes() */
2958#ifdef FEAT_MBYTE
2959 int converted = FALSE;
2960 int notconverted = FALSE;
2961 char_u *fenc; /* effective 'fileencoding' */
2962 char_u *fenc_tofree = NULL; /* allocated "fenc" */
2963#endif
2964#ifdef HAS_BW_FLAGS
2965 int wb_flags = 0;
2966#endif
2967#ifdef HAVE_ACL
2968 vim_acl_T acl = NULL; /* ACL copied from original file to
2969 backup or new file */
2970#endif
2971
2972 if (fname == NULL || *fname == NUL) /* safety check */
2973 return FAIL;
2974
2975 /*
2976 * Disallow writing from .exrc and .vimrc in current directory for
2977 * security reasons.
2978 */
2979 if (check_secure())
2980 return FAIL;
2981
2982 /* Avoid a crash for a long name. */
2983 if (STRLEN(fname) >= MAXPATHL)
2984 {
2985 EMSG(_(e_longname));
2986 return FAIL;
2987 }
2988
2989#ifdef FEAT_MBYTE
2990 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
2991 write_info.bw_conv_buf = NULL;
2992 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00002993 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 write_info.bw_restlen = 0;
2995# ifdef USE_ICONV
2996 write_info.bw_iconv_fd = (iconv_t)-1;
2997# endif
2998#endif
2999
Bram Moolenaardf177f62005-02-22 08:39:57 +00003000 /* After writing a file changedtick changes but we don't want to display
3001 * the line. */
3002 ex_no_reprint = TRUE;
3003
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004 /*
3005 * If there is no file name yet, use the one for the written file.
3006 * BF_NOTEDITED is set to reflect this (in case the write fails).
3007 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003008 * Don't do this when appending.
3009 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003011 if (buf->b_ffname == NULL
3012 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 && whole
3014 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003015#ifdef FEAT_QUICKFIX
3016 && !bt_nofile(buf)
3017#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003019 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3021 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003022 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003024 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 }
3026
3027 if (sfname == NULL)
3028 sfname = fname;
3029 /*
3030 * For Unix: Use the short file name whenever possible.
3031 * Avoids problems with networks and when directory names are changed.
3032 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3033 * another directory, which we don't detect
3034 */
3035 ffname = fname; /* remember full fname */
3036#ifdef UNIX
3037 fname = sfname;
3038#endif
3039
3040 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3041 overwriting = TRUE;
3042 else
3043 overwriting = FALSE;
3044
3045 if (exiting)
3046 settmode(TMODE_COOK); /* when exiting allow typahead now */
3047
3048 ++no_wait_return; /* don't wait for return yet */
3049
3050 /*
3051 * Set '[ and '] marks to the lines to be written.
3052 */
3053 buf->b_op_start.lnum = start;
3054 buf->b_op_start.col = 0;
3055 buf->b_op_end.lnum = end;
3056 buf->b_op_end.col = 0;
3057
3058#ifdef FEAT_AUTOCMD
3059 {
3060 aco_save_T aco;
3061 int buf_ffname = FALSE;
3062 int buf_sfname = FALSE;
3063 int buf_fname_f = FALSE;
3064 int buf_fname_s = FALSE;
3065 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003066 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003067 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
3069 /*
3070 * Apply PRE aucocommands.
3071 * Set curbuf to the buffer to be written.
3072 * Careful: The autocommands may call buf_write() recursively!
3073 */
3074 if (ffname == buf->b_ffname)
3075 buf_ffname = TRUE;
3076 if (sfname == buf->b_sfname)
3077 buf_sfname = TRUE;
3078 if (fname == buf->b_ffname)
3079 buf_fname_f = TRUE;
3080 if (fname == buf->b_sfname)
3081 buf_fname_s = TRUE;
3082
3083 /* set curwin/curbuf to buf and save a few things */
3084 aucmd_prepbuf(&aco, buf);
3085
3086 if (append)
3087 {
3088 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3089 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003090 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003091#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003092 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003093 nofile_err = TRUE;
3094 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003095#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003096 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003098 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099 }
3100 else if (filtering)
3101 {
3102 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3103 NULL, sfname, FALSE, curbuf, eap);
3104 }
3105 else if (reset_changed && whole)
3106 {
3107 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3108 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003109 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003110#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003111 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003112 nofile_err = TRUE;
3113 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003114#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003115 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003117 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 }
3119 else
3120 {
3121 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3122 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003123 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003124#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003125 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003126 nofile_err = TRUE;
3127 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003128#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003129 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003131 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 }
3133
3134 /* restore curwin/curbuf and a few other things */
3135 aucmd_restbuf(&aco);
3136
3137 /*
3138 * In three situations we return here and don't write the file:
3139 * 1. the autocommands deleted or unloaded the buffer.
3140 * 2. The autocommands abort script processing.
3141 * 3. If one of the "Cmd" autocommands was executed.
3142 */
3143 if (!buf_valid(buf))
3144 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003145 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003146 || did_cmd || nofile_err
3147#ifdef FEAT_EVAL
3148 || aborting()
3149#endif
3150 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 {
3152 --no_wait_return;
3153 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003154 if (nofile_err)
3155 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3156
Bram Moolenaar1e015462005-09-25 22:16:38 +00003157 if (nofile_err
3158#ifdef FEAT_EVAL
3159 || aborting()
3160#endif
3161 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 /* An aborting error, interrupt or exception in the
3163 * autocommands. */
3164 return FAIL;
3165 if (did_cmd)
3166 {
3167 if (buf == NULL)
3168 /* The buffer was deleted. We assume it was written
3169 * (can't retry anyway). */
3170 return OK;
3171 if (overwriting)
3172 {
3173 /* Assume the buffer was written, update the timestamp. */
3174 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003175 if (append)
3176 buf->b_flags &= ~BF_NEW;
3177 else
3178 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003180 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003181 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 /* Buffer still changed, the autocommands didn't work
3183 * properly. */
3184 return FAIL;
3185 return OK;
3186 }
3187#ifdef FEAT_EVAL
3188 if (!aborting())
3189#endif
3190 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3191 return FAIL;
3192 }
3193
3194 /*
3195 * The autocommands may have changed the number of lines in the file.
3196 * When writing the whole file, adjust the end.
3197 * When writing part of the file, assume that the autocommands only
3198 * changed the number of lines that are to be written (tricky!).
3199 */
3200 if (buf->b_ml.ml_line_count != old_line_count)
3201 {
3202 if (whole) /* write all */
3203 end = buf->b_ml.ml_line_count;
3204 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3205 end += buf->b_ml.ml_line_count - old_line_count;
3206 else /* less lines */
3207 {
3208 end -= old_line_count - buf->b_ml.ml_line_count;
3209 if (end < start)
3210 {
3211 --no_wait_return;
3212 msg_scroll = msg_save;
3213 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3214 return FAIL;
3215 }
3216 }
3217 }
3218
3219 /*
3220 * The autocommands may have changed the name of the buffer, which may
3221 * be kept in fname, ffname and sfname.
3222 */
3223 if (buf_ffname)
3224 ffname = buf->b_ffname;
3225 if (buf_sfname)
3226 sfname = buf->b_sfname;
3227 if (buf_fname_f)
3228 fname = buf->b_ffname;
3229 if (buf_fname_s)
3230 fname = buf->b_sfname;
3231 }
3232#endif
3233
3234#ifdef FEAT_NETBEANS_INTG
3235 if (usingNetbeans && isNetbeansBuffer(buf))
3236 {
3237 if (whole)
3238 {
3239 /*
3240 * b_changed can be 0 after an undo, but we still need to write
3241 * the buffer to NetBeans.
3242 */
3243 if (buf->b_changed || isNetbeansModified(buf))
3244 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003245 --no_wait_return; /* may wait for return now */
3246 msg_scroll = msg_save;
3247 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248 return retval;
3249 }
3250 else
3251 {
3252 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003253 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 buffer = NULL;
3255 goto fail;
3256 }
3257 }
3258 else
3259 {
3260 errnum = (char_u *)"E657: ";
3261 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3262 buffer = NULL;
3263 goto fail;
3264 }
3265 }
3266#endif
3267
3268 if (shortmess(SHM_OVER) && !exiting)
3269 msg_scroll = FALSE; /* overwrite previous file message */
3270 else
3271 msg_scroll = TRUE; /* don't overwrite previous file message */
3272 if (!filtering)
3273 filemess(buf,
3274#ifndef UNIX
3275 sfname,
3276#else
3277 fname,
3278#endif
3279 (char_u *)"", 0); /* show that we are busy */
3280 msg_scroll = FALSE; /* always overwrite the file message now */
3281
3282 buffer = alloc(BUFSIZE);
3283 if (buffer == NULL) /* can't allocate big buffer, use small
3284 * one (to be able to write when out of
3285 * memory) */
3286 {
3287 buffer = smallbuf;
3288 bufsize = SMBUFSIZE;
3289 }
3290 else
3291 bufsize = BUFSIZE;
3292
3293 /*
3294 * Get information about original file (if there is one).
3295 */
3296#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003297 st_old.st_dev = 0;
3298 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299 perm = -1;
3300 if (mch_stat((char *)fname, &st_old) < 0)
3301 newfile = TRUE;
3302 else
3303 {
3304 perm = st_old.st_mode;
3305 if (!S_ISREG(st_old.st_mode)) /* not a file */
3306 {
3307 if (S_ISDIR(st_old.st_mode))
3308 {
3309 errnum = (char_u *)"E502: ";
3310 errmsg = (char_u *)_("is a directory");
3311 goto fail;
3312 }
3313 if (mch_nodetype(fname) != NODE_WRITABLE)
3314 {
3315 errnum = (char_u *)"E503: ";
3316 errmsg = (char_u *)_("is not a file or writable device");
3317 goto fail;
3318 }
3319 /* It's a device of some kind (or a fifo) which we can write to
3320 * but for which we can't make a backup. */
3321 device = TRUE;
3322 newfile = TRUE;
3323 perm = -1;
3324 }
3325 }
3326#else /* !UNIX */
3327 /*
3328 * Check for a writable device name.
3329 */
3330 c = mch_nodetype(fname);
3331 if (c == NODE_OTHER)
3332 {
3333 errnum = (char_u *)"E503: ";
3334 errmsg = (char_u *)_("is not a file or writable device");
3335 goto fail;
3336 }
3337 if (c == NODE_WRITABLE)
3338 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003339# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3340 /* MS-Windows allows opening a device, but we will probably get stuck
3341 * trying to write to it. */
3342 if (!p_odev)
3343 {
3344 errnum = (char_u *)"E796: ";
3345 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3346 goto fail;
3347 }
3348# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 device = TRUE;
3350 newfile = TRUE;
3351 perm = -1;
3352 }
3353 else
3354 {
3355 perm = mch_getperm(fname);
3356 if (perm < 0)
3357 newfile = TRUE;
3358 else if (mch_isdir(fname))
3359 {
3360 errnum = (char_u *)"E502: ";
3361 errmsg = (char_u *)_("is a directory");
3362 goto fail;
3363 }
3364 if (overwriting)
3365 (void)mch_stat((char *)fname, &st_old);
3366 }
3367#endif /* !UNIX */
3368
3369 if (!device && !newfile)
3370 {
3371 /*
3372 * Check if the file is really writable (when renaming the file to
3373 * make a backup we won't discover it later).
3374 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003375 file_readonly = check_file_readonly(fname, (int)perm);
3376
Bram Moolenaar071d4272004-06-13 20:20:40 +00003377 if (!forceit && file_readonly)
3378 {
3379 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3380 {
3381 errnum = (char_u *)"E504: ";
3382 errmsg = (char_u *)_(err_readonly);
3383 }
3384 else
3385 {
3386 errnum = (char_u *)"E505: ";
3387 errmsg = (char_u *)_("is read-only (add ! to override)");
3388 }
3389 goto fail;
3390 }
3391
3392 /*
3393 * Check if the timestamp hasn't changed since reading the file.
3394 */
3395 if (overwriting)
3396 {
3397 retval = check_mtime(buf, &st_old);
3398 if (retval == FAIL)
3399 goto fail;
3400 }
3401 }
3402
3403#ifdef HAVE_ACL
3404 /*
3405 * For systems that support ACL: get the ACL from the original file.
3406 */
3407 if (!newfile)
3408 acl = mch_get_acl(fname);
3409#endif
3410
3411 /*
3412 * If 'backupskip' is not empty, don't make a backup for some files.
3413 */
3414 dobackup = (p_wb || p_bk || *p_pm != NUL);
3415#ifdef FEAT_WILDIGN
3416 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3417 dobackup = FALSE;
3418#endif
3419
3420 /*
3421 * Save the value of got_int and reset it. We don't want a previous
3422 * interruption cancel writing, only hitting CTRL-C while writing should
3423 * abort it.
3424 */
3425 prev_got_int = got_int;
3426 got_int = FALSE;
3427
3428 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3429 buf->b_saving = TRUE;
3430
3431 /*
3432 * If we are not appending or filtering, the file exists, and the
3433 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3434 * When 'patchmode' is set also make a backup when appending.
3435 *
3436 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3437 * off. This helps when editing large files on almost-full disks.
3438 */
3439 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3440 {
3441#if defined(UNIX) || defined(WIN32)
3442 struct stat st;
3443#endif
3444
3445 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3446 backup_copy = TRUE;
3447#if defined(UNIX) || defined(WIN32)
3448 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3449 {
3450 int i;
3451
3452# ifdef UNIX
3453 /*
3454 * Don't rename the file when:
3455 * - it's a hard link
3456 * - it's a symbolic link
3457 * - we don't have write permission in the directory
3458 * - we can't set the owner/group of the new file
3459 */
3460 if (st_old.st_nlink > 1
3461 || mch_lstat((char *)fname, &st) < 0
3462 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003463 || st.st_ino != st_old.st_ino
3464# ifndef HAVE_FCHOWN
3465 || st.st_uid != st_old.st_uid
3466 || st.st_gid != st_old.st_gid
3467# endif
3468 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 backup_copy = TRUE;
3470 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003471# else
3472# ifdef WIN32
3473 /* On NTFS file systems hard links are possible. */
3474 if (mch_is_linked(fname))
3475 backup_copy = TRUE;
3476 else
3477# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478# endif
3479 {
3480 /*
3481 * Check if we can create a file and set the owner/group to
3482 * the ones from the original file.
3483 * First find a file name that doesn't exist yet (use some
3484 * arbitrary numbers).
3485 */
3486 STRCPY(IObuff, fname);
3487 for (i = 4913; ; i += 123)
3488 {
3489 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003490 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491 break;
3492 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003493 fd = mch_open((char *)IObuff,
3494 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 if (fd < 0) /* can't write in directory */
3496 backup_copy = TRUE;
3497 else
3498 {
3499# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003500# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003501 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003502# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 if (mch_stat((char *)IObuff, &st) < 0
3504 || st.st_uid != st_old.st_uid
3505 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003506 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507 backup_copy = TRUE;
3508# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003509 /* Close the file before removing it, on MS-Windows we
3510 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003511 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003512 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513 }
3514 }
3515 }
3516
3517# ifdef UNIX
3518 /*
3519 * Break symlinks and/or hardlinks if we've been asked to.
3520 */
3521 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3522 {
3523 int lstat_res;
3524
3525 lstat_res = mch_lstat((char *)fname, &st);
3526
3527 /* Symlinks. */
3528 if ((bkc_flags & BKC_BREAKSYMLINK)
3529 && lstat_res == 0
3530 && st.st_ino != st_old.st_ino)
3531 backup_copy = FALSE;
3532
3533 /* Hardlinks. */
3534 if ((bkc_flags & BKC_BREAKHARDLINK)
3535 && st_old.st_nlink > 1
3536 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3537 backup_copy = FALSE;
3538 }
3539#endif
3540
3541#endif
3542
3543 /* make sure we have a valid backup extension to use */
3544 if (*p_bex == NUL)
3545 {
3546#ifdef RISCOS
3547 backup_ext = (char_u *)"/bak";
3548#else
3549 backup_ext = (char_u *)".bak";
3550#endif
3551 }
3552 else
3553 backup_ext = p_bex;
3554
3555 if (backup_copy
3556 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3557 {
3558 int bfd;
3559 char_u *copybuf, *wp;
3560 int some_error = FALSE;
3561 struct stat st_new;
3562 char_u *dirp;
3563 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003564#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565 int did_set_shortname;
3566#endif
3567
3568 copybuf = alloc(BUFSIZE + 1);
3569 if (copybuf == NULL)
3570 {
3571 some_error = TRUE; /* out of memory */
3572 goto nobackup;
3573 }
3574
3575 /*
3576 * Try to make the backup in each directory in the 'bdir' option.
3577 *
3578 * Unix semantics has it, that we may have a writable file,
3579 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3580 * - the directory is not writable,
3581 * - the file may be a symbolic link,
3582 * - the file may belong to another user/group, etc.
3583 *
3584 * For these reasons, the existing writable file must be truncated
3585 * and reused. Creation of a backup COPY will be attempted.
3586 */
3587 dirp = p_bdir;
3588 while (*dirp)
3589 {
3590#ifdef UNIX
3591 st_new.st_ino = 0;
3592 st_new.st_dev = 0;
3593 st_new.st_gid = 0;
3594#endif
3595
3596 /*
3597 * Isolate one directory name, using an entry in 'bdir'.
3598 */
3599 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3600 rootname = get_file_in_dir(fname, copybuf);
3601 if (rootname == NULL)
3602 {
3603 some_error = TRUE; /* out of memory */
3604 goto nobackup;
3605 }
3606
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003607#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 did_set_shortname = FALSE;
3609#endif
3610
3611 /*
3612 * May try twice if 'shortname' not set.
3613 */
3614 for (;;)
3615 {
3616 /*
3617 * Make backup file name.
3618 */
3619 backup = buf_modname(
3620#ifdef SHORT_FNAME
3621 TRUE,
3622#else
3623 (buf->b_p_sn || buf->b_shortname),
3624#endif
3625 rootname, backup_ext, FALSE);
3626 if (backup == NULL)
3627 {
3628 vim_free(rootname);
3629 some_error = TRUE; /* out of memory */
3630 goto nobackup;
3631 }
3632
3633 /*
3634 * Check if backup file already exists.
3635 */
3636 if (mch_stat((char *)backup, &st_new) >= 0)
3637 {
3638#ifdef UNIX
3639 /*
3640 * Check if backup file is same as original file.
3641 * May happen when modname() gave the same file back.
3642 * E.g. silly link, or file name-length reached.
3643 * If we don't check here, we either ruin the file
3644 * when copying or erase it after writing. jw.
3645 */
3646 if (st_new.st_dev == st_old.st_dev
3647 && st_new.st_ino == st_old.st_ino)
3648 {
3649 vim_free(backup);
3650 backup = NULL; /* no backup file to delete */
3651# ifndef SHORT_FNAME
3652 /*
3653 * may try again with 'shortname' set
3654 */
3655 if (!(buf->b_shortname || buf->b_p_sn))
3656 {
3657 buf->b_shortname = TRUE;
3658 did_set_shortname = TRUE;
3659 continue;
3660 }
3661 /* setting shortname didn't help */
3662 if (did_set_shortname)
3663 buf->b_shortname = FALSE;
3664# endif
3665 break;
3666 }
3667#endif
3668
3669 /*
3670 * If we are not going to keep the backup file, don't
3671 * delete an existing one, try to use another name.
3672 * Change one character, just before the extension.
3673 */
3674 if (!p_bk)
3675 {
3676 wp = backup + STRLEN(backup) - 1
3677 - STRLEN(backup_ext);
3678 if (wp < backup) /* empty file name ??? */
3679 wp = backup;
3680 *wp = 'z';
3681 while (*wp > 'a'
3682 && mch_stat((char *)backup, &st_new) >= 0)
3683 --*wp;
3684 /* They all exist??? Must be something wrong. */
3685 if (*wp == 'a')
3686 {
3687 vim_free(backup);
3688 backup = NULL;
3689 }
3690 }
3691 }
3692 break;
3693 }
3694 vim_free(rootname);
3695
3696 /*
3697 * Try to create the backup file
3698 */
3699 if (backup != NULL)
3700 {
3701 /* remove old backup, if present */
3702 mch_remove(backup);
3703 /* Open with O_EXCL to avoid the file being created while
3704 * we were sleeping (symlink hacker attack?) */
3705 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003706 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3707 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 if (bfd < 0)
3709 {
3710 vim_free(backup);
3711 backup = NULL;
3712 }
3713 else
3714 {
3715 /* set file protection same as original file, but
3716 * strip s-bit */
3717 (void)mch_setperm(backup, perm & 0777);
3718
3719#ifdef UNIX
3720 /*
3721 * Try to set the group of the backup same as the
3722 * original file. If this fails, set the protection
3723 * bits for the group same as the protection bits for
3724 * others.
3725 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003726 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003728 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729# endif
3730 )
3731 mch_setperm(backup,
3732 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003733# ifdef HAVE_SELINUX
3734 mch_copy_sec(fname, backup);
3735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736#endif
3737
3738 /*
3739 * copy the file.
3740 */
3741 write_info.bw_fd = bfd;
3742 write_info.bw_buf = copybuf;
3743#ifdef HAS_BW_FLAGS
3744 write_info.bw_flags = FIO_NOCONVERT;
3745#endif
3746 while ((write_info.bw_len = vim_read(fd, copybuf,
3747 BUFSIZE)) > 0)
3748 {
3749 if (buf_write_bytes(&write_info) == FAIL)
3750 {
3751 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3752 break;
3753 }
3754 ui_breakcheck();
3755 if (got_int)
3756 {
3757 errmsg = (char_u *)_(e_interr);
3758 break;
3759 }
3760 }
3761
3762 if (close(bfd) < 0 && errmsg == NULL)
3763 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3764 if (write_info.bw_len < 0)
3765 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3766#ifdef UNIX
3767 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3768#endif
3769#ifdef HAVE_ACL
3770 mch_set_acl(backup, acl);
3771#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003772#ifdef HAVE_SELINUX
3773 mch_copy_sec(fname, backup);
3774#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 break;
3776 }
3777 }
3778 }
3779 nobackup:
3780 close(fd); /* ignore errors for closing read file */
3781 vim_free(copybuf);
3782
3783 if (backup == NULL && errmsg == NULL)
3784 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3785 /* ignore errors when forceit is TRUE */
3786 if ((some_error || errmsg != NULL) && !forceit)
3787 {
3788 retval = FAIL;
3789 goto fail;
3790 }
3791 errmsg = NULL;
3792 }
3793 else
3794 {
3795 char_u *dirp;
3796 char_u *p;
3797 char_u *rootname;
3798
3799 /*
3800 * Make a backup by renaming the original file.
3801 */
3802 /*
3803 * If 'cpoptions' includes the "W" flag, we don't want to
3804 * overwrite a read-only file. But rename may be possible
3805 * anyway, thus we need an extra check here.
3806 */
3807 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3808 {
3809 errnum = (char_u *)"E504: ";
3810 errmsg = (char_u *)_(err_readonly);
3811 goto fail;
3812 }
3813
3814 /*
3815 *
3816 * Form the backup file name - change path/fo.o.h to
3817 * path/fo.o.h.bak Try all directories in 'backupdir', first one
3818 * that works is used.
3819 */
3820 dirp = p_bdir;
3821 while (*dirp)
3822 {
3823 /*
3824 * Isolate one directory name and make the backup file name.
3825 */
3826 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
3827 rootname = get_file_in_dir(fname, IObuff);
3828 if (rootname == NULL)
3829 backup = NULL;
3830 else
3831 {
3832 backup = buf_modname(
3833#ifdef SHORT_FNAME
3834 TRUE,
3835#else
3836 (buf->b_p_sn || buf->b_shortname),
3837#endif
3838 rootname, backup_ext, FALSE);
3839 vim_free(rootname);
3840 }
3841
3842 if (backup != NULL)
3843 {
3844 /*
3845 * If we are not going to keep the backup file, don't
3846 * delete an existing one, try to use another name.
3847 * Change one character, just before the extension.
3848 */
3849 if (!p_bk && mch_getperm(backup) >= 0)
3850 {
3851 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
3852 if (p < backup) /* empty file name ??? */
3853 p = backup;
3854 *p = 'z';
3855 while (*p > 'a' && mch_getperm(backup) >= 0)
3856 --*p;
3857 /* They all exist??? Must be something wrong! */
3858 if (*p == 'a')
3859 {
3860 vim_free(backup);
3861 backup = NULL;
3862 }
3863 }
3864 }
3865 if (backup != NULL)
3866 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003868 * Delete any existing backup and move the current version
3869 * to the backup. For safety, we don't remove the backup
3870 * until the write has finished successfully. And if the
3871 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 */
3873 /*
3874 * If the renaming of the original file to the backup file
3875 * works, quit here.
3876 */
3877 if (vim_rename(fname, backup) == 0)
3878 break;
3879
3880 vim_free(backup); /* don't do the rename below */
3881 backup = NULL;
3882 }
3883 }
3884 if (backup == NULL && !forceit)
3885 {
3886 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
3887 goto fail;
3888 }
3889 }
3890 }
3891
3892#if defined(UNIX) && !defined(ARCHIE)
3893 /* When using ":w!" and the file was read-only: make it writable */
3894 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
3895 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
3896 {
3897 perm |= 0200;
3898 (void)mch_setperm(fname, perm);
3899 made_writable = TRUE;
3900 }
3901#endif
3902
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003903 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003904 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
3905 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 {
3907 buf->b_p_ro = FALSE;
3908#ifdef FEAT_TITLE
3909 need_maketitle = TRUE; /* set window title later */
3910#endif
3911#ifdef FEAT_WINDOWS
3912 status_redraw_all(); /* redraw status lines later */
3913#endif
3914 }
3915
3916 if (end > buf->b_ml.ml_line_count)
3917 end = buf->b_ml.ml_line_count;
3918 if (buf->b_ml.ml_flags & ML_EMPTY)
3919 start = end + 1;
3920
3921 /*
3922 * If the original file is being overwritten, there is a small chance that
3923 * we crash in the middle of writing. Therefore the file is preserved now.
3924 * This makes all block numbers positive so that recovery does not need
3925 * the original file.
3926 * Don't do this if there is a backup file and we are exiting.
3927 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003928 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 && !(exiting && backup != NULL))
3930 {
3931 ml_preserve(buf, FALSE);
3932 if (got_int)
3933 {
3934 errmsg = (char_u *)_(e_interr);
3935 goto restore_backup;
3936 }
3937 }
3938
3939#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
3940 /*
3941 * Before risking to lose the original file verify if there's
3942 * a resource fork to preserve, and if cannot be done warn
3943 * the users. This happens when overwriting without backups.
3944 */
3945 if (backup == NULL && overwriting && !append)
3946 if (mch_has_resource_fork(fname))
3947 {
3948 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
3949 goto restore_backup;
3950 }
3951#endif
3952
3953#ifdef VMS
3954 vms_remove_version(fname); /* remove version */
3955#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003956 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 * multi-byte conversion. */
3958 wfname = fname;
3959
3960#ifdef FEAT_MBYTE
3961 /* Check for forced 'fileencoding' from "++opt=val" argument. */
3962 if (eap != NULL && eap->force_enc != 0)
3963 {
3964 fenc = eap->cmd + eap->force_enc;
3965 fenc = enc_canonize(fenc);
3966 fenc_tofree = fenc;
3967 }
3968 else
3969 fenc = buf->b_p_fenc;
3970
3971 /*
3972 * The file needs to be converted when 'fileencoding' is set and
3973 * 'fileencoding' differs from 'encoding'.
3974 */
3975 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
3976
3977 /*
3978 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
3979 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
3980 * Prepare the flags for it and allocate bw_conv_buf when needed.
3981 */
3982 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
3983 {
3984 wb_flags = get_fio_flags(fenc);
3985 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
3986 {
3987 /* Need to allocate a buffer to translate into. */
3988 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
3989 write_info.bw_conv_buflen = bufsize * 2;
3990 else /* FIO_UCS4 */
3991 write_info.bw_conv_buflen = bufsize * 4;
3992 write_info.bw_conv_buf
3993 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3994 if (write_info.bw_conv_buf == NULL)
3995 end = 0;
3996 }
3997 }
3998
3999# ifdef WIN3264
4000 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4001 {
4002 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4003 write_info.bw_conv_buflen = bufsize * 4;
4004 write_info.bw_conv_buf
4005 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4006 if (write_info.bw_conv_buf == NULL)
4007 end = 0;
4008 }
4009# endif
4010
4011# ifdef MACOS_X
4012 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4013 {
4014 write_info.bw_conv_buflen = bufsize * 3;
4015 write_info.bw_conv_buf
4016 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4017 if (write_info.bw_conv_buf == NULL)
4018 end = 0;
4019 }
4020# endif
4021
4022# if defined(FEAT_EVAL) || defined(USE_ICONV)
4023 if (converted && wb_flags == 0)
4024 {
4025# ifdef USE_ICONV
4026 /*
4027 * Use iconv() conversion when conversion is needed and it's not done
4028 * internally.
4029 */
4030 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4031 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4032 if (write_info.bw_iconv_fd != (iconv_t)-1)
4033 {
4034 /* We're going to use iconv(), allocate a buffer to convert in. */
4035 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4036 write_info.bw_conv_buf
4037 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4038 if (write_info.bw_conv_buf == NULL)
4039 end = 0;
4040 write_info.bw_first = TRUE;
4041 }
4042# ifdef FEAT_EVAL
4043 else
4044# endif
4045# endif
4046
4047# ifdef FEAT_EVAL
4048 /*
4049 * When the file needs to be converted with 'charconvert' after
4050 * writing, write to a temp file instead and let the conversion
4051 * overwrite the original file.
4052 */
4053 if (*p_ccv != NUL)
4054 {
4055 wfname = vim_tempname('w');
4056 if (wfname == NULL) /* Can't write without a tempfile! */
4057 {
4058 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4059 goto restore_backup;
4060 }
4061 }
4062# endif
4063 }
4064# endif
4065 if (converted && wb_flags == 0
4066# ifdef USE_ICONV
4067 && write_info.bw_iconv_fd == (iconv_t)-1
4068# endif
4069# ifdef FEAT_EVAL
4070 && wfname == fname
4071# endif
4072 )
4073 {
4074 if (!forceit)
4075 {
4076 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4077 goto restore_backup;
4078 }
4079 notconverted = TRUE;
4080 }
4081#endif
4082
4083 /*
4084 * Open the file "wfname" for writing.
4085 * We may try to open the file twice: If we can't write to the
4086 * file and forceit is TRUE we delete the existing file and try to create
4087 * a new one. If this still fails we may have lost the original file!
4088 * (this may happen when the user reached his quotum for number of files).
4089 * Appending will fail if the file does not exist and forceit is FALSE.
4090 */
4091 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4092 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4093 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004094 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 {
4096 /*
4097 * A forced write will try to create a new file if the old one is
4098 * still readonly. This may also happen when the directory is
4099 * read-only. In that case the mch_remove() will fail.
4100 */
4101 if (errmsg == NULL)
4102 {
4103#ifdef UNIX
4104 struct stat st;
4105
4106 /* Don't delete the file when it's a hard or symbolic link. */
4107 if ((!newfile && st_old.st_nlink > 1)
4108 || (mch_lstat((char *)fname, &st) == 0
4109 && (st.st_dev != st_old.st_dev
4110 || st.st_ino != st_old.st_ino)))
4111 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4112 else
4113#endif
4114 {
4115 errmsg = (char_u *)_("E212: Can't open file for writing");
4116 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4117 && perm >= 0)
4118 {
4119#ifdef UNIX
4120 /* we write to the file, thus it should be marked
4121 writable after all */
4122 if (!(perm & 0200))
4123 made_writable = TRUE;
4124 perm |= 0200;
4125 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4126 perm &= 0777;
4127#endif
4128 if (!append) /* don't remove when appending */
4129 mch_remove(wfname);
4130 continue;
4131 }
4132 }
4133 }
4134
4135restore_backup:
4136 {
4137 struct stat st;
4138
4139 /*
4140 * If we failed to open the file, we don't need a backup. Throw it
4141 * away. If we moved or removed the original file try to put the
4142 * backup in its place.
4143 */
4144 if (backup != NULL && wfname == fname)
4145 {
4146 if (backup_copy)
4147 {
4148 /*
4149 * There is a small chance that we removed the original,
4150 * try to move the copy in its place.
4151 * This may not work if the vim_rename() fails.
4152 * In that case we leave the copy around.
4153 */
4154 /* If file does not exist, put the copy in its place */
4155 if (mch_stat((char *)fname, &st) < 0)
4156 vim_rename(backup, fname);
4157 /* if original file does exist throw away the copy */
4158 if (mch_stat((char *)fname, &st) >= 0)
4159 mch_remove(backup);
4160 }
4161 else
4162 {
4163 /* try to put the original file back */
4164 vim_rename(backup, fname);
4165 }
4166 }
4167
4168 /* if original file no longer exists give an extra warning */
4169 if (!newfile && mch_stat((char *)fname, &st) < 0)
4170 end = 0;
4171 }
4172
4173#ifdef FEAT_MBYTE
4174 if (wfname != fname)
4175 vim_free(wfname);
4176#endif
4177 goto fail;
4178 }
4179 errmsg = NULL;
4180
4181#if defined(MACOS_CLASSIC) || defined(WIN3264)
4182 /* TODO: Is it need for MACOS_X? (Dany) */
4183 /*
4184 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004185 * This is done in order to preserve the resource fork and the
4186 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 */
4188 if (backup != NULL && overwriting && !append)
4189 {
4190 if (backup_copy)
4191 (void)mch_copy_file_attribute(wfname, backup);
4192 else
4193 (void)mch_copy_file_attribute(backup, wfname);
4194 }
4195
4196 if (!overwriting && !append)
4197 {
4198 if (buf->b_ffname != NULL)
4199 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004200 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 }
4202#endif
4203
4204 write_info.bw_fd = fd;
4205
4206#ifdef FEAT_CRYPT
4207 if (*buf->b_p_key && !filtering)
4208 {
4209 crypt_init_keys(buf->b_p_key);
4210 /* Write magic number, so that Vim knows that this file is encrypted
4211 * when reading it again. This also undergoes utf-8 to ucs-2/4
4212 * conversion when needed. */
4213 write_info.bw_buf = (char_u *)CRYPT_MAGIC;
4214 write_info.bw_len = CRYPT_MAGIC_LEN;
4215 write_info.bw_flags = FIO_NOCONVERT;
4216 if (buf_write_bytes(&write_info) == FAIL)
4217 end = 0;
4218 wb_flags |= FIO_ENCRYPTED;
4219 }
4220#endif
4221
4222 write_info.bw_buf = buffer;
4223 nchars = 0;
4224
4225 /* use "++bin", "++nobin" or 'binary' */
4226 if (eap != NULL && eap->force_bin != 0)
4227 write_bin = (eap->force_bin == FORCE_BIN);
4228 else
4229 write_bin = buf->b_p_bin;
4230
4231#ifdef FEAT_MBYTE
4232 /*
4233 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004234 * Skip it when appending and the file already existed, the BOM only makes
4235 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004237 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004238 {
4239 write_info.bw_len = make_bom(buffer, fenc);
4240 if (write_info.bw_len > 0)
4241 {
4242 /* don't convert, do encryption */
4243 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4244 if (buf_write_bytes(&write_info) == FAIL)
4245 end = 0;
4246 else
4247 nchars += write_info.bw_len;
4248 }
4249 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004250 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251#endif
4252
4253 write_info.bw_len = bufsize;
4254#ifdef HAS_BW_FLAGS
4255 write_info.bw_flags = wb_flags;
4256#endif
4257 fileformat = get_fileformat_force(buf, eap);
4258 s = buffer;
4259 len = 0;
4260 for (lnum = start; lnum <= end; ++lnum)
4261 {
4262 /*
4263 * The next while loop is done once for each character written.
4264 * Keep it fast!
4265 */
4266 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4267 while ((c = *++ptr) != NUL)
4268 {
4269 if (c == NL)
4270 *s = NUL; /* replace newlines with NULs */
4271 else if (c == CAR && fileformat == EOL_MAC)
4272 *s = NL; /* Mac: replace CRs with NLs */
4273 else
4274 *s = c;
4275 ++s;
4276 if (++len != bufsize)
4277 continue;
4278 if (buf_write_bytes(&write_info) == FAIL)
4279 {
4280 end = 0; /* write error: break loop */
4281 break;
4282 }
4283 nchars += bufsize;
4284 s = buffer;
4285 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004286#ifdef FEAT_MBYTE
4287 write_info.bw_start_lnum = lnum;
4288#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 }
4290 /* write failed or last line has no EOL: stop here */
4291 if (end == 0
4292 || (lnum == end
4293 && write_bin
4294 && (lnum == write_no_eol_lnum
4295 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4296 {
4297 ++lnum; /* written the line, count it */
4298 no_eol = TRUE;
4299 break;
4300 }
4301 if (fileformat == EOL_UNIX)
4302 *s++ = NL;
4303 else
4304 {
4305 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4306 if (fileformat == EOL_DOS) /* write CR-NL */
4307 {
4308 if (++len == bufsize)
4309 {
4310 if (buf_write_bytes(&write_info) == FAIL)
4311 {
4312 end = 0; /* write error: break loop */
4313 break;
4314 }
4315 nchars += bufsize;
4316 s = buffer;
4317 len = 0;
4318 }
4319 *s++ = NL;
4320 }
4321 }
4322 if (++len == bufsize && end)
4323 {
4324 if (buf_write_bytes(&write_info) == FAIL)
4325 {
4326 end = 0; /* write error: break loop */
4327 break;
4328 }
4329 nchars += bufsize;
4330 s = buffer;
4331 len = 0;
4332
4333 ui_breakcheck();
4334 if (got_int)
4335 {
4336 end = 0; /* Interrupted, break loop */
4337 break;
4338 }
4339 }
4340#ifdef VMS
4341 /*
4342 * On VMS there is a problem: newlines get added when writing blocks
4343 * at a time. Fix it by writing a line at a time.
4344 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004345 * Explanation: VAX/DECC RTL insists that records in some RMS
4346 * structures end with a newline (carriage return) character, and if
4347 * they don't it adds one.
4348 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004350 if (buf->b_fab_rfm == FAB$C_VFC
4351 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004353 int b2write;
4354
4355 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4356 ? MIN(4096, bufsize)
4357 : MIN(buf->b_fab_mrs, bufsize));
4358
4359 b2write = len;
4360 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004362 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4363 if (buf_write_bytes(&write_info) == FAIL)
4364 {
4365 end = 0;
4366 break;
4367 }
4368 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 }
4370 write_info.bw_len = bufsize;
4371 nchars += len;
4372 s = buffer;
4373 len = 0;
4374 }
4375#endif
4376 }
4377 if (len > 0 && end > 0)
4378 {
4379 write_info.bw_len = len;
4380 if (buf_write_bytes(&write_info) == FAIL)
4381 end = 0; /* write error */
4382 nchars += len;
4383 }
4384
4385#if defined(UNIX) && defined(HAVE_FSYNC)
4386 /* On many journalling file systems there is a bug that causes both the
4387 * original and the backup file to be lost when halting the system right
4388 * after writing the file. That's because only the meta-data is
4389 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004390 * been written to disk and we don't lose it.
4391 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004392 * (could be a pipe).
4393 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4394 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395 {
4396 errmsg = (char_u *)_("E667: Fsync failed");
4397 end = 0;
4398 }
4399#endif
4400
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004401#ifdef HAVE_SELINUX
4402 /* Probably need to set the security context. */
4403 if (!backup_copy)
4404 mch_copy_sec(backup, wfname);
4405#endif
4406
Bram Moolenaara5792f52005-11-23 21:25:05 +00004407#ifdef UNIX
4408 /* When creating a new file, set its owner/group to that of the original
4409 * file. Get the new device and inode number. */
4410 if (backup != NULL && !backup_copy)
4411 {
4412# ifdef HAVE_FCHOWN
4413 struct stat st;
4414
4415 /* don't change the owner when it's already OK, some systems remove
4416 * permission or ACL stuff */
4417 if (mch_stat((char *)wfname, &st) < 0
4418 || st.st_uid != st_old.st_uid
4419 || st.st_gid != st_old.st_gid)
4420 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004421 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004422 if (perm >= 0) /* set permission again, may have changed */
4423 (void)mch_setperm(wfname, perm);
4424 }
4425# endif
4426 buf_setino(buf);
4427 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004428 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004429 /* Set the inode when creating a new file. */
4430 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004431#endif
4432
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 if (close(fd) != 0)
4434 {
4435 errmsg = (char_u *)_("E512: Close failed");
4436 end = 0;
4437 }
4438
4439#ifdef UNIX
4440 if (made_writable)
4441 perm &= ~0200; /* reset 'w' bit for security reasons */
4442#endif
4443 if (perm >= 0) /* set perm. of new file same as old file */
4444 (void)mch_setperm(wfname, perm);
4445#ifdef RISCOS
4446 if (!append && !filtering)
4447 /* Set the filetype after writing the file. */
4448 mch_set_filetype(wfname, buf->b_p_oft);
4449#endif
4450#ifdef HAVE_ACL
4451 /* Probably need to set the ACL before changing the user (can't set the
4452 * ACL on a file the user doesn't own). */
4453 if (!backup_copy)
4454 mch_set_acl(wfname, acl);
4455#endif
4456
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457
4458#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4459 if (wfname != fname)
4460 {
4461 /*
4462 * The file was written to a temp file, now it needs to be converted
4463 * with 'charconvert' to (overwrite) the output file.
4464 */
4465 if (end != 0)
4466 {
4467 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4468 wfname, fname) == FAIL)
4469 {
4470 write_info.bw_conv_error = TRUE;
4471 end = 0;
4472 }
4473 }
4474 mch_remove(wfname);
4475 vim_free(wfname);
4476 }
4477#endif
4478
4479 if (end == 0)
4480 {
4481 if (errmsg == NULL)
4482 {
4483#ifdef FEAT_MBYTE
4484 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004485 {
4486 if (write_info.bw_conv_error_lnum == 0)
4487 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4488 else
4489 {
4490 errmsg_allocated = TRUE;
4491 errmsg = alloc(300);
4492 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4493 (long)write_info.bw_conv_error_lnum);
4494 }
4495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496 else
4497#endif
4498 if (got_int)
4499 errmsg = (char_u *)_(e_interr);
4500 else
4501 errmsg = (char_u *)_("E514: write error (file system full?)");
4502 }
4503
4504 /*
4505 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004506 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507 * original file when trying to make a backup when writing the file a
4508 * second time.
4509 * When "backup_copy" is set we need to copy the backup over the new
4510 * file. Otherwise rename the backup file.
4511 * If this is OK, don't give the extra warning message.
4512 */
4513 if (backup != NULL)
4514 {
4515 if (backup_copy)
4516 {
4517 /* This may take a while, if we were interrupted let the user
4518 * know we got the message. */
4519 if (got_int)
4520 {
4521 MSG(_(e_interr));
4522 out_flush();
4523 }
4524 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4525 {
4526 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004527 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4528 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 {
4530 /* copy the file. */
4531 write_info.bw_buf = smallbuf;
4532#ifdef HAS_BW_FLAGS
4533 write_info.bw_flags = FIO_NOCONVERT;
4534#endif
4535 while ((write_info.bw_len = vim_read(fd, smallbuf,
4536 SMBUFSIZE)) > 0)
4537 if (buf_write_bytes(&write_info) == FAIL)
4538 break;
4539
4540 if (close(write_info.bw_fd) >= 0
4541 && write_info.bw_len == 0)
4542 end = 1; /* success */
4543 }
4544 close(fd); /* ignore errors for closing read file */
4545 }
4546 }
4547 else
4548 {
4549 if (vim_rename(backup, fname) == 0)
4550 end = 1;
4551 }
4552 }
4553 goto fail;
4554 }
4555
4556 lnum -= start; /* compute number of written lines */
4557 --no_wait_return; /* may wait for return now */
4558
4559#if !(defined(UNIX) || defined(VMS))
4560 fname = sfname; /* use shortname now, for the messages */
4561#endif
4562 if (!filtering)
4563 {
4564 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4565 c = FALSE;
4566#ifdef FEAT_MBYTE
4567 if (write_info.bw_conv_error)
4568 {
4569 STRCAT(IObuff, _(" CONVERSION ERROR"));
4570 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004571 if (write_info.bw_conv_error_lnum != 0)
4572 {
4573 int l = STRLEN(IObuff);
4574 vim_snprintf((char *)IObuff + l, IOSIZE - l, _(" in line %ld;"),
4575 (long)write_info.bw_conv_error_lnum);
4576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 }
4578 else if (notconverted)
4579 {
4580 STRCAT(IObuff, _("[NOT converted]"));
4581 c = TRUE;
4582 }
4583 else if (converted)
4584 {
4585 STRCAT(IObuff, _("[converted]"));
4586 c = TRUE;
4587 }
4588#endif
4589 if (device)
4590 {
4591 STRCAT(IObuff, _("[Device]"));
4592 c = TRUE;
4593 }
4594 else if (newfile)
4595 {
4596 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4597 c = TRUE;
4598 }
4599 if (no_eol)
4600 {
4601 msg_add_eol();
4602 c = TRUE;
4603 }
4604 /* may add [unix/dos/mac] */
4605 if (msg_add_fileformat(fileformat))
4606 c = TRUE;
4607#ifdef FEAT_CRYPT
4608 if (wb_flags & FIO_ENCRYPTED)
4609 {
4610 STRCAT(IObuff, _("[crypted]"));
4611 c = TRUE;
4612 }
4613#endif
4614 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4615 if (!shortmess(SHM_WRITE))
4616 {
4617 if (append)
4618 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4619 else
4620 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4621 }
4622
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004623 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624 }
4625
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004626 /* When written everything correctly: reset 'modified'. Unless not
4627 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004628 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629#ifdef FEAT_MBYTE
4630 && !write_info.bw_conv_error
4631#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004632 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4633 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 {
4635 unchanged(buf, TRUE);
4636 u_unchanged(buf);
4637 }
4638
4639 /*
4640 * If written to the current file, update the timestamp of the swap file
4641 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4642 */
4643 if (overwriting)
4644 {
4645 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004646 if (append)
4647 buf->b_flags &= ~BF_NEW;
4648 else
4649 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004650 }
4651
4652 /*
4653 * If we kept a backup until now, and we are in patch mode, then we make
4654 * the backup file our 'original' file.
4655 */
4656 if (*p_pm && dobackup)
4657 {
4658 char *org = (char *)buf_modname(
4659#ifdef SHORT_FNAME
4660 TRUE,
4661#else
4662 (buf->b_p_sn || buf->b_shortname),
4663#endif
4664 fname, p_pm, FALSE);
4665
4666 if (backup != NULL)
4667 {
4668 struct stat st;
4669
4670 /*
4671 * If the original file does not exist yet
4672 * the current backup file becomes the original file
4673 */
4674 if (org == NULL)
4675 EMSG(_("E205: Patchmode: can't save original file"));
4676 else if (mch_stat(org, &st) < 0)
4677 {
4678 vim_rename(backup, (char_u *)org);
4679 vim_free(backup); /* don't delete the file */
4680 backup = NULL;
4681#ifdef UNIX
4682 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4683#endif
4684 }
4685 }
4686 /*
4687 * If there is no backup file, remember that a (new) file was
4688 * created.
4689 */
4690 else
4691 {
4692 int empty_fd;
4693
4694 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004695 || (empty_fd = mch_open(org,
4696 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004697 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698 EMSG(_("E206: patchmode: can't touch empty original file"));
4699 else
4700 close(empty_fd);
4701 }
4702 if (org != NULL)
4703 {
4704 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4705 vim_free(org);
4706 }
4707 }
4708
4709 /*
4710 * Remove the backup unless 'backup' option is set
4711 */
4712 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4713 EMSG(_("E207: Can't delete backup file"));
4714
4715#ifdef FEAT_SUN_WORKSHOP
4716 if (usingSunWorkShop)
4717 workshop_file_saved((char *) ffname);
4718#endif
4719
4720 goto nofail;
4721
4722 /*
4723 * Finish up. We get here either after failure or success.
4724 */
4725fail:
4726 --no_wait_return; /* may wait for return now */
4727nofail:
4728
4729 /* Done saving, we accept changed buffer warnings again */
4730 buf->b_saving = FALSE;
4731
4732 vim_free(backup);
4733 if (buffer != smallbuf)
4734 vim_free(buffer);
4735#ifdef FEAT_MBYTE
4736 vim_free(fenc_tofree);
4737 vim_free(write_info.bw_conv_buf);
4738# ifdef USE_ICONV
4739 if (write_info.bw_iconv_fd != (iconv_t)-1)
4740 {
4741 iconv_close(write_info.bw_iconv_fd);
4742 write_info.bw_iconv_fd = (iconv_t)-1;
4743 }
4744# endif
4745#endif
4746#ifdef HAVE_ACL
4747 mch_free_acl(acl);
4748#endif
4749
4750 if (errmsg != NULL)
4751 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004752 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753
4754 attr = hl_attr(HLF_E); /* set highlight for error messages */
4755 msg_add_fname(buf,
4756#ifndef UNIX
4757 sfname
4758#else
4759 fname
4760#endif
4761 ); /* put file name in IObuff with quotes */
4762 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
4763 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
4764 /* If the error message has the form "is ...", put the error number in
4765 * front of the file name. */
4766 if (errnum != NULL)
4767 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004768 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 mch_memmove(IObuff, errnum, (size_t)numlen);
4770 }
4771 STRCAT(IObuff, errmsg);
4772 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004773 if (errmsg_allocated)
4774 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775
4776 retval = FAIL;
4777 if (end == 0)
4778 {
4779 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
4780 attr | MSG_HIST);
4781 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
4782 attr | MSG_HIST);
4783
4784 /* Update the timestamp to avoid an "overwrite changed file"
4785 * prompt when writing again. */
4786 if (mch_stat((char *)fname, &st_old) >= 0)
4787 {
4788 buf_store_time(buf, &st_old, fname);
4789 buf->b_mtime_read = buf->b_mtime;
4790 }
4791 }
4792 }
4793 msg_scroll = msg_save;
4794
4795#ifdef FEAT_AUTOCMD
4796#ifdef FEAT_EVAL
4797 if (!should_abort(retval))
4798#else
4799 if (!got_int)
4800#endif
4801 {
4802 aco_save_T aco;
4803
4804 write_no_eol_lnum = 0; /* in case it was set by the previous read */
4805
4806 /*
4807 * Apply POST autocommands.
4808 * Careful: The autocommands may call buf_write() recursively!
4809 */
4810 aucmd_prepbuf(&aco, buf);
4811
4812 if (append)
4813 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
4814 FALSE, curbuf, eap);
4815 else if (filtering)
4816 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
4817 FALSE, curbuf, eap);
4818 else if (reset_changed && whole)
4819 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
4820 FALSE, curbuf, eap);
4821 else
4822 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
4823 FALSE, curbuf, eap);
4824
4825 /* restore curwin/curbuf and a few other things */
4826 aucmd_restbuf(&aco);
4827
4828#ifdef FEAT_EVAL
4829 if (aborting()) /* autocmds may abort script processing */
4830 retval = FALSE;
4831#endif
4832 }
4833#endif
4834
4835 got_int |= prev_got_int;
4836
4837#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4838 /* Update machine specific information. */
4839 mch_post_buffer_write(buf);
4840#endif
4841 return retval;
4842}
4843
4844/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004845 * Set the name of the current buffer. Use when the buffer doesn't have a
4846 * name and a ":r" or ":w" command with a file name is used.
4847 */
4848 static int
4849set_rw_fname(fname, sfname)
4850 char_u *fname;
4851 char_u *sfname;
4852{
4853#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00004854 buf_T *buf = curbuf;
4855
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004856 /* It's like the unnamed buffer is deleted.... */
4857 if (curbuf->b_p_bl)
4858 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
4859 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
4860# ifdef FEAT_EVAL
4861 if (aborting()) /* autocmds may abort script processing */
4862 return FAIL;
4863# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00004864 if (curbuf != buf)
4865 {
4866 /* We are in another buffer now, don't do the renaming. */
4867 EMSG(_(e_auchangedbuf));
4868 return FAIL;
4869 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004870#endif
4871
4872 if (setfname(curbuf, fname, sfname, FALSE) == OK)
4873 curbuf->b_flags |= BF_NOTEDITED;
4874
4875#ifdef FEAT_AUTOCMD
4876 /* ....and a new named one is created */
4877 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
4878 if (curbuf->b_p_bl)
4879 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
4880# ifdef FEAT_EVAL
4881 if (aborting()) /* autocmds may abort script processing */
4882 return FAIL;
4883# endif
4884
4885 /* Do filetype detection now if 'filetype' is empty. */
4886 if (*curbuf->b_p_ft == NUL)
4887 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004888 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00004889 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00004890 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004891 }
4892#endif
4893
4894 return OK;
4895}
4896
4897/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 * Put file name into IObuff with quotes.
4899 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004900 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901msg_add_fname(buf, fname)
4902 buf_T *buf;
4903 char_u *fname;
4904{
4905 if (fname == NULL)
4906 fname = (char_u *)"-stdin-";
4907 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
4908 IObuff[0] = '"';
4909 STRCAT(IObuff, "\" ");
4910}
4911
4912/*
4913 * Append message for text mode to IObuff.
4914 * Return TRUE if something appended.
4915 */
4916 static int
4917msg_add_fileformat(eol_type)
4918 int eol_type;
4919{
4920#ifndef USE_CRNL
4921 if (eol_type == EOL_DOS)
4922 {
4923 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
4924 return TRUE;
4925 }
4926#endif
4927#ifndef USE_CR
4928 if (eol_type == EOL_MAC)
4929 {
4930 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
4931 return TRUE;
4932 }
4933#endif
4934#if defined(USE_CRNL) || defined(USE_CR)
4935 if (eol_type == EOL_UNIX)
4936 {
4937 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
4938 return TRUE;
4939 }
4940#endif
4941 return FALSE;
4942}
4943
4944/*
4945 * Append line and character count to IObuff.
4946 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004947 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948msg_add_lines(insert_space, lnum, nchars)
4949 int insert_space;
4950 long lnum;
4951 long nchars;
4952{
4953 char_u *p;
4954
4955 p = IObuff + STRLEN(IObuff);
4956
4957 if (insert_space)
4958 *p++ = ' ';
4959 if (shortmess(SHM_LINES))
4960 sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
4961 else
4962 {
4963 if (lnum == 1)
4964 STRCPY(p, _("1 line, "));
4965 else
4966 sprintf((char *)p, _("%ld lines, "), lnum);
4967 p += STRLEN(p);
4968 if (nchars == 1)
4969 STRCPY(p, _("1 character"));
4970 else
4971 sprintf((char *)p, _("%ld characters"), nchars);
4972 }
4973}
4974
4975/*
4976 * Append message for missing line separator to IObuff.
4977 */
4978 static void
4979msg_add_eol()
4980{
4981 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
4982}
4983
4984/*
4985 * Check modification time of file, before writing to it.
4986 * The size isn't checked, because using a tool like "gzip" takes care of
4987 * using the same timestamp but can't set the size.
4988 */
4989 static int
4990check_mtime(buf, st)
4991 buf_T *buf;
4992 struct stat *st;
4993{
4994 if (buf->b_mtime_read != 0
4995 && time_differs((long)st->st_mtime, buf->b_mtime_read))
4996 {
4997 msg_scroll = TRUE; /* don't overwrite messages here */
4998 msg_silent = 0; /* must give this prompt */
4999 /* don't use emsg() here, don't want to flush the buffers */
5000 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5001 hl_attr(HLF_E));
5002 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5003 TRUE) == 'n')
5004 return FAIL;
5005 msg_scroll = FALSE; /* always overwrite the file message now */
5006 }
5007 return OK;
5008}
5009
5010 static int
5011time_differs(t1, t2)
5012 long t1, t2;
5013{
5014#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5015 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5016 * the seconds. Since the roundoff is done when flushing the inode, the
5017 * time may change unexpectedly by one second!!! */
5018 return (t1 - t2 > 1 || t2 - t1 > 1);
5019#else
5020 return (t1 != t2);
5021#endif
5022}
5023
5024/*
5025 * Call write() to write a number of bytes to the file.
5026 * Also handles encryption and 'encoding' conversion.
5027 *
5028 * Return FAIL for failure, OK otherwise.
5029 */
5030 static int
5031buf_write_bytes(ip)
5032 struct bw_info *ip;
5033{
5034 int wlen;
5035 char_u *buf = ip->bw_buf; /* data to write */
5036 int len = ip->bw_len; /* length of data */
5037#ifdef HAS_BW_FLAGS
5038 int flags = ip->bw_flags; /* extra flags */
5039#endif
5040
5041#ifdef FEAT_MBYTE
5042 /*
5043 * Skip conversion when writing the crypt magic number or the BOM.
5044 */
5045 if (!(flags & FIO_NOCONVERT))
5046 {
5047 char_u *p;
5048 unsigned c;
5049 int n;
5050
5051 if (flags & FIO_UTF8)
5052 {
5053 /*
5054 * Convert latin1 in the buffer to UTF-8 in the file.
5055 */
5056 p = ip->bw_conv_buf; /* translate to buffer */
5057 for (wlen = 0; wlen < len; ++wlen)
5058 p += utf_char2bytes(buf[wlen], p);
5059 buf = ip->bw_conv_buf;
5060 len = (int)(p - ip->bw_conv_buf);
5061 }
5062 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5063 {
5064 /*
5065 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5066 * Latin1 chars in the file.
5067 */
5068 if (flags & FIO_LATIN1)
5069 p = buf; /* translate in-place (can only get shorter) */
5070 else
5071 p = ip->bw_conv_buf; /* translate to buffer */
5072 for (wlen = 0; wlen < len; wlen += n)
5073 {
5074 if (wlen == 0 && ip->bw_restlen != 0)
5075 {
5076 int l;
5077
5078 /* Use remainder of previous call. Append the start of
5079 * buf[] to get a full sequence. Might still be too
5080 * short! */
5081 l = CONV_RESTLEN - ip->bw_restlen;
5082 if (l > len)
5083 l = len;
5084 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005085 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086 if (n > ip->bw_restlen + len)
5087 {
5088 /* We have an incomplete byte sequence at the end to
5089 * be written. We can't convert it without the
5090 * remaining bytes. Keep them for the next call. */
5091 if (ip->bw_restlen + len > CONV_RESTLEN)
5092 return FAIL;
5093 ip->bw_restlen += len;
5094 break;
5095 }
5096 if (n > 1)
5097 c = utf_ptr2char(ip->bw_rest);
5098 else
5099 c = ip->bw_rest[0];
5100 if (n >= ip->bw_restlen)
5101 {
5102 n -= ip->bw_restlen;
5103 ip->bw_restlen = 0;
5104 }
5105 else
5106 {
5107 ip->bw_restlen -= n;
5108 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5109 (size_t)ip->bw_restlen);
5110 n = 0;
5111 }
5112 }
5113 else
5114 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005115 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116 if (n > len - wlen)
5117 {
5118 /* We have an incomplete byte sequence at the end to
5119 * be written. We can't convert it without the
5120 * remaining bytes. Keep them for the next call. */
5121 if (len - wlen > CONV_RESTLEN)
5122 return FAIL;
5123 ip->bw_restlen = len - wlen;
5124 mch_memmove(ip->bw_rest, buf + wlen,
5125 (size_t)ip->bw_restlen);
5126 break;
5127 }
5128 if (n > 1)
5129 c = utf_ptr2char(buf + wlen);
5130 else
5131 c = buf[wlen];
5132 }
5133
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005134 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5135 {
5136 ip->bw_conv_error = TRUE;
5137 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5138 }
5139 if (c == NL)
5140 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141 }
5142 if (flags & FIO_LATIN1)
5143 len = (int)(p - buf);
5144 else
5145 {
5146 buf = ip->bw_conv_buf;
5147 len = (int)(p - ip->bw_conv_buf);
5148 }
5149 }
5150
5151# ifdef WIN3264
5152 else if (flags & FIO_CODEPAGE)
5153 {
5154 /*
5155 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5156 * codepage.
5157 */
5158 char_u *from;
5159 size_t fromlen;
5160 char_u *to;
5161 int u8c;
5162 BOOL bad = FALSE;
5163 int needed;
5164
5165 if (ip->bw_restlen > 0)
5166 {
5167 /* Need to concatenate the remainder of the previous call and
5168 * the bytes of the current call. Use the end of the
5169 * conversion buffer for this. */
5170 fromlen = len + ip->bw_restlen;
5171 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5172 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5173 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5174 }
5175 else
5176 {
5177 from = buf;
5178 fromlen = len;
5179 }
5180
5181 to = ip->bw_conv_buf;
5182 if (enc_utf8)
5183 {
5184 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5185 * The buffer has been allocated to be big enough. */
5186 while (fromlen > 0)
5187 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005188 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189 if (n > (int)fromlen) /* incomplete byte sequence */
5190 break;
5191 u8c = utf_ptr2char(from);
5192 *to++ = (u8c & 0xff);
5193 *to++ = (u8c >> 8);
5194 fromlen -= n;
5195 from += n;
5196 }
5197
5198 /* Copy remainder to ip->bw_rest[] to be used for the next
5199 * call. */
5200 if (fromlen > CONV_RESTLEN)
5201 {
5202 /* weird overlong sequence */
5203 ip->bw_conv_error = TRUE;
5204 return FAIL;
5205 }
5206 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005207 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 }
5209 else
5210 {
5211 /* Convert from enc_codepage to UCS-2, to the start of the
5212 * buffer. The buffer has been allocated to be big enough. */
5213 ip->bw_restlen = 0;
5214 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005215 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216 NULL, 0);
5217 if (needed == 0)
5218 {
5219 /* When conversion fails there may be a trailing byte. */
5220 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005221 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 NULL, 0);
5223 if (needed == 0)
5224 {
5225 /* Conversion doesn't work. */
5226 ip->bw_conv_error = TRUE;
5227 return FAIL;
5228 }
5229 /* Save the trailing byte for the next call. */
5230 ip->bw_rest[0] = from[fromlen - 1];
5231 ip->bw_restlen = 1;
5232 }
5233 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005234 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235 (LPWSTR)to, needed);
5236 if (needed == 0)
5237 {
5238 /* Safety check: Conversion doesn't work. */
5239 ip->bw_conv_error = TRUE;
5240 return FAIL;
5241 }
5242 to += needed * 2;
5243 }
5244
5245 fromlen = to - ip->bw_conv_buf;
5246 buf = to;
5247# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5248 if (FIO_GET_CP(flags) == CP_UTF8)
5249 {
5250 /* Convert from UCS-2 to UTF-8, using the remainder of the
5251 * conversion buffer. Fails when out of space. */
5252 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5253 {
5254 u8c = *from++;
5255 u8c += (*from++ << 8);
5256 to += utf_char2bytes(u8c, to);
5257 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5258 {
5259 ip->bw_conv_error = TRUE;
5260 return FAIL;
5261 }
5262 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005263 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264 }
5265 else
5266#endif
5267 {
5268 /* Convert from UCS-2 to the codepage, using the remainder of
5269 * the conversion buffer. If the conversion uses the default
5270 * character "0", the data doesn't fit in this encoding, so
5271 * fail. */
5272 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5273 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005274 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5275 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005276 if (bad)
5277 {
5278 ip->bw_conv_error = TRUE;
5279 return FAIL;
5280 }
5281 }
5282 }
5283# endif
5284
Bram Moolenaar56718732006-03-15 22:53:57 +00005285# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286 else if (flags & FIO_MACROMAN)
5287 {
5288 /*
5289 * Convert UTF-8 or latin1 to Apple MacRoman.
5290 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 char_u *from;
5292 size_t fromlen;
5293
5294 if (ip->bw_restlen > 0)
5295 {
5296 /* Need to concatenate the remainder of the previous call and
5297 * the bytes of the current call. Use the end of the
5298 * conversion buffer for this. */
5299 fromlen = len + ip->bw_restlen;
5300 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5301 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5302 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5303 }
5304 else
5305 {
5306 from = buf;
5307 fromlen = len;
5308 }
5309
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005310 if (enc2macroman(from, fromlen,
5311 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5312 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005313 {
5314 ip->bw_conv_error = TRUE;
5315 return FAIL;
5316 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318 }
5319# endif
5320
5321# ifdef USE_ICONV
5322 if (ip->bw_iconv_fd != (iconv_t)-1)
5323 {
5324 const char *from;
5325 size_t fromlen;
5326 char *to;
5327 size_t tolen;
5328
5329 /* Convert with iconv(). */
5330 if (ip->bw_restlen > 0)
5331 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005332 char *fp;
5333
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334 /* Need to concatenate the remainder of the previous call and
5335 * the bytes of the current call. Use the end of the
5336 * conversion buffer for this. */
5337 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005338 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5339 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5340 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5341 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 tolen = ip->bw_conv_buflen - fromlen;
5343 }
5344 else
5345 {
5346 from = (const char *)buf;
5347 fromlen = len;
5348 tolen = ip->bw_conv_buflen;
5349 }
5350 to = (char *)ip->bw_conv_buf;
5351
5352 if (ip->bw_first)
5353 {
5354 size_t save_len = tolen;
5355
5356 /* output the initial shift state sequence */
5357 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5358
5359 /* There is a bug in iconv() on Linux (which appears to be
5360 * wide-spread) which sets "to" to NULL and messes up "tolen".
5361 */
5362 if (to == NULL)
5363 {
5364 to = (char *)ip->bw_conv_buf;
5365 tolen = save_len;
5366 }
5367 ip->bw_first = FALSE;
5368 }
5369
5370 /*
5371 * If iconv() has an error or there is not enough room, fail.
5372 */
5373 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5374 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5375 || fromlen > CONV_RESTLEN)
5376 {
5377 ip->bw_conv_error = TRUE;
5378 return FAIL;
5379 }
5380
5381 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5382 if (fromlen > 0)
5383 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5384 ip->bw_restlen = (int)fromlen;
5385
5386 buf = ip->bw_conv_buf;
5387 len = (int)((char_u *)to - ip->bw_conv_buf);
5388 }
5389# endif
5390 }
5391#endif /* FEAT_MBYTE */
5392
5393#ifdef FEAT_CRYPT
5394 if (flags & FIO_ENCRYPTED) /* encrypt the data */
5395 {
5396 int ztemp, t, i;
5397
5398 for (i = 0; i < len; i++)
5399 {
5400 ztemp = buf[i];
5401 buf[i] = ZENCODE(ztemp, t);
5402 }
5403 }
5404#endif
5405
5406 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005407 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005408 {
5409 wlen = vim_write(ip->bw_fd, buf, len);
5410 if (wlen <= 0) /* error! */
5411 return FAIL;
5412 len -= wlen;
5413 buf += wlen;
5414 }
5415 return OK;
5416}
5417
5418#ifdef FEAT_MBYTE
5419/*
5420 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005421 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005422 */
5423 static int
5424ucs2bytes(c, pp, flags)
5425 unsigned c; /* in: character */
5426 char_u **pp; /* in/out: pointer to result */
5427 int flags; /* FIO_ flags */
5428{
5429 char_u *p = *pp;
5430 int error = FALSE;
5431 int cc;
5432
5433
5434 if (flags & FIO_UCS4)
5435 {
5436 if (flags & FIO_ENDIAN_L)
5437 {
5438 *p++ = c;
5439 *p++ = (c >> 8);
5440 *p++ = (c >> 16);
5441 *p++ = (c >> 24);
5442 }
5443 else
5444 {
5445 *p++ = (c >> 24);
5446 *p++ = (c >> 16);
5447 *p++ = (c >> 8);
5448 *p++ = c;
5449 }
5450 }
5451 else if (flags & (FIO_UCS2 | FIO_UTF16))
5452 {
5453 if (c >= 0x10000)
5454 {
5455 if (flags & FIO_UTF16)
5456 {
5457 /* Make two words, ten bits of the character in each. First
5458 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5459 c -= 0x10000;
5460 if (c >= 0x100000)
5461 error = TRUE;
5462 cc = ((c >> 10) & 0x3ff) + 0xd800;
5463 if (flags & FIO_ENDIAN_L)
5464 {
5465 *p++ = cc;
5466 *p++ = ((unsigned)cc >> 8);
5467 }
5468 else
5469 {
5470 *p++ = ((unsigned)cc >> 8);
5471 *p++ = cc;
5472 }
5473 c = (c & 0x3ff) + 0xdc00;
5474 }
5475 else
5476 error = TRUE;
5477 }
5478 if (flags & FIO_ENDIAN_L)
5479 {
5480 *p++ = c;
5481 *p++ = (c >> 8);
5482 }
5483 else
5484 {
5485 *p++ = (c >> 8);
5486 *p++ = c;
5487 }
5488 }
5489 else /* Latin1 */
5490 {
5491 if (c >= 0x100)
5492 {
5493 error = TRUE;
5494 *p++ = 0xBF;
5495 }
5496 else
5497 *p++ = c;
5498 }
5499
5500 *pp = p;
5501 return error;
5502}
5503
5504/*
5505 * Return TRUE if "a" and "b" are the same 'encoding'.
5506 * Ignores difference between "ansi" and "latin1", "ucs-4" and "ucs-4be", etc.
5507 */
5508 static int
5509same_encoding(a, b)
5510 char_u *a;
5511 char_u *b;
5512{
5513 int f;
5514
5515 if (STRCMP(a, b) == 0)
5516 return TRUE;
5517 f = get_fio_flags(a);
5518 return (f != 0 && get_fio_flags(b) == f);
5519}
5520
5521/*
5522 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5523 * internal conversion.
5524 * if "ptr" is an empty string, use 'encoding'.
5525 */
5526 static int
5527get_fio_flags(ptr)
5528 char_u *ptr;
5529{
5530 int prop;
5531
5532 if (*ptr == NUL)
5533 ptr = p_enc;
5534
5535 prop = enc_canon_props(ptr);
5536 if (prop & ENC_UNICODE)
5537 {
5538 if (prop & ENC_2BYTE)
5539 {
5540 if (prop & ENC_ENDIAN_L)
5541 return FIO_UCS2 | FIO_ENDIAN_L;
5542 return FIO_UCS2;
5543 }
5544 if (prop & ENC_4BYTE)
5545 {
5546 if (prop & ENC_ENDIAN_L)
5547 return FIO_UCS4 | FIO_ENDIAN_L;
5548 return FIO_UCS4;
5549 }
5550 if (prop & ENC_2WORD)
5551 {
5552 if (prop & ENC_ENDIAN_L)
5553 return FIO_UTF16 | FIO_ENDIAN_L;
5554 return FIO_UTF16;
5555 }
5556 return FIO_UTF8;
5557 }
5558 if (prop & ENC_LATIN1)
5559 return FIO_LATIN1;
5560 /* must be ENC_DBCS, requires iconv() */
5561 return 0;
5562}
5563
5564#ifdef WIN3264
5565/*
5566 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5567 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5568 * Used for conversion between 'encoding' and 'fileencoding'.
5569 */
5570 static int
5571get_win_fio_flags(ptr)
5572 char_u *ptr;
5573{
5574 int cp;
5575
5576 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5577 if (!enc_utf8 && enc_codepage <= 0)
5578 return 0;
5579
5580 cp = encname2codepage(ptr);
5581 if (cp == 0)
5582 {
5583# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5584 if (STRCMP(ptr, "utf-8") == 0)
5585 cp = CP_UTF8;
5586 else
5587# endif
5588 return 0;
5589 }
5590 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5591}
5592#endif
5593
5594#ifdef MACOS_X
5595/*
5596 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5597 * needed for the internal conversion to/from utf-8 or latin1.
5598 */
5599 static int
5600get_mac_fio_flags(ptr)
5601 char_u *ptr;
5602{
5603 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5604 && (enc_canon_props(ptr) & ENC_MACROMAN))
5605 return FIO_MACROMAN;
5606 return 0;
5607}
5608#endif
5609
5610/*
5611 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5612 * "size" must be at least 2.
5613 * Return the name of the encoding and set "*lenp" to the length.
5614 * Returns NULL when no BOM found.
5615 */
5616 static char_u *
5617check_for_bom(p, size, lenp, flags)
5618 char_u *p;
5619 long size;
5620 int *lenp;
5621 int flags;
5622{
5623 char *name = NULL;
5624 int len = 2;
5625
5626 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005627 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628 {
5629 name = "utf-8"; /* EF BB BF */
5630 len = 3;
5631 }
5632 else if (p[0] == 0xff && p[1] == 0xfe)
5633 {
5634 if (size >= 4 && p[2] == 0 && p[3] == 0
5635 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5636 {
5637 name = "ucs-4le"; /* FF FE 00 00 */
5638 len = 4;
5639 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005640 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005642 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5643 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 name = "utf-16le"; /* FF FE */
5645 }
5646 else if (p[0] == 0xfe && p[1] == 0xff
5647 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5648 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005649 /* Default to utf-16, it works also for ucs-2 text. */
5650 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005652 else
5653 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 }
5655 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5656 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5657 {
5658 name = "ucs-4"; /* 00 00 FE FF */
5659 len = 4;
5660 }
5661
5662 *lenp = len;
5663 return (char_u *)name;
5664}
5665
5666/*
5667 * Generate a BOM in "buf[4]" for encoding "name".
5668 * Return the length of the BOM (zero when no BOM).
5669 */
5670 static int
5671make_bom(buf, name)
5672 char_u *buf;
5673 char_u *name;
5674{
5675 int flags;
5676 char_u *p;
5677
5678 flags = get_fio_flags(name);
5679
5680 /* Can't put a BOM in a non-Unicode file. */
5681 if (flags == FIO_LATIN1 || flags == 0)
5682 return 0;
5683
5684 if (flags == FIO_UTF8) /* UTF-8 */
5685 {
5686 buf[0] = 0xef;
5687 buf[1] = 0xbb;
5688 buf[2] = 0xbf;
5689 return 3;
5690 }
5691 p = buf;
5692 (void)ucs2bytes(0xfeff, &p, flags);
5693 return (int)(p - buf);
5694}
5695#endif
5696
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005697#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005698 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699/*
5700 * Try to find a shortname by comparing the fullname with the current
5701 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005702 * Returns "full_path" or pointer into "full_path" if shortened.
5703 */
5704 char_u *
5705shorten_fname1(full_path)
5706 char_u *full_path;
5707{
5708 char_u dirname[MAXPATHL];
5709 char_u *p = full_path;
5710
5711 if (mch_dirname(dirname, MAXPATHL) == OK)
5712 {
5713 p = shorten_fname(full_path, dirname);
5714 if (p == NULL || *p == NUL)
5715 p = full_path;
5716 }
5717 return p;
5718}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005719#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005720
5721/*
5722 * Try to find a shortname by comparing the fullname with the current
5723 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 * Returns NULL if not shorter name possible, pointer into "full_path"
5725 * otherwise.
5726 */
5727 char_u *
5728shorten_fname(full_path, dir_name)
5729 char_u *full_path;
5730 char_u *dir_name;
5731{
5732 int len;
5733 char_u *p;
5734
5735 if (full_path == NULL)
5736 return NULL;
5737 len = (int)STRLEN(dir_name);
5738 if (fnamencmp(dir_name, full_path, len) == 0)
5739 {
5740 p = full_path + len;
5741#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5742 /*
5743 * MSDOS: when a file is in the root directory, dir_name will end in a
5744 * slash, since C: by itself does not define a specific dir. In this
5745 * case p may already be correct. <negri>
5746 */
5747 if (!((len > 2) && (*(p - 2) == ':')))
5748#endif
5749 {
5750 if (vim_ispathsep(*p))
5751 ++p;
5752#ifndef VMS /* the path separator is always part of the path */
5753 else
5754 p = NULL;
5755#endif
5756 }
5757 }
5758#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5759 /*
5760 * When using a file in the current drive, remove the drive name:
5761 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
5762 * a floppy from "A:\dir" to "B:\dir".
5763 */
5764 else if (len > 3
5765 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
5766 && full_path[1] == ':'
5767 && vim_ispathsep(full_path[2]))
5768 p = full_path + 2;
5769#endif
5770 else
5771 p = NULL;
5772 return p;
5773}
5774
5775/*
5776 * Shorten filenames for all buffers.
5777 * When "force" is TRUE: Use full path from now on for files currently being
5778 * edited, both for file name and swap file name. Try to shorten the file
5779 * names a bit, if safe to do so.
5780 * When "force" is FALSE: Only try to shorten absolute file names.
5781 * For buffers that have buftype "nofile" or "scratch": never change the file
5782 * name.
5783 */
5784 void
5785shorten_fnames(force)
5786 int force;
5787{
5788 char_u dirname[MAXPATHL];
5789 buf_T *buf;
5790 char_u *p;
5791
5792 mch_dirname(dirname, MAXPATHL);
5793 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5794 {
5795 if (buf->b_fname != NULL
5796#ifdef FEAT_QUICKFIX
5797 && !bt_nofile(buf)
5798#endif
5799 && !path_with_url(buf->b_fname)
5800 && (force
5801 || buf->b_sfname == NULL
5802 || mch_isFullName(buf->b_sfname)))
5803 {
5804 vim_free(buf->b_sfname);
5805 buf->b_sfname = NULL;
5806 p = shorten_fname(buf->b_ffname, dirname);
5807 if (p != NULL)
5808 {
5809 buf->b_sfname = vim_strsave(p);
5810 buf->b_fname = buf->b_sfname;
5811 }
5812 if (p == NULL || buf->b_fname == NULL)
5813 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005815
5816 /* Always make the swap file name a full path, a "nofile" buffer may
5817 * also have a swap file. */
5818 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819 }
5820#ifdef FEAT_WINDOWS
5821 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00005822 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823#endif
5824}
5825
5826#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
5827 || defined(FEAT_GUI_MSWIN) \
5828 || defined(FEAT_GUI_MAC) \
5829 || defined(PROTO)
5830/*
5831 * Shorten all filenames in "fnames[count]" by current directory.
5832 */
5833 void
5834shorten_filenames(fnames, count)
5835 char_u **fnames;
5836 int count;
5837{
5838 int i;
5839 char_u dirname[MAXPATHL];
5840 char_u *p;
5841
5842 if (fnames == NULL || count < 1)
5843 return;
5844 mch_dirname(dirname, sizeof(dirname));
5845 for (i = 0; i < count; ++i)
5846 {
5847 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
5848 {
5849 /* shorten_fname() returns pointer in given "fnames[i]". If free
5850 * "fnames[i]" first, "p" becomes invalid. So we need to copy
5851 * "p" first then free fnames[i]. */
5852 p = vim_strsave(p);
5853 vim_free(fnames[i]);
5854 fnames[i] = p;
5855 }
5856 }
5857}
5858#endif
5859
5860/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00005861 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 * fo_o_h.ext for MSDOS or when shortname option set.
5863 *
5864 * Assumed that fname is a valid name found in the filesystem we assure that
5865 * the return value is a different name and ends in 'ext'.
5866 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
5867 * characters otherwise.
5868 * Space for the returned name is allocated, must be freed later.
5869 * Returns NULL when out of memory.
5870 */
5871 char_u *
5872modname(fname, ext, prepend_dot)
5873 char_u *fname, *ext;
5874 int prepend_dot; /* may prepend a '.' to file name */
5875{
5876 return buf_modname(
5877#ifdef SHORT_FNAME
5878 TRUE,
5879#else
5880 (curbuf->b_p_sn || curbuf->b_shortname),
5881#endif
5882 fname, ext, prepend_dot);
5883}
5884
5885 char_u *
5886buf_modname(shortname, fname, ext, prepend_dot)
5887 int shortname; /* use 8.3 file name */
5888 char_u *fname, *ext;
5889 int prepend_dot; /* may prepend a '.' to file name */
5890{
5891 char_u *retval;
5892 char_u *s;
5893 char_u *e;
5894 char_u *ptr;
5895 int fnamelen, extlen;
5896
5897 extlen = (int)STRLEN(ext);
5898
5899 /*
5900 * If there is no file name we must get the name of the current directory
5901 * (we need the full path in case :cd is used).
5902 */
5903 if (fname == NULL || *fname == NUL)
5904 {
5905 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
5906 if (retval == NULL)
5907 return NULL;
5908 if (mch_dirname(retval, MAXPATHL) == FAIL ||
5909 (fnamelen = (int)STRLEN(retval)) == 0)
5910 {
5911 vim_free(retval);
5912 return NULL;
5913 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005914 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915 {
5916 retval[fnamelen++] = PATHSEP;
5917 retval[fnamelen] = NUL;
5918 }
5919#ifndef SHORT_FNAME
5920 prepend_dot = FALSE; /* nothing to prepend a dot to */
5921#endif
5922 }
5923 else
5924 {
5925 fnamelen = (int)STRLEN(fname);
5926 retval = alloc((unsigned)(fnamelen + extlen + 3));
5927 if (retval == NULL)
5928 return NULL;
5929 STRCPY(retval, fname);
5930#ifdef VMS
5931 vms_remove_version(retval); /* we do not need versions here */
5932#endif
5933 }
5934
5935 /*
5936 * search backwards until we hit a '/', '\' or ':' replacing all '.'
5937 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
5938 * Then truncate what is after the '/', '\' or ':' to 8 characters for
5939 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
5940 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005941 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 {
5943#ifndef RISCOS
5944 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005945# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005947# else
5948# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005950# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 )
5953 if (*ptr == '.') /* replace '.' by '_' */
5954 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005955#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005957 {
5958 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962
5963 /* the file name has at most BASENAMELEN characters. */
5964#ifndef SHORT_FNAME
5965 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
5966 ptr[BASENAMELEN] = '\0';
5967#endif
5968
5969 s = ptr + STRLEN(ptr);
5970
5971 /*
5972 * For 8.3 file names we may have to reduce the length.
5973 */
5974#ifdef USE_LONG_FNAME
5975 if (!USE_LONG_FNAME || shortname)
5976#else
5977# ifndef SHORT_FNAME
5978 if (shortname)
5979# endif
5980#endif
5981 {
5982 /*
5983 * If there is no file name, or the file name ends in '/', and the
5984 * extension starts with '.', put a '_' before the dot, because just
5985 * ".ext" is invalid.
5986 */
5987 if (fname == NULL || *fname == NUL
5988 || vim_ispathsep(fname[STRLEN(fname) - 1]))
5989 {
5990#ifdef RISCOS
5991 if (*ext == '/')
5992#else
5993 if (*ext == '.')
5994#endif
5995 *s++ = '_';
5996 }
5997 /*
5998 * If the extension starts with '.', truncate the base name at 8
5999 * characters
6000 */
6001#ifdef RISCOS
6002 /* We normally use '/', but swap files are '_' */
6003 else if (*ext == '/' || *ext == '_')
6004#else
6005 else if (*ext == '.')
6006#endif
6007 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006008 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 {
6010 s = ptr + 8;
6011 *s = '\0';
6012 }
6013 }
6014 /*
6015 * If the extension doesn't start with '.', and the file name
6016 * doesn't have an extension yet, append a '.'
6017 */
6018#ifdef RISCOS
6019 else if ((e = vim_strchr(ptr, '/')) == NULL)
6020 *s++ = '/';
6021#else
6022 else if ((e = vim_strchr(ptr, '.')) == NULL)
6023 *s++ = '.';
6024#endif
6025 /*
6026 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006027 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028 */
6029 else if ((int)STRLEN(e) + extlen > 4)
6030 s = e + 4 - extlen;
6031 }
6032#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6033 /*
6034 * If there is no file name, and the extension starts with '.', put a
6035 * '_' before the dot, because just ".ext" may be invalid if it's on a
6036 * FAT partition, and on HPFS it doesn't matter.
6037 */
6038 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6039 *s++ = '_';
6040#endif
6041
6042 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006043 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 * ext can start with '.' and cannot exceed 3 more characters.
6045 */
6046 STRCPY(s, ext);
6047
6048#ifndef SHORT_FNAME
6049 /*
6050 * Prepend the dot.
6051 */
6052 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6053#ifdef RISCOS
6054 '/'
6055#else
6056 '.'
6057#endif
6058#ifdef USE_LONG_FNAME
6059 && USE_LONG_FNAME
6060#endif
6061 )
6062 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006063 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064#ifdef RISCOS
6065 *e = '/';
6066#else
6067 *e = '.';
6068#endif
6069 }
6070#endif
6071
6072 /*
6073 * Check that, after appending the extension, the file name is really
6074 * different.
6075 */
6076 if (fname != NULL && STRCMP(fname, retval) == 0)
6077 {
6078 /* we search for a character that can be replaced by '_' */
6079 while (--s >= ptr)
6080 {
6081 if (*s != '_')
6082 {
6083 *s = '_';
6084 break;
6085 }
6086 }
6087 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6088 *ptr = 'v';
6089 }
6090 return retval;
6091}
6092
6093/*
6094 * Like fgets(), but if the file line is too long, it is truncated and the
6095 * rest of the line is thrown away. Returns TRUE for end-of-file.
6096 */
6097 int
6098vim_fgets(buf, size, fp)
6099 char_u *buf;
6100 int size;
6101 FILE *fp;
6102{
6103 char *eof;
6104#define FGETS_SIZE 200
6105 char tbuf[FGETS_SIZE];
6106
6107 buf[size - 2] = NUL;
6108#ifdef USE_CR
6109 eof = fgets_cr((char *)buf, size, fp);
6110#else
6111 eof = fgets((char *)buf, size, fp);
6112#endif
6113 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6114 {
6115 buf[size - 1] = NUL; /* Truncate the line */
6116
6117 /* Now throw away the rest of the line: */
6118 do
6119 {
6120 tbuf[FGETS_SIZE - 2] = NUL;
6121#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006122 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006124 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125#endif
6126 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6127 }
6128 return (eof == NULL);
6129}
6130
6131#if defined(USE_CR) || defined(PROTO)
6132/*
6133 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6134 * Returns TRUE for end-of-file.
6135 * Only used for the Mac, because it's much slower than vim_fgets().
6136 */
6137 int
6138tag_fgets(buf, size, fp)
6139 char_u *buf;
6140 int size;
6141 FILE *fp;
6142{
6143 int i = 0;
6144 int c;
6145 int eof = FALSE;
6146
6147 for (;;)
6148 {
6149 c = fgetc(fp);
6150 if (c == EOF)
6151 {
6152 eof = TRUE;
6153 break;
6154 }
6155 if (c == '\r')
6156 {
6157 /* Always store a NL for end-of-line. */
6158 if (i < size - 1)
6159 buf[i++] = '\n';
6160 c = fgetc(fp);
6161 if (c != '\n') /* Macintosh format: single CR. */
6162 ungetc(c, fp);
6163 break;
6164 }
6165 if (i < size - 1)
6166 buf[i++] = c;
6167 if (c == '\n')
6168 break;
6169 }
6170 buf[i] = NUL;
6171 return eof;
6172}
6173#endif
6174
6175/*
6176 * rename() only works if both files are on the same file system, this
6177 * function will (attempts to?) copy the file across if rename fails -- webb
6178 * Return -1 for failure, 0 for success.
6179 */
6180 int
6181vim_rename(from, to)
6182 char_u *from;
6183 char_u *to;
6184{
6185 int fd_in;
6186 int fd_out;
6187 int n;
6188 char *errmsg = NULL;
6189 char *buffer;
6190#ifdef AMIGA
6191 BPTR flock;
6192#endif
6193 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006194 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006195#ifdef HAVE_ACL
6196 vim_acl_T acl; /* ACL from original file */
6197#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006198#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6199 int use_tmp_file = FALSE;
6200#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201
6202 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006203 * When the names are identical, there is nothing to do. When they refer
6204 * to the same file (ignoring case and slash/backslash differences) but
6205 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 */
6207 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006208 {
6209#ifdef CASE_INSENSITIVE_FILENAME
6210 if (STRCMP(gettail(from), gettail(to)) != 0)
6211 use_tmp_file = TRUE;
6212 else
6213#endif
6214 return 0;
6215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216
6217 /*
6218 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6219 */
6220 if (mch_stat((char *)from, &st) < 0)
6221 return -1;
6222
Bram Moolenaar3576da72008-12-30 15:15:57 +00006223#ifdef UNIX
6224 {
6225 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006226
6227 /* It's possible for the source and destination to be the same file.
6228 * This happens when "from" and "to" differ in case and are on a FAT32
6229 * filesystem. In that case go through a temp file name. */
6230 if (mch_stat((char *)to, &st_to) >= 0
6231 && st.st_dev == st_to.st_dev
6232 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006233 use_tmp_file = TRUE;
6234 }
6235#endif
6236
6237#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6238 if (use_tmp_file)
6239 {
6240 char tempname[MAXPATHL + 1];
6241
6242 /*
6243 * Find a name that doesn't exist and is in the same directory.
6244 * Rename "from" to "tempname" and then rename "tempname" to "to".
6245 */
6246 if (STRLEN(from) >= MAXPATHL - 5)
6247 return -1;
6248 STRCPY(tempname, from);
6249 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006250 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006251 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6252 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006253 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006254 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006255 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006256 if (mch_rename(tempname, (char *)to) == 0)
6257 return 0;
6258 /* Strange, the second step failed. Try moving the
6259 * file back and return failure. */
6260 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006261 return -1;
6262 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006263 /* If it fails for one temp name it will most likely fail
6264 * for any temp name, give up. */
6265 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006266 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006267 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006268 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006269 }
6270#endif
6271
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 /*
6273 * Delete the "to" file, this is required on some systems to make the
6274 * mch_rename() work, on other systems it makes sure that we don't have
6275 * two files when the mch_rename() fails.
6276 */
6277
6278#ifdef AMIGA
6279 /*
6280 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6281 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006282 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 * deleting the "from" file (horror!) we lock it during the remove.
6284 *
6285 * When used for making a backup before writing the file: This should not
6286 * happen with ":w", because startscript() should detect this problem and
6287 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6288 * name. This problem does exist with ":w filename", but then the
6289 * original file will be somewhere else so the backup isn't really
6290 * important. If autoscripting is off the rename may fail.
6291 */
6292 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6293#endif
6294 mch_remove(to);
6295#ifdef AMIGA
6296 if (flock)
6297 UnLock(flock);
6298#endif
6299
6300 /*
6301 * First try a normal rename, return if it works.
6302 */
6303 if (mch_rename((char *)from, (char *)to) == 0)
6304 return 0;
6305
6306 /*
6307 * Rename() failed, try copying the file.
6308 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006309 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006310#ifdef HAVE_ACL
6311 /* For systems that support ACL: get the ACL from the original file. */
6312 acl = mch_get_acl(from);
6313#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6315 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006316 {
6317#ifdef HAVE_ACL
6318 mch_free_acl(acl);
6319#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006321 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006322
6323 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006324 fd_out = mch_open((char *)to,
6325 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 if (fd_out == -1)
6327 {
6328 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006329#ifdef HAVE_ACL
6330 mch_free_acl(acl);
6331#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 return -1;
6333 }
6334
6335 buffer = (char *)alloc(BUFSIZE);
6336 if (buffer == NULL)
6337 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006339 close(fd_in);
6340#ifdef HAVE_ACL
6341 mch_free_acl(acl);
6342#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343 return -1;
6344 }
6345
6346 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6347 if (vim_write(fd_out, buffer, n) != n)
6348 {
6349 errmsg = _("E208: Error writing to \"%s\"");
6350 break;
6351 }
6352
6353 vim_free(buffer);
6354 close(fd_in);
6355 if (close(fd_out) < 0)
6356 errmsg = _("E209: Error closing \"%s\"");
6357 if (n < 0)
6358 {
6359 errmsg = _("E210: Error reading \"%s\"");
6360 to = from;
6361 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006362#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006363 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006364#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006365#ifdef HAVE_ACL
6366 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006367 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006368#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 if (errmsg != NULL)
6370 {
6371 EMSG2(errmsg, to);
6372 return -1;
6373 }
6374 mch_remove(from);
6375 return 0;
6376}
6377
6378static int already_warned = FALSE;
6379
6380/*
6381 * Check if any not hidden buffer has been changed.
6382 * Postpone the check if there are characters in the stuff buffer, a global
6383 * command is being executed, a mapping is being executed or an autocommand is
6384 * busy.
6385 * Returns TRUE if some message was written (screen should be redrawn and
6386 * cursor positioned).
6387 */
6388 int
6389check_timestamps(focus)
6390 int focus; /* called for GUI focus event */
6391{
6392 buf_T *buf;
6393 int didit = 0;
6394 int n;
6395
6396 /* Don't check timestamps while system() or another low-level function may
6397 * cause us to lose and gain focus. */
6398 if (no_check_timestamps > 0)
6399 return FALSE;
6400
6401 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6402 * event and we would keep on checking if the file is steadily growing.
6403 * Do check again after typing something. */
6404 if (focus && did_check_timestamps)
6405 {
6406 need_check_timestamps = TRUE;
6407 return FALSE;
6408 }
6409
6410 if (!stuff_empty() || global_busy || !typebuf_typed()
6411#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006412 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413#endif
6414 )
6415 need_check_timestamps = TRUE; /* check later */
6416 else
6417 {
6418 ++no_wait_return;
6419 did_check_timestamps = TRUE;
6420 already_warned = FALSE;
6421 for (buf = firstbuf; buf != NULL; )
6422 {
6423 /* Only check buffers in a window. */
6424 if (buf->b_nwindows > 0)
6425 {
6426 n = buf_check_timestamp(buf, focus);
6427 if (didit < n)
6428 didit = n;
6429 if (n > 0 && !buf_valid(buf))
6430 {
6431 /* Autocommands have removed the buffer, start at the
6432 * first one again. */
6433 buf = firstbuf;
6434 continue;
6435 }
6436 }
6437 buf = buf->b_next;
6438 }
6439 --no_wait_return;
6440 need_check_timestamps = FALSE;
6441 if (need_wait_return && didit == 2)
6442 {
6443 /* make sure msg isn't overwritten */
6444 msg_puts((char_u *)"\n");
6445 out_flush();
6446 }
6447 }
6448 return didit;
6449}
6450
6451/*
6452 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6453 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6454 * empty.
6455 */
6456 static int
6457move_lines(frombuf, tobuf)
6458 buf_T *frombuf;
6459 buf_T *tobuf;
6460{
6461 buf_T *tbuf = curbuf;
6462 int retval = OK;
6463 linenr_T lnum;
6464 char_u *p;
6465
6466 /* Copy the lines in "frombuf" to "tobuf". */
6467 curbuf = tobuf;
6468 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6469 {
6470 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6471 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6472 {
6473 vim_free(p);
6474 retval = FAIL;
6475 break;
6476 }
6477 vim_free(p);
6478 }
6479
6480 /* Delete all the lines in "frombuf". */
6481 if (retval != FAIL)
6482 {
6483 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006484 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6485 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 {
6487 /* Oops! We could try putting back the saved lines, but that
6488 * might fail again... */
6489 retval = FAIL;
6490 break;
6491 }
6492 }
6493
6494 curbuf = tbuf;
6495 return retval;
6496}
6497
6498/*
6499 * Check if buffer "buf" has been changed.
6500 * Also check if the file for a new buffer unexpectedly appeared.
6501 * return 1 if a changed buffer was found.
6502 * return 2 if a message has been displayed.
6503 * return 0 otherwise.
6504 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505 int
6506buf_check_timestamp(buf, focus)
6507 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006508 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509{
6510 struct stat st;
6511 int stat_res;
6512 int retval = 0;
6513 char_u *path;
6514 char_u *tbuf;
6515 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006516 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 int helpmesg = FALSE;
6518 int reload = FALSE;
6519#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6520 int can_reload = FALSE;
6521#endif
6522 size_t orig_size = buf->b_orig_size;
6523 int orig_mode = buf->b_orig_mode;
6524#ifdef FEAT_GUI
6525 int save_mouse_correct = need_mouse_correct;
6526#endif
6527#ifdef FEAT_AUTOCMD
6528 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006529 int n;
6530 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006532 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533
6534 /* If there is no file name, the buffer is not loaded, 'buftype' is
6535 * set, we are in the middle of a save or being called recursively: ignore
6536 * this buffer. */
6537 if (buf->b_ffname == NULL
6538 || buf->b_ml.ml_mfp == NULL
6539#if defined(FEAT_QUICKFIX)
6540 || *buf->b_p_bt != NUL
6541#endif
6542 || buf->b_saving
6543#ifdef FEAT_AUTOCMD
6544 || busy
6545#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006546#ifdef FEAT_NETBEANS_INTG
6547 || isNetbeansBuffer(buf)
6548#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 )
6550 return 0;
6551
6552 if ( !(buf->b_flags & BF_NOTEDITED)
6553 && buf->b_mtime != 0
6554 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6555 || time_differs((long)st.st_mtime, buf->b_mtime)
6556#ifdef HAVE_ST_MODE
6557 || (int)st.st_mode != buf->b_orig_mode
6558#else
6559 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6560#endif
6561 ))
6562 {
6563 retval = 1;
6564
Bram Moolenaar316059c2006-01-14 21:18:42 +00006565 /* set b_mtime to stop further warnings (e.g., when executing
6566 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 if (stat_res < 0)
6568 {
6569 buf->b_mtime = 0;
6570 buf->b_orig_size = 0;
6571 buf->b_orig_mode = 0;
6572 }
6573 else
6574 buf_store_time(buf, &st, buf->b_ffname);
6575
6576 /* Don't do anything for a directory. Might contain the file
6577 * explorer. */
6578 if (mch_isdir(buf->b_fname))
6579 ;
6580
6581 /*
6582 * If 'autoread' is set, the buffer has no changes and the file still
6583 * exists, reload the buffer. Use the buffer-local option value if it
6584 * was set, the global option value otherwise.
6585 */
6586 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6587 && !bufIsChanged(buf) && stat_res >= 0)
6588 reload = TRUE;
6589 else
6590 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006591 if (stat_res < 0)
6592 reason = "deleted";
6593 else if (bufIsChanged(buf))
6594 reason = "conflict";
6595 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6596 reason = "changed";
6597 else if (orig_mode != buf->b_orig_mode)
6598 reason = "mode";
6599 else
6600 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006602#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 /*
6604 * Only give the warning if there are no FileChangedShell
6605 * autocommands.
6606 * Avoid being called recursively by setting "busy".
6607 */
6608 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006609# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006610 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6611 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006612# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006613 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6615 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006616 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 busy = FALSE;
6618 if (n)
6619 {
6620 if (!buf_valid(buf))
6621 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006622# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006623 s = get_vim_var_str(VV_FCS_CHOICE);
6624 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6625 reload = TRUE;
6626 else if (STRCMP(s, "ask") == 0)
6627 n = FALSE;
6628 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006629# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006630 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006632 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633#endif
6634 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006635 if (*reason == 'd')
6636 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 else
6638 {
6639 helpmesg = TRUE;
6640#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6641 can_reload = TRUE;
6642#endif
6643 /*
6644 * Check if the file contents really changed to avoid
6645 * giving a warning when only the timestamp was set (e.g.,
6646 * checked out of CVS). Always warn when the buffer was
6647 * changed.
6648 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006649 if (reason[2] == 'n')
6650 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006652 mesg2 = _("See \":help W12\" for more info.");
6653 }
6654 else if (reason[1] == 'h')
6655 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006657 mesg2 = _("See \":help W11\" for more info.");
6658 }
6659 else if (*reason == 'm')
6660 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006662 mesg2 = _("See \":help W16\" for more info.");
6663 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006664 else
6665 /* Only timestamp changed, store it to avoid a warning
6666 * in check_mtime() later. */
6667 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 }
6669 }
6670 }
6671
6672 }
6673 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6674 && vim_fexists(buf->b_ffname))
6675 {
6676 retval = 1;
6677 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6678 buf->b_flags |= BF_NEW_W;
6679#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6680 can_reload = TRUE;
6681#endif
6682 }
6683
6684 if (mesg != NULL)
6685 {
6686 path = home_replace_save(buf, buf->b_fname);
6687 if (path != NULL)
6688 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006689 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 mesg2 = "";
6691 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6692 + STRLEN(mesg2) + 2));
6693 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006694#ifdef FEAT_EVAL
6695 /* Set warningmsg here, before the unimportant and output-specific
6696 * mesg2 has been appended. */
6697 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6698#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6700 if (can_reload)
6701 {
6702 if (*mesg2 != NUL)
6703 {
6704 STRCAT(tbuf, "\n");
6705 STRCAT(tbuf, mesg2);
6706 }
6707 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6708 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6709 reload = TRUE;
6710 }
6711 else
6712#endif
6713 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6714 {
6715 if (*mesg2 != NUL)
6716 {
6717 STRCAT(tbuf, "; ");
6718 STRCAT(tbuf, mesg2);
6719 }
6720 EMSG(tbuf);
6721 retval = 2;
6722 }
6723 else
6724 {
Bram Moolenaared203462004-06-16 11:19:22 +00006725# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728 {
6729 msg_start();
6730 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6731 if (*mesg2 != NUL)
6732 msg_puts_attr((char_u *)mesg2,
6733 hl_attr(HLF_W) + MSG_HIST);
6734 msg_clr_eos();
6735 (void)msg_end();
6736 if (emsg_silent == 0)
6737 {
6738 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00006739# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00006741# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742 /* give the user some time to think about it */
6743 ui_delay(1000L, TRUE);
6744
6745 /* don't redraw and erase the message */
6746 redraw_cmdline = FALSE;
6747 }
6748 }
6749 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 }
6751
6752 vim_free(path);
6753 vim_free(tbuf);
6754 }
6755 }
6756
6757 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006758 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006759 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760
Bram Moolenaar56718732006-03-15 22:53:57 +00006761#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006762 /* Trigger FileChangedShell when the file was changed in any way. */
6763 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00006764 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
6765 buf->b_fname, buf->b_fname, FALSE, buf);
6766#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767#ifdef FEAT_GUI
6768 /* restore this in case an autocommand has set it; it would break
6769 * 'mousefocus' */
6770 need_mouse_correct = save_mouse_correct;
6771#endif
6772
6773 return retval;
6774}
6775
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006776/*
6777 * Reload a buffer that is already loaded.
6778 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00006779 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
6780 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006781 */
6782 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00006783buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006784 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006785 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006786{
6787 exarg_T ea;
6788 pos_T old_cursor;
6789 linenr_T old_topline;
6790 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006791 buf_T *savebuf;
6792 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006793 aco_save_T aco;
6794
6795 /* set curwin/curbuf for "buf" and save some things */
6796 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006797
6798 /* We only want to read the text from the file, not reset the syntax
6799 * highlighting, clear marks, diff status, etc. Force the fileformat
6800 * and encoding to be the same. */
6801 if (prep_exarg(&ea, buf) == OK)
6802 {
6803 old_cursor = curwin->w_cursor;
6804 old_topline = curwin->w_topline;
6805
6806 /*
6807 * To behave like when a new file is edited (matters for
6808 * BufReadPost autocommands) we first need to delete the current
6809 * buffer contents. But if reading the file fails we should keep
6810 * the old contents. Can't use memory only, the file might be
6811 * too big. Use a hidden buffer to move the buffer contents to.
6812 */
6813 if (bufempty())
6814 savebuf = NULL;
6815 else
6816 {
6817 /* Allocate a buffer without putting it in the buffer list. */
6818 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00006819 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006820 {
6821 /* Open the memline. */
6822 curbuf = savebuf;
6823 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00006824 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006825 curbuf = buf;
6826 curwin->w_buffer = buf;
6827 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00006828 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006829 || move_lines(buf, savebuf) == FAIL)
6830 {
6831 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
6832 buf->b_fname);
6833 saved = FAIL;
6834 }
6835 }
6836
6837 if (saved == OK)
6838 {
6839 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
6840#ifdef FEAT_AUTOCMD
6841 keep_filetype = TRUE; /* don't detect 'filetype' */
6842#endif
6843 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
6844 (linenr_T)0,
6845 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
6846 {
6847#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6848 if (!aborting())
6849#endif
6850 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00006851 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006852 {
6853 /* Put the text back from the save buffer. First
6854 * delete any lines that readfile() added. */
6855 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00006856 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006857 break;
6858 (void)move_lines(savebuf, buf);
6859 }
6860 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00006861 else if (buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006862 {
6863 /* Mark the buffer as unmodified and free undo info. */
6864 unchanged(buf, TRUE);
6865 u_blockfree(buf);
6866 u_clearall(buf);
6867 }
6868 }
6869 vim_free(ea.cmd);
6870
Bram Moolenaar8424a622006-04-19 21:23:36 +00006871 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006872 wipe_buffer(savebuf, FALSE);
6873
6874#ifdef FEAT_DIFF
6875 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00006876 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006877#endif
6878
6879 /* Restore the topline and cursor position and check it (lines may
6880 * have been removed). */
6881 if (old_topline > curbuf->b_ml.ml_line_count)
6882 curwin->w_topline = curbuf->b_ml.ml_line_count;
6883 else
6884 curwin->w_topline = old_topline;
6885 curwin->w_cursor = old_cursor;
6886 check_cursor();
6887 update_topline();
6888#ifdef FEAT_AUTOCMD
6889 keep_filetype = FALSE;
6890#endif
6891#ifdef FEAT_FOLDING
6892 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00006893 win_T *wp;
6894 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006895
6896 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00006897 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006898 if (wp->w_buffer == curwin->w_buffer
6899 && !foldmethodIsManual(wp))
6900 foldUpdateAll(wp);
6901 }
6902#endif
6903 /* If the mode didn't change and 'readonly' was set, keep the old
6904 * value; the user probably used the ":view" command. But don't
6905 * reset it, might have had a read error. */
6906 if (orig_mode == curbuf->b_orig_mode)
6907 curbuf->b_p_ro |= old_ro;
6908 }
6909
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006910 /* restore curwin/curbuf and a few other things */
6911 aucmd_restbuf(&aco);
6912 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006913}
6914
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 void
6916buf_store_time(buf, st, fname)
6917 buf_T *buf;
6918 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006919 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920{
6921 buf->b_mtime = (long)st->st_mtime;
6922 buf->b_orig_size = (size_t)st->st_size;
6923#ifdef HAVE_ST_MODE
6924 buf->b_orig_mode = (int)st->st_mode;
6925#else
6926 buf->b_orig_mode = mch_getperm(fname);
6927#endif
6928}
6929
6930/*
6931 * Adjust the line with missing eol, used for the next write.
6932 * Used for do_filter(), when the input lines for the filter are deleted.
6933 */
6934 void
6935write_lnum_adjust(offset)
6936 linenr_T offset;
6937{
Bram Moolenaardf177f62005-02-22 08:39:57 +00006938 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 write_no_eol_lnum += offset;
6940}
6941
6942#if defined(TEMPDIRNAMES) || defined(PROTO)
6943static long temp_count = 0; /* Temp filename counter. */
6944
6945/*
6946 * Delete the temp directory and all files it contains.
6947 */
6948 void
6949vim_deltempdir()
6950{
6951 char_u **files;
6952 int file_count;
6953 int i;
6954
6955 if (vim_tempdir != NULL)
6956 {
6957 sprintf((char *)NameBuff, "%s*", vim_tempdir);
6958 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
6959 EW_DIR|EW_FILE|EW_SILENT) == OK)
6960 {
6961 for (i = 0; i < file_count; ++i)
6962 mch_remove(files[i]);
6963 FreeWild(file_count, files);
6964 }
6965 gettail(NameBuff)[-1] = NUL;
6966 (void)mch_rmdir(NameBuff);
6967
6968 vim_free(vim_tempdir);
6969 vim_tempdir = NULL;
6970 }
6971}
6972#endif
6973
6974/*
6975 * vim_tempname(): Return a unique name that can be used for a temp file.
6976 *
6977 * The temp file is NOT created.
6978 *
6979 * The returned pointer is to allocated memory.
6980 * The returned pointer is NULL if no valid name was found.
6981 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 char_u *
6983vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00006984 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985{
6986#ifdef USE_TMPNAM
6987 char_u itmp[L_tmpnam]; /* use tmpnam() */
6988#else
6989 char_u itmp[TEMPNAMELEN];
6990#endif
6991
6992#ifdef TEMPDIRNAMES
6993 static char *(tempdirs[]) = {TEMPDIRNAMES};
6994 int i;
6995 long nr;
6996 long off;
6997# ifndef EEXIST
6998 struct stat st;
6999# endif
7000
7001 /*
7002 * This will create a directory for private use by this instance of Vim.
7003 * This is done once, and the same directory is used for all temp files.
7004 * This method avoids security problems because of symlink attacks et al.
7005 * It's also a bit faster, because we only need to check for an existing
7006 * file when creating the directory and not for each temp file.
7007 */
7008 if (vim_tempdir == NULL)
7009 {
7010 /*
7011 * Try the entries in TEMPDIRNAMES to create the temp directory.
7012 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007013 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 {
7015 /* expand $TMP, leave room for "/v1100000/999999999" */
7016 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7017 if (mch_isdir(itmp)) /* directory exists */
7018 {
7019# ifdef __EMX__
7020 /* If $TMP contains a forward slash (perhaps using bash or
7021 * tcsh), don't add a backslash, use a forward slash!
7022 * Adding 2 backslashes didn't work. */
7023 if (vim_strchr(itmp, '/') != NULL)
7024 STRCAT(itmp, "/");
7025 else
7026# endif
7027 add_pathsep(itmp);
7028
7029 /* Get an arbitrary number of up to 6 digits. When it's
7030 * unlikely that it already exists it will be faster,
7031 * otherwise it doesn't matter. The use of mkdir() avoids any
7032 * security problems because of the predictable number. */
7033 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
7034
7035 /* Try up to 10000 different values until we find a name that
7036 * doesn't exist. */
7037 for (off = 0; off < 10000L; ++off)
7038 {
7039 int r;
7040#if defined(UNIX) || defined(VMS)
7041 mode_t umask_save;
7042#endif
7043
7044 sprintf((char *)itmp + STRLEN(itmp), "v%ld", nr + off);
7045# ifndef EEXIST
7046 /* If mkdir() does not set errno to EEXIST, check for
7047 * existing file here. There is a race condition then,
7048 * although it's fail-safe. */
7049 if (mch_stat((char *)itmp, &st) >= 0)
7050 continue;
7051# endif
7052#if defined(UNIX) || defined(VMS)
7053 /* Make sure the umask doesn't remove the executable bit.
7054 * "repl" has been reported to use "177". */
7055 umask_save = umask(077);
7056#endif
7057 r = vim_mkdir(itmp, 0700);
7058#if defined(UNIX) || defined(VMS)
7059 (void)umask(umask_save);
7060#endif
7061 if (r == 0)
7062 {
7063 char_u *buf;
7064
7065 /* Directory was created, use this name.
7066 * Expand to full path; When using the current
7067 * directory a ":cd" would confuse us. */
7068 buf = alloc((unsigned)MAXPATHL + 1);
7069 if (buf != NULL)
7070 {
7071 if (vim_FullName(itmp, buf, MAXPATHL, FALSE)
7072 == FAIL)
7073 STRCPY(buf, itmp);
7074# ifdef __EMX__
7075 if (vim_strchr(buf, '/') != NULL)
7076 STRCAT(buf, "/");
7077 else
7078# endif
7079 add_pathsep(buf);
7080 vim_tempdir = vim_strsave(buf);
7081 vim_free(buf);
7082 }
7083 break;
7084 }
7085# ifdef EEXIST
7086 /* If the mkdir() didn't fail because the file/dir exists,
7087 * we probably can't create any dir here, try another
7088 * place. */
7089 if (errno != EEXIST)
7090# endif
7091 break;
7092 }
7093 if (vim_tempdir != NULL)
7094 break;
7095 }
7096 }
7097 }
7098
7099 if (vim_tempdir != NULL)
7100 {
7101 /* There is no need to check if the file exists, because we own the
7102 * directory and nobody else creates a file in it. */
7103 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7104 return vim_strsave(itmp);
7105 }
7106
7107 return NULL;
7108
7109#else /* TEMPDIRNAMES */
7110
7111# ifdef WIN3264
7112 char szTempFile[_MAX_PATH + 1];
7113 char buf4[4];
7114 char_u *retval;
7115 char_u *p;
7116
7117 STRCPY(itmp, "");
7118 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7119 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7120 strcpy(buf4, "VIM");
7121 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7122 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7123 return NULL;
7124 /* GetTempFileName() will create the file, we don't want that */
7125 (void)DeleteFile(itmp);
7126
7127 /* Backslashes in a temp file name cause problems when filtering with
7128 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7129 * didn't set 'shellslash'. */
7130 retval = vim_strsave(itmp);
7131 if (*p_shcf == '-' || p_ssl)
7132 for (p = retval; *p; ++p)
7133 if (*p == '\\')
7134 *p = '/';
7135 return retval;
7136
7137# else /* WIN3264 */
7138
7139# ifdef USE_TMPNAM
7140 /* tmpnam() will make its own name */
7141 if (*tmpnam((char *)itmp) == NUL)
7142 return NULL;
7143# else
7144 char_u *p;
7145
7146# ifdef VMS_TEMPNAM
7147 /* mktemp() is not working on VMS. It seems to be
7148 * a do-nothing function. Therefore we use tempnam().
7149 */
7150 sprintf((char *)itmp, "VIM%c", extra_char);
7151 p = (char_u *)tempnam("tmp:", (char *)itmp);
7152 if (p != NULL)
7153 {
7154 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7155 * and VIM will then be unable to find the file later */
7156 STRCPY(itmp, p);
7157 STRCAT(itmp, ".txt");
7158 free(p);
7159 }
7160 else
7161 return NULL;
7162# else
7163 STRCPY(itmp, TEMPNAME);
7164 if ((p = vim_strchr(itmp, '?')) != NULL)
7165 *p = extra_char;
7166 if (mktemp((char *)itmp) == NULL)
7167 return NULL;
7168# endif
7169# endif
7170
7171 return vim_strsave(itmp);
7172# endif /* WIN3264 */
7173#endif /* TEMPDIRNAMES */
7174}
7175
7176#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7177/*
7178 * Convert all backslashes in fname to forward slashes in-place.
7179 */
7180 void
7181forward_slash(fname)
7182 char_u *fname;
7183{
7184 char_u *p;
7185
7186 for (p = fname; *p != NUL; ++p)
7187# ifdef FEAT_MBYTE
7188 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007189 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 ++p;
7191 else
7192# endif
7193 if (*p == '\\')
7194 *p = '/';
7195}
7196#endif
7197
7198
7199/*
7200 * Code for automatic commands.
7201 *
7202 * Only included when "FEAT_AUTOCMD" has been defined.
7203 */
7204
7205#if defined(FEAT_AUTOCMD) || defined(PROTO)
7206
7207/*
7208 * The autocommands are stored in a list for each event.
7209 * Autocommands for the same pattern, that are consecutive, are joined
7210 * together, to avoid having to match the pattern too often.
7211 * The result is an array of Autopat lists, which point to AutoCmd lists:
7212 *
7213 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7214 * Autopat.cmds Autopat.cmds
7215 * | |
7216 * V V
7217 * AutoCmd.next AutoCmd.next
7218 * | |
7219 * V V
7220 * AutoCmd.next NULL
7221 * |
7222 * V
7223 * NULL
7224 *
7225 * first_autopat[1] --> Autopat.next --> NULL
7226 * Autopat.cmds
7227 * |
7228 * V
7229 * AutoCmd.next
7230 * |
7231 * V
7232 * NULL
7233 * etc.
7234 *
7235 * The order of AutoCmds is important, this is the order in which they were
7236 * defined and will have to be executed.
7237 */
7238typedef struct AutoCmd
7239{
7240 char_u *cmd; /* The command to be executed (NULL
7241 when command has been removed) */
7242 char nested; /* If autocommands nest here */
7243 char last; /* last command in list */
7244#ifdef FEAT_EVAL
7245 scid_T scriptID; /* script ID where defined */
7246#endif
7247 struct AutoCmd *next; /* Next AutoCmd in list */
7248} AutoCmd;
7249
7250typedef struct AutoPat
7251{
7252 int group; /* group ID */
7253 char_u *pat; /* pattern as typed (NULL when pattern
7254 has been removed) */
7255 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007256 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 char allow_dirs; /* Pattern may match whole path */
7258 char last; /* last pattern for apply_autocmds() */
7259 AutoCmd *cmds; /* list of commands to do */
7260 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007261 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262} AutoPat;
7263
7264static struct event_name
7265{
7266 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007267 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268} event_names[] =
7269{
7270 {"BufAdd", EVENT_BUFADD},
7271 {"BufCreate", EVENT_BUFADD},
7272 {"BufDelete", EVENT_BUFDELETE},
7273 {"BufEnter", EVENT_BUFENTER},
7274 {"BufFilePost", EVENT_BUFFILEPOST},
7275 {"BufFilePre", EVENT_BUFFILEPRE},
7276 {"BufHidden", EVENT_BUFHIDDEN},
7277 {"BufLeave", EVENT_BUFLEAVE},
7278 {"BufNew", EVENT_BUFNEW},
7279 {"BufNewFile", EVENT_BUFNEWFILE},
7280 {"BufRead", EVENT_BUFREADPOST},
7281 {"BufReadCmd", EVENT_BUFREADCMD},
7282 {"BufReadPost", EVENT_BUFREADPOST},
7283 {"BufReadPre", EVENT_BUFREADPRE},
7284 {"BufUnload", EVENT_BUFUNLOAD},
7285 {"BufWinEnter", EVENT_BUFWINENTER},
7286 {"BufWinLeave", EVENT_BUFWINLEAVE},
7287 {"BufWipeout", EVENT_BUFWIPEOUT},
7288 {"BufWrite", EVENT_BUFWRITEPRE},
7289 {"BufWritePost", EVENT_BUFWRITEPOST},
7290 {"BufWritePre", EVENT_BUFWRITEPRE},
7291 {"BufWriteCmd", EVENT_BUFWRITECMD},
7292 {"CmdwinEnter", EVENT_CMDWINENTER},
7293 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007294 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007295 {"CursorHold", EVENT_CURSORHOLD},
7296 {"CursorHoldI", EVENT_CURSORHOLDI},
7297 {"CursorMoved", EVENT_CURSORMOVED},
7298 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7300 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7302 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7303 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7304 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007305 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306 {"FileChangedRO", EVENT_FILECHANGEDRO},
7307 {"FileReadPost", EVENT_FILEREADPOST},
7308 {"FileReadPre", EVENT_FILEREADPRE},
7309 {"FileReadCmd", EVENT_FILEREADCMD},
7310 {"FileType", EVENT_FILETYPE},
7311 {"FileWritePost", EVENT_FILEWRITEPOST},
7312 {"FileWritePre", EVENT_FILEWRITEPRE},
7313 {"FileWriteCmd", EVENT_FILEWRITECMD},
7314 {"FilterReadPost", EVENT_FILTERREADPOST},
7315 {"FilterReadPre", EVENT_FILTERREADPRE},
7316 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7317 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7318 {"FocusGained", EVENT_FOCUSGAINED},
7319 {"FocusLost", EVENT_FOCUSLOST},
7320 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7321 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007322 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007323 {"InsertChange", EVENT_INSERTCHANGE},
7324 {"InsertEnter", EVENT_INSERTENTER},
7325 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007326 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007327 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7328 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007330 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007331 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7332 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007333 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007334 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007335 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 {"StdinReadPost", EVENT_STDINREADPOST},
7337 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007338 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007339 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007340 {"TabEnter", EVENT_TABENTER},
7341 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 {"TermChanged", EVENT_TERMCHANGED},
7343 {"TermResponse", EVENT_TERMRESPONSE},
7344 {"User", EVENT_USER},
7345 {"VimEnter", EVENT_VIMENTER},
7346 {"VimLeave", EVENT_VIMLEAVE},
7347 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7348 {"WinEnter", EVENT_WINENTER},
7349 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007350 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007351 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352};
7353
7354static AutoPat *first_autopat[NUM_EVENTS] =
7355{
7356 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7357 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7358 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7359 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007360 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7361 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362};
7363
7364/*
7365 * struct used to keep status while executing autocommands for an event.
7366 */
7367typedef struct AutoPatCmd
7368{
7369 AutoPat *curpat; /* next AutoPat to examine */
7370 AutoCmd *nextcmd; /* next AutoCmd to execute */
7371 int group; /* group being used */
7372 char_u *fname; /* fname to match with */
7373 char_u *sfname; /* sfname to match with */
7374 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007375 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007376 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7377 buf is deleted */
7378 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379} AutoPatCmd;
7380
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007381static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007382
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383/*
7384 * augroups stores a list of autocmd group names.
7385 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007386static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7388
7389/*
7390 * The ID of the current group. Group 0 is the default one.
7391 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392static int current_augroup = AUGROUP_DEFAULT;
7393
7394static int au_need_clean = FALSE; /* need to delete marked patterns */
7395
Bram Moolenaar754b5602006-02-09 23:53:20 +00007396static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397static void au_remove_pat __ARGS((AutoPat *ap));
7398static void au_remove_cmds __ARGS((AutoPat *ap));
7399static void au_cleanup __ARGS((void));
7400static int au_new_group __ARGS((char_u *name));
7401static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007402static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7403static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007405static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007407static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007409static 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));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7411
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007412
Bram Moolenaar754b5602006-02-09 23:53:20 +00007413static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007415static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416
7417/*
7418 * Show the autocommands for one AutoPat.
7419 */
7420 static void
7421show_autocmd(ap, event)
7422 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007423 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424{
7425 AutoCmd *ac;
7426
7427 /* Check for "got_int" (here and at various places below), which is set
7428 * when "q" has been hit for the "--more--" prompt */
7429 if (got_int)
7430 return;
7431 if (ap->pat == NULL) /* pattern has been removed */
7432 return;
7433
7434 msg_putchar('\n');
7435 if (got_int)
7436 return;
7437 if (event != last_event || ap->group != last_group)
7438 {
7439 if (ap->group != AUGROUP_DEFAULT)
7440 {
7441 if (AUGROUP_NAME(ap->group) == NULL)
7442 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7443 else
7444 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7445 msg_puts((char_u *)" ");
7446 }
7447 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7448 last_event = event;
7449 last_group = ap->group;
7450 msg_putchar('\n');
7451 if (got_int)
7452 return;
7453 }
7454 msg_col = 4;
7455 msg_outtrans(ap->pat);
7456
7457 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7458 {
7459 if (ac->cmd != NULL) /* skip removed commands */
7460 {
7461 if (msg_col >= 14)
7462 msg_putchar('\n');
7463 msg_col = 14;
7464 if (got_int)
7465 return;
7466 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007467#ifdef FEAT_EVAL
7468 if (p_verbose > 0)
7469 last_set_msg(ac->scriptID);
7470#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 if (got_int)
7472 return;
7473 if (ac->next != NULL)
7474 {
7475 msg_putchar('\n');
7476 if (got_int)
7477 return;
7478 }
7479 }
7480 }
7481}
7482
7483/*
7484 * Mark an autocommand pattern for deletion.
7485 */
7486 static void
7487au_remove_pat(ap)
7488 AutoPat *ap;
7489{
7490 vim_free(ap->pat);
7491 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007492 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 au_need_clean = TRUE;
7494}
7495
7496/*
7497 * Mark all commands for a pattern for deletion.
7498 */
7499 static void
7500au_remove_cmds(ap)
7501 AutoPat *ap;
7502{
7503 AutoCmd *ac;
7504
7505 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7506 {
7507 vim_free(ac->cmd);
7508 ac->cmd = NULL;
7509 }
7510 au_need_clean = TRUE;
7511}
7512
7513/*
7514 * Cleanup autocommands and patterns that have been deleted.
7515 * This is only done when not executing autocommands.
7516 */
7517 static void
7518au_cleanup()
7519{
7520 AutoPat *ap, **prev_ap;
7521 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007522 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523
7524 if (autocmd_busy || !au_need_clean)
7525 return;
7526
7527 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007528 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7529 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 {
7531 /* loop over all autocommand patterns */
7532 prev_ap = &(first_autopat[(int)event]);
7533 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7534 {
7535 /* loop over all commands for this pattern */
7536 prev_ac = &(ap->cmds);
7537 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7538 {
7539 /* remove the command if the pattern is to be deleted or when
7540 * the command has been marked for deletion */
7541 if (ap->pat == NULL || ac->cmd == NULL)
7542 {
7543 *prev_ac = ac->next;
7544 vim_free(ac->cmd);
7545 vim_free(ac);
7546 }
7547 else
7548 prev_ac = &(ac->next);
7549 }
7550
7551 /* remove the pattern if it has been marked for deletion */
7552 if (ap->pat == NULL)
7553 {
7554 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007555 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556 vim_free(ap);
7557 }
7558 else
7559 prev_ap = &(ap->next);
7560 }
7561 }
7562
7563 au_need_clean = FALSE;
7564}
7565
7566/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007567 * Called when buffer is freed, to remove/invalidate related buffer-local
7568 * autocmds.
7569 */
7570 void
7571aubuflocal_remove(buf)
7572 buf_T *buf;
7573{
7574 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007575 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007576 AutoPatCmd *apc;
7577
7578 /* invalidate currently executing autocommands */
7579 for (apc = active_apc_list; apc; apc = apc->next)
7580 if (buf->b_fnum == apc->arg_bufnr)
7581 apc->arg_bufnr = 0;
7582
7583 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007584 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7585 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007586 /* loop over all autocommand patterns */
7587 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7588 if (ap->buflocal_nr == buf->b_fnum)
7589 {
7590 au_remove_pat(ap);
7591 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007592 {
7593 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007594 smsg((char_u *)
7595 _("auto-removing autocommand: %s <buffer=%d>"),
7596 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007597 verbose_leave();
7598 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007599 }
7600 au_cleanup();
7601}
7602
7603/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604 * Add an autocmd group name.
7605 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7606 */
7607 static int
7608au_new_group(name)
7609 char_u *name;
7610{
7611 int i;
7612
7613 i = au_find_group(name);
7614 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7615 {
7616 /* First try using a free entry. */
7617 for (i = 0; i < augroups.ga_len; ++i)
7618 if (AUGROUP_NAME(i) == NULL)
7619 break;
7620 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7621 return AUGROUP_ERROR;
7622
7623 AUGROUP_NAME(i) = vim_strsave(name);
7624 if (AUGROUP_NAME(i) == NULL)
7625 return AUGROUP_ERROR;
7626 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628 }
7629
7630 return i;
7631}
7632
7633 static void
7634au_del_group(name)
7635 char_u *name;
7636{
7637 int i;
7638
7639 i = au_find_group(name);
7640 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7641 EMSG2(_("E367: No such group: \"%s\""), name);
7642 else
7643 {
7644 vim_free(AUGROUP_NAME(i));
7645 AUGROUP_NAME(i) = NULL;
7646 }
7647}
7648
7649/*
7650 * Find the ID of an autocmd group name.
7651 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7652 */
7653 static int
7654au_find_group(name)
7655 char_u *name;
7656{
7657 int i;
7658
7659 for (i = 0; i < augroups.ga_len; ++i)
7660 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7661 return i;
7662 return AUGROUP_ERROR;
7663}
7664
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007665/*
7666 * Return TRUE if augroup "name" exists.
7667 */
7668 int
7669au_has_group(name)
7670 char_u *name;
7671{
7672 return au_find_group(name) != AUGROUP_ERROR;
7673}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007674
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675/*
7676 * ":augroup {name}".
7677 */
7678 void
7679do_augroup(arg, del_group)
7680 char_u *arg;
7681 int del_group;
7682{
7683 int i;
7684
7685 if (del_group)
7686 {
7687 if (*arg == NUL)
7688 EMSG(_(e_argreq));
7689 else
7690 au_del_group(arg);
7691 }
7692 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
7693 current_augroup = AUGROUP_DEFAULT;
7694 else if (*arg) /* ":aug xxx": switch to group xxx */
7695 {
7696 i = au_new_group(arg);
7697 if (i != AUGROUP_ERROR)
7698 current_augroup = i;
7699 }
7700 else /* ":aug": list the group names */
7701 {
7702 msg_start();
7703 for (i = 0; i < augroups.ga_len; ++i)
7704 {
7705 if (AUGROUP_NAME(i) != NULL)
7706 {
7707 msg_puts(AUGROUP_NAME(i));
7708 msg_puts((char_u *)" ");
7709 }
7710 }
7711 msg_clr_eos();
7712 msg_end();
7713 }
7714}
7715
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007716#if defined(EXITFREE) || defined(PROTO)
7717 void
7718free_all_autocmds()
7719{
7720 for (current_augroup = -1; current_augroup < augroups.ga_len;
7721 ++current_augroup)
7722 do_autocmd((char_u *)"", TRUE);
7723 ga_clear_strings(&augroups);
7724}
7725#endif
7726
Bram Moolenaar071d4272004-06-13 20:20:40 +00007727/*
7728 * Return the event number for event name "start".
7729 * Return NUM_EVENTS if the event name was not found.
7730 * Return a pointer to the next event name in "end".
7731 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007732 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733event_name2nr(start, end)
7734 char_u *start;
7735 char_u **end;
7736{
7737 char_u *p;
7738 int i;
7739 int len;
7740
7741 /* the event name ends with end of line, a blank or a comma */
7742 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
7743 ;
7744 for (i = 0; event_names[i].name != NULL; ++i)
7745 {
7746 len = (int)STRLEN(event_names[i].name);
7747 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
7748 break;
7749 }
7750 if (*p == ',')
7751 ++p;
7752 *end = p;
7753 if (event_names[i].name == NULL)
7754 return NUM_EVENTS;
7755 return event_names[i].event;
7756}
7757
7758/*
7759 * Return the name for event "event".
7760 */
7761 static char_u *
7762event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007763 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764{
7765 int i;
7766
7767 for (i = 0; event_names[i].name != NULL; ++i)
7768 if (event_names[i].event == event)
7769 return (char_u *)event_names[i].name;
7770 return (char_u *)"Unknown";
7771}
7772
7773/*
7774 * Scan over the events. "*" stands for all events.
7775 */
7776 static char_u *
7777find_end_event(arg, have_group)
7778 char_u *arg;
7779 int have_group; /* TRUE when group name was found */
7780{
7781 char_u *pat;
7782 char_u *p;
7783
7784 if (*arg == '*')
7785 {
7786 if (arg[1] && !vim_iswhite(arg[1]))
7787 {
7788 EMSG2(_("E215: Illegal character after *: %s"), arg);
7789 return NULL;
7790 }
7791 pat = arg + 1;
7792 }
7793 else
7794 {
7795 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
7796 {
7797 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
7798 {
7799 if (have_group)
7800 EMSG2(_("E216: No such event: %s"), pat);
7801 else
7802 EMSG2(_("E216: No such group or event: %s"), pat);
7803 return NULL;
7804 }
7805 }
7806 }
7807 return pat;
7808}
7809
7810/*
7811 * Return TRUE if "event" is included in 'eventignore'.
7812 */
7813 static int
7814event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007815 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816{
7817 char_u *p = p_ei;
7818
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007819 while (*p != NUL)
7820 {
7821 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
7822 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007823 if (event_name2nr(p, &p) == event)
7824 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007825 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007826
7827 return FALSE;
7828}
7829
7830/*
7831 * Return OK when the contents of p_ei is valid, FAIL otherwise.
7832 */
7833 int
7834check_ei()
7835{
7836 char_u *p = p_ei;
7837
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007839 {
7840 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
7841 {
7842 p += 3;
7843 if (*p == ',')
7844 ++p;
7845 }
7846 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007847 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007849
7850 return OK;
7851}
7852
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007853# if defined(FEAT_SYN_HL) || defined(PROTO)
7854
7855/*
7856 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
7857 * buffer loaded into the window. "what" must start with a comma.
7858 * Returns the old value of 'eventignore' in allocated memory.
7859 */
7860 char_u *
7861au_event_disable(what)
7862 char *what;
7863{
7864 char_u *new_ei;
7865 char_u *save_ei;
7866
7867 save_ei = vim_strsave(p_ei);
7868 if (save_ei != NULL)
7869 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00007870 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007871 if (new_ei != NULL)
7872 {
7873 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00007874 set_string_option_direct((char_u *)"ei", -1, new_ei,
7875 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007876 vim_free(new_ei);
7877 }
7878 }
7879 return save_ei;
7880}
7881
7882 void
7883au_event_restore(old_ei)
7884 char_u *old_ei;
7885{
7886 if (old_ei != NULL)
7887 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00007888 set_string_option_direct((char_u *)"ei", -1, old_ei,
7889 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007890 vim_free(old_ei);
7891 }
7892}
7893# endif /* FEAT_SYN_HL */
7894
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895/*
7896 * do_autocmd() -- implements the :autocmd command. Can be used in the
7897 * following ways:
7898 *
7899 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
7900 * will be automatically executed for <event>
7901 * when editing a file matching <pat>, in
7902 * the current group.
7903 * :autocmd <event> <pat> Show the auto-commands associated with
7904 * <event> and <pat>.
7905 * :autocmd <event> Show the auto-commands associated with
7906 * <event>.
7907 * :autocmd Show all auto-commands.
7908 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
7909 * <event> and <pat>, and add the command
7910 * <cmd>, for the current group.
7911 * :autocmd! <event> <pat> Remove all auto-commands associated with
7912 * <event> and <pat> for the current group.
7913 * :autocmd! <event> Remove all auto-commands associated with
7914 * <event> for the current group.
7915 * :autocmd! Remove ALL auto-commands for the current
7916 * group.
7917 *
7918 * Multiple events and patterns may be given separated by commas. Here are
7919 * some examples:
7920 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
7921 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
7922 *
7923 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00007924 *
7925 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007926 */
7927 void
7928do_autocmd(arg, forceit)
7929 char_u *arg;
7930 int forceit;
7931{
7932 char_u *pat;
7933 char_u *envpat = NULL;
7934 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007935 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007936 int need_free = FALSE;
7937 int nested = FALSE;
7938 int group;
7939
7940 /*
7941 * Check for a legal group name. If not, use AUGROUP_ALL.
7942 */
7943 group = au_get_grouparg(&arg);
7944 if (arg == NULL) /* out of memory */
7945 return;
7946
7947 /*
7948 * Scan over the events.
7949 * If we find an illegal name, return here, don't do anything.
7950 */
7951 pat = find_end_event(arg, group != AUGROUP_ALL);
7952 if (pat == NULL)
7953 return;
7954
7955 /*
7956 * Scan over the pattern. Put a NUL at the end.
7957 */
7958 pat = skipwhite(pat);
7959 cmd = pat;
7960 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
7961 cmd++;
7962 if (*cmd)
7963 *cmd++ = NUL;
7964
7965 /* Expand environment variables in the pattern. Set 'shellslash', we want
7966 * forward slashes here. */
7967 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
7968 {
7969#ifdef BACKSLASH_IN_FILENAME
7970 int p_ssl_save = p_ssl;
7971
7972 p_ssl = TRUE;
7973#endif
7974 envpat = expand_env_save(pat);
7975#ifdef BACKSLASH_IN_FILENAME
7976 p_ssl = p_ssl_save;
7977#endif
7978 if (envpat != NULL)
7979 pat = envpat;
7980 }
7981
7982 /*
7983 * Check for "nested" flag.
7984 */
7985 cmd = skipwhite(cmd);
7986 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
7987 {
7988 nested = TRUE;
7989 cmd = skipwhite(cmd + 6);
7990 }
7991
7992 /*
7993 * Find the start of the commands.
7994 * Expand <sfile> in it.
7995 */
7996 if (*cmd != NUL)
7997 {
7998 cmd = expand_sfile(cmd);
7999 if (cmd == NULL) /* some error */
8000 return;
8001 need_free = TRUE;
8002 }
8003
8004 /*
8005 * Print header when showing autocommands.
8006 */
8007 if (!forceit && *cmd == NUL)
8008 {
8009 /* Highlight title */
8010 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8011 }
8012
8013 /*
8014 * Loop over the events.
8015 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008016 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017 last_group = AUGROUP_ERROR; /* for listing the group name */
8018 if (*arg == '*' || *arg == NUL)
8019 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008020 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8021 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008022 if (do_autocmd_event(event, pat,
8023 nested, cmd, forceit, group) == FAIL)
8024 break;
8025 }
8026 else
8027 {
8028 while (*arg && !vim_iswhite(*arg))
8029 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8030 nested, cmd, forceit, group) == FAIL)
8031 break;
8032 }
8033
8034 if (need_free)
8035 vim_free(cmd);
8036 vim_free(envpat);
8037}
8038
8039/*
8040 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8041 * The "argp" argument is advanced to the following argument.
8042 *
8043 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8044 */
8045 static int
8046au_get_grouparg(argp)
8047 char_u **argp;
8048{
8049 char_u *group_name;
8050 char_u *p;
8051 char_u *arg = *argp;
8052 int group = AUGROUP_ALL;
8053
8054 p = skiptowhite(arg);
8055 if (p > arg)
8056 {
8057 group_name = vim_strnsave(arg, (int)(p - arg));
8058 if (group_name == NULL) /* out of memory */
8059 return AUGROUP_ERROR;
8060 group = au_find_group(group_name);
8061 if (group == AUGROUP_ERROR)
8062 group = AUGROUP_ALL; /* no match, use all groups */
8063 else
8064 *argp = skipwhite(p); /* match, skip over group name */
8065 vim_free(group_name);
8066 }
8067 return group;
8068}
8069
8070/*
8071 * do_autocmd() for one event.
8072 * If *pat == NUL do for all patterns.
8073 * If *cmd == NUL show entries.
8074 * If forceit == TRUE delete entries.
8075 * If group is not AUGROUP_ALL, only use this group.
8076 */
8077 static int
8078do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008079 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008080 char_u *pat;
8081 int nested;
8082 char_u *cmd;
8083 int forceit;
8084 int group;
8085{
8086 AutoPat *ap;
8087 AutoPat **prev_ap;
8088 AutoCmd *ac;
8089 AutoCmd **prev_ac;
8090 int brace_level;
8091 char_u *endpat;
8092 int findgroup;
8093 int allgroups;
8094 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008095 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008096 int buflocal_nr;
8097 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008098
8099 if (group == AUGROUP_ALL)
8100 findgroup = current_augroup;
8101 else
8102 findgroup = group;
8103 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8104
8105 /*
8106 * Show or delete all patterns for an event.
8107 */
8108 if (*pat == NUL)
8109 {
8110 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8111 {
8112 if (forceit) /* delete the AutoPat, if it's in the current group */
8113 {
8114 if (ap->group == findgroup)
8115 au_remove_pat(ap);
8116 }
8117 else if (group == AUGROUP_ALL || ap->group == group)
8118 show_autocmd(ap, event);
8119 }
8120 }
8121
8122 /*
8123 * Loop through all the specified patterns.
8124 */
8125 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8126 {
8127 /*
8128 * Find end of the pattern.
8129 * Watch out for a comma in braces, like "*.\{obj,o\}".
8130 */
8131 brace_level = 0;
8132 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8133 || endpat[-1] == '\\'); ++endpat)
8134 {
8135 if (*endpat == '{')
8136 brace_level++;
8137 else if (*endpat == '}')
8138 brace_level--;
8139 }
8140 if (pat == endpat) /* ignore single comma */
8141 continue;
8142 patlen = (int)(endpat - pat);
8143
8144 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008145 * detect special <buflocal[=X]> buffer-local patterns
8146 */
8147 is_buflocal = FALSE;
8148 buflocal_nr = 0;
8149
8150 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8151 && pat[patlen - 1] == '>')
8152 {
8153 /* Error will be printed only for addition. printing and removing
8154 * will proceed silently. */
8155 is_buflocal = TRUE;
8156 if (patlen == 8)
8157 buflocal_nr = curbuf->b_fnum;
8158 else if (patlen > 9 && pat[7] == '=')
8159 {
8160 /* <buffer=abuf> */
8161 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8162 buflocal_nr = autocmd_bufnr;
8163 /* <buffer=123> */
8164 else if (skipdigits(pat + 8) == pat + patlen - 1)
8165 buflocal_nr = atoi((char *)pat + 8);
8166 }
8167 }
8168
8169 if (is_buflocal)
8170 {
8171 /* normalize pat into standard "<buffer>#N" form */
8172 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8173 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008174 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008175 }
8176
8177 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008178 * Find AutoPat entries with this pattern.
8179 */
8180 prev_ap = &first_autopat[(int)event];
8181 while ((ap = *prev_ap) != NULL)
8182 {
8183 if (ap->pat != NULL)
8184 {
8185 /* Accept a pattern when:
8186 * - a group was specified and it's that group, or a group was
8187 * not specified and it's the current group, or a group was
8188 * not specified and we are listing
8189 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008190 * - the pattern matches.
8191 * For <buffer[=X]>, this condition works because we normalize
8192 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008193 */
8194 if ((allgroups || ap->group == findgroup)
8195 && ap->patlen == patlen
8196 && STRNCMP(pat, ap->pat, patlen) == 0)
8197 {
8198 /*
8199 * Remove existing autocommands.
8200 * If adding any new autocmd's for this AutoPat, don't
8201 * delete the pattern from the autopat list, append to
8202 * this list.
8203 */
8204 if (forceit)
8205 {
8206 if (*cmd != NUL && ap->next == NULL)
8207 {
8208 au_remove_cmds(ap);
8209 break;
8210 }
8211 au_remove_pat(ap);
8212 }
8213
8214 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008215 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008216 */
8217 else if (*cmd == NUL)
8218 show_autocmd(ap, event);
8219
8220 /*
8221 * Add autocmd to this autopat, if it's the last one.
8222 */
8223 else if (ap->next == NULL)
8224 break;
8225 }
8226 }
8227 prev_ap = &ap->next;
8228 }
8229
8230 /*
8231 * Add a new command.
8232 */
8233 if (*cmd != NUL)
8234 {
8235 /*
8236 * If the pattern we want to add a command to does appear at the
8237 * end of the list (or not is not in the list at all), add the
8238 * pattern at the end of the list.
8239 */
8240 if (ap == NULL)
8241 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008242 /* refuse to add buffer-local ap if buffer number is invalid */
8243 if (is_buflocal && (buflocal_nr == 0
8244 || buflist_findnr(buflocal_nr) == NULL))
8245 {
8246 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8247 buflocal_nr);
8248 return FAIL;
8249 }
8250
Bram Moolenaar071d4272004-06-13 20:20:40 +00008251 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8252 if (ap == NULL)
8253 return FAIL;
8254 ap->pat = vim_strnsave(pat, patlen);
8255 ap->patlen = patlen;
8256 if (ap->pat == NULL)
8257 {
8258 vim_free(ap);
8259 return FAIL;
8260 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008261
8262 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008263 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008264 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008265 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008266 }
8267 else
8268 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008269 char_u *reg_pat;
8270
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008271 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008272 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008273 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008274 if (reg_pat != NULL)
8275 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008276 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008277 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008278 {
8279 vim_free(ap->pat);
8280 vim_free(ap);
8281 return FAIL;
8282 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008283 }
8284 ap->cmds = NULL;
8285 *prev_ap = ap;
8286 ap->next = NULL;
8287 if (group == AUGROUP_ALL)
8288 ap->group = current_augroup;
8289 else
8290 ap->group = group;
8291 }
8292
8293 /*
8294 * Add the autocmd at the end of the AutoCmd list.
8295 */
8296 prev_ac = &(ap->cmds);
8297 while ((ac = *prev_ac) != NULL)
8298 prev_ac = &ac->next;
8299 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8300 if (ac == NULL)
8301 return FAIL;
8302 ac->cmd = vim_strsave(cmd);
8303#ifdef FEAT_EVAL
8304 ac->scriptID = current_SID;
8305#endif
8306 if (ac->cmd == NULL)
8307 {
8308 vim_free(ac);
8309 return FAIL;
8310 }
8311 ac->next = NULL;
8312 *prev_ac = ac;
8313 ac->nested = nested;
8314 }
8315 }
8316
8317 au_cleanup(); /* may really delete removed patterns/commands now */
8318 return OK;
8319}
8320
8321/*
8322 * Implementation of ":doautocmd [group] event [fname]".
8323 * Return OK for success, FAIL for failure;
8324 */
8325 int
8326do_doautocmd(arg, do_msg)
8327 char_u *arg;
8328 int do_msg; /* give message for no matching autocmds? */
8329{
8330 char_u *fname;
8331 int nothing_done = TRUE;
8332 int group;
8333
8334 /*
8335 * Check for a legal group name. If not, use AUGROUP_ALL.
8336 */
8337 group = au_get_grouparg(&arg);
8338 if (arg == NULL) /* out of memory */
8339 return FAIL;
8340
8341 if (*arg == '*')
8342 {
8343 EMSG(_("E217: Can't execute autocommands for ALL events"));
8344 return FAIL;
8345 }
8346
8347 /*
8348 * Scan over the events.
8349 * If we find an illegal name, return here, don't do anything.
8350 */
8351 fname = find_end_event(arg, group != AUGROUP_ALL);
8352 if (fname == NULL)
8353 return FAIL;
8354
8355 fname = skipwhite(fname);
8356
8357 /*
8358 * Loop over the events.
8359 */
8360 while (*arg && !vim_iswhite(*arg))
8361 if (apply_autocmds_group(event_name2nr(arg, &arg),
8362 fname, NULL, TRUE, group, curbuf, NULL))
8363 nothing_done = FALSE;
8364
8365 if (nothing_done && do_msg)
8366 MSG(_("No matching autocommands"));
8367
8368#ifdef FEAT_EVAL
8369 return aborting() ? FAIL : OK;
8370#else
8371 return OK;
8372#endif
8373}
8374
8375/*
8376 * ":doautoall": execute autocommands for each loaded buffer.
8377 */
8378 void
8379ex_doautoall(eap)
8380 exarg_T *eap;
8381{
8382 int retval;
8383 aco_save_T aco;
8384 buf_T *buf;
8385
8386 /*
8387 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8388 * equal to curbuf, but for some buffers there may not be a window.
8389 * So we change the buffer for the current window for a moment. This
8390 * gives problems when the autocommands make changes to the list of
8391 * buffers or windows...
8392 */
8393 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8394 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008395 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008396 {
8397 /* find a window for this buffer and save some values */
8398 aucmd_prepbuf(&aco, buf);
8399
8400 /* execute the autocommands for this buffer */
8401 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008402
8403 /* Execute the modeline settings, but don't set window-local
8404 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008405 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008406
8407 /* restore the current window */
8408 aucmd_restbuf(&aco);
8409
8410 /* stop if there is some error or buffer was deleted */
8411 if (retval == FAIL || !buf_valid(buf))
8412 break;
8413 }
8414 }
8415
8416 check_cursor(); /* just in case lines got deleted */
8417}
8418
8419/*
8420 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008421 * Search for a visible window containing the current buffer. If there isn't
8422 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008423 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008424 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008425 */
8426 void
8427aucmd_prepbuf(aco, buf)
8428 aco_save_T *aco; /* structure to save values in */
8429 buf_T *buf; /* new curbuf */
8430{
8431 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008432#ifdef FEAT_WINDOWS
8433 int save_ea;
8434#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008435
8436 /* Find a window that is for the new buffer */
8437 if (buf == curbuf) /* be quick when buf is curbuf */
8438 win = curwin;
8439 else
8440#ifdef FEAT_WINDOWS
8441 for (win = firstwin; win != NULL; win = win->w_next)
8442 if (win->w_buffer == buf)
8443 break;
8444#else
8445 win = NULL;
8446#endif
8447
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008448 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8449 * back to using the current window. */
8450 if (win == NULL && aucmd_win == NULL)
8451 {
8452 win_alloc_aucmd_win();
8453 if (aucmd_win == NULL)
8454 win = curwin;
8455 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008456 if (win == NULL && aucmd_win_used)
8457 /* Strange recursive autocommand, fall back to using the current
8458 * window. Expect a few side effects... */
8459 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008460
8461 aco->save_curwin = curwin;
8462 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008463 if (win != NULL)
8464 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008465 /* There is a window for "buf" in the current tab page, make it the
8466 * curwin. This is preferred, it has the least side effects (esp. if
8467 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008468 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008470 }
8471 else
8472 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008473 /* There is no window for "buf", use "aucmd_win". To minimize the side
8474 * effects, insert it in a the current tab page.
8475 * Anything related to a window (e.g., setting folds) may have
8476 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008477 aco->use_aucmd_win = TRUE;
8478 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008479 aucmd_win->w_buffer = buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008481 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008482 vim_free(aucmd_win->w_localdir);
8483 aucmd_win->w_localdir = NULL;
8484
8485 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8486 * win_enter_ext(). */
8487 aucmd_win->w_localdir = NULL;
8488 aco->globaldir = globaldir;
8489 globaldir = NULL;
8490
Bram Moolenaar071d4272004-06-13 20:20:40 +00008491
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008492#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008493 /* Split the current window, put the aucmd_win in the upper half.
8494 * We don't want the BufEnter or WinEnter autocommands. */
8495 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008496 make_snapshot(SNAP_AUCMD_IDX);
8497 save_ea = p_ea;
8498 p_ea = FALSE;
8499 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8500 (void)win_comp_pos(); /* recompute window positions */
8501 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008502 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008503#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008504 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008505 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008506 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008507 aco->new_curwin = curwin;
8508 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008509}
8510
8511/*
8512 * Cleanup after executing autocommands for a (hidden) buffer.
8513 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008514 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008515 */
8516 void
8517aucmd_restbuf(aco)
8518 aco_save_T *aco; /* structure holding saved values */
8519{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008520#ifdef FEAT_WINDOWS
8521 int dummy;
8522#endif
8523
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008524 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008525 {
8526 --curbuf->b_nwindows;
8527#ifdef FEAT_WINDOWS
8528 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008529 * page. Do not trigger autocommands here. */
8530 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008531 if (curwin != aucmd_win)
8532 {
8533 tabpage_T *tp;
8534 win_T *wp;
8535
8536 FOR_ALL_TAB_WINDOWS(tp, wp)
8537 {
8538 if (wp == aucmd_win)
8539 {
8540 if (tp != curtab)
8541 goto_tabpage_tp(tp);
8542 win_goto(aucmd_win);
8543 break;
8544 }
8545 }
8546 }
8547
8548 /* Remove the window and frame from the tree of frames. */
8549 (void)winframe_remove(curwin, &dummy, NULL);
8550 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008551 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008552 last_status(FALSE); /* may need to remove last status line */
8553 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8554 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008555 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008556
8557 if (win_valid(aco->save_curwin))
8558 curwin = aco->save_curwin;
8559 else
8560 /* Hmm, original window disappeared. Just use the first one. */
8561 curwin = firstwin;
8562# ifdef FEAT_EVAL
8563 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
8564# endif
8565#else
8566 curwin = aco->save_curwin;
8567#endif
8568 curbuf = curwin->w_buffer;
8569
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008570 vim_free(globaldir);
8571 globaldir = aco->globaldir;
8572
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008573 /* the buffer contents may have changed */
8574 check_cursor();
8575 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8576 {
8577 curwin->w_topline = curbuf->b_ml.ml_line_count;
8578#ifdef FEAT_DIFF
8579 curwin->w_topfill = 0;
8580#endif
8581 }
8582#if defined(FEAT_GUI)
8583 /* Hide the scrollbars from the aucmd_win and update. */
8584 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8585 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8586 gui_may_update_scrollbars();
8587#endif
8588 }
8589 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590 {
8591 /* restore curwin */
8592#ifdef FEAT_WINDOWS
8593 if (win_valid(aco->save_curwin))
8594#endif
8595 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008596 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008597 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008598 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008599 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008600 && curbuf != aco->new_curbuf
8601 && buf_valid(aco->new_curbuf)
8602 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008603 {
8604 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008605 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008606 curwin->w_buffer = curbuf;
8607 ++curbuf->b_nwindows;
8608 }
8609
8610 curwin = aco->save_curwin;
8611 curbuf = curwin->w_buffer;
8612 }
8613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008614}
8615
8616static int autocmd_nested = FALSE;
8617
8618/*
8619 * Execute autocommands for "event" and file name "fname".
8620 * Return TRUE if some commands were executed.
8621 */
8622 int
8623apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008624 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008625 char_u *fname; /* NULL or empty means use actual file name */
8626 char_u *fname_io; /* fname to use for <afile> on cmdline */
8627 int force; /* when TRUE, ignore autocmd_busy */
8628 buf_T *buf; /* buffer for <abuf> */
8629{
8630 return apply_autocmds_group(event, fname, fname_io, force,
8631 AUGROUP_ALL, buf, NULL);
8632}
8633
8634/*
8635 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8636 * setting v:filearg.
8637 */
8638 static int
8639apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008640 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008641 char_u *fname;
8642 char_u *fname_io;
8643 int force;
8644 buf_T *buf;
8645 exarg_T *eap;
8646{
8647 return apply_autocmds_group(event, fname, fname_io, force,
8648 AUGROUP_ALL, buf, eap);
8649}
8650
8651/*
8652 * Like apply_autocmds(), but handles the caller's retval. If the script
8653 * processing is being aborted or if retval is FAIL when inside a try
8654 * conditional, no autocommands are executed. If otherwise the autocommands
8655 * cause the script to be aborted, retval is set to FAIL.
8656 */
8657 int
8658apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008659 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008660 char_u *fname; /* NULL or empty means use actual file name */
8661 char_u *fname_io; /* fname to use for <afile> on cmdline */
8662 int force; /* when TRUE, ignore autocmd_busy */
8663 buf_T *buf; /* buffer for <abuf> */
8664 int *retval; /* pointer to caller's retval */
8665{
8666 int did_cmd;
8667
Bram Moolenaar1e015462005-09-25 22:16:38 +00008668#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008669 if (should_abort(*retval))
8670 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00008671#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008672
8673 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8674 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008675 if (did_cmd
8676#ifdef FEAT_EVAL
8677 && aborting()
8678#endif
8679 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008680 *retval = FAIL;
8681 return did_cmd;
8682}
8683
Bram Moolenaard35f9712005-12-18 22:02:33 +00008684/*
8685 * Return TRUE when there is a CursorHold autocommand defined.
8686 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008687 int
8688has_cursorhold()
8689{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008690 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
8691 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008692}
Bram Moolenaard35f9712005-12-18 22:02:33 +00008693
8694/*
8695 * Return TRUE if the CursorHold event can be triggered.
8696 */
8697 int
8698trigger_cursorhold()
8699{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008700 int state;
8701
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00008702 if (!did_cursorhold && has_cursorhold() && !Recording
8703#ifdef FEAT_INS_EXPAND
8704 && !ins_compl_active()
8705#endif
8706 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00008707 {
8708 state = get_real_state();
8709 if (state == NORMAL_BUSY || (state & INSERT) != 0)
8710 return TRUE;
8711 }
8712 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00008713}
Bram Moolenaar754b5602006-02-09 23:53:20 +00008714
8715/*
8716 * Return TRUE when there is a CursorMoved autocommand defined.
8717 */
8718 int
8719has_cursormoved()
8720{
8721 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
8722}
8723
8724/*
8725 * Return TRUE when there is a CursorMovedI autocommand defined.
8726 */
8727 int
8728has_cursormovedI()
8729{
8730 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
8731}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008732
8733 static int
8734apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008735 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008736 char_u *fname; /* NULL or empty means use actual file name */
8737 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
8738 use fname */
8739 int force; /* when TRUE, ignore autocmd_busy */
8740 int group; /* group ID, or AUGROUP_ALL */
8741 buf_T *buf; /* buffer for <abuf> */
8742 exarg_T *eap; /* command arguments */
8743{
8744 char_u *sfname = NULL; /* short file name */
8745 char_u *tail;
8746 int save_changed;
8747 buf_T *old_curbuf;
8748 int retval = FALSE;
8749 char_u *save_sourcing_name;
8750 linenr_T save_sourcing_lnum;
8751 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00008752 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008753 int save_autocmd_bufnr;
8754 char_u *save_autocmd_match;
8755 int save_autocmd_busy;
8756 int save_autocmd_nested;
8757 static int nesting = 0;
8758 AutoPatCmd patcmd;
8759 AutoPat *ap;
8760#ifdef FEAT_EVAL
8761 scid_T save_current_SID;
8762 void *save_funccalp;
8763 char_u *save_cmdarg;
8764 long save_cmdbang;
8765#endif
8766 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00008767#ifdef FEAT_PROFILE
8768 proftime_T wait_time;
8769#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008770
8771 /*
8772 * Quickly return if there are no autocommands for this event or
8773 * autocommands are blocked.
8774 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00008775 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008776 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008777
8778 /*
8779 * When autocommands are busy, new autocommands are only executed when
8780 * explicitly enabled with the "nested" flag.
8781 */
8782 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008783 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008784
8785#ifdef FEAT_EVAL
8786 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00008787 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00008788 * occurred or an exception was thrown but not caught.
8789 */
8790 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008791 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792#endif
8793
8794 /*
8795 * FileChangedShell never nests, because it can create an endless loop.
8796 */
Bram Moolenaar56718732006-03-15 22:53:57 +00008797 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
8798 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008799 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008800
8801 /*
8802 * Ignore events in 'eventignore'.
8803 */
8804 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008805 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008806
8807 /*
8808 * Allow nesting of autocommands, but restrict the depth, because it's
8809 * possible to create an endless loop.
8810 */
8811 if (nesting == 10)
8812 {
8813 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008814 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 }
8816
8817 /*
8818 * Check if these autocommands are disabled. Used when doing ":all" or
8819 * ":ball".
8820 */
8821 if ( (autocmd_no_enter
8822 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
8823 || (autocmd_no_leave
8824 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008825 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008826
8827 /*
8828 * Save the autocmd_* variables and info about the current buffer.
8829 */
8830 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00008831 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832 save_autocmd_bufnr = autocmd_bufnr;
8833 save_autocmd_match = autocmd_match;
8834 save_autocmd_busy = autocmd_busy;
8835 save_autocmd_nested = autocmd_nested;
8836 save_changed = curbuf->b_changed;
8837 old_curbuf = curbuf;
8838
8839 /*
8840 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00008841 * Make a copy to avoid that changing a buffer name or directory makes it
8842 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008843 */
8844 if (fname_io == NULL)
8845 {
8846 if (fname != NULL && *fname != NUL)
8847 autocmd_fname = fname;
8848 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00008849 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008850 else
8851 autocmd_fname = NULL;
8852 }
8853 else
8854 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00008855 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00008856 autocmd_fname = vim_strsave(autocmd_fname);
8857 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008858
8859 /*
8860 * Set the buffer number to be used for <abuf>.
8861 */
8862 if (buf == NULL)
8863 autocmd_bufnr = 0;
8864 else
8865 autocmd_bufnr = buf->b_fnum;
8866
8867 /*
8868 * When the file name is NULL or empty, use the file name of buffer "buf".
8869 * Always use the full path of the file name to match with, in case
8870 * "allow_dirs" is set.
8871 */
8872 if (fname == NULL || *fname == NUL)
8873 {
8874 if (buf == NULL)
8875 fname = NULL;
8876 else
8877 {
8878#ifdef FEAT_SYN_HL
8879 if (event == EVENT_SYNTAX)
8880 fname = buf->b_p_syn;
8881 else
8882#endif
8883 if (event == EVENT_FILETYPE)
8884 fname = buf->b_p_ft;
8885 else
8886 {
8887 if (buf->b_sfname != NULL)
8888 sfname = vim_strsave(buf->b_sfname);
8889 fname = buf->b_ffname;
8890 }
8891 }
8892 if (fname == NULL)
8893 fname = (char_u *)"";
8894 fname = vim_strsave(fname); /* make a copy, so we can change it */
8895 }
8896 else
8897 {
8898 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00008899 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
8900 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00008901 if (event == EVENT_FILETYPE
8902 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00008903 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00008904 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00008905 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00008906 || event == EVENT_QUICKFIXCMDPRE
8907 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 fname = vim_strsave(fname);
8909 else
8910 fname = FullName_save(fname, FALSE);
8911 }
8912 if (fname == NULL) /* out of memory */
8913 {
8914 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008915 retval = FALSE;
8916 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008917 }
8918
8919#ifdef BACKSLASH_IN_FILENAME
8920 /*
8921 * Replace all backslashes with forward slashes. This makes the
8922 * autocommand patterns portable between Unix and MS-DOS.
8923 */
8924 if (sfname != NULL)
8925 forward_slash(sfname);
8926 forward_slash(fname);
8927#endif
8928
8929#ifdef VMS
8930 /* remove version for correct match */
8931 if (sfname != NULL)
8932 vms_remove_version(sfname);
8933 vms_remove_version(fname);
8934#endif
8935
8936 /*
8937 * Set the name to be used for <amatch>.
8938 */
8939 autocmd_match = fname;
8940
8941
8942 /* Don't redraw while doing auto commands. */
8943 ++RedrawingDisabled;
8944 save_sourcing_name = sourcing_name;
8945 sourcing_name = NULL; /* don't free this one */
8946 save_sourcing_lnum = sourcing_lnum;
8947 sourcing_lnum = 0; /* no line number here */
8948
8949#ifdef FEAT_EVAL
8950 save_current_SID = current_SID;
8951
Bram Moolenaar05159a02005-02-26 23:04:13 +00008952# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00008953 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00008954 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
8955# endif
8956
Bram Moolenaar071d4272004-06-13 20:20:40 +00008957 /* Don't use local function variables, if called from a function */
8958 save_funccalp = save_funccal();
8959#endif
8960
8961 /*
8962 * When starting to execute autocommands, save the search patterns.
8963 */
8964 if (!autocmd_busy)
8965 {
8966 save_search_patterns();
8967 saveRedobuff();
8968 did_filetype = keep_filetype;
8969 }
8970
8971 /*
8972 * Note that we are applying autocmds. Some commands need to know.
8973 */
8974 autocmd_busy = TRUE;
8975 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
8976 ++nesting; /* see matching decrement below */
8977
8978 /* Remember that FileType was triggered. Used for did_filetype(). */
8979 if (event == EVENT_FILETYPE)
8980 did_filetype = TRUE;
8981
8982 tail = gettail(fname);
8983
8984 /* Find first autocommand that matches */
8985 patcmd.curpat = first_autopat[(int)event];
8986 patcmd.nextcmd = NULL;
8987 patcmd.group = group;
8988 patcmd.fname = fname;
8989 patcmd.sfname = sfname;
8990 patcmd.tail = tail;
8991 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008992 patcmd.arg_bufnr = autocmd_bufnr;
8993 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994 auto_next_pat(&patcmd, FALSE);
8995
8996 /* found one, start executing the autocommands */
8997 if (patcmd.curpat != NULL)
8998 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008999 /* add to active_apc_list */
9000 patcmd.next = active_apc_list;
9001 active_apc_list = &patcmd;
9002
Bram Moolenaar071d4272004-06-13 20:20:40 +00009003#ifdef FEAT_EVAL
9004 /* set v:cmdarg (only when there is a matching pattern) */
9005 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9006 if (eap != NULL)
9007 {
9008 save_cmdarg = set_cmdarg(eap, NULL);
9009 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9010 }
9011 else
9012 save_cmdarg = NULL; /* avoid gcc warning */
9013#endif
9014 retval = TRUE;
9015 /* mark the last pattern, to avoid an endless loop when more patterns
9016 * are added when executing autocommands */
9017 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9018 ap->last = FALSE;
9019 ap->last = TRUE;
9020 check_lnums(TRUE); /* make sure cursor and topline are valid */
9021 do_cmdline(NULL, getnextac, (void *)&patcmd,
9022 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9023#ifdef FEAT_EVAL
9024 if (eap != NULL)
9025 {
9026 (void)set_cmdarg(NULL, save_cmdarg);
9027 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9028 }
9029#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009030 /* delete from active_apc_list */
9031 if (active_apc_list == &patcmd) /* just in case */
9032 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009033 }
9034
9035 --RedrawingDisabled;
9036 autocmd_busy = save_autocmd_busy;
9037 filechangeshell_busy = FALSE;
9038 autocmd_nested = save_autocmd_nested;
9039 vim_free(sourcing_name);
9040 sourcing_name = save_sourcing_name;
9041 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009042 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009043 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009044 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009045 autocmd_bufnr = save_autocmd_bufnr;
9046 autocmd_match = save_autocmd_match;
9047#ifdef FEAT_EVAL
9048 current_SID = save_current_SID;
9049 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009050# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009051 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009052 prof_child_exit(&wait_time);
9053# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009054#endif
9055 vim_free(fname);
9056 vim_free(sfname);
9057 --nesting; /* see matching increment above */
9058
9059 /*
9060 * When stopping to execute autocommands, restore the search patterns and
9061 * the redo buffer.
9062 */
9063 if (!autocmd_busy)
9064 {
9065 restore_search_patterns();
9066 restoreRedobuff();
9067 did_filetype = FALSE;
9068 }
9069
9070 /*
9071 * Some events don't set or reset the Changed flag.
9072 * Check if still in the same buffer!
9073 */
9074 if (curbuf == old_curbuf
9075 && (event == EVENT_BUFREADPOST
9076 || event == EVENT_BUFWRITEPOST
9077 || event == EVENT_FILEAPPENDPOST
9078 || event == EVENT_VIMLEAVE
9079 || event == EVENT_VIMLEAVEPRE))
9080 {
9081#ifdef FEAT_TITLE
9082 if (curbuf->b_changed != save_changed)
9083 need_maketitle = TRUE;
9084#endif
9085 curbuf->b_changed = save_changed;
9086 }
9087
9088 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009089
9090BYPASS_AU:
9091 /* When wiping out a buffer make sure all its buffer-local autocommands
9092 * are deleted. */
9093 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9094 aubuflocal_remove(buf);
9095
Bram Moolenaar071d4272004-06-13 20:20:40 +00009096 return retval;
9097}
9098
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009099# ifdef FEAT_EVAL
9100static char_u *old_termresponse = NULL;
9101# endif
9102
9103/*
9104 * Block triggering autocommands until unblock_autocmd() is called.
9105 * Can be used recursively, so long as it's symmetric.
9106 */
9107 void
9108block_autocmds()
9109{
9110# ifdef FEAT_EVAL
9111 /* Remember the value of v:termresponse. */
9112 if (autocmd_blocked == 0)
9113 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9114# endif
9115 ++autocmd_blocked;
9116}
9117
9118 void
9119unblock_autocmds()
9120{
9121 --autocmd_blocked;
9122
9123# ifdef FEAT_EVAL
9124 /* When v:termresponse was set while autocommands were blocked, trigger
9125 * the autocommands now. Esp. useful when executing a shell command
9126 * during startup (vimdiff). */
9127 if (autocmd_blocked == 0
9128 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9129 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9130# endif
9131}
9132
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133/*
9134 * Find next autocommand pattern that matches.
9135 */
9136 static void
9137auto_next_pat(apc, stop_at_last)
9138 AutoPatCmd *apc;
9139 int stop_at_last; /* stop when 'last' flag is set */
9140{
9141 AutoPat *ap;
9142 AutoCmd *cp;
9143 char_u *name;
9144 char *s;
9145
9146 vim_free(sourcing_name);
9147 sourcing_name = NULL;
9148
9149 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9150 {
9151 apc->curpat = NULL;
9152
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009153 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009154 * the group matches. For buffer-local autocommands only check the
9155 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156 if (ap->pat != NULL && ap->cmds != NULL
9157 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9158 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009159 /* execution-condition */
9160 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009161 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9162 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009163 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009164 {
9165 name = event_nr2name(apc->event);
9166 s = _("%s Auto commands for \"%s\"");
9167 sourcing_name = alloc((unsigned)(STRLEN(s)
9168 + STRLEN(name) + ap->patlen + 1));
9169 if (sourcing_name != NULL)
9170 {
9171 sprintf((char *)sourcing_name, s,
9172 (char *)name, (char *)ap->pat);
9173 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009174 {
9175 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009176 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009177 verbose_leave();
9178 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009179 }
9180
9181 apc->curpat = ap;
9182 apc->nextcmd = ap->cmds;
9183 /* mark last command */
9184 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9185 cp->last = FALSE;
9186 cp->last = TRUE;
9187 }
9188 line_breakcheck();
9189 if (apc->curpat != NULL) /* found a match */
9190 break;
9191 }
9192 if (stop_at_last && ap->last)
9193 break;
9194 }
9195}
9196
9197/*
9198 * Get next autocommand command.
9199 * Called by do_cmdline() to get the next line for ":if".
9200 * Returns allocated string, or NULL for end of autocommands.
9201 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009202 static char_u *
9203getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009204 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009206 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009207{
9208 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9209 char_u *retval;
9210 AutoCmd *ac;
9211
9212 /* Can be called again after returning the last line. */
9213 if (acp->curpat == NULL)
9214 return NULL;
9215
9216 /* repeat until we find an autocommand to execute */
9217 for (;;)
9218 {
9219 /* skip removed commands */
9220 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9221 if (acp->nextcmd->last)
9222 acp->nextcmd = NULL;
9223 else
9224 acp->nextcmd = acp->nextcmd->next;
9225
9226 if (acp->nextcmd != NULL)
9227 break;
9228
9229 /* at end of commands, find next pattern that matches */
9230 if (acp->curpat->last)
9231 acp->curpat = NULL;
9232 else
9233 acp->curpat = acp->curpat->next;
9234 if (acp->curpat != NULL)
9235 auto_next_pat(acp, TRUE);
9236 if (acp->curpat == NULL)
9237 return NULL;
9238 }
9239
9240 ac = acp->nextcmd;
9241
9242 if (p_verbose >= 9)
9243 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009244 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009245 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009246 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009247 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009248 }
9249 retval = vim_strsave(ac->cmd);
9250 autocmd_nested = ac->nested;
9251#ifdef FEAT_EVAL
9252 current_SID = ac->scriptID;
9253#endif
9254 if (ac->last)
9255 acp->nextcmd = NULL;
9256 else
9257 acp->nextcmd = ac->next;
9258 return retval;
9259}
9260
9261/*
9262 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009263 * To account for buffer-local autocommands, function needs to know
9264 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009265 */
9266 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009267has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009268 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009270 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009271{
9272 AutoPat *ap;
9273 char_u *fname;
9274 char_u *tail = gettail(sfname);
9275 int retval = FALSE;
9276
9277 fname = FullName_save(sfname, FALSE);
9278 if (fname == NULL)
9279 return FALSE;
9280
9281#ifdef BACKSLASH_IN_FILENAME
9282 /*
9283 * Replace all backslashes with forward slashes. This makes the
9284 * autocommand patterns portable between Unix and MS-DOS.
9285 */
9286 sfname = vim_strsave(sfname);
9287 if (sfname != NULL)
9288 forward_slash(sfname);
9289 forward_slash(fname);
9290#endif
9291
9292 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9293 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009294 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009295 ? match_file_pat(NULL, ap->reg_prog,
9296 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009297 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009298 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009299 {
9300 retval = TRUE;
9301 break;
9302 }
9303
9304 vim_free(fname);
9305#ifdef BACKSLASH_IN_FILENAME
9306 vim_free(sfname);
9307#endif
9308
9309 return retval;
9310}
9311
9312#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9313/*
9314 * Function given to ExpandGeneric() to obtain the list of autocommand group
9315 * names.
9316 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009317 char_u *
9318get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009319 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009320 int idx;
9321{
9322 if (idx == augroups.ga_len) /* add "END" add the end */
9323 return (char_u *)"END";
9324 if (idx >= augroups.ga_len) /* end of list */
9325 return NULL;
9326 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9327 return (char_u *)"";
9328 return AUGROUP_NAME(idx); /* return a name */
9329}
9330
9331static int include_groups = FALSE;
9332
9333 char_u *
9334set_context_in_autocmd(xp, arg, doautocmd)
9335 expand_T *xp;
9336 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009337 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009338{
9339 char_u *p;
9340 int group;
9341
9342 /* check for a group name, skip it if present */
9343 include_groups = FALSE;
9344 p = arg;
9345 group = au_get_grouparg(&arg);
9346 if (group == AUGROUP_ERROR)
9347 return NULL;
9348 /* If there only is a group name that's what we expand. */
9349 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9350 {
9351 arg = p;
9352 group = AUGROUP_ALL;
9353 }
9354
9355 /* skip over event name */
9356 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9357 if (*p == ',')
9358 arg = p + 1;
9359 if (*p == NUL)
9360 {
9361 if (group == AUGROUP_ALL)
9362 include_groups = TRUE;
9363 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9364 xp->xp_pattern = arg;
9365 return NULL;
9366 }
9367
9368 /* skip over pattern */
9369 arg = skipwhite(p);
9370 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9371 arg++;
9372 if (*arg)
9373 return arg; /* expand (next) command */
9374
9375 if (doautocmd)
9376 xp->xp_context = EXPAND_FILES; /* expand file names */
9377 else
9378 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9379 return NULL;
9380}
9381
9382/*
9383 * Function given to ExpandGeneric() to obtain the list of event names.
9384 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009385 char_u *
9386get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009387 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009388 int idx;
9389{
9390 if (idx < augroups.ga_len) /* First list group names, if wanted */
9391 {
9392 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9393 return (char_u *)""; /* skip deleted entries */
9394 return AUGROUP_NAME(idx); /* return a name */
9395 }
9396 return (char_u *)event_names[idx - augroups.ga_len].name;
9397}
9398
9399#endif /* FEAT_CMDL_COMPL */
9400
9401/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009402 * Return TRUE if autocmd is supported.
9403 */
9404 int
9405autocmd_supported(name)
9406 char_u *name;
9407{
9408 char_u *p;
9409
9410 return (event_name2nr(name, &p) != NUM_EVENTS);
9411}
9412
9413/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009414 * Return TRUE if an autocommand is defined for a group, event and
9415 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9416 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9417 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9418 * Used for:
9419 * exists("#Group") or
9420 * exists("#Group#Event") or
9421 * exists("#Group#Event#pat") or
9422 * exists("#Event") or
9423 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009424 */
9425 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009426au_exists(arg)
9427 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009428{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009429 char_u *arg_save;
9430 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009431 char_u *event_name;
9432 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009433 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009435 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009436 int group;
9437 int retval = FALSE;
9438
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009439 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009440 arg_save = vim_strsave(arg);
9441 if (arg_save == NULL)
9442 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009443 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009444 if (p != NULL)
9445 *p++ = NUL;
9446
9447 /* First, look for an autocmd group name */
9448 group = au_find_group(arg_save);
9449 if (group == AUGROUP_ERROR)
9450 {
9451 /* Didn't match a group name, assume the first argument is an event. */
9452 group = AUGROUP_ALL;
9453 event_name = arg_save;
9454 }
9455 else
9456 {
9457 if (p == NULL)
9458 {
9459 /* "Group": group name is present and it's recognized */
9460 retval = TRUE;
9461 goto theend;
9462 }
9463
9464 /* Must be "Group#Event" or "Group#Event#pat". */
9465 event_name = p;
9466 p = vim_strchr(event_name, '#');
9467 if (p != NULL)
9468 *p++ = NUL; /* "Group#Event#pat" */
9469 }
9470
9471 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009472
9473 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009474 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009475
9476 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009477 if (event == NUM_EVENTS)
9478 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009479
9480 /* Find the first autocommand for this event.
9481 * If there isn't any, return FALSE;
9482 * If there is one and no pattern given, return TRUE; */
9483 ap = first_autopat[(int)event];
9484 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009485 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009486 if (pattern == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009487 {
9488 retval = TRUE;
9489 goto theend;
9490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009491
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009492 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9493 /* for pattern "<buffer=N>, fnamecmp() will work fine */
9494 if (STRICMP(pattern, "<buffer>") == 0)
9495 buflocal_buf = curbuf;
9496
Bram Moolenaar071d4272004-06-13 20:20:40 +00009497 /* Check if there is an autocommand with the given pattern. */
9498 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009499 /* only use a pattern when it has not been removed and has commands. */
9500 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009501 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009502 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009503 && (buflocal_buf == NULL
9504 ? fnamecmp(ap->pat, pattern) == 0
9505 : ap->buflocal_nr == buflocal_buf->b_fnum))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009506 {
9507 retval = TRUE;
9508 break;
9509 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009510
Bram Moolenaar195d6352005-12-19 22:08:24 +00009511theend:
9512 vim_free(arg_save);
9513 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009514}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009515
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009516#else /* FEAT_AUTOCMD */
9517
9518/*
9519 * Prepare for executing commands for (hidden) buffer "buf".
9520 * This is the non-autocommand version, it simply saves "curbuf" and sets
9521 * "curbuf" and "curwin" to match "buf".
9522 */
9523 void
9524aucmd_prepbuf(aco, buf)
9525 aco_save_T *aco; /* structure to save values in */
9526 buf_T *buf; /* new curbuf */
9527{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009528 aco->save_curbuf = curbuf;
9529 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009530 curbuf = buf;
9531 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009532 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009533}
9534
9535/*
9536 * Restore after executing commands for a (hidden) buffer.
9537 * This is the non-autocommand version.
9538 */
9539 void
9540aucmd_restbuf(aco)
9541 aco_save_T *aco; /* structure holding saved values */
9542{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009543 --curbuf->b_nwindows;
9544 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009545 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009546 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009547}
9548
Bram Moolenaar071d4272004-06-13 20:20:40 +00009549#endif /* FEAT_AUTOCMD */
9550
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009551
Bram Moolenaar071d4272004-06-13 20:20:40 +00009552#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9553/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009554 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9555 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9556 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009557 * Used for autocommands and 'wildignore'.
9558 * Returns TRUE if there is a match, FALSE otherwise.
9559 */
9560 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009561match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009562 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009563 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009564 char_u *fname; /* full path of file name */
9565 char_u *sfname; /* short file name or NULL */
9566 char_u *tail; /* tail of path */
9567 int allow_dirs; /* allow matching with dir */
9568{
9569 regmatch_T regmatch;
9570 int result = FALSE;
9571#ifdef FEAT_OSFILETYPE
9572 int no_pattern = FALSE; /* TRUE if check is filetype only */
9573 char_u *type_start;
9574 char_u c;
9575 int match = FALSE;
9576#endif
9577
9578#ifdef CASE_INSENSITIVE_FILENAME
9579 regmatch.rm_ic = TRUE; /* Always ignore case */
9580#else
9581 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9582#endif
9583#ifdef FEAT_OSFILETYPE
9584 if (*pattern == '<')
9585 {
9586 /* There is a filetype condition specified with this pattern.
9587 * Check the filetype matches first. If not, don't bother with the
9588 * pattern (set regprog to NULL).
9589 * Always use magic for the regexp.
9590 */
9591
9592 for (type_start = pattern + 1; (c = *pattern); pattern++)
9593 {
9594 if ((c == ';' || c == '>') && match == FALSE)
9595 {
9596 *pattern = NUL; /* Terminate the string */
9597 match = mch_check_filetype(fname, type_start);
9598 *pattern = c; /* Restore the terminator */
9599 type_start = pattern + 1;
9600 }
9601 if (c == '>')
9602 break;
9603 }
9604
9605 /* (c should never be NUL, but check anyway) */
9606 if (match == FALSE || c == NUL)
9607 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9608 else if (*pattern == NUL)
9609 {
9610 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9611 no_pattern = TRUE; /* Always matches - don't check pat. */
9612 }
9613 else
9614 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9615 }
9616 else
9617#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009618 {
9619 if (prog != NULL)
9620 regmatch.regprog = prog;
9621 else
9622 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009624
9625 /*
9626 * Try for a match with the pattern with:
9627 * 1. the full file name, when the pattern has a '/'.
9628 * 2. the short file name, when the pattern has a '/'.
9629 * 3. the tail of the file name, when the pattern has no '/'.
9630 */
9631 if (
9632#ifdef FEAT_OSFILETYPE
9633 /* If the check is for a filetype only and we don't care
9634 * about the path then skip all the regexp stuff.
9635 */
9636 no_pattern ||
9637#endif
9638 (regmatch.regprog != NULL
9639 && ((allow_dirs
9640 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9641 || (sfname != NULL
9642 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9643 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9644 result = TRUE;
9645
Bram Moolenaar748bf032005-02-02 23:04:36 +00009646 if (prog == NULL)
9647 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009648 return result;
9649}
9650#endif
9651
9652#if defined(FEAT_WILDIGN) || defined(PROTO)
9653/*
9654 * Return TRUE if a file matches with a pattern in "list".
9655 * "list" is a comma-separated list of patterns, like 'wildignore'.
9656 * "sfname" is the short file name or NULL, "ffname" the long file name.
9657 */
9658 int
9659match_file_list(list, sfname, ffname)
9660 char_u *list;
9661 char_u *sfname;
9662 char_u *ffname;
9663{
9664 char_u buf[100];
9665 char_u *tail;
9666 char_u *regpat;
9667 char allow_dirs;
9668 int match;
9669 char_u *p;
9670
9671 tail = gettail(sfname);
9672
9673 /* try all patterns in 'wildignore' */
9674 p = list;
9675 while (*p)
9676 {
9677 copy_option_part(&p, buf, 100, ",");
9678 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9679 if (regpat == NULL)
9680 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00009681 match = match_file_pat(regpat, NULL, ffname, sfname,
9682 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009683 vim_free(regpat);
9684 if (match)
9685 return TRUE;
9686 }
9687 return FALSE;
9688}
9689#endif
9690
9691/*
9692 * Convert the given pattern "pat" which has shell style wildcards in it, into
9693 * a regular expression, and return the result in allocated memory. If there
9694 * is a directory path separator to be matched, then TRUE is put in
9695 * allow_dirs, otherwise FALSE is put there -- webb.
9696 * Handle backslashes before special characters, like "\*" and "\ ".
9697 *
9698 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
9699 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
9700 *
9701 * Returns NULL when out of memory.
9702 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009703 char_u *
9704file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
9705 char_u *pat;
9706 char_u *pat_end; /* first char after pattern or NULL */
9707 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +00009708 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009709{
9710 int size;
9711 char_u *endp;
9712 char_u *reg_pat;
9713 char_u *p;
9714 int i;
9715 int nested = 0;
9716 int add_dollar = TRUE;
9717#ifdef FEAT_OSFILETYPE
9718 int check_length = 0;
9719#endif
9720
9721 if (allow_dirs != NULL)
9722 *allow_dirs = FALSE;
9723 if (pat_end == NULL)
9724 pat_end = pat + STRLEN(pat);
9725
9726#ifdef FEAT_OSFILETYPE
9727 /* Find out how much of the string is the filetype check */
9728 if (*pat == '<')
9729 {
9730 /* Count chars until the next '>' */
9731 for (p = pat + 1; p < pat_end && *p != '>'; p++)
9732 ;
9733 if (p < pat_end)
9734 {
9735 /* Pattern is of the form <.*>.* */
9736 check_length = p - pat + 1;
9737 if (p + 1 >= pat_end)
9738 {
9739 /* The 'pattern' is a filetype check ONLY */
9740 reg_pat = (char_u *)alloc(check_length + 1);
9741 if (reg_pat != NULL)
9742 {
9743 mch_memmove(reg_pat, pat, (size_t)check_length);
9744 reg_pat[check_length] = NUL;
9745 }
9746 return reg_pat;
9747 }
9748 }
9749 /* else: there was no closing '>' - assume it was a normal pattern */
9750
9751 }
9752 pat += check_length;
9753 size = 2 + check_length;
9754#else
9755 size = 2; /* '^' at start, '$' at end */
9756#endif
9757
9758 for (p = pat; p < pat_end; p++)
9759 {
9760 switch (*p)
9761 {
9762 case '*':
9763 case '.':
9764 case ',':
9765 case '{':
9766 case '}':
9767 case '~':
9768 size += 2; /* extra backslash */
9769 break;
9770#ifdef BACKSLASH_IN_FILENAME
9771 case '\\':
9772 case '/':
9773 size += 4; /* could become "[\/]" */
9774 break;
9775#endif
9776 default:
9777 size++;
9778# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009779 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009780 {
9781 ++p;
9782 ++size;
9783 }
9784# endif
9785 break;
9786 }
9787 }
9788 reg_pat = alloc(size + 1);
9789 if (reg_pat == NULL)
9790 return NULL;
9791
9792#ifdef FEAT_OSFILETYPE
9793 /* Copy the type check in to the start. */
9794 if (check_length)
9795 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
9796 i = check_length;
9797#else
9798 i = 0;
9799#endif
9800
9801 if (pat[0] == '*')
9802 while (pat[0] == '*' && pat < pat_end - 1)
9803 pat++;
9804 else
9805 reg_pat[i++] = '^';
9806 endp = pat_end - 1;
9807 if (*endp == '*')
9808 {
9809 while (endp - pat > 0 && *endp == '*')
9810 endp--;
9811 add_dollar = FALSE;
9812 }
9813 for (p = pat; *p && nested >= 0 && p <= endp; p++)
9814 {
9815 switch (*p)
9816 {
9817 case '*':
9818 reg_pat[i++] = '.';
9819 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +00009820 while (p[1] == '*') /* "**" matches like "*" */
9821 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009822 break;
9823 case '.':
9824#ifdef RISCOS
9825 if (allow_dirs != NULL)
9826 *allow_dirs = TRUE;
9827 /* FALLTHROUGH */
9828#endif
9829 case '~':
9830 reg_pat[i++] = '\\';
9831 reg_pat[i++] = *p;
9832 break;
9833 case '?':
9834#ifdef RISCOS
9835 case '#':
9836#endif
9837 reg_pat[i++] = '.';
9838 break;
9839 case '\\':
9840 if (p[1] == NUL)
9841 break;
9842#ifdef BACKSLASH_IN_FILENAME
9843 if (!no_bslash)
9844 {
9845 /* translate:
9846 * "\x" to "\\x" e.g., "dir\file"
9847 * "\*" to "\\.*" e.g., "dir\*.c"
9848 * "\?" to "\\." e.g., "dir\??.c"
9849 * "\+" to "\+" e.g., "fileX\+.c"
9850 */
9851 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
9852 && p[1] != '+')
9853 {
9854 reg_pat[i++] = '[';
9855 reg_pat[i++] = '\\';
9856 reg_pat[i++] = '/';
9857 reg_pat[i++] = ']';
9858 if (allow_dirs != NULL)
9859 *allow_dirs = TRUE;
9860 break;
9861 }
9862 }
9863#endif
9864 if (*++p == '?'
9865#ifdef BACKSLASH_IN_FILENAME
9866 && no_bslash
9867#endif
9868 )
9869 reg_pat[i++] = '?';
9870 else
9871 if (*p == ',')
9872 reg_pat[i++] = ',';
9873 else
9874 {
9875 if (allow_dirs != NULL && vim_ispathsep(*p)
9876#ifdef BACKSLASH_IN_FILENAME
9877 && (!no_bslash || *p != '\\')
9878#endif
9879 )
9880 *allow_dirs = TRUE;
9881 reg_pat[i++] = '\\';
9882 reg_pat[i++] = *p;
9883 }
9884 break;
9885#ifdef BACKSLASH_IN_FILENAME
9886 case '/':
9887 reg_pat[i++] = '[';
9888 reg_pat[i++] = '\\';
9889 reg_pat[i++] = '/';
9890 reg_pat[i++] = ']';
9891 if (allow_dirs != NULL)
9892 *allow_dirs = TRUE;
9893 break;
9894#endif
9895 case '{':
9896 reg_pat[i++] = '\\';
9897 reg_pat[i++] = '(';
9898 nested++;
9899 break;
9900 case '}':
9901 reg_pat[i++] = '\\';
9902 reg_pat[i++] = ')';
9903 --nested;
9904 break;
9905 case ',':
9906 if (nested)
9907 {
9908 reg_pat[i++] = '\\';
9909 reg_pat[i++] = '|';
9910 }
9911 else
9912 reg_pat[i++] = ',';
9913 break;
9914 default:
9915# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009916 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009917 reg_pat[i++] = *p++;
9918 else
9919# endif
9920 if (allow_dirs != NULL && vim_ispathsep(*p))
9921 *allow_dirs = TRUE;
9922 reg_pat[i++] = *p;
9923 break;
9924 }
9925 }
9926 if (add_dollar)
9927 reg_pat[i++] = '$';
9928 reg_pat[i] = NUL;
9929 if (nested != 0)
9930 {
9931 if (nested < 0)
9932 EMSG(_("E219: Missing {."));
9933 else
9934 EMSG(_("E220: Missing }."));
9935 vim_free(reg_pat);
9936 reg_pat = NULL;
9937 }
9938 return reg_pat;
9939}