blob: de123a09ce6c5e088f41782b98cc8293bd8e37a8 [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
24#ifdef HAVE_FCNTL_H
25# include <fcntl.h>
26#endif
27
28#ifdef __TANDEM
29# include <limits.h> /* for SSIZE_MAX */
30#endif
31
32#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
33# include <utime.h> /* for struct utimbuf */
34#endif
35
36#define BUFSIZE 8192 /* size of normal write buffer */
37#define SMBUFSIZE 256 /* size of emergency write buffer */
38
39#ifdef FEAT_CRYPT
40# define CRYPT_MAGIC "VimCrypt~01!" /* "01" is the version nr */
41# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
42#endif
43
44/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000045#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000046
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000047#if defined(sun) && defined(S_ISCHR)
48# define OPEN_CHR_FILES
49static int is_dev_fd_file(char_u *fname);
50#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#ifdef FEAT_MBYTE
52static char_u *next_fenc __ARGS((char_u **pp));
53# ifdef FEAT_EVAL
54static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
55# endif
56#endif
57#ifdef FEAT_VIMINFO
58static void check_marks_read __ARGS((void));
59#endif
60#ifdef FEAT_CRYPT
61static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, long *filesizep, int newfile));
62#endif
63#ifdef UNIX
64static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
65#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000066static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000067static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000068static void msg_add_eol __ARGS((void));
69static int check_mtime __ARGS((buf_T *buf, struct stat *s));
70static int time_differs __ARGS((long t1, long t2));
71#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000072static 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 +000073static int au_find_group __ARGS((char_u *name));
74
75# define AUGROUP_DEFAULT -1 /* default autocmd group */
76# define AUGROUP_ERROR -2 /* errornouse autocmd group */
77# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000078#endif
79
80#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
81# define HAS_BW_FLAGS
82# define FIO_LATIN1 0x01 /* convert Latin1 */
83# define FIO_UTF8 0x02 /* convert UTF-8 */
84# define FIO_UCS2 0x04 /* convert UCS-2 */
85# define FIO_UCS4 0x08 /* convert UCS-4 */
86# define FIO_UTF16 0x10 /* convert UTF-16 */
87# ifdef WIN3264
88# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
89# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
90# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
91# endif
92# ifdef MACOS_X
93# define FIO_MACROMAN 0x20 /* convert MacRoman */
94# endif
95# define FIO_ENDIAN_L 0x80 /* little endian */
96# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
97# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
98# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
99# define FIO_ALL -1 /* allow all formats */
100#endif
101
102/* When converting, a read() or write() may leave some bytes to be converted
103 * for the next call. The value is guessed... */
104#define CONV_RESTLEN 30
105
106/* We have to guess how much a sequence of bytes may expand when converting
107 * with iconv() to be able to allocate a buffer. */
108#define ICONV_MULT 8
109
110/*
111 * Structure to pass arguments from buf_write() to buf_write_bytes().
112 */
113struct bw_info
114{
115 int bw_fd; /* file descriptor */
116 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000117 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118#ifdef HAS_BW_FLAGS
119 int bw_flags; /* FIO_ flags */
120#endif
121#ifdef FEAT_MBYTE
122 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
123 int bw_restlen; /* nr of bytes in bw_rest[] */
124 int bw_first; /* first write call */
125 char_u *bw_conv_buf; /* buffer for writing converted chars */
126 int bw_conv_buflen; /* size of bw_conv_buf */
127 int bw_conv_error; /* set for conversion error */
128# ifdef USE_ICONV
129 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
130# endif
131#endif
132};
133
134static int buf_write_bytes __ARGS((struct bw_info *ip));
135
136#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000137static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
139static int same_encoding __ARGS((char_u *a, char_u *b));
140static int get_fio_flags __ARGS((char_u *ptr));
141static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
142static int make_bom __ARGS((char_u *buf, char_u *name));
143# ifdef WIN3264
144static int get_win_fio_flags __ARGS((char_u *ptr));
145# endif
146# ifdef MACOS_X
147static int get_mac_fio_flags __ARGS((char_u *ptr));
148# endif
149#endif
150static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
151
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 Moolenaar071d4272004-06-13 20:20:40 +0000302 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303
304 /*
305 * If there is no file name yet, use the one for the read file.
306 * BF_NOTEDITED is set to reflect this.
307 * Don't do this for a read from a filter.
308 * Only do this when 'cpoptions' contains the 'f' flag.
309 */
310 if (curbuf->b_ffname == NULL
311 && !filtering
312 && fname != NULL
313 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
314 && !(flags & READ_DUMMY))
315 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000316 if (set_rw_fname(fname, sfname) == FAIL)
317 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318 }
319
Bram Moolenaardf177f62005-02-22 08:39:57 +0000320 /* After reading a file the cursor line changes but we don't want to
321 * display the line. */
322 ex_no_reprint = TRUE;
323
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000324 /* don't display the file info for another buffer now */
325 need_fileinfo = FALSE;
326
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327 /*
328 * For Unix: Use the short file name whenever possible.
329 * Avoids problems with networks and when directory names are changed.
330 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
331 * another directory, which we don't detect.
332 */
333 if (sfname == NULL)
334 sfname = fname;
335#if defined(UNIX) || defined(__EMX__)
336 fname = sfname;
337#endif
338
339#ifdef FEAT_AUTOCMD
340 /*
341 * The BufReadCmd and FileReadCmd events intercept the reading process by
342 * executing the associated commands instead.
343 */
344 if (!filtering && !read_stdin && !read_buffer)
345 {
346 pos_T pos;
347
348 pos = curbuf->b_op_start;
349
350 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
351 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
352 curbuf->b_op_start.col = 0;
353
354 if (newfile)
355 {
356 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
357 FALSE, curbuf, eap))
358#ifdef FEAT_EVAL
359 return aborting() ? FAIL : OK;
360#else
361 return OK;
362#endif
363 }
364 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
365 FALSE, NULL, eap))
366#ifdef FEAT_EVAL
367 return aborting() ? FAIL : OK;
368#else
369 return OK;
370#endif
371
372 curbuf->b_op_start = pos;
373 }
374#endif
375
376 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
377 msg_scroll = FALSE; /* overwrite previous file message */
378 else
379 msg_scroll = TRUE; /* don't overwrite previous file message */
380
381 /*
382 * If the name ends in a path separator, we can't open it. Check here,
383 * because reading the file may actually work, but then creating the swap
384 * file may destroy it! Reported on MS-DOS and Win 95.
385 * If the name is too long we might crash further on, quit here.
386 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000387 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000388 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000389 p = fname + STRLEN(fname);
390 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000391 {
392 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
393 msg_end();
394 msg_scroll = msg_save;
395 return FAIL;
396 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 }
398
399#ifdef UNIX
400 /*
401 * On Unix it is possible to read a directory, so we have to
402 * check for it before the mch_open().
403 */
404 if (!read_stdin && !read_buffer)
405 {
406 perm = mch_getperm(fname);
407 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
408# ifdef S_ISFIFO
409 && !S_ISFIFO(perm) /* ... or fifo */
410# endif
411# ifdef S_ISSOCK
412 && !S_ISSOCK(perm) /* ... or socket */
413# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000414# ifdef OPEN_CHR_FILES
415 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
416 /* ... or a character special file named /dev/fd/<n> */
417# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 )
419 {
420 if (S_ISDIR(perm))
421 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
422 else
423 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
424 msg_end();
425 msg_scroll = msg_save;
426 return FAIL;
427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000429# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
430 /*
431 * MS-Windows allows opening a device, but we will probably get stuck
432 * trying to read it.
433 */
434 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
435 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000436 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000437 msg_end();
438 msg_scroll = msg_save;
439 return FAIL;
440 }
441# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000442 }
443#endif
444
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 {
448 if (eap != NULL && eap->force_ff != 0)
449 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
450 else if (*p_ffs != NUL)
451 set_fileformat(default_fileformat(), OPT_LOCAL);
452 }
453
454 /* set or reset 'binary' */
455 if (eap != NULL && eap->force_bin != 0)
456 {
457 int oldval = curbuf->b_p_bin;
458
459 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
460 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
461 }
462
463 /*
464 * When opening a new file we take the readonly flag from the file.
465 * Default is r/w, can be set to r/o below.
466 * Don't reset it when in readonly mode
467 * Only set/reset b_p_ro when BF_CHECK_RO is set.
468 */
469 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000470 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 curbuf->b_p_ro = FALSE;
472
473 if (newfile && !read_stdin && !read_buffer)
474 {
475 /* Remember time of file.
476 * For RISCOS, also remember the filetype.
477 */
478 if (mch_stat((char *)fname, &st) >= 0)
479 {
480 buf_store_time(curbuf, &st, fname);
481 curbuf->b_mtime_read = curbuf->b_mtime;
482
483#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
484 /* Read the filetype into the buffer local filetype option. */
485 mch_read_filetype(fname);
486#endif
487#ifdef UNIX
488 /*
489 * Use the protection bits of the original file for the swap file.
490 * This makes it possible for others to read the name of the
491 * edited file from the swapfile, but only if they can read the
492 * edited file.
493 * Remove the "write" and "execute" bits for group and others
494 * (they must not write the swapfile).
495 * Add the "read" and "write" bits for the user, otherwise we may
496 * not be able to write to the file ourselves.
497 * Setting the bits is done below, after creating the swap file.
498 */
499 swap_mode = (st.st_mode & 0644) | 0600;
500#endif
501#ifdef FEAT_CW_EDITOR
502 /* Get the FSSpec on MacOS
503 * TODO: Update it properly when the buffer name changes
504 */
505 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
506#endif
507#ifdef VMS
508 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000509 curbuf->b_fab_rat = st.st_fab_rat;
510 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511#endif
512 }
513 else
514 {
515 curbuf->b_mtime = 0;
516 curbuf->b_mtime_read = 0;
517 curbuf->b_orig_size = 0;
518 curbuf->b_orig_mode = 0;
519 }
520
521 /* Reset the "new file" flag. It will be set again below when the
522 * file doesn't exist. */
523 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
524 }
525
526/*
527 * for UNIX: check readonly with perm and mch_access()
528 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
529 * for MSDOS and Amiga: check readonly by trying to open the file for writing
530 */
531 file_readonly = FALSE;
532 if (read_stdin)
533 {
534#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
535 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
536 setmode(0, O_BINARY);
537#endif
538 }
539 else if (!read_buffer)
540 {
541#ifdef USE_MCH_ACCESS
542 if (
543# ifdef UNIX
544 !(perm & 0222) ||
545# endif
546 mch_access((char *)fname, W_OK))
547 file_readonly = TRUE;
548 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
549#else
550 if (!newfile
551 || readonlymode
552 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
553 {
554 file_readonly = TRUE;
555 /* try to open ro */
556 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
557 }
558#endif
559 }
560
561 if (fd < 0) /* cannot open at all */
562 {
563#ifndef UNIX
564 int isdir_f;
565#endif
566 msg_scroll = msg_save;
567#ifndef UNIX
568 /*
569 * On MSDOS and Amiga we can't open a directory, check here.
570 */
571 isdir_f = (mch_isdir(fname));
572 perm = mch_getperm(fname); /* check if the file exists */
573 if (isdir_f)
574 {
575 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
576 curbuf->b_p_ro = TRUE; /* must use "w!" now */
577 }
578 else
579#endif
580 if (newfile)
581 {
582 if (perm < 0)
583 {
584 /*
585 * Set the 'new-file' flag, so that when the file has
586 * been created by someone else, a ":w" will complain.
587 */
588 curbuf->b_flags |= BF_NEW;
589
590 /* Create a swap file now, so that other Vims are warned
591 * that we are editing this file. Don't do this for a
592 * "nofile" or "nowrite" buffer type. */
593#ifdef FEAT_QUICKFIX
594 if (!bt_dontwrite(curbuf))
595#endif
596 check_need_swap(newfile);
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000597 if (dir_of_file_exists(fname))
598 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
599 else
600 filemess(curbuf, sfname,
601 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602#ifdef FEAT_VIMINFO
603 /* Even though this is a new file, it might have been
604 * edited before and deleted. Get the old marks. */
605 check_marks_read();
606#endif
607#ifdef FEAT_MBYTE
608 if (eap != NULL && eap->force_enc != 0)
609 {
610 /* set forced 'fileencoding' */
611 fenc = enc_canonize(eap->cmd + eap->force_enc);
612 if (fenc != NULL)
613 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000614 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 vim_free(fenc);
616 }
617#endif
618#ifdef FEAT_AUTOCMD
619 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
620 FALSE, curbuf, eap);
621#endif
622 /* remember the current fileformat */
623 save_file_ff(curbuf);
624
625#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
626 if (aborting()) /* autocmds may abort script processing */
627 return FAIL;
628#endif
629 return OK; /* a new file is not an error */
630 }
631 else
632 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000633 filemess(curbuf, sfname, (char_u *)(
634# ifdef EFBIG
635 (errno == EFBIG) ? _("[File too big]") :
636# endif
637 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 curbuf->b_p_ro = TRUE; /* must use "w!" now */
639 }
640 }
641
642 return FAIL;
643 }
644
645 /*
646 * Only set the 'ro' flag for readonly files the first time they are
647 * loaded. Help files always get readonly mode
648 */
649 if ((check_readonly && file_readonly) || curbuf->b_help)
650 curbuf->b_p_ro = TRUE;
651
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000652 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000654 /* Don't change 'eol' if reading from buffer as it will already be
655 * correctly set when reading stdin. */
656 if (!read_buffer)
657 {
658 curbuf->b_p_eol = TRUE;
659 curbuf->b_start_eol = TRUE;
660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661#ifdef FEAT_MBYTE
662 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000663 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664#endif
665 }
666
667 /* Create a swap file now, so that other Vims are warned that we are
668 * editing this file.
669 * Don't do this for a "nofile" or "nowrite" buffer type. */
670#ifdef FEAT_QUICKFIX
671 if (!bt_dontwrite(curbuf))
672#endif
673 {
674 check_need_swap(newfile);
675#ifdef UNIX
676 /* Set swap file protection bits after creating it. */
677 if (swap_mode > 0 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
678 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
679#endif
680 }
681
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000682#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683 /* If "Quit" selected at ATTENTION dialog, don't load the file */
684 if (swap_exists_action == SEA_QUIT)
685 {
686 if (!read_buffer && !read_stdin)
687 close(fd);
688 return FAIL;
689 }
690#endif
691
692 ++no_wait_return; /* don't wait for return yet */
693
694 /*
695 * Set '[ mark to the line above where the lines go (line 1 if zero).
696 */
697 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
698 curbuf->b_op_start.col = 0;
699
700#ifdef FEAT_AUTOCMD
701 if (!read_buffer)
702 {
703 int m = msg_scroll;
704 int n = msg_scrolled;
705 buf_T *old_curbuf = curbuf;
706
707 /*
708 * The file must be closed again, the autocommands may want to change
709 * the file before reading it.
710 */
711 if (!read_stdin)
712 close(fd); /* ignore errors */
713
714 /*
715 * The output from the autocommands should not overwrite anything and
716 * should not be overwritten: Set msg_scroll, restore its value if no
717 * output was done.
718 */
719 msg_scroll = TRUE;
720 if (filtering)
721 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
722 FALSE, curbuf, eap);
723 else if (read_stdin)
724 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
725 FALSE, curbuf, eap);
726 else if (newfile)
727 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
728 FALSE, curbuf, eap);
729 else
730 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
731 FALSE, NULL, eap);
732 if (msg_scrolled == n)
733 msg_scroll = m;
734
735#ifdef FEAT_EVAL
736 if (aborting()) /* autocmds may abort script processing */
737 {
738 --no_wait_return;
739 msg_scroll = msg_save;
740 curbuf->b_p_ro = TRUE; /* must use "w!" now */
741 return FAIL;
742 }
743#endif
744 /*
745 * Don't allow the autocommands to change the current buffer.
746 * Try to re-open the file.
747 */
748 if (!read_stdin && (curbuf != old_curbuf
749 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
750 {
751 --no_wait_return;
752 msg_scroll = msg_save;
753 if (fd < 0)
754 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
755 else
756 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
757 curbuf->b_p_ro = TRUE; /* must use "w!" now */
758 return FAIL;
759 }
760 }
761#endif /* FEAT_AUTOCMD */
762
763 /* Autocommands may add lines to the file, need to check if it is empty */
764 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
765
766 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
767 {
768 /*
769 * Show the user that we are busy reading the input. Sometimes this
770 * may take a while. When reading from stdin another program may
771 * still be running, don't move the cursor to the last line, unless
772 * always using the GUI.
773 */
774 if (read_stdin)
775 {
776#ifndef ALWAYS_USE_GUI
777 mch_msg(_("Vim: Reading from stdin...\n"));
778#endif
779#ifdef FEAT_GUI
780 /* Also write a message in the GUI window, if there is one. */
781 if (gui.in_use && !gui.dying && !gui.starting)
782 {
783 p = (char_u *)_("Reading from stdin...");
784 gui_write(p, (int)STRLEN(p));
785 }
786#endif
787 }
788 else if (!read_buffer)
789 filemess(curbuf, sfname, (char_u *)"", 0);
790 }
791
792 msg_scroll = FALSE; /* overwrite the file message */
793
794 /*
795 * Set linecnt now, before the "retry" caused by a wrong guess for
796 * fileformat, and after the autocommands, which may change them.
797 */
798 linecnt = curbuf->b_ml.ml_line_count;
799
800#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000801 /* "++bad=" argument. */
802 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000803 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000804 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000805 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000806 curbuf->b_bad_char = eap->bad_char;
807 }
808 else
809 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000810
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000812 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 */
814 if (eap != NULL && eap->force_enc != 0)
815 {
816 fenc = enc_canonize(eap->cmd + eap->force_enc);
817 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000818 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819 }
820 else if (curbuf->b_p_bin)
821 {
822 fenc = (char_u *)""; /* binary: don't convert */
823 fenc_alloced = FALSE;
824 }
825 else if (curbuf->b_help)
826 {
827 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000828 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829
830 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
831 * fails it must be latin1.
832 * Always do this when 'encoding' is "utf-8". Otherwise only do
833 * this when needed to avoid [converted] remarks all the time.
834 * It is needed when the first line contains non-ASCII characters.
835 * That is only in *.??x files. */
836 fenc = (char_u *)"latin1";
837 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000838 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000840 fc = fname[STRLEN(fname) - 1];
841 if (TOLOWER_ASC(fc) == 'x')
842 {
843 /* Read the first line (and a bit more). Immediately rewind to
844 * the start of the file. If the read() fails "len" is -1. */
845 len = vim_read(fd, firstline, 80);
846 lseek(fd, (off_t)0L, SEEK_SET);
847 for (p = firstline; p < firstline + len; ++p)
848 if (*p >= 0x80)
849 {
850 c = TRUE;
851 break;
852 }
853 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854 }
855
856 if (c)
857 {
858 fenc_next = fenc;
859 fenc = (char_u *)"utf-8";
860
861 /* When the file is utf-8 but a character doesn't fit in
862 * 'encoding' don't retry. In help text editing utf-8 bytes
863 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000864 if (!enc_utf8)
865 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 }
867 fenc_alloced = FALSE;
868 }
869 else if (*p_fencs == NUL)
870 {
871 fenc = curbuf->b_p_fenc; /* use format from buffer */
872 fenc_alloced = FALSE;
873 }
874 else
875 {
876 fenc_next = p_fencs; /* try items in 'fileencodings' */
877 fenc = next_fenc(&fenc_next);
878 fenc_alloced = TRUE;
879 }
880#endif
881
882 /*
883 * Jump back here to retry reading the file in different ways.
884 * Reasons to retry:
885 * - encoding conversion failed: try another one from "fenc_next"
886 * - BOM detected and fenc was set, need to setup conversion
887 * - "fileformat" check failed: try another
888 *
889 * Variables set for special retry actions:
890 * "file_rewind" Rewind the file to start reading it again.
891 * "advance_fenc" Advance "fenc" using "fenc_next".
892 * "skip_read" Re-use already read bytes (BOM detected).
893 * "did_iconv" iconv() conversion failed, try 'charconvert'.
894 * "keep_fileformat" Don't reset "fileformat".
895 *
896 * Other status indicators:
897 * "tmpname" When != NULL did conversion with 'charconvert'.
898 * Output file has to be deleted afterwards.
899 * "iconv_fd" When != -1 did conversion with iconv().
900 */
901retry:
902
903 if (file_rewind)
904 {
905 if (read_buffer)
906 {
907 read_buf_lnum = 1;
908 read_buf_col = 0;
909 }
910 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
911 {
912 /* Can't rewind the file, give up. */
913 error = TRUE;
914 goto failed;
915 }
916 /* Delete the previously read lines. */
917 while (lnum > from)
918 ml_delete(lnum--, FALSE);
919 file_rewind = FALSE;
920#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000921 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000922 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000924 curbuf->b_start_bomb = FALSE;
925 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000926 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927#endif
928 }
929
930 /*
931 * When retrying with another "fenc" and the first time "fileformat"
932 * will be reset.
933 */
934 if (keep_fileformat)
935 keep_fileformat = FALSE;
936 else
937 {
938 if (eap != NULL && eap->force_ff != 0)
939 fileformat = get_fileformat_force(curbuf, eap);
940 else if (curbuf->b_p_bin)
941 fileformat = EOL_UNIX; /* binary: use Unix format */
942 else if (*p_ffs == NUL)
943 fileformat = get_fileformat(curbuf);/* use format from buffer */
944 else
945 fileformat = EOL_UNKNOWN; /* detect from file */
946 }
947
948#ifdef FEAT_MBYTE
949# ifdef USE_ICONV
950 if (iconv_fd != (iconv_t)-1)
951 {
952 /* aborted conversion with iconv(), close the descriptor */
953 iconv_close(iconv_fd);
954 iconv_fd = (iconv_t)-1;
955 }
956# endif
957
958 if (advance_fenc)
959 {
960 /*
961 * Try the next entry in 'fileencodings'.
962 */
963 advance_fenc = FALSE;
964
965 if (eap != NULL && eap->force_enc != 0)
966 {
967 /* Conversion given with "++cc=" wasn't possible, read
968 * without conversion. */
969 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000970 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971 if (fenc_alloced)
972 vim_free(fenc);
973 fenc = (char_u *)"";
974 fenc_alloced = FALSE;
975 }
976 else
977 {
978 if (fenc_alloced)
979 vim_free(fenc);
980 if (fenc_next != NULL)
981 {
982 fenc = next_fenc(&fenc_next);
983 fenc_alloced = (fenc_next != NULL);
984 }
985 else
986 {
987 fenc = (char_u *)"";
988 fenc_alloced = FALSE;
989 }
990 }
991 if (tmpname != NULL)
992 {
993 mch_remove(tmpname); /* delete converted file */
994 vim_free(tmpname);
995 tmpname = NULL;
996 }
997 }
998
999 /*
1000 * Conversion is required when the encoding of the file is different
1001 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4 (requires
1002 * conversion to UTF-8).
1003 */
1004 fio_flags = 0;
1005 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
1006 if (converted || enc_unicode != 0)
1007 {
1008
1009 /* "ucs-bom" means we need to check the first bytes of the file
1010 * for a BOM. */
1011 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1012 fio_flags = FIO_UCSBOM;
1013
1014 /*
1015 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1016 * done. This is handled below after read(). Prepare the
1017 * fio_flags to avoid having to parse the string each time.
1018 * Also check for Unicode to Latin1 conversion, because iconv()
1019 * appears not to handle this correctly. This works just like
1020 * conversion to UTF-8 except how the resulting character is put in
1021 * the buffer.
1022 */
1023 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1024 fio_flags = get_fio_flags(fenc);
1025
1026# ifdef WIN3264
1027 /*
1028 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1029 * is handled with MultiByteToWideChar().
1030 */
1031 if (fio_flags == 0)
1032 fio_flags = get_win_fio_flags(fenc);
1033# endif
1034
1035# ifdef MACOS_X
1036 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1037 if (fio_flags == 0)
1038 fio_flags = get_mac_fio_flags(fenc);
1039# endif
1040
1041# ifdef USE_ICONV
1042 /*
1043 * Try using iconv() if we can't convert internally.
1044 */
1045 if (fio_flags == 0
1046# ifdef FEAT_EVAL
1047 && !did_iconv
1048# endif
1049 )
1050 iconv_fd = (iconv_t)my_iconv_open(
1051 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1052# endif
1053
1054# ifdef FEAT_EVAL
1055 /*
1056 * Use the 'charconvert' expression when conversion is required
1057 * and we can't do it internally or with iconv().
1058 */
1059 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1060# ifdef USE_ICONV
1061 && iconv_fd == (iconv_t)-1
1062# endif
1063 )
1064 {
1065# ifdef USE_ICONV
1066 did_iconv = FALSE;
1067# endif
1068 /* Skip conversion when it's already done (retry for wrong
1069 * "fileformat"). */
1070 if (tmpname == NULL)
1071 {
1072 tmpname = readfile_charconvert(fname, fenc, &fd);
1073 if (tmpname == NULL)
1074 {
1075 /* Conversion failed. Try another one. */
1076 advance_fenc = TRUE;
1077 if (fd < 0)
1078 {
1079 /* Re-opening the original file failed! */
1080 EMSG(_("E202: Conversion made file unreadable!"));
1081 error = TRUE;
1082 goto failed;
1083 }
1084 goto retry;
1085 }
1086 }
1087 }
1088 else
1089# endif
1090 {
1091 if (fio_flags == 0
1092# ifdef USE_ICONV
1093 && iconv_fd == (iconv_t)-1
1094# endif
1095 )
1096 {
1097 /* Conversion wanted but we can't.
1098 * Try the next conversion in 'fileencodings' */
1099 advance_fenc = TRUE;
1100 goto retry;
1101 }
1102 }
1103 }
1104
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001105 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001107 * stdin or fixed at a specific encoding. */
1108 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109#endif
1110
1111 if (!skip_read)
1112 {
1113 linerest = 0;
1114 filesize = 0;
1115 skip_count = lines_to_skip;
1116 read_count = lines_to_read;
1117#ifdef FEAT_MBYTE
1118 conv_restlen = 0;
1119#endif
1120 }
1121
1122 while (!error && !got_int)
1123 {
1124 /*
1125 * We allocate as much space for the file as we can get, plus
1126 * space for the old line plus room for one terminating NUL.
1127 * The amount is limited by the fact that read() only can read
1128 * upto max_unsigned characters (and other things).
1129 */
1130#if SIZEOF_INT <= 2
1131 if (linerest >= 0x7ff0)
1132 {
1133 ++split;
1134 *ptr = NL; /* split line by inserting a NL */
1135 size = 1;
1136 }
1137 else
1138#endif
1139 {
1140 if (!skip_read)
1141 {
1142#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001143# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144 size = SSIZE_MAX; /* use max I/O size, 52K */
1145# else
1146 size = 0x10000L; /* use buffer >= 64K */
1147# endif
1148#else
1149 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1150#endif
1151
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001152 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153 {
1154 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1155 FALSE)) != NULL)
1156 break;
1157 }
1158 if (new_buffer == NULL)
1159 {
1160 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1161 error = TRUE;
1162 break;
1163 }
1164 if (linerest) /* copy characters from the previous buffer */
1165 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1166 vim_free(buffer);
1167 buffer = new_buffer;
1168 ptr = buffer + linerest;
1169 line_start = buffer;
1170
1171#ifdef FEAT_MBYTE
1172 /* May need room to translate into.
1173 * For iconv() we don't really know the required space, use a
1174 * factor ICONV_MULT.
1175 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1176 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1177 * become up to 4 bytes, size must be multiple of 2
1178 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1179 * multiple of 2
1180 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1181 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001182 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183# ifdef USE_ICONV
1184 if (iconv_fd != (iconv_t)-1)
1185 size = size / ICONV_MULT;
1186 else
1187# endif
1188 if (fio_flags & FIO_LATIN1)
1189 size = size / 2;
1190 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1191 size = (size * 2 / 3) & ~1;
1192 else if (fio_flags & FIO_UCS4)
1193 size = (size * 2 / 3) & ~3;
1194 else if (fio_flags == FIO_UCSBOM)
1195 size = size / ICONV_MULT; /* worst case */
1196# ifdef WIN3264
1197 else if (fio_flags & FIO_CODEPAGE)
1198 size = size / ICONV_MULT; /* also worst case */
1199# endif
1200# ifdef MACOS_X
1201 else if (fio_flags & FIO_MACROMAN)
1202 size = size / ICONV_MULT; /* also worst case */
1203# endif
1204#endif
1205
1206#ifdef FEAT_MBYTE
1207 if (conv_restlen > 0)
1208 {
1209 /* Insert unconverted bytes from previous line. */
1210 mch_memmove(ptr, conv_rest, conv_restlen);
1211 ptr += conv_restlen;
1212 size -= conv_restlen;
1213 }
1214#endif
1215
1216 if (read_buffer)
1217 {
1218 /*
1219 * Read bytes from curbuf. Used for converting text read
1220 * from stdin.
1221 */
1222 if (read_buf_lnum > from)
1223 size = 0;
1224 else
1225 {
1226 int n, ni;
1227 long tlen;
1228
1229 tlen = 0;
1230 for (;;)
1231 {
1232 p = ml_get(read_buf_lnum) + read_buf_col;
1233 n = (int)STRLEN(p);
1234 if ((int)tlen + n + 1 > size)
1235 {
1236 /* Filled up to "size", append partial line.
1237 * Change NL to NUL to reverse the effect done
1238 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001239 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240 for (ni = 0; ni < n; ++ni)
1241 {
1242 if (p[ni] == NL)
1243 ptr[tlen++] = NUL;
1244 else
1245 ptr[tlen++] = p[ni];
1246 }
1247 read_buf_col += n;
1248 break;
1249 }
1250 else
1251 {
1252 /* Append whole line and new-line. Change NL
1253 * to NUL to reverse the effect done below. */
1254 for (ni = 0; ni < n; ++ni)
1255 {
1256 if (p[ni] == NL)
1257 ptr[tlen++] = NUL;
1258 else
1259 ptr[tlen++] = p[ni];
1260 }
1261 ptr[tlen++] = NL;
1262 read_buf_col = 0;
1263 if (++read_buf_lnum > from)
1264 {
1265 /* When the last line didn't have an
1266 * end-of-line don't add it now either. */
1267 if (!curbuf->b_p_eol)
1268 --tlen;
1269 size = tlen;
1270 break;
1271 }
1272 }
1273 }
1274 }
1275 }
1276 else
1277 {
1278 /*
1279 * Read bytes from the file.
1280 */
1281 size = vim_read(fd, ptr, size);
1282 }
1283
1284 if (size <= 0)
1285 {
1286 if (size < 0) /* read error */
1287 error = TRUE;
1288#ifdef FEAT_MBYTE
1289 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001290 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001291 /*
1292 * Reached end-of-file but some trailing bytes could
1293 * not be converted. Truncated file?
1294 */
1295
1296 /* When we did a conversion report an error. */
1297 if (fio_flags != 0
1298# ifdef USE_ICONV
1299 || iconv_fd != (iconv_t)-1
1300# endif
1301 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001302 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001303 if (conv_error == 0)
1304 conv_error = curbuf->b_ml.ml_line_count
1305 - linecnt + 1;
1306 }
1307 /* Remember the first linenr with an illegal byte */
1308 else if (illegal_byte == 0)
1309 illegal_byte = curbuf->b_ml.ml_line_count
1310 - linecnt + 1;
1311 if (bad_char_behavior == BAD_DROP)
1312 {
1313 *(ptr - conv_restlen) = NUL;
1314 conv_restlen = 0;
1315 }
1316 else
1317 {
1318 /* Replace the trailing bytes with the replacement
1319 * character if we were converting; if we weren't,
1320 * leave the UTF8 checking code to do it, as it
1321 * works slightly differently. */
1322 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1323# ifdef USE_ICONV
1324 || iconv_fd != (iconv_t)-1
1325# endif
1326 ))
1327 {
1328 while (conv_restlen > 0)
1329 {
1330 *(--ptr) = bad_char_behavior;
1331 --conv_restlen;
1332 }
1333 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001334 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001335# ifdef USE_ICONV
1336 if (iconv_fd != (iconv_t)-1)
1337 {
1338 iconv_close(iconv_fd);
1339 iconv_fd = (iconv_t)-1;
1340 }
1341# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001342 }
1343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001344#endif
1345 }
1346
1347#ifdef FEAT_CRYPT
1348 /*
1349 * At start of file: Check for magic number of encryption.
1350 */
1351 if (filesize == 0)
1352 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1353 &filesize, newfile);
1354 /*
1355 * Decrypt the read bytes.
1356 */
1357 if (cryptkey != NULL && size > 0)
1358 for (p = ptr; p < ptr + size; ++p)
1359 ZDECODE(*p);
1360#endif
1361 }
1362 skip_read = FALSE;
1363
1364#ifdef FEAT_MBYTE
1365 /*
1366 * At start of file (or after crypt magic number): Check for BOM.
1367 * Also check for a BOM for other Unicode encodings, but not after
1368 * converting with 'charconvert' or when a BOM has already been
1369 * found.
1370 */
1371 if ((filesize == 0
1372# ifdef FEAT_CRYPT
1373 || (filesize == CRYPT_MAGIC_LEN && cryptkey != NULL)
1374# endif
1375 )
1376 && (fio_flags == FIO_UCSBOM
1377 || (!curbuf->b_p_bomb
1378 && tmpname == NULL
1379 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1380 {
1381 char_u *ccname;
1382 int blen;
1383
1384 /* no BOM detection in a short file or in binary mode */
1385 if (size < 2 || curbuf->b_p_bin)
1386 ccname = NULL;
1387 else
1388 ccname = check_for_bom(ptr, size, &blen,
1389 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1390 if (ccname != NULL)
1391 {
1392 /* Remove BOM from the text */
1393 filesize += blen;
1394 size -= blen;
1395 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001396 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001397 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001399 curbuf->b_start_bomb = TRUE;
1400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401 }
1402
1403 if (fio_flags == FIO_UCSBOM)
1404 {
1405 if (ccname == NULL)
1406 {
1407 /* No BOM detected: retry with next encoding. */
1408 advance_fenc = TRUE;
1409 }
1410 else
1411 {
1412 /* BOM detected: set "fenc" and jump back */
1413 if (fenc_alloced)
1414 vim_free(fenc);
1415 fenc = ccname;
1416 fenc_alloced = FALSE;
1417 }
1418 /* retry reading without getting new bytes or rewinding */
1419 skip_read = TRUE;
1420 goto retry;
1421 }
1422 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001423
1424 /* Include not converted bytes. */
1425 ptr -= conv_restlen;
1426 size += conv_restlen;
1427 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428#endif
1429 /*
1430 * Break here for a read error or end-of-file.
1431 */
1432 if (size <= 0)
1433 break;
1434
1435#ifdef FEAT_MBYTE
1436
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437# ifdef USE_ICONV
1438 if (iconv_fd != (iconv_t)-1)
1439 {
1440 /*
1441 * Attempt conversion of the read bytes to 'encoding' using
1442 * iconv().
1443 */
1444 const char *fromp;
1445 char *top;
1446 size_t from_size;
1447 size_t to_size;
1448
1449 fromp = (char *)ptr;
1450 from_size = size;
1451 ptr += size;
1452 top = (char *)ptr;
1453 to_size = real_size - size;
1454
1455 /*
1456 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001457 * another conversion. Except for when there is no
1458 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001460 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1461 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1463 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001464 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001465 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001466 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001467 if (conv_error == 0)
1468 conv_error = readfile_linenr(linecnt,
1469 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001470
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001471 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001472 ++fromp;
1473 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001474 if (bad_char_behavior == BAD_KEEP)
1475 {
1476 *top++ = *(fromp - 1);
1477 --to_size;
1478 }
1479 else if (bad_char_behavior != BAD_DROP)
1480 {
1481 *top++ = bad_char_behavior;
1482 --to_size;
1483 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485
1486 if (from_size > 0)
1487 {
1488 /* Some remaining characters, keep them for the next
1489 * round. */
1490 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1491 conv_restlen = (int)from_size;
1492 }
1493
1494 /* move the linerest to before the converted characters */
1495 line_start = ptr - linerest;
1496 mch_memmove(line_start, buffer, (size_t)linerest);
1497 size = (long)((char_u *)top - ptr);
1498 }
1499# endif
1500
1501# ifdef WIN3264
1502 if (fio_flags & FIO_CODEPAGE)
1503 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001504 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001505 WCHAR ucs2buf[3];
1506 int ucs2len;
1507 int codepage = FIO_GET_CP(fio_flags);
1508 int bytelen;
1509 int found_bad;
1510 char replstr[2];
1511
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512 /*
1513 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001514 * a codepage, using standard MS-Windows functions. This
1515 * requires two steps:
1516 * 1. convert from 'fileencoding' to ucs-2
1517 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001519 * Because there may be illegal bytes AND an incomplete byte
1520 * sequence at the end, we may have to do the conversion one
1521 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001524 /* Replacement string for WideCharToMultiByte(). */
1525 if (bad_char_behavior > 0)
1526 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001528 replstr[0] = '?';
1529 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530
1531 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001532 * Move the bytes to the end of the buffer, so that we have
1533 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001535 src = ptr + real_size - size;
1536 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001538 /*
1539 * Do the conversion.
1540 */
1541 dst = ptr;
1542 size = size;
1543 while (size > 0)
1544 {
1545 found_bad = FALSE;
1546
1547# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1548 if (codepage == CP_UTF8)
1549 {
1550 /* Handle CP_UTF8 input ourselves to be able to handle
1551 * trailing bytes properly.
1552 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001553 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001554 if (bytelen > size)
1555 {
1556 /* Only got some bytes of a character. Normally
1557 * it's put in "conv_rest", but if it's too long
1558 * deal with it as if they were illegal bytes. */
1559 if (bytelen <= CONV_RESTLEN)
1560 break;
1561
1562 /* weird overlong byte sequence */
1563 bytelen = size;
1564 found_bad = TRUE;
1565 }
1566 else
1567 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001568 int u8c = utf_ptr2char(src);
1569
Bram Moolenaar86e01082005-12-29 22:45:34 +00001570 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001571 found_bad = TRUE;
1572 ucs2buf[0] = u8c;
1573 ucs2len = 1;
1574 }
1575 }
1576 else
1577# endif
1578 {
1579 /* We don't know how long the byte sequence is, try
1580 * from one to three bytes. */
1581 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1582 ++bytelen)
1583 {
1584 ucs2len = MultiByteToWideChar(codepage,
1585 MB_ERR_INVALID_CHARS,
1586 (LPCSTR)src, bytelen,
1587 ucs2buf, 3);
1588 if (ucs2len > 0)
1589 break;
1590 }
1591 if (ucs2len == 0)
1592 {
1593 /* If we have only one byte then it's probably an
1594 * incomplete byte sequence. Otherwise discard
1595 * one byte as a bad character. */
1596 if (size == 1)
1597 break;
1598 found_bad = TRUE;
1599 bytelen = 1;
1600 }
1601 }
1602
1603 if (!found_bad)
1604 {
1605 int i;
1606
1607 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1608 if (enc_utf8)
1609 {
1610 /* From UCS-2 to UTF-8. Cannot fail. */
1611 for (i = 0; i < ucs2len; ++i)
1612 dst += utf_char2bytes(ucs2buf[i], dst);
1613 }
1614 else
1615 {
1616 BOOL bad = FALSE;
1617 int dstlen;
1618
1619 /* From UCS-2 to "enc_codepage". If the
1620 * conversion uses the default character "?",
1621 * the data doesn't fit in this encoding. */
1622 dstlen = WideCharToMultiByte(enc_codepage, 0,
1623 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001624 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001625 replstr, &bad);
1626 if (bad)
1627 found_bad = TRUE;
1628 else
1629 dst += dstlen;
1630 }
1631 }
1632
1633 if (found_bad)
1634 {
1635 /* Deal with bytes we can't convert. */
1636 if (can_retry)
1637 goto rewind_retry;
1638 if (conv_error == 0)
1639 conv_error = readfile_linenr(linecnt, ptr, dst);
1640 if (bad_char_behavior != BAD_DROP)
1641 {
1642 if (bad_char_behavior == BAD_KEEP)
1643 {
1644 mch_memmove(dst, src, bytelen);
1645 dst += bytelen;
1646 }
1647 else
1648 *dst++ = bad_char_behavior;
1649 }
1650 }
1651
1652 src += bytelen;
1653 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001655
1656 if (size > 0)
1657 {
1658 /* An incomplete byte sequence remaining. */
1659 mch_memmove(conv_rest, src, size);
1660 conv_restlen = size;
1661 }
1662
1663 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001664 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 }
1666 else
1667# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001668# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 if (fio_flags & FIO_MACROMAN)
1670 {
1671 /*
1672 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001673 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001675 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 }
1678 else
1679# endif
1680 if (fio_flags != 0)
1681 {
1682 int u8c;
1683 char_u *dest;
1684 char_u *tail = NULL;
1685
1686 /*
1687 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1688 * "enc_utf8" not set: Convert Unicode to Latin1.
1689 * Go from end to start through the buffer, because the number
1690 * of bytes may increase.
1691 * "dest" points to after where the UTF-8 bytes go, "p" points
1692 * to after the next character to convert.
1693 */
1694 dest = ptr + real_size;
1695 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1696 {
1697 p = ptr + size;
1698 if (fio_flags == FIO_UTF8)
1699 {
1700 /* Check for a trailing incomplete UTF-8 sequence */
1701 tail = ptr + size - 1;
1702 while (tail > ptr && (*tail & 0xc0) == 0x80)
1703 --tail;
1704 if (tail + utf_byte2len(*tail) <= ptr + size)
1705 tail = NULL;
1706 else
1707 p = tail;
1708 }
1709 }
1710 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1711 {
1712 /* Check for a trailing byte */
1713 p = ptr + (size & ~1);
1714 if (size & 1)
1715 tail = p;
1716 if ((fio_flags & FIO_UTF16) && p > ptr)
1717 {
1718 /* Check for a trailing leading word */
1719 if (fio_flags & FIO_ENDIAN_L)
1720 {
1721 u8c = (*--p << 8);
1722 u8c += *--p;
1723 }
1724 else
1725 {
1726 u8c = *--p;
1727 u8c += (*--p << 8);
1728 }
1729 if (u8c >= 0xd800 && u8c <= 0xdbff)
1730 tail = p;
1731 else
1732 p += 2;
1733 }
1734 }
1735 else /* FIO_UCS4 */
1736 {
1737 /* Check for trailing 1, 2 or 3 bytes */
1738 p = ptr + (size & ~3);
1739 if (size & 3)
1740 tail = p;
1741 }
1742
1743 /* If there is a trailing incomplete sequence move it to
1744 * conv_rest[]. */
1745 if (tail != NULL)
1746 {
1747 conv_restlen = (int)((ptr + size) - tail);
1748 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1749 size -= conv_restlen;
1750 }
1751
1752
1753 while (p > ptr)
1754 {
1755 if (fio_flags & FIO_LATIN1)
1756 u8c = *--p;
1757 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1758 {
1759 if (fio_flags & FIO_ENDIAN_L)
1760 {
1761 u8c = (*--p << 8);
1762 u8c += *--p;
1763 }
1764 else
1765 {
1766 u8c = *--p;
1767 u8c += (*--p << 8);
1768 }
1769 if ((fio_flags & FIO_UTF16)
1770 && u8c >= 0xdc00 && u8c <= 0xdfff)
1771 {
1772 int u16c;
1773
1774 if (p == ptr)
1775 {
1776 /* Missing leading word. */
1777 if (can_retry)
1778 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001779 if (conv_error == 0)
1780 conv_error = readfile_linenr(linecnt,
1781 ptr, p);
1782 if (bad_char_behavior == BAD_DROP)
1783 continue;
1784 if (bad_char_behavior != BAD_KEEP)
1785 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786 }
1787
1788 /* found second word of double-word, get the first
1789 * word and compute the resulting character */
1790 if (fio_flags & FIO_ENDIAN_L)
1791 {
1792 u16c = (*--p << 8);
1793 u16c += *--p;
1794 }
1795 else
1796 {
1797 u16c = *--p;
1798 u16c += (*--p << 8);
1799 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001800 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1801 + (u8c & 0x3ff);
1802
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 /* Check if the word is indeed a leading word. */
1804 if (u16c < 0xd800 || u16c > 0xdbff)
1805 {
1806 if (can_retry)
1807 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001808 if (conv_error == 0)
1809 conv_error = readfile_linenr(linecnt,
1810 ptr, p);
1811 if (bad_char_behavior == BAD_DROP)
1812 continue;
1813 if (bad_char_behavior != BAD_KEEP)
1814 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
1817 }
1818 else if (fio_flags & FIO_UCS4)
1819 {
1820 if (fio_flags & FIO_ENDIAN_L)
1821 {
1822 u8c = (*--p << 24);
1823 u8c += (*--p << 16);
1824 u8c += (*--p << 8);
1825 u8c += *--p;
1826 }
1827 else /* big endian */
1828 {
1829 u8c = *--p;
1830 u8c += (*--p << 8);
1831 u8c += (*--p << 16);
1832 u8c += (*--p << 24);
1833 }
1834 }
1835 else /* UTF-8 */
1836 {
1837 if (*--p < 0x80)
1838 u8c = *p;
1839 else
1840 {
1841 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001842 p -= len;
1843 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 if (len == 0)
1845 {
1846 /* Not a valid UTF-8 character, retry with
1847 * another fenc when possible, otherwise just
1848 * report the error. */
1849 if (can_retry)
1850 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001851 if (conv_error == 0)
1852 conv_error = readfile_linenr(linecnt,
1853 ptr, p);
1854 if (bad_char_behavior == BAD_DROP)
1855 continue;
1856 if (bad_char_behavior != BAD_KEEP)
1857 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 }
1860 }
1861 if (enc_utf8) /* produce UTF-8 */
1862 {
1863 dest -= utf_char2len(u8c);
1864 (void)utf_char2bytes(u8c, dest);
1865 }
1866 else /* produce Latin1 */
1867 {
1868 --dest;
1869 if (u8c >= 0x100)
1870 {
1871 /* character doesn't fit in latin1, retry with
1872 * another fenc when possible, otherwise just
1873 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001874 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001876 if (conv_error == 0)
1877 conv_error = readfile_linenr(linecnt, ptr, p);
1878 if (bad_char_behavior == BAD_DROP)
1879 ++dest;
1880 else if (bad_char_behavior == BAD_KEEP)
1881 *dest = u8c;
1882 else if (eap != NULL && eap->bad_char != 0)
1883 *dest = bad_char_behavior;
1884 else
1885 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 }
1887 else
1888 *dest = u8c;
1889 }
1890 }
1891
1892 /* move the linerest to before the converted characters */
1893 line_start = dest - linerest;
1894 mch_memmove(line_start, buffer, (size_t)linerest);
1895 size = (long)((ptr + real_size) - dest);
1896 ptr = dest;
1897 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001898 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001900 int incomplete_tail = FALSE;
1901
1902 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1903 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001905 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 int l;
1907
1908 if (todo <= 0)
1909 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (*p >= 0x80)
1911 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 /* A length of 1 means it's an illegal byte. Accept
1913 * an incomplete character at the end though, the next
1914 * read() will get the next bytes, we'll check it
1915 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001916 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001917 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001919 /* Avoid retrying with a different encoding when
1920 * a truncated file is more likely, or attempting
1921 * to read the rest of an incomplete sequence when
1922 * we have already done so. */
1923 if (p > ptr || filesize > 0)
1924 incomplete_tail = TRUE;
1925 /* Incomplete byte sequence, move it to conv_rest[]
1926 * and try to read the rest of it, unless we've
1927 * already done so. */
1928 if (p > ptr)
1929 {
1930 conv_restlen = todo;
1931 mch_memmove(conv_rest, p, conv_restlen);
1932 size -= conv_restlen;
1933 break;
1934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001936 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001937 {
1938 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00001939 * do that, unless at EOF where a truncated
1940 * file is more likely than a conversion error. */
1941 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001942 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001943# ifdef USE_ICONV
1944 /* When we did a conversion report an error. */
1945 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
1946 conv_error = readfile_linenr(linecnt, ptr, p);
1947# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001948 /* Remember the first linenr with an illegal byte */
1949 if (conv_error == 0 && illegal_byte == 0)
1950 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001951
1952 /* Drop, keep or replace the bad byte. */
1953 if (bad_char_behavior == BAD_DROP)
1954 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001955 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001956 --p;
1957 --size;
1958 }
1959 else if (bad_char_behavior != BAD_KEEP)
1960 *p = bad_char_behavior;
1961 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001962 else
1963 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
1965 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001966 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 {
1968 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001970 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001972 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
1973 /* iconv() failed, try 'charconvert' */
1974 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 else
1976# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001977 /* use next item from 'fileencodings' */
1978 advance_fenc = TRUE;
1979 file_rewind = TRUE;
1980 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 }
1982 }
1983#endif
1984
1985 /* count the number of characters (after conversion!) */
1986 filesize += size;
1987
1988 /*
1989 * when reading the first part of a file: guess EOL type
1990 */
1991 if (fileformat == EOL_UNKNOWN)
1992 {
1993 /* First try finding a NL, for Dos and Unix */
1994 if (try_dos || try_unix)
1995 {
1996 for (p = ptr; p < ptr + size; ++p)
1997 {
1998 if (*p == NL)
1999 {
2000 if (!try_unix
2001 || (try_dos && p > ptr && p[-1] == CAR))
2002 fileformat = EOL_DOS;
2003 else
2004 fileformat = EOL_UNIX;
2005 break;
2006 }
2007 }
2008
2009 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2010 if (fileformat == EOL_UNIX && try_mac)
2011 {
2012 /* Need to reset the counters when retrying fenc. */
2013 try_mac = 1;
2014 try_unix = 1;
2015 for (; p >= ptr && *p != CAR; p--)
2016 ;
2017 if (p >= ptr)
2018 {
2019 for (p = ptr; p < ptr + size; ++p)
2020 {
2021 if (*p == NL)
2022 try_unix++;
2023 else if (*p == CAR)
2024 try_mac++;
2025 }
2026 if (try_mac > try_unix)
2027 fileformat = EOL_MAC;
2028 }
2029 }
2030 }
2031
2032 /* No NL found: may use Mac format */
2033 if (fileformat == EOL_UNKNOWN && try_mac)
2034 fileformat = EOL_MAC;
2035
2036 /* Still nothing found? Use first format in 'ffs' */
2037 if (fileformat == EOL_UNKNOWN)
2038 fileformat = default_fileformat();
2039
2040 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002041 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 set_fileformat(fileformat, OPT_LOCAL);
2043 }
2044 }
2045
2046 /*
2047 * This loop is executed once for every character read.
2048 * Keep it fast!
2049 */
2050 if (fileformat == EOL_MAC)
2051 {
2052 --ptr;
2053 while (++ptr, --size >= 0)
2054 {
2055 /* catch most common case first */
2056 if ((c = *ptr) != NUL && c != CAR && c != NL)
2057 continue;
2058 if (c == NUL)
2059 *ptr = NL; /* NULs are replaced by newlines! */
2060 else if (c == NL)
2061 *ptr = CAR; /* NLs are replaced by CRs! */
2062 else
2063 {
2064 if (skip_count == 0)
2065 {
2066 *ptr = NUL; /* end of line */
2067 len = (colnr_T) (ptr - line_start + 1);
2068 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2069 {
2070 error = TRUE;
2071 break;
2072 }
2073 ++lnum;
2074 if (--read_count == 0)
2075 {
2076 error = TRUE; /* break loop */
2077 line_start = ptr; /* nothing left to write */
2078 break;
2079 }
2080 }
2081 else
2082 --skip_count;
2083 line_start = ptr + 1;
2084 }
2085 }
2086 }
2087 else
2088 {
2089 --ptr;
2090 while (++ptr, --size >= 0)
2091 {
2092 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2093 continue;
2094 if (c == NUL)
2095 *ptr = NL; /* NULs are replaced by newlines! */
2096 else
2097 {
2098 if (skip_count == 0)
2099 {
2100 *ptr = NUL; /* end of line */
2101 len = (colnr_T)(ptr - line_start + 1);
2102 if (fileformat == EOL_DOS)
2103 {
2104 if (ptr[-1] == CAR) /* remove CR */
2105 {
2106 ptr[-1] = NUL;
2107 --len;
2108 }
2109 /*
2110 * Reading in Dos format, but no CR-LF found!
2111 * When 'fileformats' includes "unix", delete all
2112 * the lines read so far and start all over again.
2113 * Otherwise give an error message later.
2114 */
2115 else if (ff_error != EOL_DOS)
2116 {
2117 if ( try_unix
2118 && !read_stdin
2119 && (read_buffer
2120 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2121 {
2122 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002123 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 set_fileformat(EOL_UNIX, OPT_LOCAL);
2125 file_rewind = TRUE;
2126 keep_fileformat = TRUE;
2127 goto retry;
2128 }
2129 ff_error = EOL_DOS;
2130 }
2131 }
2132 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2133 {
2134 error = TRUE;
2135 break;
2136 }
2137 ++lnum;
2138 if (--read_count == 0)
2139 {
2140 error = TRUE; /* break loop */
2141 line_start = ptr; /* nothing left to write */
2142 break;
2143 }
2144 }
2145 else
2146 --skip_count;
2147 line_start = ptr + 1;
2148 }
2149 }
2150 }
2151 linerest = (long)(ptr - line_start);
2152 ui_breakcheck();
2153 }
2154
2155failed:
2156 /* not an error, max. number of lines reached */
2157 if (error && read_count == 0)
2158 error = FALSE;
2159
2160 /*
2161 * If we get EOF in the middle of a line, note the fact and
2162 * complete the line ourselves.
2163 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2164 */
2165 if (!error
2166 && !got_int
2167 && linerest != 0
2168 && !(!curbuf->b_p_bin
2169 && fileformat == EOL_DOS
2170 && *line_start == Ctrl_Z
2171 && ptr == line_start + 1))
2172 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002173 /* remember for when writing */
2174 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 curbuf->b_p_eol = FALSE;
2176 *ptr = NUL;
2177 if (ml_append(lnum, line_start,
2178 (colnr_T)(ptr - line_start + 1), newfile) == FAIL)
2179 error = TRUE;
2180 else
2181 read_no_eol_lnum = ++lnum;
2182 }
2183
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002184 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 save_file_ff(curbuf); /* remember the current file format */
2186
2187#ifdef FEAT_CRYPT
2188 if (cryptkey != curbuf->b_p_key)
2189 vim_free(cryptkey);
2190#endif
2191
2192#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002193 /* If editing a new file: set 'fenc' for the current buffer.
2194 * Also for ":read ++edit file". */
2195 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002197 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 if (fenc_alloced)
2199 vim_free(fenc);
2200# ifdef USE_ICONV
2201 if (iconv_fd != (iconv_t)-1)
2202 {
2203 iconv_close(iconv_fd);
2204 iconv_fd = (iconv_t)-1;
2205 }
2206# endif
2207#endif
2208
2209 if (!read_buffer && !read_stdin)
2210 close(fd); /* errors are ignored */
2211 vim_free(buffer);
2212
2213#ifdef HAVE_DUP
2214 if (read_stdin)
2215 {
2216 /* Use stderr for stdin, makes shell commands work. */
2217 close(0);
2218 dup(2);
2219 }
2220#endif
2221
2222#ifdef FEAT_MBYTE
2223 if (tmpname != NULL)
2224 {
2225 mch_remove(tmpname); /* delete converted file */
2226 vim_free(tmpname);
2227 }
2228#endif
2229 --no_wait_return; /* may wait for return now */
2230
2231 /*
2232 * In recovery mode everything but autocommands is skipped.
2233 */
2234 if (!recoverymode)
2235 {
2236 /* need to delete the last line, which comes from the empty buffer */
2237 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2238 {
2239#ifdef FEAT_NETBEANS_INTG
2240 netbeansFireChanges = 0;
2241#endif
2242 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2243#ifdef FEAT_NETBEANS_INTG
2244 netbeansFireChanges = 1;
2245#endif
2246 --linecnt;
2247 }
2248 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2249 if (filesize == 0)
2250 linecnt = 0;
2251 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002252 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002254#ifdef FEAT_DIFF
2255 /* After reading the text into the buffer the diff info needs to
2256 * be updated. */
2257 diff_invalidate(curbuf);
2258#endif
2259#ifdef FEAT_FOLDING
2260 /* All folds in the window are invalid now. Mark them for update
2261 * before triggering autocommands. */
2262 foldUpdateAll(curwin);
2263#endif
2264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 else if (linecnt) /* appended at least one line */
2266 appended_lines_mark(from, linecnt);
2267
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268#ifndef ALWAYS_USE_GUI
2269 /*
2270 * If we were reading from the same terminal as where messages go,
2271 * the screen will have been messed up.
2272 * Switch on raw mode now and clear the screen.
2273 */
2274 if (read_stdin)
2275 {
2276 settmode(TMODE_RAW); /* set to raw mode */
2277 starttermcap();
2278 screenclear();
2279 }
2280#endif
2281
2282 if (got_int)
2283 {
2284 if (!(flags & READ_DUMMY))
2285 {
2286 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2287 if (newfile)
2288 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2289 }
2290 msg_scroll = msg_save;
2291#ifdef FEAT_VIMINFO
2292 check_marks_read();
2293#endif
2294 return OK; /* an interrupt isn't really an error */
2295 }
2296
2297 if (!filtering && !(flags & READ_DUMMY))
2298 {
2299 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2300 c = FALSE;
2301
2302#ifdef UNIX
2303# ifdef S_ISFIFO
2304 if (S_ISFIFO(perm)) /* fifo or socket */
2305 {
2306 STRCAT(IObuff, _("[fifo/socket]"));
2307 c = TRUE;
2308 }
2309# else
2310# ifdef S_IFIFO
2311 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2312 {
2313 STRCAT(IObuff, _("[fifo]"));
2314 c = TRUE;
2315 }
2316# endif
2317# ifdef S_IFSOCK
2318 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2319 {
2320 STRCAT(IObuff, _("[socket]"));
2321 c = TRUE;
2322 }
2323# endif
2324# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002325# ifdef OPEN_CHR_FILES
2326 if (S_ISCHR(perm)) /* or character special */
2327 {
2328 STRCAT(IObuff, _("[character special]"));
2329 c = TRUE;
2330 }
2331# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332#endif
2333 if (curbuf->b_p_ro)
2334 {
2335 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2336 c = TRUE;
2337 }
2338 if (read_no_eol_lnum)
2339 {
2340 msg_add_eol();
2341 c = TRUE;
2342 }
2343 if (ff_error == EOL_DOS)
2344 {
2345 STRCAT(IObuff, _("[CR missing]"));
2346 c = TRUE;
2347 }
2348 if (ff_error == EOL_MAC)
2349 {
2350 STRCAT(IObuff, _("[NL found]"));
2351 c = TRUE;
2352 }
2353 if (split)
2354 {
2355 STRCAT(IObuff, _("[long lines split]"));
2356 c = TRUE;
2357 }
2358#ifdef FEAT_MBYTE
2359 if (notconverted)
2360 {
2361 STRCAT(IObuff, _("[NOT converted]"));
2362 c = TRUE;
2363 }
2364 else if (converted)
2365 {
2366 STRCAT(IObuff, _("[converted]"));
2367 c = TRUE;
2368 }
2369#endif
2370#ifdef FEAT_CRYPT
2371 if (cryptkey != NULL)
2372 {
2373 STRCAT(IObuff, _("[crypted]"));
2374 c = TRUE;
2375 }
2376#endif
2377#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002378 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002380 sprintf((char *)IObuff + STRLEN(IObuff),
2381 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 c = TRUE;
2383 }
2384 else if (illegal_byte > 0)
2385 {
2386 sprintf((char *)IObuff + STRLEN(IObuff),
2387 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2388 c = TRUE;
2389 }
2390 else
2391#endif
2392 if (error)
2393 {
2394 STRCAT(IObuff, _("[READ ERRORS]"));
2395 c = TRUE;
2396 }
2397 if (msg_add_fileformat(fileformat))
2398 c = TRUE;
2399#ifdef FEAT_CRYPT
2400 if (cryptkey != NULL)
2401 msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN);
2402 else
2403#endif
2404 msg_add_lines(c, (long)linecnt, filesize);
2405
2406 vim_free(keep_msg);
2407 keep_msg = NULL;
2408 msg_scrolled_ign = TRUE;
2409#ifdef ALWAYS_USE_GUI
2410 /* Don't show the message when reading stdin, it would end up in a
2411 * message box (which might be shown when exiting!) */
2412 if (read_stdin || read_buffer)
2413 p = msg_may_trunc(FALSE, IObuff);
2414 else
2415#endif
2416 p = msg_trunc_attr(IObuff, FALSE, 0);
2417 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002418 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 /* Need to repeat the message after redrawing when:
2420 * - When reading from stdin (the screen will be cleared next).
2421 * - When restart_edit is set (otherwise there will be a delay
2422 * before redrawing).
2423 * - When the screen was scrolled but there is no wait-return
2424 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002425 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 msg_scrolled_ign = FALSE;
2427 }
2428
2429 /* with errors writing the file requires ":w!" */
2430 if (newfile && (error
2431#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002432 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002433 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434#endif
2435 ))
2436 curbuf->b_p_ro = TRUE;
2437
2438 u_clearline(); /* cannot use "U" command after adding lines */
2439
2440 /*
2441 * In Ex mode: cursor at last new line.
2442 * Otherwise: cursor at first new line.
2443 */
2444 if (exmode_active)
2445 curwin->w_cursor.lnum = from + linecnt;
2446 else
2447 curwin->w_cursor.lnum = from + 1;
2448 check_cursor_lnum();
2449 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2450
2451 /*
2452 * Set '[ and '] marks to the newly read lines.
2453 */
2454 curbuf->b_op_start.lnum = from + 1;
2455 curbuf->b_op_start.col = 0;
2456 curbuf->b_op_end.lnum = from + linecnt;
2457 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002458
2459#ifdef WIN32
2460 /*
2461 * Work around a weird problem: When a file has two links (only
2462 * possible on NTFS) and we write through one link, then stat() it
2463 * throught the other link, the timestamp information may be wrong.
2464 * It's correct again after reading the file, thus reset the timestamp
2465 * here.
2466 */
2467 if (newfile && !read_stdin && !read_buffer
2468 && mch_stat((char *)fname, &st) >= 0)
2469 {
2470 buf_store_time(curbuf, &st, fname);
2471 curbuf->b_mtime_read = curbuf->b_mtime;
2472 }
2473#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 }
2475 msg_scroll = msg_save;
2476
2477#ifdef FEAT_VIMINFO
2478 /*
2479 * Get the marks before executing autocommands, so they can be used there.
2480 */
2481 check_marks_read();
2482#endif
2483
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 /*
2485 * Trick: We remember if the last line of the read didn't have
2486 * an eol for when writing it again. This is required for
2487 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2488 */
2489 write_no_eol_lnum = read_no_eol_lnum;
2490
Bram Moolenaardf177f62005-02-22 08:39:57 +00002491#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if (!read_stdin && !read_buffer)
2493 {
2494 int m = msg_scroll;
2495 int n = msg_scrolled;
2496
2497 /* Save the fileformat now, otherwise the buffer will be considered
2498 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002499 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 save_file_ff(curbuf);
2501
2502 /*
2503 * The output from the autocommands should not overwrite anything and
2504 * should not be overwritten: Set msg_scroll, restore its value if no
2505 * output was done.
2506 */
2507 msg_scroll = TRUE;
2508 if (filtering)
2509 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2510 FALSE, curbuf, eap);
2511 else if (newfile)
2512 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2513 FALSE, curbuf, eap);
2514 else
2515 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2516 FALSE, NULL, eap);
2517 if (msg_scrolled == n)
2518 msg_scroll = m;
2519#ifdef FEAT_EVAL
2520 if (aborting()) /* autocmds may abort script processing */
2521 return FAIL;
2522#endif
2523 }
2524#endif
2525
2526 if (recoverymode && error)
2527 return FAIL;
2528 return OK;
2529}
2530
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002531#ifdef OPEN_CHR_FILES
2532/*
2533 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2534 * which is the name of files used for process substitution output by
2535 * some shells on some operating systems, e.g., bash on SunOS.
2536 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2537 */
2538 static int
2539is_dev_fd_file(fname)
2540 char_u *fname;
2541{
2542 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2543 && VIM_ISDIGIT(fname[8])
2544 && *skipdigits(fname + 9) == NUL
2545 && (fname[9] != NUL
2546 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2547}
2548#endif
2549
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002550#ifdef FEAT_MBYTE
2551
2552/*
2553 * From the current line count and characters read after that, estimate the
2554 * line number where we are now.
2555 * Used for error messages that include a line number.
2556 */
2557 static linenr_T
2558readfile_linenr(linecnt, p, endp)
2559 linenr_T linecnt; /* line count before reading more bytes */
2560 char_u *p; /* start of more bytes read */
2561 char_u *endp; /* end of more bytes read */
2562{
2563 char_u *s;
2564 linenr_T lnum;
2565
2566 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2567 for (s = p; s < endp; ++s)
2568 if (*s == '\n')
2569 ++lnum;
2570 return lnum;
2571}
2572#endif
2573
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002575 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2576 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 * Returns OK or FAIL.
2578 */
2579 int
2580prep_exarg(eap, buf)
2581 exarg_T *eap;
2582 buf_T *buf;
2583{
2584 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2585#ifdef FEAT_MBYTE
2586 + STRLEN(buf->b_p_fenc)
2587#endif
2588 + 15));
2589 if (eap->cmd == NULL)
2590 return FAIL;
2591
2592#ifdef FEAT_MBYTE
2593 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2594 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002595 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596#else
2597 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2598#endif
2599 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002600
2601 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002602 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002603 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 return OK;
2605}
2606
2607#ifdef FEAT_MBYTE
2608/*
2609 * Find next fileencoding to use from 'fileencodings'.
2610 * "pp" points to fenc_next. It's advanced to the next item.
2611 * When there are no more items, an empty string is returned and *pp is set to
2612 * NULL.
2613 * When *pp is not set to NULL, the result is in allocated memory.
2614 */
2615 static char_u *
2616next_fenc(pp)
2617 char_u **pp;
2618{
2619 char_u *p;
2620 char_u *r;
2621
2622 if (**pp == NUL)
2623 {
2624 *pp = NULL;
2625 return (char_u *)"";
2626 }
2627 p = vim_strchr(*pp, ',');
2628 if (p == NULL)
2629 {
2630 r = enc_canonize(*pp);
2631 *pp += STRLEN(*pp);
2632 }
2633 else
2634 {
2635 r = vim_strnsave(*pp, (int)(p - *pp));
2636 *pp = p + 1;
2637 if (r != NULL)
2638 {
2639 p = enc_canonize(r);
2640 vim_free(r);
2641 r = p;
2642 }
2643 }
2644 if (r == NULL) /* out of memory */
2645 {
2646 r = (char_u *)"";
2647 *pp = NULL;
2648 }
2649 return r;
2650}
2651
2652# ifdef FEAT_EVAL
2653/*
2654 * Convert a file with the 'charconvert' expression.
2655 * This closes the file which is to be read, converts it and opens the
2656 * resulting file for reading.
2657 * Returns name of the resulting converted file (the caller should delete it
2658 * after reading it).
2659 * Returns NULL if the conversion failed ("*fdp" is not set) .
2660 */
2661 static char_u *
2662readfile_charconvert(fname, fenc, fdp)
2663 char_u *fname; /* name of input file */
2664 char_u *fenc; /* converted from */
2665 int *fdp; /* in/out: file descriptor of file */
2666{
2667 char_u *tmpname;
2668 char_u *errmsg = NULL;
2669
2670 tmpname = vim_tempname('r');
2671 if (tmpname == NULL)
2672 errmsg = (char_u *)_("Can't find temp file for conversion");
2673 else
2674 {
2675 close(*fdp); /* close the input file, ignore errors */
2676 *fdp = -1;
2677 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2678 fname, tmpname) == FAIL)
2679 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2680 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2681 O_RDONLY | O_EXTRA, 0)) < 0)
2682 errmsg = (char_u *)_("can't read output of 'charconvert'");
2683 }
2684
2685 if (errmsg != NULL)
2686 {
2687 /* Don't use emsg(), it breaks mappings, the retry with
2688 * another type of conversion might still work. */
2689 MSG(errmsg);
2690 if (tmpname != NULL)
2691 {
2692 mch_remove(tmpname); /* delete converted file */
2693 vim_free(tmpname);
2694 tmpname = NULL;
2695 }
2696 }
2697
2698 /* If the input file is closed, open it (caller should check for error). */
2699 if (*fdp < 0)
2700 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2701
2702 return tmpname;
2703}
2704# endif
2705
2706#endif
2707
2708#ifdef FEAT_VIMINFO
2709/*
2710 * Read marks for the current buffer from the viminfo file, when we support
2711 * buffer marks and the buffer has a name.
2712 */
2713 static void
2714check_marks_read()
2715{
2716 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2717 && curbuf->b_ffname != NULL)
2718 read_viminfo(NULL, FALSE, TRUE, FALSE);
2719
2720 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2721 * the ' parameter after opening a buffer. */
2722 curbuf->b_marks_read = TRUE;
2723}
2724#endif
2725
2726#ifdef FEAT_CRYPT
2727/*
2728 * Check for magic number used for encryption.
2729 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2730 * *filesizep are updated.
2731 * Return the (new) encryption key, NULL for no encryption.
2732 */
2733 static char_u *
2734check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile)
2735 char_u *cryptkey; /* previous encryption key or NULL */
2736 char_u *ptr; /* pointer to read bytes */
2737 long *sizep; /* length of read bytes */
2738 long *filesizep; /* nr of bytes used from file */
2739 int newfile; /* editing a new buffer */
2740{
2741 if (*sizep >= CRYPT_MAGIC_LEN
2742 && STRNCMP(ptr, CRYPT_MAGIC, CRYPT_MAGIC_LEN) == 0)
2743 {
2744 if (cryptkey == NULL)
2745 {
2746 if (*curbuf->b_p_key)
2747 cryptkey = curbuf->b_p_key;
2748 else
2749 {
2750 /* When newfile is TRUE, store the typed key
2751 * in the 'key' option and don't free it. */
2752 cryptkey = get_crypt_key(newfile, FALSE);
2753 /* check if empty key entered */
2754 if (cryptkey != NULL && *cryptkey == NUL)
2755 {
2756 if (cryptkey != curbuf->b_p_key)
2757 vim_free(cryptkey);
2758 cryptkey = NULL;
2759 }
2760 }
2761 }
2762
2763 if (cryptkey != NULL)
2764 {
2765 crypt_init_keys(cryptkey);
2766
2767 /* Remove magic number from the text */
2768 *filesizep += CRYPT_MAGIC_LEN;
2769 *sizep -= CRYPT_MAGIC_LEN;
2770 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN, (size_t)*sizep);
2771 }
2772 }
2773 /* When starting to edit a new file which does not have
2774 * encryption, clear the 'key' option, except when
2775 * starting up (called with -x argument) */
2776 else if (newfile && *curbuf->b_p_key && !starting)
2777 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2778
2779 return cryptkey;
2780}
2781#endif
2782
2783#ifdef UNIX
2784 static void
2785set_file_time(fname, atime, mtime)
2786 char_u *fname;
2787 time_t atime; /* access time */
2788 time_t mtime; /* modification time */
2789{
2790# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2791 struct utimbuf buf;
2792
2793 buf.actime = atime;
2794 buf.modtime = mtime;
2795 (void)utime((char *)fname, &buf);
2796# else
2797# if defined(HAVE_UTIMES)
2798 struct timeval tvp[2];
2799
2800 tvp[0].tv_sec = atime;
2801 tvp[0].tv_usec = 0;
2802 tvp[1].tv_sec = mtime;
2803 tvp[1].tv_usec = 0;
2804# ifdef NeXT
2805 (void)utimes((char *)fname, tvp);
2806# else
2807 (void)utimes((char *)fname, (const struct timeval *)&tvp);
2808# endif
2809# endif
2810# endif
2811}
2812#endif /* UNIX */
2813
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002814#if defined(VMS) && !defined(MIN)
2815/* Older DECC compiler for VAX doesn't define MIN() */
2816# define MIN(a, b) ((a) < (b) ? (a) : (b))
2817#endif
2818
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00002820 * Return TRUE if a file appears to be read-only from the file permissions.
2821 */
2822 int
2823check_file_readonly(fname, perm)
2824 char_u *fname; /* full path to file */
2825 int perm; /* known permissions on file */
2826{
2827#ifndef USE_MCH_ACCESS
2828 int fd = 0;
2829#endif
2830
2831 return (
2832#ifdef USE_MCH_ACCESS
2833# ifdef UNIX
2834 (perm & 0222) == 0 ||
2835# endif
2836 mch_access((char *)fname, W_OK)
2837#else
2838 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
2839 ? TRUE : (close(fd), FALSE)
2840#endif
2841 );
2842}
2843
2844
2845/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00002846 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847 *
2848 * We do our own buffering here because fwrite() is so slow.
2849 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00002850 * If "forceit" is true, we don't care for errors when attempting backups.
2851 * In case of an error everything possible is done to restore the original
2852 * file. But when "forceit" is TRUE, we risk loosing it.
2853 *
2854 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
2855 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 *
2857 * This function must NOT use NameBuff (because it's called by autowrite()).
2858 *
2859 * return FAIL for failure, OK otherwise
2860 */
2861 int
2862buf_write(buf, fname, sfname, start, end, eap, append, forceit,
2863 reset_changed, filtering)
2864 buf_T *buf;
2865 char_u *fname;
2866 char_u *sfname;
2867 linenr_T start, end;
2868 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
2869 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00002870 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 int forceit;
2872 int reset_changed;
2873 int filtering;
2874{
2875 int fd;
2876 char_u *backup = NULL;
2877 int backup_copy = FALSE; /* copy the original file? */
2878 int dobackup;
2879 char_u *ffname;
2880 char_u *wfname = NULL; /* name of file to write to */
2881 char_u *s;
2882 char_u *ptr;
2883 char_u c;
2884 int len;
2885 linenr_T lnum;
2886 long nchars;
2887 char_u *errmsg = NULL;
2888 char_u *errnum = NULL;
2889 char_u *buffer;
2890 char_u smallbuf[SMBUFSIZE];
2891 char_u *backup_ext;
2892 int bufsize;
2893 long perm; /* file permissions */
2894 int retval = OK;
2895 int newfile = FALSE; /* TRUE if file doesn't exist yet */
2896 int msg_save = msg_scroll;
2897 int overwriting; /* TRUE if writing over original */
2898 int no_eol = FALSE; /* no end-of-line written */
2899 int device = FALSE; /* writing to a device */
2900 struct stat st_old;
2901 int prev_got_int = got_int;
2902 int file_readonly = FALSE; /* overwritten file is read-only */
2903 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
2904#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
2905 int made_writable = FALSE; /* 'w' bit has been set */
2906#endif
2907 /* writing everything */
2908 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
2909#ifdef FEAT_AUTOCMD
2910 linenr_T old_line_count = buf->b_ml.ml_line_count;
2911#endif
2912 int attr;
2913 int fileformat;
2914 int write_bin;
2915 struct bw_info write_info; /* info for buf_write_bytes() */
2916#ifdef FEAT_MBYTE
2917 int converted = FALSE;
2918 int notconverted = FALSE;
2919 char_u *fenc; /* effective 'fileencoding' */
2920 char_u *fenc_tofree = NULL; /* allocated "fenc" */
2921#endif
2922#ifdef HAS_BW_FLAGS
2923 int wb_flags = 0;
2924#endif
2925#ifdef HAVE_ACL
2926 vim_acl_T acl = NULL; /* ACL copied from original file to
2927 backup or new file */
2928#endif
2929
2930 if (fname == NULL || *fname == NUL) /* safety check */
2931 return FAIL;
2932
2933 /*
2934 * Disallow writing from .exrc and .vimrc in current directory for
2935 * security reasons.
2936 */
2937 if (check_secure())
2938 return FAIL;
2939
2940 /* Avoid a crash for a long name. */
2941 if (STRLEN(fname) >= MAXPATHL)
2942 {
2943 EMSG(_(e_longname));
2944 return FAIL;
2945 }
2946
2947#ifdef FEAT_MBYTE
2948 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
2949 write_info.bw_conv_buf = NULL;
2950 write_info.bw_conv_error = FALSE;
2951 write_info.bw_restlen = 0;
2952# ifdef USE_ICONV
2953 write_info.bw_iconv_fd = (iconv_t)-1;
2954# endif
2955#endif
2956
Bram Moolenaardf177f62005-02-22 08:39:57 +00002957 /* After writing a file changedtick changes but we don't want to display
2958 * the line. */
2959 ex_no_reprint = TRUE;
2960
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 /*
2962 * If there is no file name yet, use the one for the written file.
2963 * BF_NOTEDITED is set to reflect this (in case the write fails).
2964 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00002965 * Don't do this when appending.
2966 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002968 if (buf->b_ffname == NULL
2969 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 && whole
2971 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002972#ifdef FEAT_QUICKFIX
2973 && !bt_nofile(buf)
2974#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00002976 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
2978 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002979 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002981 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 }
2983
2984 if (sfname == NULL)
2985 sfname = fname;
2986 /*
2987 * For Unix: Use the short file name whenever possible.
2988 * Avoids problems with networks and when directory names are changed.
2989 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
2990 * another directory, which we don't detect
2991 */
2992 ffname = fname; /* remember full fname */
2993#ifdef UNIX
2994 fname = sfname;
2995#endif
2996
2997 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
2998 overwriting = TRUE;
2999 else
3000 overwriting = FALSE;
3001
3002 if (exiting)
3003 settmode(TMODE_COOK); /* when exiting allow typahead now */
3004
3005 ++no_wait_return; /* don't wait for return yet */
3006
3007 /*
3008 * Set '[ and '] marks to the lines to be written.
3009 */
3010 buf->b_op_start.lnum = start;
3011 buf->b_op_start.col = 0;
3012 buf->b_op_end.lnum = end;
3013 buf->b_op_end.col = 0;
3014
3015#ifdef FEAT_AUTOCMD
3016 {
3017 aco_save_T aco;
3018 int buf_ffname = FALSE;
3019 int buf_sfname = FALSE;
3020 int buf_fname_f = FALSE;
3021 int buf_fname_s = FALSE;
3022 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003023 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003024 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025
3026 /*
3027 * Apply PRE aucocommands.
3028 * Set curbuf to the buffer to be written.
3029 * Careful: The autocommands may call buf_write() recursively!
3030 */
3031 if (ffname == buf->b_ffname)
3032 buf_ffname = TRUE;
3033 if (sfname == buf->b_sfname)
3034 buf_sfname = TRUE;
3035 if (fname == buf->b_ffname)
3036 buf_fname_f = TRUE;
3037 if (fname == buf->b_sfname)
3038 buf_fname_s = TRUE;
3039
3040 /* set curwin/curbuf to buf and save a few things */
3041 aucmd_prepbuf(&aco, buf);
3042
3043 if (append)
3044 {
3045 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3046 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003047 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003048#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003049 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003050 nofile_err = TRUE;
3051 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003052#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003053 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003055 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 }
3057 else if (filtering)
3058 {
3059 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3060 NULL, sfname, FALSE, curbuf, eap);
3061 }
3062 else if (reset_changed && whole)
3063 {
3064 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3065 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003066 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003067#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003068 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003069 nofile_err = TRUE;
3070 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003071#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003072 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 }
3076 else
3077 {
3078 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3079 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003080 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003081#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003082 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003083 nofile_err = TRUE;
3084 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003085#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003086 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003088 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 }
3090
3091 /* restore curwin/curbuf and a few other things */
3092 aucmd_restbuf(&aco);
3093
3094 /*
3095 * In three situations we return here and don't write the file:
3096 * 1. the autocommands deleted or unloaded the buffer.
3097 * 2. The autocommands abort script processing.
3098 * 3. If one of the "Cmd" autocommands was executed.
3099 */
3100 if (!buf_valid(buf))
3101 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003102 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003103 || did_cmd || nofile_err
3104#ifdef FEAT_EVAL
3105 || aborting()
3106#endif
3107 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 {
3109 --no_wait_return;
3110 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003111 if (nofile_err)
3112 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3113
Bram Moolenaar1e015462005-09-25 22:16:38 +00003114 if (nofile_err
3115#ifdef FEAT_EVAL
3116 || aborting()
3117#endif
3118 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 /* An aborting error, interrupt or exception in the
3120 * autocommands. */
3121 return FAIL;
3122 if (did_cmd)
3123 {
3124 if (buf == NULL)
3125 /* The buffer was deleted. We assume it was written
3126 * (can't retry anyway). */
3127 return OK;
3128 if (overwriting)
3129 {
3130 /* Assume the buffer was written, update the timestamp. */
3131 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003132 if (append)
3133 buf->b_flags &= ~BF_NEW;
3134 else
3135 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003137 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003138 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 /* Buffer still changed, the autocommands didn't work
3140 * properly. */
3141 return FAIL;
3142 return OK;
3143 }
3144#ifdef FEAT_EVAL
3145 if (!aborting())
3146#endif
3147 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3148 return FAIL;
3149 }
3150
3151 /*
3152 * The autocommands may have changed the number of lines in the file.
3153 * When writing the whole file, adjust the end.
3154 * When writing part of the file, assume that the autocommands only
3155 * changed the number of lines that are to be written (tricky!).
3156 */
3157 if (buf->b_ml.ml_line_count != old_line_count)
3158 {
3159 if (whole) /* write all */
3160 end = buf->b_ml.ml_line_count;
3161 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3162 end += buf->b_ml.ml_line_count - old_line_count;
3163 else /* less lines */
3164 {
3165 end -= old_line_count - buf->b_ml.ml_line_count;
3166 if (end < start)
3167 {
3168 --no_wait_return;
3169 msg_scroll = msg_save;
3170 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3171 return FAIL;
3172 }
3173 }
3174 }
3175
3176 /*
3177 * The autocommands may have changed the name of the buffer, which may
3178 * be kept in fname, ffname and sfname.
3179 */
3180 if (buf_ffname)
3181 ffname = buf->b_ffname;
3182 if (buf_sfname)
3183 sfname = buf->b_sfname;
3184 if (buf_fname_f)
3185 fname = buf->b_ffname;
3186 if (buf_fname_s)
3187 fname = buf->b_sfname;
3188 }
3189#endif
3190
3191#ifdef FEAT_NETBEANS_INTG
3192 if (usingNetbeans && isNetbeansBuffer(buf))
3193 {
3194 if (whole)
3195 {
3196 /*
3197 * b_changed can be 0 after an undo, but we still need to write
3198 * the buffer to NetBeans.
3199 */
3200 if (buf->b_changed || isNetbeansModified(buf))
3201 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003202 --no_wait_return; /* may wait for return now */
3203 msg_scroll = msg_save;
3204 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205 return retval;
3206 }
3207 else
3208 {
3209 errnum = (char_u *)"E656: ";
3210 errmsg = (char_u *)_("NetBeans dissallows writes of unmodified buffers");
3211 buffer = NULL;
3212 goto fail;
3213 }
3214 }
3215 else
3216 {
3217 errnum = (char_u *)"E657: ";
3218 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3219 buffer = NULL;
3220 goto fail;
3221 }
3222 }
3223#endif
3224
3225 if (shortmess(SHM_OVER) && !exiting)
3226 msg_scroll = FALSE; /* overwrite previous file message */
3227 else
3228 msg_scroll = TRUE; /* don't overwrite previous file message */
3229 if (!filtering)
3230 filemess(buf,
3231#ifndef UNIX
3232 sfname,
3233#else
3234 fname,
3235#endif
3236 (char_u *)"", 0); /* show that we are busy */
3237 msg_scroll = FALSE; /* always overwrite the file message now */
3238
3239 buffer = alloc(BUFSIZE);
3240 if (buffer == NULL) /* can't allocate big buffer, use small
3241 * one (to be able to write when out of
3242 * memory) */
3243 {
3244 buffer = smallbuf;
3245 bufsize = SMBUFSIZE;
3246 }
3247 else
3248 bufsize = BUFSIZE;
3249
3250 /*
3251 * Get information about original file (if there is one).
3252 */
3253#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003254 st_old.st_dev = 0;
3255 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 perm = -1;
3257 if (mch_stat((char *)fname, &st_old) < 0)
3258 newfile = TRUE;
3259 else
3260 {
3261 perm = st_old.st_mode;
3262 if (!S_ISREG(st_old.st_mode)) /* not a file */
3263 {
3264 if (S_ISDIR(st_old.st_mode))
3265 {
3266 errnum = (char_u *)"E502: ";
3267 errmsg = (char_u *)_("is a directory");
3268 goto fail;
3269 }
3270 if (mch_nodetype(fname) != NODE_WRITABLE)
3271 {
3272 errnum = (char_u *)"E503: ";
3273 errmsg = (char_u *)_("is not a file or writable device");
3274 goto fail;
3275 }
3276 /* It's a device of some kind (or a fifo) which we can write to
3277 * but for which we can't make a backup. */
3278 device = TRUE;
3279 newfile = TRUE;
3280 perm = -1;
3281 }
3282 }
3283#else /* !UNIX */
3284 /*
3285 * Check for a writable device name.
3286 */
3287 c = mch_nodetype(fname);
3288 if (c == NODE_OTHER)
3289 {
3290 errnum = (char_u *)"E503: ";
3291 errmsg = (char_u *)_("is not a file or writable device");
3292 goto fail;
3293 }
3294 if (c == NODE_WRITABLE)
3295 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003296# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3297 /* MS-Windows allows opening a device, but we will probably get stuck
3298 * trying to write to it. */
3299 if (!p_odev)
3300 {
3301 errnum = (char_u *)"E796: ";
3302 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3303 goto fail;
3304 }
3305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306 device = TRUE;
3307 newfile = TRUE;
3308 perm = -1;
3309 }
3310 else
3311 {
3312 perm = mch_getperm(fname);
3313 if (perm < 0)
3314 newfile = TRUE;
3315 else if (mch_isdir(fname))
3316 {
3317 errnum = (char_u *)"E502: ";
3318 errmsg = (char_u *)_("is a directory");
3319 goto fail;
3320 }
3321 if (overwriting)
3322 (void)mch_stat((char *)fname, &st_old);
3323 }
3324#endif /* !UNIX */
3325
3326 if (!device && !newfile)
3327 {
3328 /*
3329 * Check if the file is really writable (when renaming the file to
3330 * make a backup we won't discover it later).
3331 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003332 file_readonly = check_file_readonly(fname, (int)perm);
3333
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 if (!forceit && file_readonly)
3335 {
3336 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3337 {
3338 errnum = (char_u *)"E504: ";
3339 errmsg = (char_u *)_(err_readonly);
3340 }
3341 else
3342 {
3343 errnum = (char_u *)"E505: ";
3344 errmsg = (char_u *)_("is read-only (add ! to override)");
3345 }
3346 goto fail;
3347 }
3348
3349 /*
3350 * Check if the timestamp hasn't changed since reading the file.
3351 */
3352 if (overwriting)
3353 {
3354 retval = check_mtime(buf, &st_old);
3355 if (retval == FAIL)
3356 goto fail;
3357 }
3358 }
3359
3360#ifdef HAVE_ACL
3361 /*
3362 * For systems that support ACL: get the ACL from the original file.
3363 */
3364 if (!newfile)
3365 acl = mch_get_acl(fname);
3366#endif
3367
3368 /*
3369 * If 'backupskip' is not empty, don't make a backup for some files.
3370 */
3371 dobackup = (p_wb || p_bk || *p_pm != NUL);
3372#ifdef FEAT_WILDIGN
3373 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3374 dobackup = FALSE;
3375#endif
3376
3377 /*
3378 * Save the value of got_int and reset it. We don't want a previous
3379 * interruption cancel writing, only hitting CTRL-C while writing should
3380 * abort it.
3381 */
3382 prev_got_int = got_int;
3383 got_int = FALSE;
3384
3385 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3386 buf->b_saving = TRUE;
3387
3388 /*
3389 * If we are not appending or filtering, the file exists, and the
3390 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3391 * When 'patchmode' is set also make a backup when appending.
3392 *
3393 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3394 * off. This helps when editing large files on almost-full disks.
3395 */
3396 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3397 {
3398#if defined(UNIX) || defined(WIN32)
3399 struct stat st;
3400#endif
3401
3402 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3403 backup_copy = TRUE;
3404#if defined(UNIX) || defined(WIN32)
3405 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3406 {
3407 int i;
3408
3409# ifdef UNIX
3410 /*
3411 * Don't rename the file when:
3412 * - it's a hard link
3413 * - it's a symbolic link
3414 * - we don't have write permission in the directory
3415 * - we can't set the owner/group of the new file
3416 */
3417 if (st_old.st_nlink > 1
3418 || mch_lstat((char *)fname, &st) < 0
3419 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003420 || st.st_ino != st_old.st_ino
3421# ifndef HAVE_FCHOWN
3422 || st.st_uid != st_old.st_uid
3423 || st.st_gid != st_old.st_gid
3424# endif
3425 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 backup_copy = TRUE;
3427 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003428# else
3429# ifdef WIN32
3430 /* On NTFS file systems hard links are possible. */
3431 if (mch_is_linked(fname))
3432 backup_copy = TRUE;
3433 else
3434# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435# endif
3436 {
3437 /*
3438 * Check if we can create a file and set the owner/group to
3439 * the ones from the original file.
3440 * First find a file name that doesn't exist yet (use some
3441 * arbitrary numbers).
3442 */
3443 STRCPY(IObuff, fname);
3444 for (i = 4913; ; i += 123)
3445 {
3446 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003447 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 break;
3449 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003450 fd = mch_open((char *)IObuff,
3451 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452 if (fd < 0) /* can't write in directory */
3453 backup_copy = TRUE;
3454 else
3455 {
3456# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003457# ifdef HAVE_FCHOWN
3458 fchown(fd, st_old.st_uid, st_old.st_gid);
3459# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 if (mch_stat((char *)IObuff, &st) < 0
3461 || st.st_uid != st_old.st_uid
3462 || st.st_gid != st_old.st_gid
3463 || st.st_mode != perm)
3464 backup_copy = TRUE;
3465# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003466 /* Close the file before removing it, on MS-Windows we
3467 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003468 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003469 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470 }
3471 }
3472 }
3473
3474# ifdef UNIX
3475 /*
3476 * Break symlinks and/or hardlinks if we've been asked to.
3477 */
3478 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3479 {
3480 int lstat_res;
3481
3482 lstat_res = mch_lstat((char *)fname, &st);
3483
3484 /* Symlinks. */
3485 if ((bkc_flags & BKC_BREAKSYMLINK)
3486 && lstat_res == 0
3487 && st.st_ino != st_old.st_ino)
3488 backup_copy = FALSE;
3489
3490 /* Hardlinks. */
3491 if ((bkc_flags & BKC_BREAKHARDLINK)
3492 && st_old.st_nlink > 1
3493 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3494 backup_copy = FALSE;
3495 }
3496#endif
3497
3498#endif
3499
3500 /* make sure we have a valid backup extension to use */
3501 if (*p_bex == NUL)
3502 {
3503#ifdef RISCOS
3504 backup_ext = (char_u *)"/bak";
3505#else
3506 backup_ext = (char_u *)".bak";
3507#endif
3508 }
3509 else
3510 backup_ext = p_bex;
3511
3512 if (backup_copy
3513 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3514 {
3515 int bfd;
3516 char_u *copybuf, *wp;
3517 int some_error = FALSE;
3518 struct stat st_new;
3519 char_u *dirp;
3520 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003521#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522 int did_set_shortname;
3523#endif
3524
3525 copybuf = alloc(BUFSIZE + 1);
3526 if (copybuf == NULL)
3527 {
3528 some_error = TRUE; /* out of memory */
3529 goto nobackup;
3530 }
3531
3532 /*
3533 * Try to make the backup in each directory in the 'bdir' option.
3534 *
3535 * Unix semantics has it, that we may have a writable file,
3536 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3537 * - the directory is not writable,
3538 * - the file may be a symbolic link,
3539 * - the file may belong to another user/group, etc.
3540 *
3541 * For these reasons, the existing writable file must be truncated
3542 * and reused. Creation of a backup COPY will be attempted.
3543 */
3544 dirp = p_bdir;
3545 while (*dirp)
3546 {
3547#ifdef UNIX
3548 st_new.st_ino = 0;
3549 st_new.st_dev = 0;
3550 st_new.st_gid = 0;
3551#endif
3552
3553 /*
3554 * Isolate one directory name, using an entry in 'bdir'.
3555 */
3556 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3557 rootname = get_file_in_dir(fname, copybuf);
3558 if (rootname == NULL)
3559 {
3560 some_error = TRUE; /* out of memory */
3561 goto nobackup;
3562 }
3563
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003564#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565 did_set_shortname = FALSE;
3566#endif
3567
3568 /*
3569 * May try twice if 'shortname' not set.
3570 */
3571 for (;;)
3572 {
3573 /*
3574 * Make backup file name.
3575 */
3576 backup = buf_modname(
3577#ifdef SHORT_FNAME
3578 TRUE,
3579#else
3580 (buf->b_p_sn || buf->b_shortname),
3581#endif
3582 rootname, backup_ext, FALSE);
3583 if (backup == NULL)
3584 {
3585 vim_free(rootname);
3586 some_error = TRUE; /* out of memory */
3587 goto nobackup;
3588 }
3589
3590 /*
3591 * Check if backup file already exists.
3592 */
3593 if (mch_stat((char *)backup, &st_new) >= 0)
3594 {
3595#ifdef UNIX
3596 /*
3597 * Check if backup file is same as original file.
3598 * May happen when modname() gave the same file back.
3599 * E.g. silly link, or file name-length reached.
3600 * If we don't check here, we either ruin the file
3601 * when copying or erase it after writing. jw.
3602 */
3603 if (st_new.st_dev == st_old.st_dev
3604 && st_new.st_ino == st_old.st_ino)
3605 {
3606 vim_free(backup);
3607 backup = NULL; /* no backup file to delete */
3608# ifndef SHORT_FNAME
3609 /*
3610 * may try again with 'shortname' set
3611 */
3612 if (!(buf->b_shortname || buf->b_p_sn))
3613 {
3614 buf->b_shortname = TRUE;
3615 did_set_shortname = TRUE;
3616 continue;
3617 }
3618 /* setting shortname didn't help */
3619 if (did_set_shortname)
3620 buf->b_shortname = FALSE;
3621# endif
3622 break;
3623 }
3624#endif
3625
3626 /*
3627 * If we are not going to keep the backup file, don't
3628 * delete an existing one, try to use another name.
3629 * Change one character, just before the extension.
3630 */
3631 if (!p_bk)
3632 {
3633 wp = backup + STRLEN(backup) - 1
3634 - STRLEN(backup_ext);
3635 if (wp < backup) /* empty file name ??? */
3636 wp = backup;
3637 *wp = 'z';
3638 while (*wp > 'a'
3639 && mch_stat((char *)backup, &st_new) >= 0)
3640 --*wp;
3641 /* They all exist??? Must be something wrong. */
3642 if (*wp == 'a')
3643 {
3644 vim_free(backup);
3645 backup = NULL;
3646 }
3647 }
3648 }
3649 break;
3650 }
3651 vim_free(rootname);
3652
3653 /*
3654 * Try to create the backup file
3655 */
3656 if (backup != NULL)
3657 {
3658 /* remove old backup, if present */
3659 mch_remove(backup);
3660 /* Open with O_EXCL to avoid the file being created while
3661 * we were sleeping (symlink hacker attack?) */
3662 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003663 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3664 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665 if (bfd < 0)
3666 {
3667 vim_free(backup);
3668 backup = NULL;
3669 }
3670 else
3671 {
3672 /* set file protection same as original file, but
3673 * strip s-bit */
3674 (void)mch_setperm(backup, perm & 0777);
3675
3676#ifdef UNIX
3677 /*
3678 * Try to set the group of the backup same as the
3679 * original file. If this fails, set the protection
3680 * bits for the group same as the protection bits for
3681 * others.
3682 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003683 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003685 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686# endif
3687 )
3688 mch_setperm(backup,
3689 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003690# ifdef HAVE_SELINUX
3691 mch_copy_sec(fname, backup);
3692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693#endif
3694
3695 /*
3696 * copy the file.
3697 */
3698 write_info.bw_fd = bfd;
3699 write_info.bw_buf = copybuf;
3700#ifdef HAS_BW_FLAGS
3701 write_info.bw_flags = FIO_NOCONVERT;
3702#endif
3703 while ((write_info.bw_len = vim_read(fd, copybuf,
3704 BUFSIZE)) > 0)
3705 {
3706 if (buf_write_bytes(&write_info) == FAIL)
3707 {
3708 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3709 break;
3710 }
3711 ui_breakcheck();
3712 if (got_int)
3713 {
3714 errmsg = (char_u *)_(e_interr);
3715 break;
3716 }
3717 }
3718
3719 if (close(bfd) < 0 && errmsg == NULL)
3720 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3721 if (write_info.bw_len < 0)
3722 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3723#ifdef UNIX
3724 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3725#endif
3726#ifdef HAVE_ACL
3727 mch_set_acl(backup, acl);
3728#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003729#ifdef HAVE_SELINUX
3730 mch_copy_sec(fname, backup);
3731#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 break;
3733 }
3734 }
3735 }
3736 nobackup:
3737 close(fd); /* ignore errors for closing read file */
3738 vim_free(copybuf);
3739
3740 if (backup == NULL && errmsg == NULL)
3741 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3742 /* ignore errors when forceit is TRUE */
3743 if ((some_error || errmsg != NULL) && !forceit)
3744 {
3745 retval = FAIL;
3746 goto fail;
3747 }
3748 errmsg = NULL;
3749 }
3750 else
3751 {
3752 char_u *dirp;
3753 char_u *p;
3754 char_u *rootname;
3755
3756 /*
3757 * Make a backup by renaming the original file.
3758 */
3759 /*
3760 * If 'cpoptions' includes the "W" flag, we don't want to
3761 * overwrite a read-only file. But rename may be possible
3762 * anyway, thus we need an extra check here.
3763 */
3764 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3765 {
3766 errnum = (char_u *)"E504: ";
3767 errmsg = (char_u *)_(err_readonly);
3768 goto fail;
3769 }
3770
3771 /*
3772 *
3773 * Form the backup file name - change path/fo.o.h to
3774 * path/fo.o.h.bak Try all directories in 'backupdir', first one
3775 * that works is used.
3776 */
3777 dirp = p_bdir;
3778 while (*dirp)
3779 {
3780 /*
3781 * Isolate one directory name and make the backup file name.
3782 */
3783 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
3784 rootname = get_file_in_dir(fname, IObuff);
3785 if (rootname == NULL)
3786 backup = NULL;
3787 else
3788 {
3789 backup = buf_modname(
3790#ifdef SHORT_FNAME
3791 TRUE,
3792#else
3793 (buf->b_p_sn || buf->b_shortname),
3794#endif
3795 rootname, backup_ext, FALSE);
3796 vim_free(rootname);
3797 }
3798
3799 if (backup != NULL)
3800 {
3801 /*
3802 * If we are not going to keep the backup file, don't
3803 * delete an existing one, try to use another name.
3804 * Change one character, just before the extension.
3805 */
3806 if (!p_bk && mch_getperm(backup) >= 0)
3807 {
3808 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
3809 if (p < backup) /* empty file name ??? */
3810 p = backup;
3811 *p = 'z';
3812 while (*p > 'a' && mch_getperm(backup) >= 0)
3813 --*p;
3814 /* They all exist??? Must be something wrong! */
3815 if (*p == 'a')
3816 {
3817 vim_free(backup);
3818 backup = NULL;
3819 }
3820 }
3821 }
3822 if (backup != NULL)
3823 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003825 * Delete any existing backup and move the current version
3826 * to the backup. For safety, we don't remove the backup
3827 * until the write has finished successfully. And if the
3828 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829 */
3830 /*
3831 * If the renaming of the original file to the backup file
3832 * works, quit here.
3833 */
3834 if (vim_rename(fname, backup) == 0)
3835 break;
3836
3837 vim_free(backup); /* don't do the rename below */
3838 backup = NULL;
3839 }
3840 }
3841 if (backup == NULL && !forceit)
3842 {
3843 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
3844 goto fail;
3845 }
3846 }
3847 }
3848
3849#if defined(UNIX) && !defined(ARCHIE)
3850 /* When using ":w!" and the file was read-only: make it writable */
3851 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
3852 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
3853 {
3854 perm |= 0200;
3855 (void)mch_setperm(fname, perm);
3856 made_writable = TRUE;
3857 }
3858#endif
3859
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003860 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003861 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
3862 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 {
3864 buf->b_p_ro = FALSE;
3865#ifdef FEAT_TITLE
3866 need_maketitle = TRUE; /* set window title later */
3867#endif
3868#ifdef FEAT_WINDOWS
3869 status_redraw_all(); /* redraw status lines later */
3870#endif
3871 }
3872
3873 if (end > buf->b_ml.ml_line_count)
3874 end = buf->b_ml.ml_line_count;
3875 if (buf->b_ml.ml_flags & ML_EMPTY)
3876 start = end + 1;
3877
3878 /*
3879 * If the original file is being overwritten, there is a small chance that
3880 * we crash in the middle of writing. Therefore the file is preserved now.
3881 * This makes all block numbers positive so that recovery does not need
3882 * the original file.
3883 * Don't do this if there is a backup file and we are exiting.
3884 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003885 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 && !(exiting && backup != NULL))
3887 {
3888 ml_preserve(buf, FALSE);
3889 if (got_int)
3890 {
3891 errmsg = (char_u *)_(e_interr);
3892 goto restore_backup;
3893 }
3894 }
3895
3896#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
3897 /*
3898 * Before risking to lose the original file verify if there's
3899 * a resource fork to preserve, and if cannot be done warn
3900 * the users. This happens when overwriting without backups.
3901 */
3902 if (backup == NULL && overwriting && !append)
3903 if (mch_has_resource_fork(fname))
3904 {
3905 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
3906 goto restore_backup;
3907 }
3908#endif
3909
3910#ifdef VMS
3911 vms_remove_version(fname); /* remove version */
3912#endif
3913 /* Default: write the the file directly. May write to a temp file for
3914 * multi-byte conversion. */
3915 wfname = fname;
3916
3917#ifdef FEAT_MBYTE
3918 /* Check for forced 'fileencoding' from "++opt=val" argument. */
3919 if (eap != NULL && eap->force_enc != 0)
3920 {
3921 fenc = eap->cmd + eap->force_enc;
3922 fenc = enc_canonize(fenc);
3923 fenc_tofree = fenc;
3924 }
3925 else
3926 fenc = buf->b_p_fenc;
3927
3928 /*
3929 * The file needs to be converted when 'fileencoding' is set and
3930 * 'fileencoding' differs from 'encoding'.
3931 */
3932 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
3933
3934 /*
3935 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
3936 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
3937 * Prepare the flags for it and allocate bw_conv_buf when needed.
3938 */
3939 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
3940 {
3941 wb_flags = get_fio_flags(fenc);
3942 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
3943 {
3944 /* Need to allocate a buffer to translate into. */
3945 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
3946 write_info.bw_conv_buflen = bufsize * 2;
3947 else /* FIO_UCS4 */
3948 write_info.bw_conv_buflen = bufsize * 4;
3949 write_info.bw_conv_buf
3950 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3951 if (write_info.bw_conv_buf == NULL)
3952 end = 0;
3953 }
3954 }
3955
3956# ifdef WIN3264
3957 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
3958 {
3959 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
3960 write_info.bw_conv_buflen = bufsize * 4;
3961 write_info.bw_conv_buf
3962 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3963 if (write_info.bw_conv_buf == NULL)
3964 end = 0;
3965 }
3966# endif
3967
3968# ifdef MACOS_X
3969 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
3970 {
3971 write_info.bw_conv_buflen = bufsize * 3;
3972 write_info.bw_conv_buf
3973 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3974 if (write_info.bw_conv_buf == NULL)
3975 end = 0;
3976 }
3977# endif
3978
3979# if defined(FEAT_EVAL) || defined(USE_ICONV)
3980 if (converted && wb_flags == 0)
3981 {
3982# ifdef USE_ICONV
3983 /*
3984 * Use iconv() conversion when conversion is needed and it's not done
3985 * internally.
3986 */
3987 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
3988 enc_utf8 ? (char_u *)"utf-8" : p_enc);
3989 if (write_info.bw_iconv_fd != (iconv_t)-1)
3990 {
3991 /* We're going to use iconv(), allocate a buffer to convert in. */
3992 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
3993 write_info.bw_conv_buf
3994 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3995 if (write_info.bw_conv_buf == NULL)
3996 end = 0;
3997 write_info.bw_first = TRUE;
3998 }
3999# ifdef FEAT_EVAL
4000 else
4001# endif
4002# endif
4003
4004# ifdef FEAT_EVAL
4005 /*
4006 * When the file needs to be converted with 'charconvert' after
4007 * writing, write to a temp file instead and let the conversion
4008 * overwrite the original file.
4009 */
4010 if (*p_ccv != NUL)
4011 {
4012 wfname = vim_tempname('w');
4013 if (wfname == NULL) /* Can't write without a tempfile! */
4014 {
4015 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4016 goto restore_backup;
4017 }
4018 }
4019# endif
4020 }
4021# endif
4022 if (converted && wb_flags == 0
4023# ifdef USE_ICONV
4024 && write_info.bw_iconv_fd == (iconv_t)-1
4025# endif
4026# ifdef FEAT_EVAL
4027 && wfname == fname
4028# endif
4029 )
4030 {
4031 if (!forceit)
4032 {
4033 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4034 goto restore_backup;
4035 }
4036 notconverted = TRUE;
4037 }
4038#endif
4039
4040 /*
4041 * Open the file "wfname" for writing.
4042 * We may try to open the file twice: If we can't write to the
4043 * file and forceit is TRUE we delete the existing file and try to create
4044 * a new one. If this still fails we may have lost the original file!
4045 * (this may happen when the user reached his quotum for number of files).
4046 * Appending will fail if the file does not exist and forceit is FALSE.
4047 */
4048 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4049 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4050 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004051 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052 {
4053 /*
4054 * A forced write will try to create a new file if the old one is
4055 * still readonly. This may also happen when the directory is
4056 * read-only. In that case the mch_remove() will fail.
4057 */
4058 if (errmsg == NULL)
4059 {
4060#ifdef UNIX
4061 struct stat st;
4062
4063 /* Don't delete the file when it's a hard or symbolic link. */
4064 if ((!newfile && st_old.st_nlink > 1)
4065 || (mch_lstat((char *)fname, &st) == 0
4066 && (st.st_dev != st_old.st_dev
4067 || st.st_ino != st_old.st_ino)))
4068 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4069 else
4070#endif
4071 {
4072 errmsg = (char_u *)_("E212: Can't open file for writing");
4073 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4074 && perm >= 0)
4075 {
4076#ifdef UNIX
4077 /* we write to the file, thus it should be marked
4078 writable after all */
4079 if (!(perm & 0200))
4080 made_writable = TRUE;
4081 perm |= 0200;
4082 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4083 perm &= 0777;
4084#endif
4085 if (!append) /* don't remove when appending */
4086 mch_remove(wfname);
4087 continue;
4088 }
4089 }
4090 }
4091
4092restore_backup:
4093 {
4094 struct stat st;
4095
4096 /*
4097 * If we failed to open the file, we don't need a backup. Throw it
4098 * away. If we moved or removed the original file try to put the
4099 * backup in its place.
4100 */
4101 if (backup != NULL && wfname == fname)
4102 {
4103 if (backup_copy)
4104 {
4105 /*
4106 * There is a small chance that we removed the original,
4107 * try to move the copy in its place.
4108 * This may not work if the vim_rename() fails.
4109 * In that case we leave the copy around.
4110 */
4111 /* If file does not exist, put the copy in its place */
4112 if (mch_stat((char *)fname, &st) < 0)
4113 vim_rename(backup, fname);
4114 /* if original file does exist throw away the copy */
4115 if (mch_stat((char *)fname, &st) >= 0)
4116 mch_remove(backup);
4117 }
4118 else
4119 {
4120 /* try to put the original file back */
4121 vim_rename(backup, fname);
4122 }
4123 }
4124
4125 /* if original file no longer exists give an extra warning */
4126 if (!newfile && mch_stat((char *)fname, &st) < 0)
4127 end = 0;
4128 }
4129
4130#ifdef FEAT_MBYTE
4131 if (wfname != fname)
4132 vim_free(wfname);
4133#endif
4134 goto fail;
4135 }
4136 errmsg = NULL;
4137
4138#if defined(MACOS_CLASSIC) || defined(WIN3264)
4139 /* TODO: Is it need for MACOS_X? (Dany) */
4140 /*
4141 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004142 * This is done in order to preserve the resource fork and the
4143 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 */
4145 if (backup != NULL && overwriting && !append)
4146 {
4147 if (backup_copy)
4148 (void)mch_copy_file_attribute(wfname, backup);
4149 else
4150 (void)mch_copy_file_attribute(backup, wfname);
4151 }
4152
4153 if (!overwriting && !append)
4154 {
4155 if (buf->b_ffname != NULL)
4156 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004157 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 }
4159#endif
4160
4161 write_info.bw_fd = fd;
4162
4163#ifdef FEAT_CRYPT
4164 if (*buf->b_p_key && !filtering)
4165 {
4166 crypt_init_keys(buf->b_p_key);
4167 /* Write magic number, so that Vim knows that this file is encrypted
4168 * when reading it again. This also undergoes utf-8 to ucs-2/4
4169 * conversion when needed. */
4170 write_info.bw_buf = (char_u *)CRYPT_MAGIC;
4171 write_info.bw_len = CRYPT_MAGIC_LEN;
4172 write_info.bw_flags = FIO_NOCONVERT;
4173 if (buf_write_bytes(&write_info) == FAIL)
4174 end = 0;
4175 wb_flags |= FIO_ENCRYPTED;
4176 }
4177#endif
4178
4179 write_info.bw_buf = buffer;
4180 nchars = 0;
4181
4182 /* use "++bin", "++nobin" or 'binary' */
4183 if (eap != NULL && eap->force_bin != 0)
4184 write_bin = (eap->force_bin == FORCE_BIN);
4185 else
4186 write_bin = buf->b_p_bin;
4187
4188#ifdef FEAT_MBYTE
4189 /*
4190 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004191 * Skip it when appending and the file already existed, the BOM only makes
4192 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004194 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 {
4196 write_info.bw_len = make_bom(buffer, fenc);
4197 if (write_info.bw_len > 0)
4198 {
4199 /* don't convert, do encryption */
4200 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4201 if (buf_write_bytes(&write_info) == FAIL)
4202 end = 0;
4203 else
4204 nchars += write_info.bw_len;
4205 }
4206 }
4207#endif
4208
4209 write_info.bw_len = bufsize;
4210#ifdef HAS_BW_FLAGS
4211 write_info.bw_flags = wb_flags;
4212#endif
4213 fileformat = get_fileformat_force(buf, eap);
4214 s = buffer;
4215 len = 0;
4216 for (lnum = start; lnum <= end; ++lnum)
4217 {
4218 /*
4219 * The next while loop is done once for each character written.
4220 * Keep it fast!
4221 */
4222 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4223 while ((c = *++ptr) != NUL)
4224 {
4225 if (c == NL)
4226 *s = NUL; /* replace newlines with NULs */
4227 else if (c == CAR && fileformat == EOL_MAC)
4228 *s = NL; /* Mac: replace CRs with NLs */
4229 else
4230 *s = c;
4231 ++s;
4232 if (++len != bufsize)
4233 continue;
4234 if (buf_write_bytes(&write_info) == FAIL)
4235 {
4236 end = 0; /* write error: break loop */
4237 break;
4238 }
4239 nchars += bufsize;
4240 s = buffer;
4241 len = 0;
4242 }
4243 /* write failed or last line has no EOL: stop here */
4244 if (end == 0
4245 || (lnum == end
4246 && write_bin
4247 && (lnum == write_no_eol_lnum
4248 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4249 {
4250 ++lnum; /* written the line, count it */
4251 no_eol = TRUE;
4252 break;
4253 }
4254 if (fileformat == EOL_UNIX)
4255 *s++ = NL;
4256 else
4257 {
4258 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4259 if (fileformat == EOL_DOS) /* write CR-NL */
4260 {
4261 if (++len == bufsize)
4262 {
4263 if (buf_write_bytes(&write_info) == FAIL)
4264 {
4265 end = 0; /* write error: break loop */
4266 break;
4267 }
4268 nchars += bufsize;
4269 s = buffer;
4270 len = 0;
4271 }
4272 *s++ = NL;
4273 }
4274 }
4275 if (++len == bufsize && end)
4276 {
4277 if (buf_write_bytes(&write_info) == FAIL)
4278 {
4279 end = 0; /* write error: break loop */
4280 break;
4281 }
4282 nchars += bufsize;
4283 s = buffer;
4284 len = 0;
4285
4286 ui_breakcheck();
4287 if (got_int)
4288 {
4289 end = 0; /* Interrupted, break loop */
4290 break;
4291 }
4292 }
4293#ifdef VMS
4294 /*
4295 * On VMS there is a problem: newlines get added when writing blocks
4296 * at a time. Fix it by writing a line at a time.
4297 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004298 * Explanation: VAX/DECC RTL insists that records in some RMS
4299 * structures end with a newline (carriage return) character, and if
4300 * they don't it adds one.
4301 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004303 if (buf->b_fab_rfm == FAB$C_VFC
4304 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004306 int b2write;
4307
4308 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4309 ? MIN(4096, bufsize)
4310 : MIN(buf->b_fab_mrs, bufsize));
4311
4312 b2write = len;
4313 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004315 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4316 if (buf_write_bytes(&write_info) == FAIL)
4317 {
4318 end = 0;
4319 break;
4320 }
4321 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 }
4323 write_info.bw_len = bufsize;
4324 nchars += len;
4325 s = buffer;
4326 len = 0;
4327 }
4328#endif
4329 }
4330 if (len > 0 && end > 0)
4331 {
4332 write_info.bw_len = len;
4333 if (buf_write_bytes(&write_info) == FAIL)
4334 end = 0; /* write error */
4335 nchars += len;
4336 }
4337
4338#if defined(UNIX) && defined(HAVE_FSYNC)
4339 /* On many journalling file systems there is a bug that causes both the
4340 * original and the backup file to be lost when halting the system right
4341 * after writing the file. That's because only the meta-data is
4342 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004343 * been written to disk and we don't lose it.
4344 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004345 * (could be a pipe).
4346 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4347 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348 {
4349 errmsg = (char_u *)_("E667: Fsync failed");
4350 end = 0;
4351 }
4352#endif
4353
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004354#ifdef HAVE_SELINUX
4355 /* Probably need to set the security context. */
4356 if (!backup_copy)
4357 mch_copy_sec(backup, wfname);
4358#endif
4359
Bram Moolenaara5792f52005-11-23 21:25:05 +00004360#ifdef UNIX
4361 /* When creating a new file, set its owner/group to that of the original
4362 * file. Get the new device and inode number. */
4363 if (backup != NULL && !backup_copy)
4364 {
4365# ifdef HAVE_FCHOWN
4366 struct stat st;
4367
4368 /* don't change the owner when it's already OK, some systems remove
4369 * permission or ACL stuff */
4370 if (mch_stat((char *)wfname, &st) < 0
4371 || st.st_uid != st_old.st_uid
4372 || st.st_gid != st_old.st_gid)
4373 {
4374 fchown(fd, st_old.st_uid, st_old.st_gid);
4375 if (perm >= 0) /* set permission again, may have changed */
4376 (void)mch_setperm(wfname, perm);
4377 }
4378# endif
4379 buf_setino(buf);
4380 }
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004381 else if (buf->b_dev < 0)
4382 /* Set the inode when creating a new file. */
4383 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004384#endif
4385
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386 if (close(fd) != 0)
4387 {
4388 errmsg = (char_u *)_("E512: Close failed");
4389 end = 0;
4390 }
4391
4392#ifdef UNIX
4393 if (made_writable)
4394 perm &= ~0200; /* reset 'w' bit for security reasons */
4395#endif
4396 if (perm >= 0) /* set perm. of new file same as old file */
4397 (void)mch_setperm(wfname, perm);
4398#ifdef RISCOS
4399 if (!append && !filtering)
4400 /* Set the filetype after writing the file. */
4401 mch_set_filetype(wfname, buf->b_p_oft);
4402#endif
4403#ifdef HAVE_ACL
4404 /* Probably need to set the ACL before changing the user (can't set the
4405 * ACL on a file the user doesn't own). */
4406 if (!backup_copy)
4407 mch_set_acl(wfname, acl);
4408#endif
4409
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410
4411#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4412 if (wfname != fname)
4413 {
4414 /*
4415 * The file was written to a temp file, now it needs to be converted
4416 * with 'charconvert' to (overwrite) the output file.
4417 */
4418 if (end != 0)
4419 {
4420 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4421 wfname, fname) == FAIL)
4422 {
4423 write_info.bw_conv_error = TRUE;
4424 end = 0;
4425 }
4426 }
4427 mch_remove(wfname);
4428 vim_free(wfname);
4429 }
4430#endif
4431
4432 if (end == 0)
4433 {
4434 if (errmsg == NULL)
4435 {
4436#ifdef FEAT_MBYTE
4437 if (write_info.bw_conv_error)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004438 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 else
4440#endif
4441 if (got_int)
4442 errmsg = (char_u *)_(e_interr);
4443 else
4444 errmsg = (char_u *)_("E514: write error (file system full?)");
4445 }
4446
4447 /*
4448 * If we have a backup file, try to put it in place of the new file,
4449 * because the new file is probably corrupt. This avoids loosing the
4450 * original file when trying to make a backup when writing the file a
4451 * second time.
4452 * When "backup_copy" is set we need to copy the backup over the new
4453 * file. Otherwise rename the backup file.
4454 * If this is OK, don't give the extra warning message.
4455 */
4456 if (backup != NULL)
4457 {
4458 if (backup_copy)
4459 {
4460 /* This may take a while, if we were interrupted let the user
4461 * know we got the message. */
4462 if (got_int)
4463 {
4464 MSG(_(e_interr));
4465 out_flush();
4466 }
4467 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4468 {
4469 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004470 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4471 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004472 {
4473 /* copy the file. */
4474 write_info.bw_buf = smallbuf;
4475#ifdef HAS_BW_FLAGS
4476 write_info.bw_flags = FIO_NOCONVERT;
4477#endif
4478 while ((write_info.bw_len = vim_read(fd, smallbuf,
4479 SMBUFSIZE)) > 0)
4480 if (buf_write_bytes(&write_info) == FAIL)
4481 break;
4482
4483 if (close(write_info.bw_fd) >= 0
4484 && write_info.bw_len == 0)
4485 end = 1; /* success */
4486 }
4487 close(fd); /* ignore errors for closing read file */
4488 }
4489 }
4490 else
4491 {
4492 if (vim_rename(backup, fname) == 0)
4493 end = 1;
4494 }
4495 }
4496 goto fail;
4497 }
4498
4499 lnum -= start; /* compute number of written lines */
4500 --no_wait_return; /* may wait for return now */
4501
4502#if !(defined(UNIX) || defined(VMS))
4503 fname = sfname; /* use shortname now, for the messages */
4504#endif
4505 if (!filtering)
4506 {
4507 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4508 c = FALSE;
4509#ifdef FEAT_MBYTE
4510 if (write_info.bw_conv_error)
4511 {
4512 STRCAT(IObuff, _(" CONVERSION ERROR"));
4513 c = TRUE;
4514 }
4515 else if (notconverted)
4516 {
4517 STRCAT(IObuff, _("[NOT converted]"));
4518 c = TRUE;
4519 }
4520 else if (converted)
4521 {
4522 STRCAT(IObuff, _("[converted]"));
4523 c = TRUE;
4524 }
4525#endif
4526 if (device)
4527 {
4528 STRCAT(IObuff, _("[Device]"));
4529 c = TRUE;
4530 }
4531 else if (newfile)
4532 {
4533 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4534 c = TRUE;
4535 }
4536 if (no_eol)
4537 {
4538 msg_add_eol();
4539 c = TRUE;
4540 }
4541 /* may add [unix/dos/mac] */
4542 if (msg_add_fileformat(fileformat))
4543 c = TRUE;
4544#ifdef FEAT_CRYPT
4545 if (wb_flags & FIO_ENCRYPTED)
4546 {
4547 STRCAT(IObuff, _("[crypted]"));
4548 c = TRUE;
4549 }
4550#endif
4551 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4552 if (!shortmess(SHM_WRITE))
4553 {
4554 if (append)
4555 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4556 else
4557 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4558 }
4559
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004560 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561 }
4562
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004563 /* When written everything correctly: reset 'modified'. Unless not
4564 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004565 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566#ifdef FEAT_MBYTE
4567 && !write_info.bw_conv_error
4568#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004569 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4570 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 {
4572 unchanged(buf, TRUE);
4573 u_unchanged(buf);
4574 }
4575
4576 /*
4577 * If written to the current file, update the timestamp of the swap file
4578 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4579 */
4580 if (overwriting)
4581 {
4582 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004583 if (append)
4584 buf->b_flags &= ~BF_NEW;
4585 else
4586 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 }
4588
4589 /*
4590 * If we kept a backup until now, and we are in patch mode, then we make
4591 * the backup file our 'original' file.
4592 */
4593 if (*p_pm && dobackup)
4594 {
4595 char *org = (char *)buf_modname(
4596#ifdef SHORT_FNAME
4597 TRUE,
4598#else
4599 (buf->b_p_sn || buf->b_shortname),
4600#endif
4601 fname, p_pm, FALSE);
4602
4603 if (backup != NULL)
4604 {
4605 struct stat st;
4606
4607 /*
4608 * If the original file does not exist yet
4609 * the current backup file becomes the original file
4610 */
4611 if (org == NULL)
4612 EMSG(_("E205: Patchmode: can't save original file"));
4613 else if (mch_stat(org, &st) < 0)
4614 {
4615 vim_rename(backup, (char_u *)org);
4616 vim_free(backup); /* don't delete the file */
4617 backup = NULL;
4618#ifdef UNIX
4619 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4620#endif
4621 }
4622 }
4623 /*
4624 * If there is no backup file, remember that a (new) file was
4625 * created.
4626 */
4627 else
4628 {
4629 int empty_fd;
4630
4631 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004632 || (empty_fd = mch_open(org,
4633 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004634 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 EMSG(_("E206: patchmode: can't touch empty original file"));
4636 else
4637 close(empty_fd);
4638 }
4639 if (org != NULL)
4640 {
4641 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4642 vim_free(org);
4643 }
4644 }
4645
4646 /*
4647 * Remove the backup unless 'backup' option is set
4648 */
4649 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4650 EMSG(_("E207: Can't delete backup file"));
4651
4652#ifdef FEAT_SUN_WORKSHOP
4653 if (usingSunWorkShop)
4654 workshop_file_saved((char *) ffname);
4655#endif
4656
4657 goto nofail;
4658
4659 /*
4660 * Finish up. We get here either after failure or success.
4661 */
4662fail:
4663 --no_wait_return; /* may wait for return now */
4664nofail:
4665
4666 /* Done saving, we accept changed buffer warnings again */
4667 buf->b_saving = FALSE;
4668
4669 vim_free(backup);
4670 if (buffer != smallbuf)
4671 vim_free(buffer);
4672#ifdef FEAT_MBYTE
4673 vim_free(fenc_tofree);
4674 vim_free(write_info.bw_conv_buf);
4675# ifdef USE_ICONV
4676 if (write_info.bw_iconv_fd != (iconv_t)-1)
4677 {
4678 iconv_close(write_info.bw_iconv_fd);
4679 write_info.bw_iconv_fd = (iconv_t)-1;
4680 }
4681# endif
4682#endif
4683#ifdef HAVE_ACL
4684 mch_free_acl(acl);
4685#endif
4686
4687 if (errmsg != NULL)
4688 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004689 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690
4691 attr = hl_attr(HLF_E); /* set highlight for error messages */
4692 msg_add_fname(buf,
4693#ifndef UNIX
4694 sfname
4695#else
4696 fname
4697#endif
4698 ); /* put file name in IObuff with quotes */
4699 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
4700 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
4701 /* If the error message has the form "is ...", put the error number in
4702 * front of the file name. */
4703 if (errnum != NULL)
4704 {
4705 mch_memmove(IObuff + numlen, IObuff, STRLEN(IObuff) + 1);
4706 mch_memmove(IObuff, errnum, (size_t)numlen);
4707 }
4708 STRCAT(IObuff, errmsg);
4709 emsg(IObuff);
4710
4711 retval = FAIL;
4712 if (end == 0)
4713 {
4714 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
4715 attr | MSG_HIST);
4716 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
4717 attr | MSG_HIST);
4718
4719 /* Update the timestamp to avoid an "overwrite changed file"
4720 * prompt when writing again. */
4721 if (mch_stat((char *)fname, &st_old) >= 0)
4722 {
4723 buf_store_time(buf, &st_old, fname);
4724 buf->b_mtime_read = buf->b_mtime;
4725 }
4726 }
4727 }
4728 msg_scroll = msg_save;
4729
4730#ifdef FEAT_AUTOCMD
4731#ifdef FEAT_EVAL
4732 if (!should_abort(retval))
4733#else
4734 if (!got_int)
4735#endif
4736 {
4737 aco_save_T aco;
4738
4739 write_no_eol_lnum = 0; /* in case it was set by the previous read */
4740
4741 /*
4742 * Apply POST autocommands.
4743 * Careful: The autocommands may call buf_write() recursively!
4744 */
4745 aucmd_prepbuf(&aco, buf);
4746
4747 if (append)
4748 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
4749 FALSE, curbuf, eap);
4750 else if (filtering)
4751 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
4752 FALSE, curbuf, eap);
4753 else if (reset_changed && whole)
4754 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
4755 FALSE, curbuf, eap);
4756 else
4757 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
4758 FALSE, curbuf, eap);
4759
4760 /* restore curwin/curbuf and a few other things */
4761 aucmd_restbuf(&aco);
4762
4763#ifdef FEAT_EVAL
4764 if (aborting()) /* autocmds may abort script processing */
4765 retval = FALSE;
4766#endif
4767 }
4768#endif
4769
4770 got_int |= prev_got_int;
4771
4772#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4773 /* Update machine specific information. */
4774 mch_post_buffer_write(buf);
4775#endif
4776 return retval;
4777}
4778
4779/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004780 * Set the name of the current buffer. Use when the buffer doesn't have a
4781 * name and a ":r" or ":w" command with a file name is used.
4782 */
4783 static int
4784set_rw_fname(fname, sfname)
4785 char_u *fname;
4786 char_u *sfname;
4787{
4788#ifdef FEAT_AUTOCMD
4789 /* It's like the unnamed buffer is deleted.... */
4790 if (curbuf->b_p_bl)
4791 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
4792 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
4793# ifdef FEAT_EVAL
4794 if (aborting()) /* autocmds may abort script processing */
4795 return FAIL;
4796# endif
4797#endif
4798
4799 if (setfname(curbuf, fname, sfname, FALSE) == OK)
4800 curbuf->b_flags |= BF_NOTEDITED;
4801
4802#ifdef FEAT_AUTOCMD
4803 /* ....and a new named one is created */
4804 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
4805 if (curbuf->b_p_bl)
4806 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
4807# ifdef FEAT_EVAL
4808 if (aborting()) /* autocmds may abort script processing */
4809 return FAIL;
4810# endif
4811
4812 /* Do filetype detection now if 'filetype' is empty. */
4813 if (*curbuf->b_p_ft == NUL)
4814 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004815 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00004816 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00004817 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004818 }
4819#endif
4820
4821 return OK;
4822}
4823
4824/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 * Put file name into IObuff with quotes.
4826 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004827 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828msg_add_fname(buf, fname)
4829 buf_T *buf;
4830 char_u *fname;
4831{
4832 if (fname == NULL)
4833 fname = (char_u *)"-stdin-";
4834 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
4835 IObuff[0] = '"';
4836 STRCAT(IObuff, "\" ");
4837}
4838
4839/*
4840 * Append message for text mode to IObuff.
4841 * Return TRUE if something appended.
4842 */
4843 static int
4844msg_add_fileformat(eol_type)
4845 int eol_type;
4846{
4847#ifndef USE_CRNL
4848 if (eol_type == EOL_DOS)
4849 {
4850 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
4851 return TRUE;
4852 }
4853#endif
4854#ifndef USE_CR
4855 if (eol_type == EOL_MAC)
4856 {
4857 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
4858 return TRUE;
4859 }
4860#endif
4861#if defined(USE_CRNL) || defined(USE_CR)
4862 if (eol_type == EOL_UNIX)
4863 {
4864 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
4865 return TRUE;
4866 }
4867#endif
4868 return FALSE;
4869}
4870
4871/*
4872 * Append line and character count to IObuff.
4873 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004874 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875msg_add_lines(insert_space, lnum, nchars)
4876 int insert_space;
4877 long lnum;
4878 long nchars;
4879{
4880 char_u *p;
4881
4882 p = IObuff + STRLEN(IObuff);
4883
4884 if (insert_space)
4885 *p++ = ' ';
4886 if (shortmess(SHM_LINES))
4887 sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
4888 else
4889 {
4890 if (lnum == 1)
4891 STRCPY(p, _("1 line, "));
4892 else
4893 sprintf((char *)p, _("%ld lines, "), lnum);
4894 p += STRLEN(p);
4895 if (nchars == 1)
4896 STRCPY(p, _("1 character"));
4897 else
4898 sprintf((char *)p, _("%ld characters"), nchars);
4899 }
4900}
4901
4902/*
4903 * Append message for missing line separator to IObuff.
4904 */
4905 static void
4906msg_add_eol()
4907{
4908 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
4909}
4910
4911/*
4912 * Check modification time of file, before writing to it.
4913 * The size isn't checked, because using a tool like "gzip" takes care of
4914 * using the same timestamp but can't set the size.
4915 */
4916 static int
4917check_mtime(buf, st)
4918 buf_T *buf;
4919 struct stat *st;
4920{
4921 if (buf->b_mtime_read != 0
4922 && time_differs((long)st->st_mtime, buf->b_mtime_read))
4923 {
4924 msg_scroll = TRUE; /* don't overwrite messages here */
4925 msg_silent = 0; /* must give this prompt */
4926 /* don't use emsg() here, don't want to flush the buffers */
4927 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
4928 hl_attr(HLF_E));
4929 if (ask_yesno((char_u *)_("Do you really want to write to it"),
4930 TRUE) == 'n')
4931 return FAIL;
4932 msg_scroll = FALSE; /* always overwrite the file message now */
4933 }
4934 return OK;
4935}
4936
4937 static int
4938time_differs(t1, t2)
4939 long t1, t2;
4940{
4941#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
4942 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
4943 * the seconds. Since the roundoff is done when flushing the inode, the
4944 * time may change unexpectedly by one second!!! */
4945 return (t1 - t2 > 1 || t2 - t1 > 1);
4946#else
4947 return (t1 != t2);
4948#endif
4949}
4950
4951/*
4952 * Call write() to write a number of bytes to the file.
4953 * Also handles encryption and 'encoding' conversion.
4954 *
4955 * Return FAIL for failure, OK otherwise.
4956 */
4957 static int
4958buf_write_bytes(ip)
4959 struct bw_info *ip;
4960{
4961 int wlen;
4962 char_u *buf = ip->bw_buf; /* data to write */
4963 int len = ip->bw_len; /* length of data */
4964#ifdef HAS_BW_FLAGS
4965 int flags = ip->bw_flags; /* extra flags */
4966#endif
4967
4968#ifdef FEAT_MBYTE
4969 /*
4970 * Skip conversion when writing the crypt magic number or the BOM.
4971 */
4972 if (!(flags & FIO_NOCONVERT))
4973 {
4974 char_u *p;
4975 unsigned c;
4976 int n;
4977
4978 if (flags & FIO_UTF8)
4979 {
4980 /*
4981 * Convert latin1 in the buffer to UTF-8 in the file.
4982 */
4983 p = ip->bw_conv_buf; /* translate to buffer */
4984 for (wlen = 0; wlen < len; ++wlen)
4985 p += utf_char2bytes(buf[wlen], p);
4986 buf = ip->bw_conv_buf;
4987 len = (int)(p - ip->bw_conv_buf);
4988 }
4989 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
4990 {
4991 /*
4992 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
4993 * Latin1 chars in the file.
4994 */
4995 if (flags & FIO_LATIN1)
4996 p = buf; /* translate in-place (can only get shorter) */
4997 else
4998 p = ip->bw_conv_buf; /* translate to buffer */
4999 for (wlen = 0; wlen < len; wlen += n)
5000 {
5001 if (wlen == 0 && ip->bw_restlen != 0)
5002 {
5003 int l;
5004
5005 /* Use remainder of previous call. Append the start of
5006 * buf[] to get a full sequence. Might still be too
5007 * short! */
5008 l = CONV_RESTLEN - ip->bw_restlen;
5009 if (l > len)
5010 l = len;
5011 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005012 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005013 if (n > ip->bw_restlen + len)
5014 {
5015 /* We have an incomplete byte sequence at the end to
5016 * be written. We can't convert it without the
5017 * remaining bytes. Keep them for the next call. */
5018 if (ip->bw_restlen + len > CONV_RESTLEN)
5019 return FAIL;
5020 ip->bw_restlen += len;
5021 break;
5022 }
5023 if (n > 1)
5024 c = utf_ptr2char(ip->bw_rest);
5025 else
5026 c = ip->bw_rest[0];
5027 if (n >= ip->bw_restlen)
5028 {
5029 n -= ip->bw_restlen;
5030 ip->bw_restlen = 0;
5031 }
5032 else
5033 {
5034 ip->bw_restlen -= n;
5035 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5036 (size_t)ip->bw_restlen);
5037 n = 0;
5038 }
5039 }
5040 else
5041 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005042 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 if (n > len - wlen)
5044 {
5045 /* We have an incomplete byte sequence at the end to
5046 * be written. We can't convert it without the
5047 * remaining bytes. Keep them for the next call. */
5048 if (len - wlen > CONV_RESTLEN)
5049 return FAIL;
5050 ip->bw_restlen = len - wlen;
5051 mch_memmove(ip->bw_rest, buf + wlen,
5052 (size_t)ip->bw_restlen);
5053 break;
5054 }
5055 if (n > 1)
5056 c = utf_ptr2char(buf + wlen);
5057 else
5058 c = buf[wlen];
5059 }
5060
5061 ip->bw_conv_error |= ucs2bytes(c, &p, flags);
5062 }
5063 if (flags & FIO_LATIN1)
5064 len = (int)(p - buf);
5065 else
5066 {
5067 buf = ip->bw_conv_buf;
5068 len = (int)(p - ip->bw_conv_buf);
5069 }
5070 }
5071
5072# ifdef WIN3264
5073 else if (flags & FIO_CODEPAGE)
5074 {
5075 /*
5076 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5077 * codepage.
5078 */
5079 char_u *from;
5080 size_t fromlen;
5081 char_u *to;
5082 int u8c;
5083 BOOL bad = FALSE;
5084 int needed;
5085
5086 if (ip->bw_restlen > 0)
5087 {
5088 /* Need to concatenate the remainder of the previous call and
5089 * the bytes of the current call. Use the end of the
5090 * conversion buffer for this. */
5091 fromlen = len + ip->bw_restlen;
5092 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5093 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5094 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5095 }
5096 else
5097 {
5098 from = buf;
5099 fromlen = len;
5100 }
5101
5102 to = ip->bw_conv_buf;
5103 if (enc_utf8)
5104 {
5105 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5106 * The buffer has been allocated to be big enough. */
5107 while (fromlen > 0)
5108 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005109 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005110 if (n > (int)fromlen) /* incomplete byte sequence */
5111 break;
5112 u8c = utf_ptr2char(from);
5113 *to++ = (u8c & 0xff);
5114 *to++ = (u8c >> 8);
5115 fromlen -= n;
5116 from += n;
5117 }
5118
5119 /* Copy remainder to ip->bw_rest[] to be used for the next
5120 * call. */
5121 if (fromlen > CONV_RESTLEN)
5122 {
5123 /* weird overlong sequence */
5124 ip->bw_conv_error = TRUE;
5125 return FAIL;
5126 }
5127 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005128 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005129 }
5130 else
5131 {
5132 /* Convert from enc_codepage to UCS-2, to the start of the
5133 * buffer. The buffer has been allocated to be big enough. */
5134 ip->bw_restlen = 0;
5135 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005136 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005137 NULL, 0);
5138 if (needed == 0)
5139 {
5140 /* When conversion fails there may be a trailing byte. */
5141 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005142 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143 NULL, 0);
5144 if (needed == 0)
5145 {
5146 /* Conversion doesn't work. */
5147 ip->bw_conv_error = TRUE;
5148 return FAIL;
5149 }
5150 /* Save the trailing byte for the next call. */
5151 ip->bw_rest[0] = from[fromlen - 1];
5152 ip->bw_restlen = 1;
5153 }
5154 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005155 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156 (LPWSTR)to, needed);
5157 if (needed == 0)
5158 {
5159 /* Safety check: Conversion doesn't work. */
5160 ip->bw_conv_error = TRUE;
5161 return FAIL;
5162 }
5163 to += needed * 2;
5164 }
5165
5166 fromlen = to - ip->bw_conv_buf;
5167 buf = to;
5168# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5169 if (FIO_GET_CP(flags) == CP_UTF8)
5170 {
5171 /* Convert from UCS-2 to UTF-8, using the remainder of the
5172 * conversion buffer. Fails when out of space. */
5173 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5174 {
5175 u8c = *from++;
5176 u8c += (*from++ << 8);
5177 to += utf_char2bytes(u8c, to);
5178 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5179 {
5180 ip->bw_conv_error = TRUE;
5181 return FAIL;
5182 }
5183 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005184 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185 }
5186 else
5187#endif
5188 {
5189 /* Convert from UCS-2 to the codepage, using the remainder of
5190 * the conversion buffer. If the conversion uses the default
5191 * character "0", the data doesn't fit in this encoding, so
5192 * fail. */
5193 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5194 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005195 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5196 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 if (bad)
5198 {
5199 ip->bw_conv_error = TRUE;
5200 return FAIL;
5201 }
5202 }
5203 }
5204# endif
5205
Bram Moolenaar56718732006-03-15 22:53:57 +00005206# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 else if (flags & FIO_MACROMAN)
5208 {
5209 /*
5210 * Convert UTF-8 or latin1 to Apple MacRoman.
5211 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 char_u *from;
5213 size_t fromlen;
5214
5215 if (ip->bw_restlen > 0)
5216 {
5217 /* Need to concatenate the remainder of the previous call and
5218 * the bytes of the current call. Use the end of the
5219 * conversion buffer for this. */
5220 fromlen = len + ip->bw_restlen;
5221 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5222 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5223 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5224 }
5225 else
5226 {
5227 from = buf;
5228 fromlen = len;
5229 }
5230
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005231 if (enc2macroman(from, fromlen,
5232 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5233 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234 {
5235 ip->bw_conv_error = TRUE;
5236 return FAIL;
5237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005239 }
5240# endif
5241
5242# ifdef USE_ICONV
5243 if (ip->bw_iconv_fd != (iconv_t)-1)
5244 {
5245 const char *from;
5246 size_t fromlen;
5247 char *to;
5248 size_t tolen;
5249
5250 /* Convert with iconv(). */
5251 if (ip->bw_restlen > 0)
5252 {
5253 /* Need to concatenate the remainder of the previous call and
5254 * the bytes of the current call. Use the end of the
5255 * conversion buffer for this. */
5256 fromlen = len + ip->bw_restlen;
5257 from = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5258 mch_memmove((void *)from, ip->bw_rest, (size_t)ip->bw_restlen);
5259 mch_memmove((void *)(from + ip->bw_restlen), buf, (size_t)len);
5260 tolen = ip->bw_conv_buflen - fromlen;
5261 }
5262 else
5263 {
5264 from = (const char *)buf;
5265 fromlen = len;
5266 tolen = ip->bw_conv_buflen;
5267 }
5268 to = (char *)ip->bw_conv_buf;
5269
5270 if (ip->bw_first)
5271 {
5272 size_t save_len = tolen;
5273
5274 /* output the initial shift state sequence */
5275 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5276
5277 /* There is a bug in iconv() on Linux (which appears to be
5278 * wide-spread) which sets "to" to NULL and messes up "tolen".
5279 */
5280 if (to == NULL)
5281 {
5282 to = (char *)ip->bw_conv_buf;
5283 tolen = save_len;
5284 }
5285 ip->bw_first = FALSE;
5286 }
5287
5288 /*
5289 * If iconv() has an error or there is not enough room, fail.
5290 */
5291 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5292 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5293 || fromlen > CONV_RESTLEN)
5294 {
5295 ip->bw_conv_error = TRUE;
5296 return FAIL;
5297 }
5298
5299 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5300 if (fromlen > 0)
5301 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5302 ip->bw_restlen = (int)fromlen;
5303
5304 buf = ip->bw_conv_buf;
5305 len = (int)((char_u *)to - ip->bw_conv_buf);
5306 }
5307# endif
5308 }
5309#endif /* FEAT_MBYTE */
5310
5311#ifdef FEAT_CRYPT
5312 if (flags & FIO_ENCRYPTED) /* encrypt the data */
5313 {
5314 int ztemp, t, i;
5315
5316 for (i = 0; i < len; i++)
5317 {
5318 ztemp = buf[i];
5319 buf[i] = ZENCODE(ztemp, t);
5320 }
5321 }
5322#endif
5323
5324 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005325 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326 {
5327 wlen = vim_write(ip->bw_fd, buf, len);
5328 if (wlen <= 0) /* error! */
5329 return FAIL;
5330 len -= wlen;
5331 buf += wlen;
5332 }
5333 return OK;
5334}
5335
5336#ifdef FEAT_MBYTE
5337/*
5338 * Convert a Unicode character to bytes.
5339 */
5340 static int
5341ucs2bytes(c, pp, flags)
5342 unsigned c; /* in: character */
5343 char_u **pp; /* in/out: pointer to result */
5344 int flags; /* FIO_ flags */
5345{
5346 char_u *p = *pp;
5347 int error = FALSE;
5348 int cc;
5349
5350
5351 if (flags & FIO_UCS4)
5352 {
5353 if (flags & FIO_ENDIAN_L)
5354 {
5355 *p++ = c;
5356 *p++ = (c >> 8);
5357 *p++ = (c >> 16);
5358 *p++ = (c >> 24);
5359 }
5360 else
5361 {
5362 *p++ = (c >> 24);
5363 *p++ = (c >> 16);
5364 *p++ = (c >> 8);
5365 *p++ = c;
5366 }
5367 }
5368 else if (flags & (FIO_UCS2 | FIO_UTF16))
5369 {
5370 if (c >= 0x10000)
5371 {
5372 if (flags & FIO_UTF16)
5373 {
5374 /* Make two words, ten bits of the character in each. First
5375 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5376 c -= 0x10000;
5377 if (c >= 0x100000)
5378 error = TRUE;
5379 cc = ((c >> 10) & 0x3ff) + 0xd800;
5380 if (flags & FIO_ENDIAN_L)
5381 {
5382 *p++ = cc;
5383 *p++ = ((unsigned)cc >> 8);
5384 }
5385 else
5386 {
5387 *p++ = ((unsigned)cc >> 8);
5388 *p++ = cc;
5389 }
5390 c = (c & 0x3ff) + 0xdc00;
5391 }
5392 else
5393 error = TRUE;
5394 }
5395 if (flags & FIO_ENDIAN_L)
5396 {
5397 *p++ = c;
5398 *p++ = (c >> 8);
5399 }
5400 else
5401 {
5402 *p++ = (c >> 8);
5403 *p++ = c;
5404 }
5405 }
5406 else /* Latin1 */
5407 {
5408 if (c >= 0x100)
5409 {
5410 error = TRUE;
5411 *p++ = 0xBF;
5412 }
5413 else
5414 *p++ = c;
5415 }
5416
5417 *pp = p;
5418 return error;
5419}
5420
5421/*
5422 * Return TRUE if "a" and "b" are the same 'encoding'.
5423 * Ignores difference between "ansi" and "latin1", "ucs-4" and "ucs-4be", etc.
5424 */
5425 static int
5426same_encoding(a, b)
5427 char_u *a;
5428 char_u *b;
5429{
5430 int f;
5431
5432 if (STRCMP(a, b) == 0)
5433 return TRUE;
5434 f = get_fio_flags(a);
5435 return (f != 0 && get_fio_flags(b) == f);
5436}
5437
5438/*
5439 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5440 * internal conversion.
5441 * if "ptr" is an empty string, use 'encoding'.
5442 */
5443 static int
5444get_fio_flags(ptr)
5445 char_u *ptr;
5446{
5447 int prop;
5448
5449 if (*ptr == NUL)
5450 ptr = p_enc;
5451
5452 prop = enc_canon_props(ptr);
5453 if (prop & ENC_UNICODE)
5454 {
5455 if (prop & ENC_2BYTE)
5456 {
5457 if (prop & ENC_ENDIAN_L)
5458 return FIO_UCS2 | FIO_ENDIAN_L;
5459 return FIO_UCS2;
5460 }
5461 if (prop & ENC_4BYTE)
5462 {
5463 if (prop & ENC_ENDIAN_L)
5464 return FIO_UCS4 | FIO_ENDIAN_L;
5465 return FIO_UCS4;
5466 }
5467 if (prop & ENC_2WORD)
5468 {
5469 if (prop & ENC_ENDIAN_L)
5470 return FIO_UTF16 | FIO_ENDIAN_L;
5471 return FIO_UTF16;
5472 }
5473 return FIO_UTF8;
5474 }
5475 if (prop & ENC_LATIN1)
5476 return FIO_LATIN1;
5477 /* must be ENC_DBCS, requires iconv() */
5478 return 0;
5479}
5480
5481#ifdef WIN3264
5482/*
5483 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5484 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5485 * Used for conversion between 'encoding' and 'fileencoding'.
5486 */
5487 static int
5488get_win_fio_flags(ptr)
5489 char_u *ptr;
5490{
5491 int cp;
5492
5493 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5494 if (!enc_utf8 && enc_codepage <= 0)
5495 return 0;
5496
5497 cp = encname2codepage(ptr);
5498 if (cp == 0)
5499 {
5500# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5501 if (STRCMP(ptr, "utf-8") == 0)
5502 cp = CP_UTF8;
5503 else
5504# endif
5505 return 0;
5506 }
5507 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5508}
5509#endif
5510
5511#ifdef MACOS_X
5512/*
5513 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5514 * needed for the internal conversion to/from utf-8 or latin1.
5515 */
5516 static int
5517get_mac_fio_flags(ptr)
5518 char_u *ptr;
5519{
5520 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5521 && (enc_canon_props(ptr) & ENC_MACROMAN))
5522 return FIO_MACROMAN;
5523 return 0;
5524}
5525#endif
5526
5527/*
5528 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5529 * "size" must be at least 2.
5530 * Return the name of the encoding and set "*lenp" to the length.
5531 * Returns NULL when no BOM found.
5532 */
5533 static char_u *
5534check_for_bom(p, size, lenp, flags)
5535 char_u *p;
5536 long size;
5537 int *lenp;
5538 int flags;
5539{
5540 char *name = NULL;
5541 int len = 2;
5542
5543 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
5544 && (flags == FIO_ALL || flags == 0))
5545 {
5546 name = "utf-8"; /* EF BB BF */
5547 len = 3;
5548 }
5549 else if (p[0] == 0xff && p[1] == 0xfe)
5550 {
5551 if (size >= 4 && p[2] == 0 && p[3] == 0
5552 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5553 {
5554 name = "ucs-4le"; /* FF FE 00 00 */
5555 len = 4;
5556 }
5557 else if (flags == FIO_ALL || flags == (FIO_UCS2 | FIO_ENDIAN_L))
5558 name = "ucs-2le"; /* FF FE */
5559 else if (flags == (FIO_UTF16 | FIO_ENDIAN_L))
5560 name = "utf-16le"; /* FF FE */
5561 }
5562 else if (p[0] == 0xfe && p[1] == 0xff
5563 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5564 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005565 /* Default to utf-16, it works also for ucs-2 text. */
5566 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005568 else
5569 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570 }
5571 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5572 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5573 {
5574 name = "ucs-4"; /* 00 00 FE FF */
5575 len = 4;
5576 }
5577
5578 *lenp = len;
5579 return (char_u *)name;
5580}
5581
5582/*
5583 * Generate a BOM in "buf[4]" for encoding "name".
5584 * Return the length of the BOM (zero when no BOM).
5585 */
5586 static int
5587make_bom(buf, name)
5588 char_u *buf;
5589 char_u *name;
5590{
5591 int flags;
5592 char_u *p;
5593
5594 flags = get_fio_flags(name);
5595
5596 /* Can't put a BOM in a non-Unicode file. */
5597 if (flags == FIO_LATIN1 || flags == 0)
5598 return 0;
5599
5600 if (flags == FIO_UTF8) /* UTF-8 */
5601 {
5602 buf[0] = 0xef;
5603 buf[1] = 0xbb;
5604 buf[2] = 0xbf;
5605 return 3;
5606 }
5607 p = buf;
5608 (void)ucs2bytes(0xfeff, &p, flags);
5609 return (int)(p - buf);
5610}
5611#endif
5612
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005613#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005614 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615/*
5616 * Try to find a shortname by comparing the fullname with the current
5617 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005618 * Returns "full_path" or pointer into "full_path" if shortened.
5619 */
5620 char_u *
5621shorten_fname1(full_path)
5622 char_u *full_path;
5623{
5624 char_u dirname[MAXPATHL];
5625 char_u *p = full_path;
5626
5627 if (mch_dirname(dirname, MAXPATHL) == OK)
5628 {
5629 p = shorten_fname(full_path, dirname);
5630 if (p == NULL || *p == NUL)
5631 p = full_path;
5632 }
5633 return p;
5634}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005635#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005636
5637/*
5638 * Try to find a shortname by comparing the fullname with the current
5639 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640 * Returns NULL if not shorter name possible, pointer into "full_path"
5641 * otherwise.
5642 */
5643 char_u *
5644shorten_fname(full_path, dir_name)
5645 char_u *full_path;
5646 char_u *dir_name;
5647{
5648 int len;
5649 char_u *p;
5650
5651 if (full_path == NULL)
5652 return NULL;
5653 len = (int)STRLEN(dir_name);
5654 if (fnamencmp(dir_name, full_path, len) == 0)
5655 {
5656 p = full_path + len;
5657#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5658 /*
5659 * MSDOS: when a file is in the root directory, dir_name will end in a
5660 * slash, since C: by itself does not define a specific dir. In this
5661 * case p may already be correct. <negri>
5662 */
5663 if (!((len > 2) && (*(p - 2) == ':')))
5664#endif
5665 {
5666 if (vim_ispathsep(*p))
5667 ++p;
5668#ifndef VMS /* the path separator is always part of the path */
5669 else
5670 p = NULL;
5671#endif
5672 }
5673 }
5674#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5675 /*
5676 * When using a file in the current drive, remove the drive name:
5677 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
5678 * a floppy from "A:\dir" to "B:\dir".
5679 */
5680 else if (len > 3
5681 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
5682 && full_path[1] == ':'
5683 && vim_ispathsep(full_path[2]))
5684 p = full_path + 2;
5685#endif
5686 else
5687 p = NULL;
5688 return p;
5689}
5690
5691/*
5692 * Shorten filenames for all buffers.
5693 * When "force" is TRUE: Use full path from now on for files currently being
5694 * edited, both for file name and swap file name. Try to shorten the file
5695 * names a bit, if safe to do so.
5696 * When "force" is FALSE: Only try to shorten absolute file names.
5697 * For buffers that have buftype "nofile" or "scratch": never change the file
5698 * name.
5699 */
5700 void
5701shorten_fnames(force)
5702 int force;
5703{
5704 char_u dirname[MAXPATHL];
5705 buf_T *buf;
5706 char_u *p;
5707
5708 mch_dirname(dirname, MAXPATHL);
5709 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5710 {
5711 if (buf->b_fname != NULL
5712#ifdef FEAT_QUICKFIX
5713 && !bt_nofile(buf)
5714#endif
5715 && !path_with_url(buf->b_fname)
5716 && (force
5717 || buf->b_sfname == NULL
5718 || mch_isFullName(buf->b_sfname)))
5719 {
5720 vim_free(buf->b_sfname);
5721 buf->b_sfname = NULL;
5722 p = shorten_fname(buf->b_ffname, dirname);
5723 if (p != NULL)
5724 {
5725 buf->b_sfname = vim_strsave(p);
5726 buf->b_fname = buf->b_sfname;
5727 }
5728 if (p == NULL || buf->b_fname == NULL)
5729 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005731
5732 /* Always make the swap file name a full path, a "nofile" buffer may
5733 * also have a swap file. */
5734 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 }
5736#ifdef FEAT_WINDOWS
5737 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00005738 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739#endif
5740}
5741
5742#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
5743 || defined(FEAT_GUI_MSWIN) \
5744 || defined(FEAT_GUI_MAC) \
5745 || defined(PROTO)
5746/*
5747 * Shorten all filenames in "fnames[count]" by current directory.
5748 */
5749 void
5750shorten_filenames(fnames, count)
5751 char_u **fnames;
5752 int count;
5753{
5754 int i;
5755 char_u dirname[MAXPATHL];
5756 char_u *p;
5757
5758 if (fnames == NULL || count < 1)
5759 return;
5760 mch_dirname(dirname, sizeof(dirname));
5761 for (i = 0; i < count; ++i)
5762 {
5763 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
5764 {
5765 /* shorten_fname() returns pointer in given "fnames[i]". If free
5766 * "fnames[i]" first, "p" becomes invalid. So we need to copy
5767 * "p" first then free fnames[i]. */
5768 p = vim_strsave(p);
5769 vim_free(fnames[i]);
5770 fnames[i] = p;
5771 }
5772 }
5773}
5774#endif
5775
5776/*
5777 * add extention to file name - change path/fo.o.h to path/fo.o.h.ext or
5778 * fo_o_h.ext for MSDOS or when shortname option set.
5779 *
5780 * Assumed that fname is a valid name found in the filesystem we assure that
5781 * the return value is a different name and ends in 'ext'.
5782 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
5783 * characters otherwise.
5784 * Space for the returned name is allocated, must be freed later.
5785 * Returns NULL when out of memory.
5786 */
5787 char_u *
5788modname(fname, ext, prepend_dot)
5789 char_u *fname, *ext;
5790 int prepend_dot; /* may prepend a '.' to file name */
5791{
5792 return buf_modname(
5793#ifdef SHORT_FNAME
5794 TRUE,
5795#else
5796 (curbuf->b_p_sn || curbuf->b_shortname),
5797#endif
5798 fname, ext, prepend_dot);
5799}
5800
5801 char_u *
5802buf_modname(shortname, fname, ext, prepend_dot)
5803 int shortname; /* use 8.3 file name */
5804 char_u *fname, *ext;
5805 int prepend_dot; /* may prepend a '.' to file name */
5806{
5807 char_u *retval;
5808 char_u *s;
5809 char_u *e;
5810 char_u *ptr;
5811 int fnamelen, extlen;
5812
5813 extlen = (int)STRLEN(ext);
5814
5815 /*
5816 * If there is no file name we must get the name of the current directory
5817 * (we need the full path in case :cd is used).
5818 */
5819 if (fname == NULL || *fname == NUL)
5820 {
5821 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
5822 if (retval == NULL)
5823 return NULL;
5824 if (mch_dirname(retval, MAXPATHL) == FAIL ||
5825 (fnamelen = (int)STRLEN(retval)) == 0)
5826 {
5827 vim_free(retval);
5828 return NULL;
5829 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005830 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831 {
5832 retval[fnamelen++] = PATHSEP;
5833 retval[fnamelen] = NUL;
5834 }
5835#ifndef SHORT_FNAME
5836 prepend_dot = FALSE; /* nothing to prepend a dot to */
5837#endif
5838 }
5839 else
5840 {
5841 fnamelen = (int)STRLEN(fname);
5842 retval = alloc((unsigned)(fnamelen + extlen + 3));
5843 if (retval == NULL)
5844 return NULL;
5845 STRCPY(retval, fname);
5846#ifdef VMS
5847 vms_remove_version(retval); /* we do not need versions here */
5848#endif
5849 }
5850
5851 /*
5852 * search backwards until we hit a '/', '\' or ':' replacing all '.'
5853 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
5854 * Then truncate what is after the '/', '\' or ':' to 8 characters for
5855 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
5856 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005857 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005858 {
5859#ifndef RISCOS
5860 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005861# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005863# else
5864# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005866# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868 )
5869 if (*ptr == '.') /* replace '.' by '_' */
5870 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005871#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005873 {
5874 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005876 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005877 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878
5879 /* the file name has at most BASENAMELEN characters. */
5880#ifndef SHORT_FNAME
5881 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
5882 ptr[BASENAMELEN] = '\0';
5883#endif
5884
5885 s = ptr + STRLEN(ptr);
5886
5887 /*
5888 * For 8.3 file names we may have to reduce the length.
5889 */
5890#ifdef USE_LONG_FNAME
5891 if (!USE_LONG_FNAME || shortname)
5892#else
5893# ifndef SHORT_FNAME
5894 if (shortname)
5895# endif
5896#endif
5897 {
5898 /*
5899 * If there is no file name, or the file name ends in '/', and the
5900 * extension starts with '.', put a '_' before the dot, because just
5901 * ".ext" is invalid.
5902 */
5903 if (fname == NULL || *fname == NUL
5904 || vim_ispathsep(fname[STRLEN(fname) - 1]))
5905 {
5906#ifdef RISCOS
5907 if (*ext == '/')
5908#else
5909 if (*ext == '.')
5910#endif
5911 *s++ = '_';
5912 }
5913 /*
5914 * If the extension starts with '.', truncate the base name at 8
5915 * characters
5916 */
5917#ifdef RISCOS
5918 /* We normally use '/', but swap files are '_' */
5919 else if (*ext == '/' || *ext == '_')
5920#else
5921 else if (*ext == '.')
5922#endif
5923 {
5924 if (s - ptr > (size_t)8)
5925 {
5926 s = ptr + 8;
5927 *s = '\0';
5928 }
5929 }
5930 /*
5931 * If the extension doesn't start with '.', and the file name
5932 * doesn't have an extension yet, append a '.'
5933 */
5934#ifdef RISCOS
5935 else if ((e = vim_strchr(ptr, '/')) == NULL)
5936 *s++ = '/';
5937#else
5938 else if ((e = vim_strchr(ptr, '.')) == NULL)
5939 *s++ = '.';
5940#endif
5941 /*
5942 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00005943 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 */
5945 else if ((int)STRLEN(e) + extlen > 4)
5946 s = e + 4 - extlen;
5947 }
5948#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
5949 /*
5950 * If there is no file name, and the extension starts with '.', put a
5951 * '_' before the dot, because just ".ext" may be invalid if it's on a
5952 * FAT partition, and on HPFS it doesn't matter.
5953 */
5954 else if ((fname == NULL || *fname == NUL) && *ext == '.')
5955 *s++ = '_';
5956#endif
5957
5958 /*
5959 * Append the extention.
5960 * ext can start with '.' and cannot exceed 3 more characters.
5961 */
5962 STRCPY(s, ext);
5963
5964#ifndef SHORT_FNAME
5965 /*
5966 * Prepend the dot.
5967 */
5968 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
5969#ifdef RISCOS
5970 '/'
5971#else
5972 '.'
5973#endif
5974#ifdef USE_LONG_FNAME
5975 && USE_LONG_FNAME
5976#endif
5977 )
5978 {
5979 mch_memmove(e + 1, e, STRLEN(e) + 1);
5980#ifdef RISCOS
5981 *e = '/';
5982#else
5983 *e = '.';
5984#endif
5985 }
5986#endif
5987
5988 /*
5989 * Check that, after appending the extension, the file name is really
5990 * different.
5991 */
5992 if (fname != NULL && STRCMP(fname, retval) == 0)
5993 {
5994 /* we search for a character that can be replaced by '_' */
5995 while (--s >= ptr)
5996 {
5997 if (*s != '_')
5998 {
5999 *s = '_';
6000 break;
6001 }
6002 }
6003 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6004 *ptr = 'v';
6005 }
6006 return retval;
6007}
6008
6009/*
6010 * Like fgets(), but if the file line is too long, it is truncated and the
6011 * rest of the line is thrown away. Returns TRUE for end-of-file.
6012 */
6013 int
6014vim_fgets(buf, size, fp)
6015 char_u *buf;
6016 int size;
6017 FILE *fp;
6018{
6019 char *eof;
6020#define FGETS_SIZE 200
6021 char tbuf[FGETS_SIZE];
6022
6023 buf[size - 2] = NUL;
6024#ifdef USE_CR
6025 eof = fgets_cr((char *)buf, size, fp);
6026#else
6027 eof = fgets((char *)buf, size, fp);
6028#endif
6029 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6030 {
6031 buf[size - 1] = NUL; /* Truncate the line */
6032
6033 /* Now throw away the rest of the line: */
6034 do
6035 {
6036 tbuf[FGETS_SIZE - 2] = NUL;
6037#ifdef USE_CR
6038 fgets_cr((char *)tbuf, FGETS_SIZE, fp);
6039#else
6040 fgets((char *)tbuf, FGETS_SIZE, fp);
6041#endif
6042 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6043 }
6044 return (eof == NULL);
6045}
6046
6047#if defined(USE_CR) || defined(PROTO)
6048/*
6049 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6050 * Returns TRUE for end-of-file.
6051 * Only used for the Mac, because it's much slower than vim_fgets().
6052 */
6053 int
6054tag_fgets(buf, size, fp)
6055 char_u *buf;
6056 int size;
6057 FILE *fp;
6058{
6059 int i = 0;
6060 int c;
6061 int eof = FALSE;
6062
6063 for (;;)
6064 {
6065 c = fgetc(fp);
6066 if (c == EOF)
6067 {
6068 eof = TRUE;
6069 break;
6070 }
6071 if (c == '\r')
6072 {
6073 /* Always store a NL for end-of-line. */
6074 if (i < size - 1)
6075 buf[i++] = '\n';
6076 c = fgetc(fp);
6077 if (c != '\n') /* Macintosh format: single CR. */
6078 ungetc(c, fp);
6079 break;
6080 }
6081 if (i < size - 1)
6082 buf[i++] = c;
6083 if (c == '\n')
6084 break;
6085 }
6086 buf[i] = NUL;
6087 return eof;
6088}
6089#endif
6090
6091/*
6092 * rename() only works if both files are on the same file system, this
6093 * function will (attempts to?) copy the file across if rename fails -- webb
6094 * Return -1 for failure, 0 for success.
6095 */
6096 int
6097vim_rename(from, to)
6098 char_u *from;
6099 char_u *to;
6100{
6101 int fd_in;
6102 int fd_out;
6103 int n;
6104 char *errmsg = NULL;
6105 char *buffer;
6106#ifdef AMIGA
6107 BPTR flock;
6108#endif
6109 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006110 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006111#ifdef HAVE_ACL
6112 vim_acl_T acl; /* ACL from original file */
6113#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114
6115 /*
6116 * When the names are identical, there is nothing to do.
6117 */
6118 if (fnamecmp(from, to) == 0)
6119 return 0;
6120
6121 /*
6122 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6123 */
6124 if (mch_stat((char *)from, &st) < 0)
6125 return -1;
6126
6127 /*
6128 * Delete the "to" file, this is required on some systems to make the
6129 * mch_rename() work, on other systems it makes sure that we don't have
6130 * two files when the mch_rename() fails.
6131 */
6132
6133#ifdef AMIGA
6134 /*
6135 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6136 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006137 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 * deleting the "from" file (horror!) we lock it during the remove.
6139 *
6140 * When used for making a backup before writing the file: This should not
6141 * happen with ":w", because startscript() should detect this problem and
6142 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6143 * name. This problem does exist with ":w filename", but then the
6144 * original file will be somewhere else so the backup isn't really
6145 * important. If autoscripting is off the rename may fail.
6146 */
6147 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6148#endif
6149 mch_remove(to);
6150#ifdef AMIGA
6151 if (flock)
6152 UnLock(flock);
6153#endif
6154
6155 /*
6156 * First try a normal rename, return if it works.
6157 */
6158 if (mch_rename((char *)from, (char *)to) == 0)
6159 return 0;
6160
6161 /*
6162 * Rename() failed, try copying the file.
6163 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006164 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006165#ifdef HAVE_ACL
6166 /* For systems that support ACL: get the ACL from the original file. */
6167 acl = mch_get_acl(from);
6168#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6170 if (fd_in == -1)
6171 return -1;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006172
6173 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006174 fd_out = mch_open((char *)to,
6175 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 if (fd_out == -1)
6177 {
6178 close(fd_in);
6179 return -1;
6180 }
6181
6182 buffer = (char *)alloc(BUFSIZE);
6183 if (buffer == NULL)
6184 {
6185 close(fd_in);
6186 close(fd_out);
6187 return -1;
6188 }
6189
6190 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6191 if (vim_write(fd_out, buffer, n) != n)
6192 {
6193 errmsg = _("E208: Error writing to \"%s\"");
6194 break;
6195 }
6196
6197 vim_free(buffer);
6198 close(fd_in);
6199 if (close(fd_out) < 0)
6200 errmsg = _("E209: Error closing \"%s\"");
6201 if (n < 0)
6202 {
6203 errmsg = _("E210: Error reading \"%s\"");
6204 to = from;
6205 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006206#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006207 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006208#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006209#ifdef HAVE_ACL
6210 mch_set_acl(to, acl);
6211#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 if (errmsg != NULL)
6213 {
6214 EMSG2(errmsg, to);
6215 return -1;
6216 }
6217 mch_remove(from);
6218 return 0;
6219}
6220
6221static int already_warned = FALSE;
6222
6223/*
6224 * Check if any not hidden buffer has been changed.
6225 * Postpone the check if there are characters in the stuff buffer, a global
6226 * command is being executed, a mapping is being executed or an autocommand is
6227 * busy.
6228 * Returns TRUE if some message was written (screen should be redrawn and
6229 * cursor positioned).
6230 */
6231 int
6232check_timestamps(focus)
6233 int focus; /* called for GUI focus event */
6234{
6235 buf_T *buf;
6236 int didit = 0;
6237 int n;
6238
6239 /* Don't check timestamps while system() or another low-level function may
6240 * cause us to lose and gain focus. */
6241 if (no_check_timestamps > 0)
6242 return FALSE;
6243
6244 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6245 * event and we would keep on checking if the file is steadily growing.
6246 * Do check again after typing something. */
6247 if (focus && did_check_timestamps)
6248 {
6249 need_check_timestamps = TRUE;
6250 return FALSE;
6251 }
6252
6253 if (!stuff_empty() || global_busy || !typebuf_typed()
6254#ifdef FEAT_AUTOCMD
Bram Moolenaar5555acc2006-04-07 21:33:12 +00006255 || autocmd_busy || curbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256#endif
6257 )
6258 need_check_timestamps = TRUE; /* check later */
6259 else
6260 {
6261 ++no_wait_return;
6262 did_check_timestamps = TRUE;
6263 already_warned = FALSE;
6264 for (buf = firstbuf; buf != NULL; )
6265 {
6266 /* Only check buffers in a window. */
6267 if (buf->b_nwindows > 0)
6268 {
6269 n = buf_check_timestamp(buf, focus);
6270 if (didit < n)
6271 didit = n;
6272 if (n > 0 && !buf_valid(buf))
6273 {
6274 /* Autocommands have removed the buffer, start at the
6275 * first one again. */
6276 buf = firstbuf;
6277 continue;
6278 }
6279 }
6280 buf = buf->b_next;
6281 }
6282 --no_wait_return;
6283 need_check_timestamps = FALSE;
6284 if (need_wait_return && didit == 2)
6285 {
6286 /* make sure msg isn't overwritten */
6287 msg_puts((char_u *)"\n");
6288 out_flush();
6289 }
6290 }
6291 return didit;
6292}
6293
6294/*
6295 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6296 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6297 * empty.
6298 */
6299 static int
6300move_lines(frombuf, tobuf)
6301 buf_T *frombuf;
6302 buf_T *tobuf;
6303{
6304 buf_T *tbuf = curbuf;
6305 int retval = OK;
6306 linenr_T lnum;
6307 char_u *p;
6308
6309 /* Copy the lines in "frombuf" to "tobuf". */
6310 curbuf = tobuf;
6311 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6312 {
6313 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6314 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6315 {
6316 vim_free(p);
6317 retval = FAIL;
6318 break;
6319 }
6320 vim_free(p);
6321 }
6322
6323 /* Delete all the lines in "frombuf". */
6324 if (retval != FAIL)
6325 {
6326 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006327 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6328 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 {
6330 /* Oops! We could try putting back the saved lines, but that
6331 * might fail again... */
6332 retval = FAIL;
6333 break;
6334 }
6335 }
6336
6337 curbuf = tbuf;
6338 return retval;
6339}
6340
6341/*
6342 * Check if buffer "buf" has been changed.
6343 * Also check if the file for a new buffer unexpectedly appeared.
6344 * return 1 if a changed buffer was found.
6345 * return 2 if a message has been displayed.
6346 * return 0 otherwise.
6347 */
6348/*ARGSUSED*/
6349 int
6350buf_check_timestamp(buf, focus)
6351 buf_T *buf;
6352 int focus; /* called for GUI focus event */
6353{
6354 struct stat st;
6355 int stat_res;
6356 int retval = 0;
6357 char_u *path;
6358 char_u *tbuf;
6359 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006360 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 int helpmesg = FALSE;
6362 int reload = FALSE;
6363#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6364 int can_reload = FALSE;
6365#endif
6366 size_t orig_size = buf->b_orig_size;
6367 int orig_mode = buf->b_orig_mode;
6368#ifdef FEAT_GUI
6369 int save_mouse_correct = need_mouse_correct;
6370#endif
6371#ifdef FEAT_AUTOCMD
6372 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006373 int n;
6374 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006376 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377
6378 /* If there is no file name, the buffer is not loaded, 'buftype' is
6379 * set, we are in the middle of a save or being called recursively: ignore
6380 * this buffer. */
6381 if (buf->b_ffname == NULL
6382 || buf->b_ml.ml_mfp == NULL
6383#if defined(FEAT_QUICKFIX)
6384 || *buf->b_p_bt != NUL
6385#endif
6386 || buf->b_saving
6387#ifdef FEAT_AUTOCMD
6388 || busy
6389#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006390#ifdef FEAT_NETBEANS_INTG
6391 || isNetbeansBuffer(buf)
6392#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393 )
6394 return 0;
6395
6396 if ( !(buf->b_flags & BF_NOTEDITED)
6397 && buf->b_mtime != 0
6398 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6399 || time_differs((long)st.st_mtime, buf->b_mtime)
6400#ifdef HAVE_ST_MODE
6401 || (int)st.st_mode != buf->b_orig_mode
6402#else
6403 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6404#endif
6405 ))
6406 {
6407 retval = 1;
6408
Bram Moolenaar316059c2006-01-14 21:18:42 +00006409 /* set b_mtime to stop further warnings (e.g., when executing
6410 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 if (stat_res < 0)
6412 {
6413 buf->b_mtime = 0;
6414 buf->b_orig_size = 0;
6415 buf->b_orig_mode = 0;
6416 }
6417 else
6418 buf_store_time(buf, &st, buf->b_ffname);
6419
6420 /* Don't do anything for a directory. Might contain the file
6421 * explorer. */
6422 if (mch_isdir(buf->b_fname))
6423 ;
6424
6425 /*
6426 * If 'autoread' is set, the buffer has no changes and the file still
6427 * exists, reload the buffer. Use the buffer-local option value if it
6428 * was set, the global option value otherwise.
6429 */
6430 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6431 && !bufIsChanged(buf) && stat_res >= 0)
6432 reload = TRUE;
6433 else
6434 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006435 if (stat_res < 0)
6436 reason = "deleted";
6437 else if (bufIsChanged(buf))
6438 reason = "conflict";
6439 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6440 reason = "changed";
6441 else if (orig_mode != buf->b_orig_mode)
6442 reason = "mode";
6443 else
6444 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006446#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447 /*
6448 * Only give the warning if there are no FileChangedShell
6449 * autocommands.
6450 * Avoid being called recursively by setting "busy".
6451 */
6452 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006453# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006454 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6455 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6458 buf->b_fname, buf->b_fname, FALSE, buf);
6459 busy = FALSE;
6460 if (n)
6461 {
6462 if (!buf_valid(buf))
6463 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006464# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006465 s = get_vim_var_str(VV_FCS_CHOICE);
6466 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6467 reload = TRUE;
6468 else if (STRCMP(s, "ask") == 0)
6469 n = FALSE;
6470 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006471# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006472 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006474 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475#endif
6476 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006477 if (*reason == 'd')
6478 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 else
6480 {
6481 helpmesg = TRUE;
6482#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6483 can_reload = TRUE;
6484#endif
6485 /*
6486 * Check if the file contents really changed to avoid
6487 * giving a warning when only the timestamp was set (e.g.,
6488 * checked out of CVS). Always warn when the buffer was
6489 * changed.
6490 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006491 if (reason[2] == 'n')
6492 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006494 mesg2 = _("See \":help W12\" for more info.");
6495 }
6496 else if (reason[1] == 'h')
6497 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006499 mesg2 = _("See \":help W11\" for more info.");
6500 }
6501 else if (*reason == 'm')
6502 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006504 mesg2 = _("See \":help W16\" for more info.");
6505 }
6506 /* Else: only timestamp changed, ignored */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 }
6508 }
6509 }
6510
6511 }
6512 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6513 && vim_fexists(buf->b_ffname))
6514 {
6515 retval = 1;
6516 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6517 buf->b_flags |= BF_NEW_W;
6518#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6519 can_reload = TRUE;
6520#endif
6521 }
6522
6523 if (mesg != NULL)
6524 {
6525 path = home_replace_save(buf, buf->b_fname);
6526 if (path != NULL)
6527 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006528 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529 mesg2 = "";
6530 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6531 + STRLEN(mesg2) + 2));
6532 sprintf((char *)tbuf, mesg, path);
6533#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6534 if (can_reload)
6535 {
6536 if (*mesg2 != NUL)
6537 {
6538 STRCAT(tbuf, "\n");
6539 STRCAT(tbuf, mesg2);
6540 }
6541 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6542 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6543 reload = TRUE;
6544 }
6545 else
6546#endif
6547 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6548 {
6549 if (*mesg2 != NUL)
6550 {
6551 STRCAT(tbuf, "; ");
6552 STRCAT(tbuf, mesg2);
6553 }
6554 EMSG(tbuf);
6555 retval = 2;
6556 }
6557 else
6558 {
Bram Moolenaared203462004-06-16 11:19:22 +00006559# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006561# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 {
6563 msg_start();
6564 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6565 if (*mesg2 != NUL)
6566 msg_puts_attr((char_u *)mesg2,
6567 hl_attr(HLF_W) + MSG_HIST);
6568 msg_clr_eos();
6569 (void)msg_end();
6570 if (emsg_silent == 0)
6571 {
6572 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00006573# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00006575# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 /* give the user some time to think about it */
6577 ui_delay(1000L, TRUE);
6578
6579 /* don't redraw and erase the message */
6580 redraw_cmdline = FALSE;
6581 }
6582 }
6583 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 }
6585
6586 vim_free(path);
6587 vim_free(tbuf);
6588 }
6589 }
6590
6591 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006592 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006593 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594
Bram Moolenaar56718732006-03-15 22:53:57 +00006595#ifdef FEAT_AUTOCMD
6596 if (buf_valid(buf))
6597 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
6598 buf->b_fname, buf->b_fname, FALSE, buf);
6599#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600#ifdef FEAT_GUI
6601 /* restore this in case an autocommand has set it; it would break
6602 * 'mousefocus' */
6603 need_mouse_correct = save_mouse_correct;
6604#endif
6605
6606 return retval;
6607}
6608
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006609/*
6610 * Reload a buffer that is already loaded.
6611 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00006612 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
6613 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006614 */
6615 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00006616buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006617 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006618 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006619{
6620 exarg_T ea;
6621 pos_T old_cursor;
6622 linenr_T old_topline;
6623 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006624 buf_T *savebuf;
6625 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006626 aco_save_T aco;
6627
6628 /* set curwin/curbuf for "buf" and save some things */
6629 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006630
6631 /* We only want to read the text from the file, not reset the syntax
6632 * highlighting, clear marks, diff status, etc. Force the fileformat
6633 * and encoding to be the same. */
6634 if (prep_exarg(&ea, buf) == OK)
6635 {
6636 old_cursor = curwin->w_cursor;
6637 old_topline = curwin->w_topline;
6638
6639 /*
6640 * To behave like when a new file is edited (matters for
6641 * BufReadPost autocommands) we first need to delete the current
6642 * buffer contents. But if reading the file fails we should keep
6643 * the old contents. Can't use memory only, the file might be
6644 * too big. Use a hidden buffer to move the buffer contents to.
6645 */
6646 if (bufempty())
6647 savebuf = NULL;
6648 else
6649 {
6650 /* Allocate a buffer without putting it in the buffer list. */
6651 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00006652 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006653 {
6654 /* Open the memline. */
6655 curbuf = savebuf;
6656 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00006657 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006658 curbuf = buf;
6659 curwin->w_buffer = buf;
6660 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00006661 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006662 || move_lines(buf, savebuf) == FAIL)
6663 {
6664 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
6665 buf->b_fname);
6666 saved = FAIL;
6667 }
6668 }
6669
6670 if (saved == OK)
6671 {
6672 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
6673#ifdef FEAT_AUTOCMD
6674 keep_filetype = TRUE; /* don't detect 'filetype' */
6675#endif
6676 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
6677 (linenr_T)0,
6678 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
6679 {
6680#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6681 if (!aborting())
6682#endif
6683 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00006684 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006685 {
6686 /* Put the text back from the save buffer. First
6687 * delete any lines that readfile() added. */
6688 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00006689 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006690 break;
6691 (void)move_lines(savebuf, buf);
6692 }
6693 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00006694 else if (buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006695 {
6696 /* Mark the buffer as unmodified and free undo info. */
6697 unchanged(buf, TRUE);
6698 u_blockfree(buf);
6699 u_clearall(buf);
6700 }
6701 }
6702 vim_free(ea.cmd);
6703
Bram Moolenaar8424a622006-04-19 21:23:36 +00006704 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006705 wipe_buffer(savebuf, FALSE);
6706
6707#ifdef FEAT_DIFF
6708 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00006709 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006710#endif
6711
6712 /* Restore the topline and cursor position and check it (lines may
6713 * have been removed). */
6714 if (old_topline > curbuf->b_ml.ml_line_count)
6715 curwin->w_topline = curbuf->b_ml.ml_line_count;
6716 else
6717 curwin->w_topline = old_topline;
6718 curwin->w_cursor = old_cursor;
6719 check_cursor();
6720 update_topline();
6721#ifdef FEAT_AUTOCMD
6722 keep_filetype = FALSE;
6723#endif
6724#ifdef FEAT_FOLDING
6725 {
6726 win_T *wp;
6727
6728 /* Update folds unless they are defined manually. */
6729 FOR_ALL_WINDOWS(wp)
6730 if (wp->w_buffer == curwin->w_buffer
6731 && !foldmethodIsManual(wp))
6732 foldUpdateAll(wp);
6733 }
6734#endif
6735 /* If the mode didn't change and 'readonly' was set, keep the old
6736 * value; the user probably used the ":view" command. But don't
6737 * reset it, might have had a read error. */
6738 if (orig_mode == curbuf->b_orig_mode)
6739 curbuf->b_p_ro |= old_ro;
6740 }
6741
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006742 /* restore curwin/curbuf and a few other things */
6743 aucmd_restbuf(&aco);
6744 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006745}
6746
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747/*ARGSUSED*/
6748 void
6749buf_store_time(buf, st, fname)
6750 buf_T *buf;
6751 struct stat *st;
6752 char_u *fname;
6753{
6754 buf->b_mtime = (long)st->st_mtime;
6755 buf->b_orig_size = (size_t)st->st_size;
6756#ifdef HAVE_ST_MODE
6757 buf->b_orig_mode = (int)st->st_mode;
6758#else
6759 buf->b_orig_mode = mch_getperm(fname);
6760#endif
6761}
6762
6763/*
6764 * Adjust the line with missing eol, used for the next write.
6765 * Used for do_filter(), when the input lines for the filter are deleted.
6766 */
6767 void
6768write_lnum_adjust(offset)
6769 linenr_T offset;
6770{
Bram Moolenaardf177f62005-02-22 08:39:57 +00006771 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 write_no_eol_lnum += offset;
6773}
6774
6775#if defined(TEMPDIRNAMES) || defined(PROTO)
6776static long temp_count = 0; /* Temp filename counter. */
6777
6778/*
6779 * Delete the temp directory and all files it contains.
6780 */
6781 void
6782vim_deltempdir()
6783{
6784 char_u **files;
6785 int file_count;
6786 int i;
6787
6788 if (vim_tempdir != NULL)
6789 {
6790 sprintf((char *)NameBuff, "%s*", vim_tempdir);
6791 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
6792 EW_DIR|EW_FILE|EW_SILENT) == OK)
6793 {
6794 for (i = 0; i < file_count; ++i)
6795 mch_remove(files[i]);
6796 FreeWild(file_count, files);
6797 }
6798 gettail(NameBuff)[-1] = NUL;
6799 (void)mch_rmdir(NameBuff);
6800
6801 vim_free(vim_tempdir);
6802 vim_tempdir = NULL;
6803 }
6804}
6805#endif
6806
6807/*
6808 * vim_tempname(): Return a unique name that can be used for a temp file.
6809 *
6810 * The temp file is NOT created.
6811 *
6812 * The returned pointer is to allocated memory.
6813 * The returned pointer is NULL if no valid name was found.
6814 */
6815/*ARGSUSED*/
6816 char_u *
6817vim_tempname(extra_char)
6818 int extra_char; /* character to use in the name instead of '?' */
6819{
6820#ifdef USE_TMPNAM
6821 char_u itmp[L_tmpnam]; /* use tmpnam() */
6822#else
6823 char_u itmp[TEMPNAMELEN];
6824#endif
6825
6826#ifdef TEMPDIRNAMES
6827 static char *(tempdirs[]) = {TEMPDIRNAMES};
6828 int i;
6829 long nr;
6830 long off;
6831# ifndef EEXIST
6832 struct stat st;
6833# endif
6834
6835 /*
6836 * This will create a directory for private use by this instance of Vim.
6837 * This is done once, and the same directory is used for all temp files.
6838 * This method avoids security problems because of symlink attacks et al.
6839 * It's also a bit faster, because we only need to check for an existing
6840 * file when creating the directory and not for each temp file.
6841 */
6842 if (vim_tempdir == NULL)
6843 {
6844 /*
6845 * Try the entries in TEMPDIRNAMES to create the temp directory.
6846 */
6847 for (i = 0; i < sizeof(tempdirs) / sizeof(char *); ++i)
6848 {
6849 /* expand $TMP, leave room for "/v1100000/999999999" */
6850 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
6851 if (mch_isdir(itmp)) /* directory exists */
6852 {
6853# ifdef __EMX__
6854 /* If $TMP contains a forward slash (perhaps using bash or
6855 * tcsh), don't add a backslash, use a forward slash!
6856 * Adding 2 backslashes didn't work. */
6857 if (vim_strchr(itmp, '/') != NULL)
6858 STRCAT(itmp, "/");
6859 else
6860# endif
6861 add_pathsep(itmp);
6862
6863 /* Get an arbitrary number of up to 6 digits. When it's
6864 * unlikely that it already exists it will be faster,
6865 * otherwise it doesn't matter. The use of mkdir() avoids any
6866 * security problems because of the predictable number. */
6867 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
6868
6869 /* Try up to 10000 different values until we find a name that
6870 * doesn't exist. */
6871 for (off = 0; off < 10000L; ++off)
6872 {
6873 int r;
6874#if defined(UNIX) || defined(VMS)
6875 mode_t umask_save;
6876#endif
6877
6878 sprintf((char *)itmp + STRLEN(itmp), "v%ld", nr + off);
6879# ifndef EEXIST
6880 /* If mkdir() does not set errno to EEXIST, check for
6881 * existing file here. There is a race condition then,
6882 * although it's fail-safe. */
6883 if (mch_stat((char *)itmp, &st) >= 0)
6884 continue;
6885# endif
6886#if defined(UNIX) || defined(VMS)
6887 /* Make sure the umask doesn't remove the executable bit.
6888 * "repl" has been reported to use "177". */
6889 umask_save = umask(077);
6890#endif
6891 r = vim_mkdir(itmp, 0700);
6892#if defined(UNIX) || defined(VMS)
6893 (void)umask(umask_save);
6894#endif
6895 if (r == 0)
6896 {
6897 char_u *buf;
6898
6899 /* Directory was created, use this name.
6900 * Expand to full path; When using the current
6901 * directory a ":cd" would confuse us. */
6902 buf = alloc((unsigned)MAXPATHL + 1);
6903 if (buf != NULL)
6904 {
6905 if (vim_FullName(itmp, buf, MAXPATHL, FALSE)
6906 == FAIL)
6907 STRCPY(buf, itmp);
6908# ifdef __EMX__
6909 if (vim_strchr(buf, '/') != NULL)
6910 STRCAT(buf, "/");
6911 else
6912# endif
6913 add_pathsep(buf);
6914 vim_tempdir = vim_strsave(buf);
6915 vim_free(buf);
6916 }
6917 break;
6918 }
6919# ifdef EEXIST
6920 /* If the mkdir() didn't fail because the file/dir exists,
6921 * we probably can't create any dir here, try another
6922 * place. */
6923 if (errno != EEXIST)
6924# endif
6925 break;
6926 }
6927 if (vim_tempdir != NULL)
6928 break;
6929 }
6930 }
6931 }
6932
6933 if (vim_tempdir != NULL)
6934 {
6935 /* There is no need to check if the file exists, because we own the
6936 * directory and nobody else creates a file in it. */
6937 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
6938 return vim_strsave(itmp);
6939 }
6940
6941 return NULL;
6942
6943#else /* TEMPDIRNAMES */
6944
6945# ifdef WIN3264
6946 char szTempFile[_MAX_PATH + 1];
6947 char buf4[4];
6948 char_u *retval;
6949 char_u *p;
6950
6951 STRCPY(itmp, "");
6952 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
6953 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
6954 strcpy(buf4, "VIM");
6955 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
6956 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
6957 return NULL;
6958 /* GetTempFileName() will create the file, we don't want that */
6959 (void)DeleteFile(itmp);
6960
6961 /* Backslashes in a temp file name cause problems when filtering with
6962 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
6963 * didn't set 'shellslash'. */
6964 retval = vim_strsave(itmp);
6965 if (*p_shcf == '-' || p_ssl)
6966 for (p = retval; *p; ++p)
6967 if (*p == '\\')
6968 *p = '/';
6969 return retval;
6970
6971# else /* WIN3264 */
6972
6973# ifdef USE_TMPNAM
6974 /* tmpnam() will make its own name */
6975 if (*tmpnam((char *)itmp) == NUL)
6976 return NULL;
6977# else
6978 char_u *p;
6979
6980# ifdef VMS_TEMPNAM
6981 /* mktemp() is not working on VMS. It seems to be
6982 * a do-nothing function. Therefore we use tempnam().
6983 */
6984 sprintf((char *)itmp, "VIM%c", extra_char);
6985 p = (char_u *)tempnam("tmp:", (char *)itmp);
6986 if (p != NULL)
6987 {
6988 /* VMS will use '.LOG' if we don't explicitly specify an extension,
6989 * and VIM will then be unable to find the file later */
6990 STRCPY(itmp, p);
6991 STRCAT(itmp, ".txt");
6992 free(p);
6993 }
6994 else
6995 return NULL;
6996# else
6997 STRCPY(itmp, TEMPNAME);
6998 if ((p = vim_strchr(itmp, '?')) != NULL)
6999 *p = extra_char;
7000 if (mktemp((char *)itmp) == NULL)
7001 return NULL;
7002# endif
7003# endif
7004
7005 return vim_strsave(itmp);
7006# endif /* WIN3264 */
7007#endif /* TEMPDIRNAMES */
7008}
7009
7010#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7011/*
7012 * Convert all backslashes in fname to forward slashes in-place.
7013 */
7014 void
7015forward_slash(fname)
7016 char_u *fname;
7017{
7018 char_u *p;
7019
7020 for (p = fname; *p != NUL; ++p)
7021# ifdef FEAT_MBYTE
7022 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007023 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 ++p;
7025 else
7026# endif
7027 if (*p == '\\')
7028 *p = '/';
7029}
7030#endif
7031
7032
7033/*
7034 * Code for automatic commands.
7035 *
7036 * Only included when "FEAT_AUTOCMD" has been defined.
7037 */
7038
7039#if defined(FEAT_AUTOCMD) || defined(PROTO)
7040
7041/*
7042 * The autocommands are stored in a list for each event.
7043 * Autocommands for the same pattern, that are consecutive, are joined
7044 * together, to avoid having to match the pattern too often.
7045 * The result is an array of Autopat lists, which point to AutoCmd lists:
7046 *
7047 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7048 * Autopat.cmds Autopat.cmds
7049 * | |
7050 * V V
7051 * AutoCmd.next AutoCmd.next
7052 * | |
7053 * V V
7054 * AutoCmd.next NULL
7055 * |
7056 * V
7057 * NULL
7058 *
7059 * first_autopat[1] --> Autopat.next --> NULL
7060 * Autopat.cmds
7061 * |
7062 * V
7063 * AutoCmd.next
7064 * |
7065 * V
7066 * NULL
7067 * etc.
7068 *
7069 * The order of AutoCmds is important, this is the order in which they were
7070 * defined and will have to be executed.
7071 */
7072typedef struct AutoCmd
7073{
7074 char_u *cmd; /* The command to be executed (NULL
7075 when command has been removed) */
7076 char nested; /* If autocommands nest here */
7077 char last; /* last command in list */
7078#ifdef FEAT_EVAL
7079 scid_T scriptID; /* script ID where defined */
7080#endif
7081 struct AutoCmd *next; /* Next AutoCmd in list */
7082} AutoCmd;
7083
7084typedef struct AutoPat
7085{
7086 int group; /* group ID */
7087 char_u *pat; /* pattern as typed (NULL when pattern
7088 has been removed) */
7089 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007090 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 char allow_dirs; /* Pattern may match whole path */
7092 char last; /* last pattern for apply_autocmds() */
7093 AutoCmd *cmds; /* list of commands to do */
7094 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007095 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096} AutoPat;
7097
7098static struct event_name
7099{
7100 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007101 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102} event_names[] =
7103{
7104 {"BufAdd", EVENT_BUFADD},
7105 {"BufCreate", EVENT_BUFADD},
7106 {"BufDelete", EVENT_BUFDELETE},
7107 {"BufEnter", EVENT_BUFENTER},
7108 {"BufFilePost", EVENT_BUFFILEPOST},
7109 {"BufFilePre", EVENT_BUFFILEPRE},
7110 {"BufHidden", EVENT_BUFHIDDEN},
7111 {"BufLeave", EVENT_BUFLEAVE},
7112 {"BufNew", EVENT_BUFNEW},
7113 {"BufNewFile", EVENT_BUFNEWFILE},
7114 {"BufRead", EVENT_BUFREADPOST},
7115 {"BufReadCmd", EVENT_BUFREADCMD},
7116 {"BufReadPost", EVENT_BUFREADPOST},
7117 {"BufReadPre", EVENT_BUFREADPRE},
7118 {"BufUnload", EVENT_BUFUNLOAD},
7119 {"BufWinEnter", EVENT_BUFWINENTER},
7120 {"BufWinLeave", EVENT_BUFWINLEAVE},
7121 {"BufWipeout", EVENT_BUFWIPEOUT},
7122 {"BufWrite", EVENT_BUFWRITEPRE},
7123 {"BufWritePost", EVENT_BUFWRITEPOST},
7124 {"BufWritePre", EVENT_BUFWRITEPRE},
7125 {"BufWriteCmd", EVENT_BUFWRITECMD},
7126 {"CmdwinEnter", EVENT_CMDWINENTER},
7127 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007128 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007129 {"CursorHold", EVENT_CURSORHOLD},
7130 {"CursorHoldI", EVENT_CURSORHOLDI},
7131 {"CursorMoved", EVENT_CURSORMOVED},
7132 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7134 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7136 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7137 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7138 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007139 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 {"FileChangedRO", EVENT_FILECHANGEDRO},
7141 {"FileReadPost", EVENT_FILEREADPOST},
7142 {"FileReadPre", EVENT_FILEREADPRE},
7143 {"FileReadCmd", EVENT_FILEREADCMD},
7144 {"FileType", EVENT_FILETYPE},
7145 {"FileWritePost", EVENT_FILEWRITEPOST},
7146 {"FileWritePre", EVENT_FILEWRITEPRE},
7147 {"FileWriteCmd", EVENT_FILEWRITECMD},
7148 {"FilterReadPost", EVENT_FILTERREADPOST},
7149 {"FilterReadPre", EVENT_FILTERREADPRE},
7150 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7151 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7152 {"FocusGained", EVENT_FOCUSGAINED},
7153 {"FocusLost", EVENT_FOCUSLOST},
7154 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7155 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007156 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007157 {"InsertChange", EVENT_INSERTCHANGE},
7158 {"InsertEnter", EVENT_INSERTENTER},
7159 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007160 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007161 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7162 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007164 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007165 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7166 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007167 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007168 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007169 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 {"StdinReadPost", EVENT_STDINREADPOST},
7171 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007172 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007173 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007174 {"TabEnter", EVENT_TABENTER},
7175 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176 {"TermChanged", EVENT_TERMCHANGED},
7177 {"TermResponse", EVENT_TERMRESPONSE},
7178 {"User", EVENT_USER},
7179 {"VimEnter", EVENT_VIMENTER},
7180 {"VimLeave", EVENT_VIMLEAVE},
7181 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7182 {"WinEnter", EVENT_WINENTER},
7183 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007184 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007185 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007186};
7187
7188static AutoPat *first_autopat[NUM_EVENTS] =
7189{
7190 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7191 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7192 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7193 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007194 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7195 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196};
7197
7198/*
7199 * struct used to keep status while executing autocommands for an event.
7200 */
7201typedef struct AutoPatCmd
7202{
7203 AutoPat *curpat; /* next AutoPat to examine */
7204 AutoCmd *nextcmd; /* next AutoCmd to execute */
7205 int group; /* group being used */
7206 char_u *fname; /* fname to match with */
7207 char_u *sfname; /* sfname to match with */
7208 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007209 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007210 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7211 buf is deleted */
7212 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213} AutoPatCmd;
7214
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007215static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007216
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217/*
7218 * augroups stores a list of autocmd group names.
7219 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007220static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7222
7223/*
7224 * The ID of the current group. Group 0 is the default one.
7225 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226static int current_augroup = AUGROUP_DEFAULT;
7227
7228static int au_need_clean = FALSE; /* need to delete marked patterns */
7229
Bram Moolenaar754b5602006-02-09 23:53:20 +00007230static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231static void au_remove_pat __ARGS((AutoPat *ap));
7232static void au_remove_cmds __ARGS((AutoPat *ap));
7233static void au_cleanup __ARGS((void));
7234static int au_new_group __ARGS((char_u *name));
7235static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007236static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7237static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007239static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007241static 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 +00007242static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007243static 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 +00007244static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7245
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007246
Bram Moolenaar754b5602006-02-09 23:53:20 +00007247static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007248static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007249static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250
7251/*
7252 * Show the autocommands for one AutoPat.
7253 */
7254 static void
7255show_autocmd(ap, event)
7256 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007257 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258{
7259 AutoCmd *ac;
7260
7261 /* Check for "got_int" (here and at various places below), which is set
7262 * when "q" has been hit for the "--more--" prompt */
7263 if (got_int)
7264 return;
7265 if (ap->pat == NULL) /* pattern has been removed */
7266 return;
7267
7268 msg_putchar('\n');
7269 if (got_int)
7270 return;
7271 if (event != last_event || ap->group != last_group)
7272 {
7273 if (ap->group != AUGROUP_DEFAULT)
7274 {
7275 if (AUGROUP_NAME(ap->group) == NULL)
7276 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7277 else
7278 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7279 msg_puts((char_u *)" ");
7280 }
7281 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7282 last_event = event;
7283 last_group = ap->group;
7284 msg_putchar('\n');
7285 if (got_int)
7286 return;
7287 }
7288 msg_col = 4;
7289 msg_outtrans(ap->pat);
7290
7291 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7292 {
7293 if (ac->cmd != NULL) /* skip removed commands */
7294 {
7295 if (msg_col >= 14)
7296 msg_putchar('\n');
7297 msg_col = 14;
7298 if (got_int)
7299 return;
7300 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007301#ifdef FEAT_EVAL
7302 if (p_verbose > 0)
7303 last_set_msg(ac->scriptID);
7304#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305 if (got_int)
7306 return;
7307 if (ac->next != NULL)
7308 {
7309 msg_putchar('\n');
7310 if (got_int)
7311 return;
7312 }
7313 }
7314 }
7315}
7316
7317/*
7318 * Mark an autocommand pattern for deletion.
7319 */
7320 static void
7321au_remove_pat(ap)
7322 AutoPat *ap;
7323{
7324 vim_free(ap->pat);
7325 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007326 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327 au_need_clean = TRUE;
7328}
7329
7330/*
7331 * Mark all commands for a pattern for deletion.
7332 */
7333 static void
7334au_remove_cmds(ap)
7335 AutoPat *ap;
7336{
7337 AutoCmd *ac;
7338
7339 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7340 {
7341 vim_free(ac->cmd);
7342 ac->cmd = NULL;
7343 }
7344 au_need_clean = TRUE;
7345}
7346
7347/*
7348 * Cleanup autocommands and patterns that have been deleted.
7349 * This is only done when not executing autocommands.
7350 */
7351 static void
7352au_cleanup()
7353{
7354 AutoPat *ap, **prev_ap;
7355 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007356 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357
7358 if (autocmd_busy || !au_need_clean)
7359 return;
7360
7361 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007362 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7363 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364 {
7365 /* loop over all autocommand patterns */
7366 prev_ap = &(first_autopat[(int)event]);
7367 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7368 {
7369 /* loop over all commands for this pattern */
7370 prev_ac = &(ap->cmds);
7371 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7372 {
7373 /* remove the command if the pattern is to be deleted or when
7374 * the command has been marked for deletion */
7375 if (ap->pat == NULL || ac->cmd == NULL)
7376 {
7377 *prev_ac = ac->next;
7378 vim_free(ac->cmd);
7379 vim_free(ac);
7380 }
7381 else
7382 prev_ac = &(ac->next);
7383 }
7384
7385 /* remove the pattern if it has been marked for deletion */
7386 if (ap->pat == NULL)
7387 {
7388 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007389 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 vim_free(ap);
7391 }
7392 else
7393 prev_ap = &(ap->next);
7394 }
7395 }
7396
7397 au_need_clean = FALSE;
7398}
7399
7400/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007401 * Called when buffer is freed, to remove/invalidate related buffer-local
7402 * autocmds.
7403 */
7404 void
7405aubuflocal_remove(buf)
7406 buf_T *buf;
7407{
7408 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007409 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007410 AutoPatCmd *apc;
7411
7412 /* invalidate currently executing autocommands */
7413 for (apc = active_apc_list; apc; apc = apc->next)
7414 if (buf->b_fnum == apc->arg_bufnr)
7415 apc->arg_bufnr = 0;
7416
7417 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007418 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7419 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007420 /* loop over all autocommand patterns */
7421 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7422 if (ap->buflocal_nr == buf->b_fnum)
7423 {
7424 au_remove_pat(ap);
7425 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007426 {
7427 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007428 smsg((char_u *)
7429 _("auto-removing autocommand: %s <buffer=%d>"),
7430 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007431 verbose_leave();
7432 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007433 }
7434 au_cleanup();
7435}
7436
7437/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 * Add an autocmd group name.
7439 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7440 */
7441 static int
7442au_new_group(name)
7443 char_u *name;
7444{
7445 int i;
7446
7447 i = au_find_group(name);
7448 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7449 {
7450 /* First try using a free entry. */
7451 for (i = 0; i < augroups.ga_len; ++i)
7452 if (AUGROUP_NAME(i) == NULL)
7453 break;
7454 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7455 return AUGROUP_ERROR;
7456
7457 AUGROUP_NAME(i) = vim_strsave(name);
7458 if (AUGROUP_NAME(i) == NULL)
7459 return AUGROUP_ERROR;
7460 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 }
7463
7464 return i;
7465}
7466
7467 static void
7468au_del_group(name)
7469 char_u *name;
7470{
7471 int i;
7472
7473 i = au_find_group(name);
7474 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7475 EMSG2(_("E367: No such group: \"%s\""), name);
7476 else
7477 {
7478 vim_free(AUGROUP_NAME(i));
7479 AUGROUP_NAME(i) = NULL;
7480 }
7481}
7482
7483/*
7484 * Find the ID of an autocmd group name.
7485 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7486 */
7487 static int
7488au_find_group(name)
7489 char_u *name;
7490{
7491 int i;
7492
7493 for (i = 0; i < augroups.ga_len; ++i)
7494 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7495 return i;
7496 return AUGROUP_ERROR;
7497}
7498
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007499/*
7500 * Return TRUE if augroup "name" exists.
7501 */
7502 int
7503au_has_group(name)
7504 char_u *name;
7505{
7506 return au_find_group(name) != AUGROUP_ERROR;
7507}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007508
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509/*
7510 * ":augroup {name}".
7511 */
7512 void
7513do_augroup(arg, del_group)
7514 char_u *arg;
7515 int del_group;
7516{
7517 int i;
7518
7519 if (del_group)
7520 {
7521 if (*arg == NUL)
7522 EMSG(_(e_argreq));
7523 else
7524 au_del_group(arg);
7525 }
7526 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
7527 current_augroup = AUGROUP_DEFAULT;
7528 else if (*arg) /* ":aug xxx": switch to group xxx */
7529 {
7530 i = au_new_group(arg);
7531 if (i != AUGROUP_ERROR)
7532 current_augroup = i;
7533 }
7534 else /* ":aug": list the group names */
7535 {
7536 msg_start();
7537 for (i = 0; i < augroups.ga_len; ++i)
7538 {
7539 if (AUGROUP_NAME(i) != NULL)
7540 {
7541 msg_puts(AUGROUP_NAME(i));
7542 msg_puts((char_u *)" ");
7543 }
7544 }
7545 msg_clr_eos();
7546 msg_end();
7547 }
7548}
7549
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007550#if defined(EXITFREE) || defined(PROTO)
7551 void
7552free_all_autocmds()
7553{
7554 for (current_augroup = -1; current_augroup < augroups.ga_len;
7555 ++current_augroup)
7556 do_autocmd((char_u *)"", TRUE);
7557 ga_clear_strings(&augroups);
7558}
7559#endif
7560
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561/*
7562 * Return the event number for event name "start".
7563 * Return NUM_EVENTS if the event name was not found.
7564 * Return a pointer to the next event name in "end".
7565 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007566 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567event_name2nr(start, end)
7568 char_u *start;
7569 char_u **end;
7570{
7571 char_u *p;
7572 int i;
7573 int len;
7574
7575 /* the event name ends with end of line, a blank or a comma */
7576 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
7577 ;
7578 for (i = 0; event_names[i].name != NULL; ++i)
7579 {
7580 len = (int)STRLEN(event_names[i].name);
7581 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
7582 break;
7583 }
7584 if (*p == ',')
7585 ++p;
7586 *end = p;
7587 if (event_names[i].name == NULL)
7588 return NUM_EVENTS;
7589 return event_names[i].event;
7590}
7591
7592/*
7593 * Return the name for event "event".
7594 */
7595 static char_u *
7596event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007597 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598{
7599 int i;
7600
7601 for (i = 0; event_names[i].name != NULL; ++i)
7602 if (event_names[i].event == event)
7603 return (char_u *)event_names[i].name;
7604 return (char_u *)"Unknown";
7605}
7606
7607/*
7608 * Scan over the events. "*" stands for all events.
7609 */
7610 static char_u *
7611find_end_event(arg, have_group)
7612 char_u *arg;
7613 int have_group; /* TRUE when group name was found */
7614{
7615 char_u *pat;
7616 char_u *p;
7617
7618 if (*arg == '*')
7619 {
7620 if (arg[1] && !vim_iswhite(arg[1]))
7621 {
7622 EMSG2(_("E215: Illegal character after *: %s"), arg);
7623 return NULL;
7624 }
7625 pat = arg + 1;
7626 }
7627 else
7628 {
7629 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
7630 {
7631 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
7632 {
7633 if (have_group)
7634 EMSG2(_("E216: No such event: %s"), pat);
7635 else
7636 EMSG2(_("E216: No such group or event: %s"), pat);
7637 return NULL;
7638 }
7639 }
7640 }
7641 return pat;
7642}
7643
7644/*
7645 * Return TRUE if "event" is included in 'eventignore'.
7646 */
7647 static int
7648event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007649 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650{
7651 char_u *p = p_ei;
7652
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007653 while (*p != NUL)
7654 {
7655 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
7656 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657 if (event_name2nr(p, &p) == event)
7658 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660
7661 return FALSE;
7662}
7663
7664/*
7665 * Return OK when the contents of p_ei is valid, FAIL otherwise.
7666 */
7667 int
7668check_ei()
7669{
7670 char_u *p = p_ei;
7671
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007673 {
7674 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
7675 {
7676 p += 3;
7677 if (*p == ',')
7678 ++p;
7679 }
7680 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007681 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00007682 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007683
7684 return OK;
7685}
7686
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007687# if defined(FEAT_SYN_HL) || defined(PROTO)
7688
7689/*
7690 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
7691 * buffer loaded into the window. "what" must start with a comma.
7692 * Returns the old value of 'eventignore' in allocated memory.
7693 */
7694 char_u *
7695au_event_disable(what)
7696 char *what;
7697{
7698 char_u *new_ei;
7699 char_u *save_ei;
7700
7701 save_ei = vim_strsave(p_ei);
7702 if (save_ei != NULL)
7703 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00007704 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007705 if (new_ei != NULL)
7706 {
7707 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00007708 set_string_option_direct((char_u *)"ei", -1, new_ei,
7709 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007710 vim_free(new_ei);
7711 }
7712 }
7713 return save_ei;
7714}
7715
7716 void
7717au_event_restore(old_ei)
7718 char_u *old_ei;
7719{
7720 if (old_ei != NULL)
7721 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00007722 set_string_option_direct((char_u *)"ei", -1, old_ei,
7723 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007724 vim_free(old_ei);
7725 }
7726}
7727# endif /* FEAT_SYN_HL */
7728
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729/*
7730 * do_autocmd() -- implements the :autocmd command. Can be used in the
7731 * following ways:
7732 *
7733 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
7734 * will be automatically executed for <event>
7735 * when editing a file matching <pat>, in
7736 * the current group.
7737 * :autocmd <event> <pat> Show the auto-commands associated with
7738 * <event> and <pat>.
7739 * :autocmd <event> Show the auto-commands associated with
7740 * <event>.
7741 * :autocmd Show all auto-commands.
7742 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
7743 * <event> and <pat>, and add the command
7744 * <cmd>, for the current group.
7745 * :autocmd! <event> <pat> Remove all auto-commands associated with
7746 * <event> and <pat> for the current group.
7747 * :autocmd! <event> Remove all auto-commands associated with
7748 * <event> for the current group.
7749 * :autocmd! Remove ALL auto-commands for the current
7750 * group.
7751 *
7752 * Multiple events and patterns may be given separated by commas. Here are
7753 * some examples:
7754 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
7755 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
7756 *
7757 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00007758 *
7759 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760 */
7761 void
7762do_autocmd(arg, forceit)
7763 char_u *arg;
7764 int forceit;
7765{
7766 char_u *pat;
7767 char_u *envpat = NULL;
7768 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007769 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770 int need_free = FALSE;
7771 int nested = FALSE;
7772 int group;
7773
7774 /*
7775 * Check for a legal group name. If not, use AUGROUP_ALL.
7776 */
7777 group = au_get_grouparg(&arg);
7778 if (arg == NULL) /* out of memory */
7779 return;
7780
7781 /*
7782 * Scan over the events.
7783 * If we find an illegal name, return here, don't do anything.
7784 */
7785 pat = find_end_event(arg, group != AUGROUP_ALL);
7786 if (pat == NULL)
7787 return;
7788
7789 /*
7790 * Scan over the pattern. Put a NUL at the end.
7791 */
7792 pat = skipwhite(pat);
7793 cmd = pat;
7794 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
7795 cmd++;
7796 if (*cmd)
7797 *cmd++ = NUL;
7798
7799 /* Expand environment variables in the pattern. Set 'shellslash', we want
7800 * forward slashes here. */
7801 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
7802 {
7803#ifdef BACKSLASH_IN_FILENAME
7804 int p_ssl_save = p_ssl;
7805
7806 p_ssl = TRUE;
7807#endif
7808 envpat = expand_env_save(pat);
7809#ifdef BACKSLASH_IN_FILENAME
7810 p_ssl = p_ssl_save;
7811#endif
7812 if (envpat != NULL)
7813 pat = envpat;
7814 }
7815
7816 /*
7817 * Check for "nested" flag.
7818 */
7819 cmd = skipwhite(cmd);
7820 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
7821 {
7822 nested = TRUE;
7823 cmd = skipwhite(cmd + 6);
7824 }
7825
7826 /*
7827 * Find the start of the commands.
7828 * Expand <sfile> in it.
7829 */
7830 if (*cmd != NUL)
7831 {
7832 cmd = expand_sfile(cmd);
7833 if (cmd == NULL) /* some error */
7834 return;
7835 need_free = TRUE;
7836 }
7837
7838 /*
7839 * Print header when showing autocommands.
7840 */
7841 if (!forceit && *cmd == NUL)
7842 {
7843 /* Highlight title */
7844 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
7845 }
7846
7847 /*
7848 * Loop over the events.
7849 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007850 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851 last_group = AUGROUP_ERROR; /* for listing the group name */
7852 if (*arg == '*' || *arg == NUL)
7853 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00007854 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7855 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 if (do_autocmd_event(event, pat,
7857 nested, cmd, forceit, group) == FAIL)
7858 break;
7859 }
7860 else
7861 {
7862 while (*arg && !vim_iswhite(*arg))
7863 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
7864 nested, cmd, forceit, group) == FAIL)
7865 break;
7866 }
7867
7868 if (need_free)
7869 vim_free(cmd);
7870 vim_free(envpat);
7871}
7872
7873/*
7874 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
7875 * The "argp" argument is advanced to the following argument.
7876 *
7877 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
7878 */
7879 static int
7880au_get_grouparg(argp)
7881 char_u **argp;
7882{
7883 char_u *group_name;
7884 char_u *p;
7885 char_u *arg = *argp;
7886 int group = AUGROUP_ALL;
7887
7888 p = skiptowhite(arg);
7889 if (p > arg)
7890 {
7891 group_name = vim_strnsave(arg, (int)(p - arg));
7892 if (group_name == NULL) /* out of memory */
7893 return AUGROUP_ERROR;
7894 group = au_find_group(group_name);
7895 if (group == AUGROUP_ERROR)
7896 group = AUGROUP_ALL; /* no match, use all groups */
7897 else
7898 *argp = skipwhite(p); /* match, skip over group name */
7899 vim_free(group_name);
7900 }
7901 return group;
7902}
7903
7904/*
7905 * do_autocmd() for one event.
7906 * If *pat == NUL do for all patterns.
7907 * If *cmd == NUL show entries.
7908 * If forceit == TRUE delete entries.
7909 * If group is not AUGROUP_ALL, only use this group.
7910 */
7911 static int
7912do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007913 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914 char_u *pat;
7915 int nested;
7916 char_u *cmd;
7917 int forceit;
7918 int group;
7919{
7920 AutoPat *ap;
7921 AutoPat **prev_ap;
7922 AutoCmd *ac;
7923 AutoCmd **prev_ac;
7924 int brace_level;
7925 char_u *endpat;
7926 int findgroup;
7927 int allgroups;
7928 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007929 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007930 int buflocal_nr;
7931 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007932
7933 if (group == AUGROUP_ALL)
7934 findgroup = current_augroup;
7935 else
7936 findgroup = group;
7937 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
7938
7939 /*
7940 * Show or delete all patterns for an event.
7941 */
7942 if (*pat == NUL)
7943 {
7944 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7945 {
7946 if (forceit) /* delete the AutoPat, if it's in the current group */
7947 {
7948 if (ap->group == findgroup)
7949 au_remove_pat(ap);
7950 }
7951 else if (group == AUGROUP_ALL || ap->group == group)
7952 show_autocmd(ap, event);
7953 }
7954 }
7955
7956 /*
7957 * Loop through all the specified patterns.
7958 */
7959 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
7960 {
7961 /*
7962 * Find end of the pattern.
7963 * Watch out for a comma in braces, like "*.\{obj,o\}".
7964 */
7965 brace_level = 0;
7966 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
7967 || endpat[-1] == '\\'); ++endpat)
7968 {
7969 if (*endpat == '{')
7970 brace_level++;
7971 else if (*endpat == '}')
7972 brace_level--;
7973 }
7974 if (pat == endpat) /* ignore single comma */
7975 continue;
7976 patlen = (int)(endpat - pat);
7977
7978 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007979 * detect special <buflocal[=X]> buffer-local patterns
7980 */
7981 is_buflocal = FALSE;
7982 buflocal_nr = 0;
7983
7984 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
7985 && pat[patlen - 1] == '>')
7986 {
7987 /* Error will be printed only for addition. printing and removing
7988 * will proceed silently. */
7989 is_buflocal = TRUE;
7990 if (patlen == 8)
7991 buflocal_nr = curbuf->b_fnum;
7992 else if (patlen > 9 && pat[7] == '=')
7993 {
7994 /* <buffer=abuf> */
7995 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
7996 buflocal_nr = autocmd_bufnr;
7997 /* <buffer=123> */
7998 else if (skipdigits(pat + 8) == pat + patlen - 1)
7999 buflocal_nr = atoi((char *)pat + 8);
8000 }
8001 }
8002
8003 if (is_buflocal)
8004 {
8005 /* normalize pat into standard "<buffer>#N" form */
8006 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8007 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008008 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008009 }
8010
8011 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008012 * Find AutoPat entries with this pattern.
8013 */
8014 prev_ap = &first_autopat[(int)event];
8015 while ((ap = *prev_ap) != NULL)
8016 {
8017 if (ap->pat != NULL)
8018 {
8019 /* Accept a pattern when:
8020 * - a group was specified and it's that group, or a group was
8021 * not specified and it's the current group, or a group was
8022 * not specified and we are listing
8023 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008024 * - the pattern matches.
8025 * For <buffer[=X]>, this condition works because we normalize
8026 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008027 */
8028 if ((allgroups || ap->group == findgroup)
8029 && ap->patlen == patlen
8030 && STRNCMP(pat, ap->pat, patlen) == 0)
8031 {
8032 /*
8033 * Remove existing autocommands.
8034 * If adding any new autocmd's for this AutoPat, don't
8035 * delete the pattern from the autopat list, append to
8036 * this list.
8037 */
8038 if (forceit)
8039 {
8040 if (*cmd != NUL && ap->next == NULL)
8041 {
8042 au_remove_cmds(ap);
8043 break;
8044 }
8045 au_remove_pat(ap);
8046 }
8047
8048 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008049 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008050 */
8051 else if (*cmd == NUL)
8052 show_autocmd(ap, event);
8053
8054 /*
8055 * Add autocmd to this autopat, if it's the last one.
8056 */
8057 else if (ap->next == NULL)
8058 break;
8059 }
8060 }
8061 prev_ap = &ap->next;
8062 }
8063
8064 /*
8065 * Add a new command.
8066 */
8067 if (*cmd != NUL)
8068 {
8069 /*
8070 * If the pattern we want to add a command to does appear at the
8071 * end of the list (or not is not in the list at all), add the
8072 * pattern at the end of the list.
8073 */
8074 if (ap == NULL)
8075 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008076 /* refuse to add buffer-local ap if buffer number is invalid */
8077 if (is_buflocal && (buflocal_nr == 0
8078 || buflist_findnr(buflocal_nr) == NULL))
8079 {
8080 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8081 buflocal_nr);
8082 return FAIL;
8083 }
8084
Bram Moolenaar071d4272004-06-13 20:20:40 +00008085 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8086 if (ap == NULL)
8087 return FAIL;
8088 ap->pat = vim_strnsave(pat, patlen);
8089 ap->patlen = patlen;
8090 if (ap->pat == NULL)
8091 {
8092 vim_free(ap);
8093 return FAIL;
8094 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008095
8096 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008098 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008099 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008100 }
8101 else
8102 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008103 char_u *reg_pat;
8104
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008105 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008106 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008107 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008108 if (reg_pat != NULL)
8109 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008110 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008111 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008112 {
8113 vim_free(ap->pat);
8114 vim_free(ap);
8115 return FAIL;
8116 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008117 }
8118 ap->cmds = NULL;
8119 *prev_ap = ap;
8120 ap->next = NULL;
8121 if (group == AUGROUP_ALL)
8122 ap->group = current_augroup;
8123 else
8124 ap->group = group;
8125 }
8126
8127 /*
8128 * Add the autocmd at the end of the AutoCmd list.
8129 */
8130 prev_ac = &(ap->cmds);
8131 while ((ac = *prev_ac) != NULL)
8132 prev_ac = &ac->next;
8133 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8134 if (ac == NULL)
8135 return FAIL;
8136 ac->cmd = vim_strsave(cmd);
8137#ifdef FEAT_EVAL
8138 ac->scriptID = current_SID;
8139#endif
8140 if (ac->cmd == NULL)
8141 {
8142 vim_free(ac);
8143 return FAIL;
8144 }
8145 ac->next = NULL;
8146 *prev_ac = ac;
8147 ac->nested = nested;
8148 }
8149 }
8150
8151 au_cleanup(); /* may really delete removed patterns/commands now */
8152 return OK;
8153}
8154
8155/*
8156 * Implementation of ":doautocmd [group] event [fname]".
8157 * Return OK for success, FAIL for failure;
8158 */
8159 int
8160do_doautocmd(arg, do_msg)
8161 char_u *arg;
8162 int do_msg; /* give message for no matching autocmds? */
8163{
8164 char_u *fname;
8165 int nothing_done = TRUE;
8166 int group;
8167
8168 /*
8169 * Check for a legal group name. If not, use AUGROUP_ALL.
8170 */
8171 group = au_get_grouparg(&arg);
8172 if (arg == NULL) /* out of memory */
8173 return FAIL;
8174
8175 if (*arg == '*')
8176 {
8177 EMSG(_("E217: Can't execute autocommands for ALL events"));
8178 return FAIL;
8179 }
8180
8181 /*
8182 * Scan over the events.
8183 * If we find an illegal name, return here, don't do anything.
8184 */
8185 fname = find_end_event(arg, group != AUGROUP_ALL);
8186 if (fname == NULL)
8187 return FAIL;
8188
8189 fname = skipwhite(fname);
8190
8191 /*
8192 * Loop over the events.
8193 */
8194 while (*arg && !vim_iswhite(*arg))
8195 if (apply_autocmds_group(event_name2nr(arg, &arg),
8196 fname, NULL, TRUE, group, curbuf, NULL))
8197 nothing_done = FALSE;
8198
8199 if (nothing_done && do_msg)
8200 MSG(_("No matching autocommands"));
8201
8202#ifdef FEAT_EVAL
8203 return aborting() ? FAIL : OK;
8204#else
8205 return OK;
8206#endif
8207}
8208
8209/*
8210 * ":doautoall": execute autocommands for each loaded buffer.
8211 */
8212 void
8213ex_doautoall(eap)
8214 exarg_T *eap;
8215{
8216 int retval;
8217 aco_save_T aco;
8218 buf_T *buf;
8219
8220 /*
8221 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8222 * equal to curbuf, but for some buffers there may not be a window.
8223 * So we change the buffer for the current window for a moment. This
8224 * gives problems when the autocommands make changes to the list of
8225 * buffers or windows...
8226 */
8227 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8228 {
8229 if (curbuf->b_ml.ml_mfp != NULL)
8230 {
8231 /* find a window for this buffer and save some values */
8232 aucmd_prepbuf(&aco, buf);
8233
8234 /* execute the autocommands for this buffer */
8235 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008236
8237 /* Execute the modeline settings, but don't set window-local
8238 * options if we are using the current window for another buffer. */
8239 do_modelines(aco.save_curwin == NULL ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008240
8241 /* restore the current window */
8242 aucmd_restbuf(&aco);
8243
8244 /* stop if there is some error or buffer was deleted */
8245 if (retval == FAIL || !buf_valid(buf))
8246 break;
8247 }
8248 }
8249
8250 check_cursor(); /* just in case lines got deleted */
8251}
8252
8253/*
8254 * Prepare for executing autocommands for (hidden) buffer "buf".
8255 * Search a window for the current buffer. Save the cursor position and
8256 * screen offset.
8257 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008258 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008259 */
8260 void
8261aucmd_prepbuf(aco, buf)
8262 aco_save_T *aco; /* structure to save values in */
8263 buf_T *buf; /* new curbuf */
8264{
8265 win_T *win;
8266
8267 aco->new_curbuf = buf;
8268
8269 /* Find a window that is for the new buffer */
8270 if (buf == curbuf) /* be quick when buf is curbuf */
8271 win = curwin;
8272 else
8273#ifdef FEAT_WINDOWS
8274 for (win = firstwin; win != NULL; win = win->w_next)
8275 if (win->w_buffer == buf)
8276 break;
8277#else
8278 win = NULL;
8279#endif
8280
8281 /*
8282 * Prefer to use an existing window for the buffer, it has the least side
8283 * effects (esp. if "buf" is curbuf).
8284 * Otherwise, use curwin for "buf". It might make some items in the
8285 * window invalid. At least save the cursor and topline.
8286 */
8287 if (win != NULL)
8288 {
8289 /* there is a window for "buf", make it the curwin */
8290 aco->save_curwin = curwin;
8291 curwin = win;
8292 aco->save_buf = win->w_buffer;
8293 aco->new_curwin = win;
8294 }
8295 else
8296 {
8297 /* there is no window for "buf", use curwin */
8298 aco->save_curwin = NULL;
8299 aco->save_buf = curbuf;
8300 --curbuf->b_nwindows;
8301 curwin->w_buffer = buf;
8302 ++buf->b_nwindows;
8303
8304 /* save cursor and topline, set them to safe values */
8305 aco->save_cursor = curwin->w_cursor;
8306 curwin->w_cursor.lnum = 1;
8307 curwin->w_cursor.col = 0;
8308 aco->save_topline = curwin->w_topline;
8309 curwin->w_topline = 1;
8310#ifdef FEAT_DIFF
8311 aco->save_topfill = curwin->w_topfill;
8312 curwin->w_topfill = 0;
8313#endif
8314 }
8315
8316 curbuf = buf;
8317}
8318
8319/*
8320 * Cleanup after executing autocommands for a (hidden) buffer.
8321 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008322 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323 */
8324 void
8325aucmd_restbuf(aco)
8326 aco_save_T *aco; /* structure holding saved values */
8327{
8328 if (aco->save_curwin != NULL)
8329 {
8330 /* restore curwin */
8331#ifdef FEAT_WINDOWS
8332 if (win_valid(aco->save_curwin))
8333#endif
8334 {
8335 /* restore the buffer which was previously edited by curwin, if
8336 * it's still the same window and it's valid */
8337 if (curwin == aco->new_curwin
8338 && buf_valid(aco->save_buf)
8339 && aco->save_buf->b_ml.ml_mfp != NULL)
8340 {
8341 --curbuf->b_nwindows;
8342 curbuf = aco->save_buf;
8343 curwin->w_buffer = curbuf;
8344 ++curbuf->b_nwindows;
8345 }
8346
8347 curwin = aco->save_curwin;
8348 curbuf = curwin->w_buffer;
8349 }
8350 }
8351 else
8352 {
8353 /* restore buffer for curwin if it still exists and is loaded */
8354 if (buf_valid(aco->save_buf) && aco->save_buf->b_ml.ml_mfp != NULL)
8355 {
8356 --curbuf->b_nwindows;
8357 curbuf = aco->save_buf;
8358 curwin->w_buffer = curbuf;
8359 ++curbuf->b_nwindows;
8360 curwin->w_cursor = aco->save_cursor;
8361 check_cursor();
8362 /* check topline < line_count, in case lines got deleted */
8363 if (aco->save_topline <= curbuf->b_ml.ml_line_count)
8364 {
8365 curwin->w_topline = aco->save_topline;
8366#ifdef FEAT_DIFF
8367 curwin->w_topfill = aco->save_topfill;
8368#endif
8369 }
8370 else
8371 {
8372 curwin->w_topline = curbuf->b_ml.ml_line_count;
8373#ifdef FEAT_DIFF
8374 curwin->w_topfill = 0;
8375#endif
8376 }
8377 }
8378 }
8379}
8380
8381static int autocmd_nested = FALSE;
8382
8383/*
8384 * Execute autocommands for "event" and file name "fname".
8385 * Return TRUE if some commands were executed.
8386 */
8387 int
8388apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008389 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008390 char_u *fname; /* NULL or empty means use actual file name */
8391 char_u *fname_io; /* fname to use for <afile> on cmdline */
8392 int force; /* when TRUE, ignore autocmd_busy */
8393 buf_T *buf; /* buffer for <abuf> */
8394{
8395 return apply_autocmds_group(event, fname, fname_io, force,
8396 AUGROUP_ALL, buf, NULL);
8397}
8398
8399/*
8400 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8401 * setting v:filearg.
8402 */
8403 static int
8404apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008405 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008406 char_u *fname;
8407 char_u *fname_io;
8408 int force;
8409 buf_T *buf;
8410 exarg_T *eap;
8411{
8412 return apply_autocmds_group(event, fname, fname_io, force,
8413 AUGROUP_ALL, buf, eap);
8414}
8415
8416/*
8417 * Like apply_autocmds(), but handles the caller's retval. If the script
8418 * processing is being aborted or if retval is FAIL when inside a try
8419 * conditional, no autocommands are executed. If otherwise the autocommands
8420 * cause the script to be aborted, retval is set to FAIL.
8421 */
8422 int
8423apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008424 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008425 char_u *fname; /* NULL or empty means use actual file name */
8426 char_u *fname_io; /* fname to use for <afile> on cmdline */
8427 int force; /* when TRUE, ignore autocmd_busy */
8428 buf_T *buf; /* buffer for <abuf> */
8429 int *retval; /* pointer to caller's retval */
8430{
8431 int did_cmd;
8432
Bram Moolenaar1e015462005-09-25 22:16:38 +00008433#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008434 if (should_abort(*retval))
8435 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00008436#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437
8438 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8439 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008440 if (did_cmd
8441#ifdef FEAT_EVAL
8442 && aborting()
8443#endif
8444 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008445 *retval = FAIL;
8446 return did_cmd;
8447}
8448
Bram Moolenaard35f9712005-12-18 22:02:33 +00008449/*
8450 * Return TRUE when there is a CursorHold autocommand defined.
8451 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008452 int
8453has_cursorhold()
8454{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008455 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
8456 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008457}
Bram Moolenaard35f9712005-12-18 22:02:33 +00008458
8459/*
8460 * Return TRUE if the CursorHold event can be triggered.
8461 */
8462 int
8463trigger_cursorhold()
8464{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008465 int state;
8466
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00008467 if (!did_cursorhold && has_cursorhold() && !Recording
8468#ifdef FEAT_INS_EXPAND
8469 && !ins_compl_active()
8470#endif
8471 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00008472 {
8473 state = get_real_state();
8474 if (state == NORMAL_BUSY || (state & INSERT) != 0)
8475 return TRUE;
8476 }
8477 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00008478}
Bram Moolenaar754b5602006-02-09 23:53:20 +00008479
8480/*
8481 * Return TRUE when there is a CursorMoved autocommand defined.
8482 */
8483 int
8484has_cursormoved()
8485{
8486 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
8487}
8488
8489/*
8490 * Return TRUE when there is a CursorMovedI autocommand defined.
8491 */
8492 int
8493has_cursormovedI()
8494{
8495 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
8496}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008497
8498 static int
8499apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008500 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008501 char_u *fname; /* NULL or empty means use actual file name */
8502 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
8503 use fname */
8504 int force; /* when TRUE, ignore autocmd_busy */
8505 int group; /* group ID, or AUGROUP_ALL */
8506 buf_T *buf; /* buffer for <abuf> */
8507 exarg_T *eap; /* command arguments */
8508{
8509 char_u *sfname = NULL; /* short file name */
8510 char_u *tail;
8511 int save_changed;
8512 buf_T *old_curbuf;
8513 int retval = FALSE;
8514 char_u *save_sourcing_name;
8515 linenr_T save_sourcing_lnum;
8516 char_u *save_autocmd_fname;
8517 int save_autocmd_bufnr;
8518 char_u *save_autocmd_match;
8519 int save_autocmd_busy;
8520 int save_autocmd_nested;
8521 static int nesting = 0;
8522 AutoPatCmd patcmd;
8523 AutoPat *ap;
8524#ifdef FEAT_EVAL
8525 scid_T save_current_SID;
8526 void *save_funccalp;
8527 char_u *save_cmdarg;
8528 long save_cmdbang;
8529#endif
8530 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00008531#ifdef FEAT_PROFILE
8532 proftime_T wait_time;
8533#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008534
8535 /*
8536 * Quickly return if there are no autocommands for this event or
8537 * autocommands are blocked.
8538 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00008539 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008540 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008541
8542 /*
8543 * When autocommands are busy, new autocommands are only executed when
8544 * explicitly enabled with the "nested" flag.
8545 */
8546 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008547 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008548
8549#ifdef FEAT_EVAL
8550 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00008551 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00008552 * occurred or an exception was thrown but not caught.
8553 */
8554 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008555 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008556#endif
8557
8558 /*
8559 * FileChangedShell never nests, because it can create an endless loop.
8560 */
Bram Moolenaar56718732006-03-15 22:53:57 +00008561 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
8562 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008563 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008564
8565 /*
8566 * Ignore events in 'eventignore'.
8567 */
8568 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008569 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008570
8571 /*
8572 * Allow nesting of autocommands, but restrict the depth, because it's
8573 * possible to create an endless loop.
8574 */
8575 if (nesting == 10)
8576 {
8577 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008578 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008579 }
8580
8581 /*
8582 * Check if these autocommands are disabled. Used when doing ":all" or
8583 * ":ball".
8584 */
8585 if ( (autocmd_no_enter
8586 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
8587 || (autocmd_no_leave
8588 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008589 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590
8591 /*
8592 * Save the autocmd_* variables and info about the current buffer.
8593 */
8594 save_autocmd_fname = autocmd_fname;
8595 save_autocmd_bufnr = autocmd_bufnr;
8596 save_autocmd_match = autocmd_match;
8597 save_autocmd_busy = autocmd_busy;
8598 save_autocmd_nested = autocmd_nested;
8599 save_changed = curbuf->b_changed;
8600 old_curbuf = curbuf;
8601
8602 /*
8603 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00008604 * Make a copy to avoid that changing a buffer name or directory makes it
8605 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008606 */
8607 if (fname_io == NULL)
8608 {
8609 if (fname != NULL && *fname != NUL)
8610 autocmd_fname = fname;
8611 else if (buf != NULL)
8612 autocmd_fname = buf->b_fname;
8613 else
8614 autocmd_fname = NULL;
8615 }
8616 else
8617 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00008618 if (autocmd_fname != NULL)
8619 autocmd_fname = FullName_save(autocmd_fname, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008620
8621 /*
8622 * Set the buffer number to be used for <abuf>.
8623 */
8624 if (buf == NULL)
8625 autocmd_bufnr = 0;
8626 else
8627 autocmd_bufnr = buf->b_fnum;
8628
8629 /*
8630 * When the file name is NULL or empty, use the file name of buffer "buf".
8631 * Always use the full path of the file name to match with, in case
8632 * "allow_dirs" is set.
8633 */
8634 if (fname == NULL || *fname == NUL)
8635 {
8636 if (buf == NULL)
8637 fname = NULL;
8638 else
8639 {
8640#ifdef FEAT_SYN_HL
8641 if (event == EVENT_SYNTAX)
8642 fname = buf->b_p_syn;
8643 else
8644#endif
8645 if (event == EVENT_FILETYPE)
8646 fname = buf->b_p_ft;
8647 else
8648 {
8649 if (buf->b_sfname != NULL)
8650 sfname = vim_strsave(buf->b_sfname);
8651 fname = buf->b_ffname;
8652 }
8653 }
8654 if (fname == NULL)
8655 fname = (char_u *)"";
8656 fname = vim_strsave(fname); /* make a copy, so we can change it */
8657 }
8658 else
8659 {
8660 sfname = vim_strsave(fname);
Bram Moolenaar7c626922005-02-07 22:01:03 +00008661 /* Don't try expanding FileType, Syntax, WindowID or QuickFixCmd* */
8662 if (event == EVENT_FILETYPE
8663 || event == EVENT_SYNTAX
8664 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00008665 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00008666 || event == EVENT_QUICKFIXCMDPRE
8667 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008668 fname = vim_strsave(fname);
8669 else
8670 fname = FullName_save(fname, FALSE);
8671 }
8672 if (fname == NULL) /* out of memory */
8673 {
8674 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008675 retval = FALSE;
8676 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008677 }
8678
8679#ifdef BACKSLASH_IN_FILENAME
8680 /*
8681 * Replace all backslashes with forward slashes. This makes the
8682 * autocommand patterns portable between Unix and MS-DOS.
8683 */
8684 if (sfname != NULL)
8685 forward_slash(sfname);
8686 forward_slash(fname);
8687#endif
8688
8689#ifdef VMS
8690 /* remove version for correct match */
8691 if (sfname != NULL)
8692 vms_remove_version(sfname);
8693 vms_remove_version(fname);
8694#endif
8695
8696 /*
8697 * Set the name to be used for <amatch>.
8698 */
8699 autocmd_match = fname;
8700
8701
8702 /* Don't redraw while doing auto commands. */
8703 ++RedrawingDisabled;
8704 save_sourcing_name = sourcing_name;
8705 sourcing_name = NULL; /* don't free this one */
8706 save_sourcing_lnum = sourcing_lnum;
8707 sourcing_lnum = 0; /* no line number here */
8708
8709#ifdef FEAT_EVAL
8710 save_current_SID = current_SID;
8711
Bram Moolenaar05159a02005-02-26 23:04:13 +00008712# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00008713 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00008714 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
8715# endif
8716
Bram Moolenaar071d4272004-06-13 20:20:40 +00008717 /* Don't use local function variables, if called from a function */
8718 save_funccalp = save_funccal();
8719#endif
8720
8721 /*
8722 * When starting to execute autocommands, save the search patterns.
8723 */
8724 if (!autocmd_busy)
8725 {
8726 save_search_patterns();
8727 saveRedobuff();
8728 did_filetype = keep_filetype;
8729 }
8730
8731 /*
8732 * Note that we are applying autocmds. Some commands need to know.
8733 */
8734 autocmd_busy = TRUE;
8735 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
8736 ++nesting; /* see matching decrement below */
8737
8738 /* Remember that FileType was triggered. Used for did_filetype(). */
8739 if (event == EVENT_FILETYPE)
8740 did_filetype = TRUE;
8741
8742 tail = gettail(fname);
8743
8744 /* Find first autocommand that matches */
8745 patcmd.curpat = first_autopat[(int)event];
8746 patcmd.nextcmd = NULL;
8747 patcmd.group = group;
8748 patcmd.fname = fname;
8749 patcmd.sfname = sfname;
8750 patcmd.tail = tail;
8751 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008752 patcmd.arg_bufnr = autocmd_bufnr;
8753 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008754 auto_next_pat(&patcmd, FALSE);
8755
8756 /* found one, start executing the autocommands */
8757 if (patcmd.curpat != NULL)
8758 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008759 /* add to active_apc_list */
8760 patcmd.next = active_apc_list;
8761 active_apc_list = &patcmd;
8762
Bram Moolenaar071d4272004-06-13 20:20:40 +00008763#ifdef FEAT_EVAL
8764 /* set v:cmdarg (only when there is a matching pattern) */
8765 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
8766 if (eap != NULL)
8767 {
8768 save_cmdarg = set_cmdarg(eap, NULL);
8769 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
8770 }
8771 else
8772 save_cmdarg = NULL; /* avoid gcc warning */
8773#endif
8774 retval = TRUE;
8775 /* mark the last pattern, to avoid an endless loop when more patterns
8776 * are added when executing autocommands */
8777 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
8778 ap->last = FALSE;
8779 ap->last = TRUE;
8780 check_lnums(TRUE); /* make sure cursor and topline are valid */
8781 do_cmdline(NULL, getnextac, (void *)&patcmd,
8782 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
8783#ifdef FEAT_EVAL
8784 if (eap != NULL)
8785 {
8786 (void)set_cmdarg(NULL, save_cmdarg);
8787 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
8788 }
8789#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008790 /* delete from active_apc_list */
8791 if (active_apc_list == &patcmd) /* just in case */
8792 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008793 }
8794
8795 --RedrawingDisabled;
8796 autocmd_busy = save_autocmd_busy;
8797 filechangeshell_busy = FALSE;
8798 autocmd_nested = save_autocmd_nested;
8799 vim_free(sourcing_name);
8800 sourcing_name = save_sourcing_name;
8801 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00008802 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008803 autocmd_fname = save_autocmd_fname;
8804 autocmd_bufnr = save_autocmd_bufnr;
8805 autocmd_match = save_autocmd_match;
8806#ifdef FEAT_EVAL
8807 current_SID = save_current_SID;
8808 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00008809# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00008810 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00008811 prof_child_exit(&wait_time);
8812# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008813#endif
8814 vim_free(fname);
8815 vim_free(sfname);
8816 --nesting; /* see matching increment above */
8817
8818 /*
8819 * When stopping to execute autocommands, restore the search patterns and
8820 * the redo buffer.
8821 */
8822 if (!autocmd_busy)
8823 {
8824 restore_search_patterns();
8825 restoreRedobuff();
8826 did_filetype = FALSE;
8827 }
8828
8829 /*
8830 * Some events don't set or reset the Changed flag.
8831 * Check if still in the same buffer!
8832 */
8833 if (curbuf == old_curbuf
8834 && (event == EVENT_BUFREADPOST
8835 || event == EVENT_BUFWRITEPOST
8836 || event == EVENT_FILEAPPENDPOST
8837 || event == EVENT_VIMLEAVE
8838 || event == EVENT_VIMLEAVEPRE))
8839 {
8840#ifdef FEAT_TITLE
8841 if (curbuf->b_changed != save_changed)
8842 need_maketitle = TRUE;
8843#endif
8844 curbuf->b_changed = save_changed;
8845 }
8846
8847 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008848
8849BYPASS_AU:
8850 /* When wiping out a buffer make sure all its buffer-local autocommands
8851 * are deleted. */
8852 if (event == EVENT_BUFWIPEOUT && buf != NULL)
8853 aubuflocal_remove(buf);
8854
Bram Moolenaar071d4272004-06-13 20:20:40 +00008855 return retval;
8856}
8857
Bram Moolenaar78ab3312007-09-29 12:16:41 +00008858# ifdef FEAT_EVAL
8859static char_u *old_termresponse = NULL;
8860# endif
8861
8862/*
8863 * Block triggering autocommands until unblock_autocmd() is called.
8864 * Can be used recursively, so long as it's symmetric.
8865 */
8866 void
8867block_autocmds()
8868{
8869# ifdef FEAT_EVAL
8870 /* Remember the value of v:termresponse. */
8871 if (autocmd_blocked == 0)
8872 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
8873# endif
8874 ++autocmd_blocked;
8875}
8876
8877 void
8878unblock_autocmds()
8879{
8880 --autocmd_blocked;
8881
8882# ifdef FEAT_EVAL
8883 /* When v:termresponse was set while autocommands were blocked, trigger
8884 * the autocommands now. Esp. useful when executing a shell command
8885 * during startup (vimdiff). */
8886 if (autocmd_blocked == 0
8887 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
8888 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
8889# endif
8890}
8891
Bram Moolenaar071d4272004-06-13 20:20:40 +00008892/*
8893 * Find next autocommand pattern that matches.
8894 */
8895 static void
8896auto_next_pat(apc, stop_at_last)
8897 AutoPatCmd *apc;
8898 int stop_at_last; /* stop when 'last' flag is set */
8899{
8900 AutoPat *ap;
8901 AutoCmd *cp;
8902 char_u *name;
8903 char *s;
8904
8905 vim_free(sourcing_name);
8906 sourcing_name = NULL;
8907
8908 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
8909 {
8910 apc->curpat = NULL;
8911
8912 /* only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008913 * the group matches. For buffer-local autocommands only check the
8914 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915 if (ap->pat != NULL && ap->cmds != NULL
8916 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
8917 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008918 /* execution-condition */
8919 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00008920 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
8921 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008922 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008923 {
8924 name = event_nr2name(apc->event);
8925 s = _("%s Auto commands for \"%s\"");
8926 sourcing_name = alloc((unsigned)(STRLEN(s)
8927 + STRLEN(name) + ap->patlen + 1));
8928 if (sourcing_name != NULL)
8929 {
8930 sprintf((char *)sourcing_name, s,
8931 (char *)name, (char *)ap->pat);
8932 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008933 {
8934 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00008935 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008936 verbose_leave();
8937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 }
8939
8940 apc->curpat = ap;
8941 apc->nextcmd = ap->cmds;
8942 /* mark last command */
8943 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
8944 cp->last = FALSE;
8945 cp->last = TRUE;
8946 }
8947 line_breakcheck();
8948 if (apc->curpat != NULL) /* found a match */
8949 break;
8950 }
8951 if (stop_at_last && ap->last)
8952 break;
8953 }
8954}
8955
8956/*
8957 * Get next autocommand command.
8958 * Called by do_cmdline() to get the next line for ":if".
8959 * Returns allocated string, or NULL for end of autocommands.
8960 */
8961/* ARGSUSED */
8962 static char_u *
8963getnextac(c, cookie, indent)
8964 int c; /* not used */
8965 void *cookie;
8966 int indent; /* not used */
8967{
8968 AutoPatCmd *acp = (AutoPatCmd *)cookie;
8969 char_u *retval;
8970 AutoCmd *ac;
8971
8972 /* Can be called again after returning the last line. */
8973 if (acp->curpat == NULL)
8974 return NULL;
8975
8976 /* repeat until we find an autocommand to execute */
8977 for (;;)
8978 {
8979 /* skip removed commands */
8980 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
8981 if (acp->nextcmd->last)
8982 acp->nextcmd = NULL;
8983 else
8984 acp->nextcmd = acp->nextcmd->next;
8985
8986 if (acp->nextcmd != NULL)
8987 break;
8988
8989 /* at end of commands, find next pattern that matches */
8990 if (acp->curpat->last)
8991 acp->curpat = NULL;
8992 else
8993 acp->curpat = acp->curpat->next;
8994 if (acp->curpat != NULL)
8995 auto_next_pat(acp, TRUE);
8996 if (acp->curpat == NULL)
8997 return NULL;
8998 }
8999
9000 ac = acp->nextcmd;
9001
9002 if (p_verbose >= 9)
9003 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009004 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009005 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009007 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008 }
9009 retval = vim_strsave(ac->cmd);
9010 autocmd_nested = ac->nested;
9011#ifdef FEAT_EVAL
9012 current_SID = ac->scriptID;
9013#endif
9014 if (ac->last)
9015 acp->nextcmd = NULL;
9016 else
9017 acp->nextcmd = ac->next;
9018 return retval;
9019}
9020
9021/*
9022 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009023 * To account for buffer-local autocommands, function needs to know
9024 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 */
9026 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009027has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009028 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009029 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009030 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031{
9032 AutoPat *ap;
9033 char_u *fname;
9034 char_u *tail = gettail(sfname);
9035 int retval = FALSE;
9036
9037 fname = FullName_save(sfname, FALSE);
9038 if (fname == NULL)
9039 return FALSE;
9040
9041#ifdef BACKSLASH_IN_FILENAME
9042 /*
9043 * Replace all backslashes with forward slashes. This makes the
9044 * autocommand patterns portable between Unix and MS-DOS.
9045 */
9046 sfname = vim_strsave(sfname);
9047 if (sfname != NULL)
9048 forward_slash(sfname);
9049 forward_slash(fname);
9050#endif
9051
9052 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9053 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009054 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009055 ? match_file_pat(NULL, ap->reg_prog,
9056 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009057 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009058 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009059 {
9060 retval = TRUE;
9061 break;
9062 }
9063
9064 vim_free(fname);
9065#ifdef BACKSLASH_IN_FILENAME
9066 vim_free(sfname);
9067#endif
9068
9069 return retval;
9070}
9071
9072#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9073/*
9074 * Function given to ExpandGeneric() to obtain the list of autocommand group
9075 * names.
9076 */
9077/*ARGSUSED*/
9078 char_u *
9079get_augroup_name(xp, idx)
9080 expand_T *xp;
9081 int idx;
9082{
9083 if (idx == augroups.ga_len) /* add "END" add the end */
9084 return (char_u *)"END";
9085 if (idx >= augroups.ga_len) /* end of list */
9086 return NULL;
9087 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9088 return (char_u *)"";
9089 return AUGROUP_NAME(idx); /* return a name */
9090}
9091
9092static int include_groups = FALSE;
9093
9094 char_u *
9095set_context_in_autocmd(xp, arg, doautocmd)
9096 expand_T *xp;
9097 char_u *arg;
9098 int doautocmd; /* TRUE for :doautocmd, FALSE for :autocmd */
9099{
9100 char_u *p;
9101 int group;
9102
9103 /* check for a group name, skip it if present */
9104 include_groups = FALSE;
9105 p = arg;
9106 group = au_get_grouparg(&arg);
9107 if (group == AUGROUP_ERROR)
9108 return NULL;
9109 /* If there only is a group name that's what we expand. */
9110 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9111 {
9112 arg = p;
9113 group = AUGROUP_ALL;
9114 }
9115
9116 /* skip over event name */
9117 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9118 if (*p == ',')
9119 arg = p + 1;
9120 if (*p == NUL)
9121 {
9122 if (group == AUGROUP_ALL)
9123 include_groups = TRUE;
9124 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9125 xp->xp_pattern = arg;
9126 return NULL;
9127 }
9128
9129 /* skip over pattern */
9130 arg = skipwhite(p);
9131 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9132 arg++;
9133 if (*arg)
9134 return arg; /* expand (next) command */
9135
9136 if (doautocmd)
9137 xp->xp_context = EXPAND_FILES; /* expand file names */
9138 else
9139 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9140 return NULL;
9141}
9142
9143/*
9144 * Function given to ExpandGeneric() to obtain the list of event names.
9145 */
9146/*ARGSUSED*/
9147 char_u *
9148get_event_name(xp, idx)
9149 expand_T *xp;
9150 int idx;
9151{
9152 if (idx < augroups.ga_len) /* First list group names, if wanted */
9153 {
9154 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9155 return (char_u *)""; /* skip deleted entries */
9156 return AUGROUP_NAME(idx); /* return a name */
9157 }
9158 return (char_u *)event_names[idx - augroups.ga_len].name;
9159}
9160
9161#endif /* FEAT_CMDL_COMPL */
9162
9163/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009164 * Return TRUE if autocmd is supported.
9165 */
9166 int
9167autocmd_supported(name)
9168 char_u *name;
9169{
9170 char_u *p;
9171
9172 return (event_name2nr(name, &p) != NUM_EVENTS);
9173}
9174
9175/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009176 * Return TRUE if an autocommand is defined for a group, event and
9177 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9178 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9179 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9180 * Used for:
9181 * exists("#Group") or
9182 * exists("#Group#Event") or
9183 * exists("#Group#Event#pat") or
9184 * exists("#Event") or
9185 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009186 */
9187 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009188au_exists(arg)
9189 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009190{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009191 char_u *arg_save;
9192 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009193 char_u *event_name;
9194 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009195 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009196 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009197 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009198 int group;
9199 int retval = FALSE;
9200
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009201 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009202 arg_save = vim_strsave(arg);
9203 if (arg_save == NULL)
9204 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009205 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009206 if (p != NULL)
9207 *p++ = NUL;
9208
9209 /* First, look for an autocmd group name */
9210 group = au_find_group(arg_save);
9211 if (group == AUGROUP_ERROR)
9212 {
9213 /* Didn't match a group name, assume the first argument is an event. */
9214 group = AUGROUP_ALL;
9215 event_name = arg_save;
9216 }
9217 else
9218 {
9219 if (p == NULL)
9220 {
9221 /* "Group": group name is present and it's recognized */
9222 retval = TRUE;
9223 goto theend;
9224 }
9225
9226 /* Must be "Group#Event" or "Group#Event#pat". */
9227 event_name = p;
9228 p = vim_strchr(event_name, '#');
9229 if (p != NULL)
9230 *p++ = NUL; /* "Group#Event#pat" */
9231 }
9232
9233 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009234
9235 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009236 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237
9238 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009239 if (event == NUM_EVENTS)
9240 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009241
9242 /* Find the first autocommand for this event.
9243 * If there isn't any, return FALSE;
9244 * If there is one and no pattern given, return TRUE; */
9245 ap = first_autopat[(int)event];
9246 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009247 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009248 if (pattern == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009249 {
9250 retval = TRUE;
9251 goto theend;
9252 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009253
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009254 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9255 /* for pattern "<buffer=N>, fnamecmp() will work fine */
9256 if (STRICMP(pattern, "<buffer>") == 0)
9257 buflocal_buf = curbuf;
9258
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259 /* Check if there is an autocommand with the given pattern. */
9260 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009261 /* only use a pattern when it has not been removed and has commands. */
9262 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009263 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009264 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009265 && (buflocal_buf == NULL
9266 ? fnamecmp(ap->pat, pattern) == 0
9267 : ap->buflocal_nr == buflocal_buf->b_fnum))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009268 {
9269 retval = TRUE;
9270 break;
9271 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009272
Bram Moolenaar195d6352005-12-19 22:08:24 +00009273theend:
9274 vim_free(arg_save);
9275 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009276}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009277
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009278#else /* FEAT_AUTOCMD */
9279
9280/*
9281 * Prepare for executing commands for (hidden) buffer "buf".
9282 * This is the non-autocommand version, it simply saves "curbuf" and sets
9283 * "curbuf" and "curwin" to match "buf".
9284 */
9285 void
9286aucmd_prepbuf(aco, buf)
9287 aco_save_T *aco; /* structure to save values in */
9288 buf_T *buf; /* new curbuf */
9289{
Bram Moolenaar6ae90982008-03-11 21:02:00 +00009290 aco->save_buf = curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009291 curbuf = buf;
9292 curwin->w_buffer = buf;
9293}
9294
9295/*
9296 * Restore after executing commands for a (hidden) buffer.
9297 * This is the non-autocommand version.
9298 */
9299 void
9300aucmd_restbuf(aco)
9301 aco_save_T *aco; /* structure holding saved values */
9302{
9303 curbuf = aco->save_buf;
9304 curwin->w_buffer = curbuf;
9305}
9306
Bram Moolenaar071d4272004-06-13 20:20:40 +00009307#endif /* FEAT_AUTOCMD */
9308
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009309
Bram Moolenaar071d4272004-06-13 20:20:40 +00009310#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9311/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009312 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9313 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9314 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009315 * Used for autocommands and 'wildignore'.
9316 * Returns TRUE if there is a match, FALSE otherwise.
9317 */
9318 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009319match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009320 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009321 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009322 char_u *fname; /* full path of file name */
9323 char_u *sfname; /* short file name or NULL */
9324 char_u *tail; /* tail of path */
9325 int allow_dirs; /* allow matching with dir */
9326{
9327 regmatch_T regmatch;
9328 int result = FALSE;
9329#ifdef FEAT_OSFILETYPE
9330 int no_pattern = FALSE; /* TRUE if check is filetype only */
9331 char_u *type_start;
9332 char_u c;
9333 int match = FALSE;
9334#endif
9335
9336#ifdef CASE_INSENSITIVE_FILENAME
9337 regmatch.rm_ic = TRUE; /* Always ignore case */
9338#else
9339 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9340#endif
9341#ifdef FEAT_OSFILETYPE
9342 if (*pattern == '<')
9343 {
9344 /* There is a filetype condition specified with this pattern.
9345 * Check the filetype matches first. If not, don't bother with the
9346 * pattern (set regprog to NULL).
9347 * Always use magic for the regexp.
9348 */
9349
9350 for (type_start = pattern + 1; (c = *pattern); pattern++)
9351 {
9352 if ((c == ';' || c == '>') && match == FALSE)
9353 {
9354 *pattern = NUL; /* Terminate the string */
9355 match = mch_check_filetype(fname, type_start);
9356 *pattern = c; /* Restore the terminator */
9357 type_start = pattern + 1;
9358 }
9359 if (c == '>')
9360 break;
9361 }
9362
9363 /* (c should never be NUL, but check anyway) */
9364 if (match == FALSE || c == NUL)
9365 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9366 else if (*pattern == NUL)
9367 {
9368 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9369 no_pattern = TRUE; /* Always matches - don't check pat. */
9370 }
9371 else
9372 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9373 }
9374 else
9375#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009376 {
9377 if (prog != NULL)
9378 regmatch.regprog = prog;
9379 else
9380 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9381 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009382
9383 /*
9384 * Try for a match with the pattern with:
9385 * 1. the full file name, when the pattern has a '/'.
9386 * 2. the short file name, when the pattern has a '/'.
9387 * 3. the tail of the file name, when the pattern has no '/'.
9388 */
9389 if (
9390#ifdef FEAT_OSFILETYPE
9391 /* If the check is for a filetype only and we don't care
9392 * about the path then skip all the regexp stuff.
9393 */
9394 no_pattern ||
9395#endif
9396 (regmatch.regprog != NULL
9397 && ((allow_dirs
9398 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9399 || (sfname != NULL
9400 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9401 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9402 result = TRUE;
9403
Bram Moolenaar748bf032005-02-02 23:04:36 +00009404 if (prog == NULL)
9405 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009406 return result;
9407}
9408#endif
9409
9410#if defined(FEAT_WILDIGN) || defined(PROTO)
9411/*
9412 * Return TRUE if a file matches with a pattern in "list".
9413 * "list" is a comma-separated list of patterns, like 'wildignore'.
9414 * "sfname" is the short file name or NULL, "ffname" the long file name.
9415 */
9416 int
9417match_file_list(list, sfname, ffname)
9418 char_u *list;
9419 char_u *sfname;
9420 char_u *ffname;
9421{
9422 char_u buf[100];
9423 char_u *tail;
9424 char_u *regpat;
9425 char allow_dirs;
9426 int match;
9427 char_u *p;
9428
9429 tail = gettail(sfname);
9430
9431 /* try all patterns in 'wildignore' */
9432 p = list;
9433 while (*p)
9434 {
9435 copy_option_part(&p, buf, 100, ",");
9436 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9437 if (regpat == NULL)
9438 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00009439 match = match_file_pat(regpat, NULL, ffname, sfname,
9440 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441 vim_free(regpat);
9442 if (match)
9443 return TRUE;
9444 }
9445 return FALSE;
9446}
9447#endif
9448
9449/*
9450 * Convert the given pattern "pat" which has shell style wildcards in it, into
9451 * a regular expression, and return the result in allocated memory. If there
9452 * is a directory path separator to be matched, then TRUE is put in
9453 * allow_dirs, otherwise FALSE is put there -- webb.
9454 * Handle backslashes before special characters, like "\*" and "\ ".
9455 *
9456 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
9457 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
9458 *
9459 * Returns NULL when out of memory.
9460 */
9461/*ARGSUSED*/
9462 char_u *
9463file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
9464 char_u *pat;
9465 char_u *pat_end; /* first char after pattern or NULL */
9466 char *allow_dirs; /* Result passed back out in here */
9467 int no_bslash; /* Don't use a backward slash as pathsep */
9468{
9469 int size;
9470 char_u *endp;
9471 char_u *reg_pat;
9472 char_u *p;
9473 int i;
9474 int nested = 0;
9475 int add_dollar = TRUE;
9476#ifdef FEAT_OSFILETYPE
9477 int check_length = 0;
9478#endif
9479
9480 if (allow_dirs != NULL)
9481 *allow_dirs = FALSE;
9482 if (pat_end == NULL)
9483 pat_end = pat + STRLEN(pat);
9484
9485#ifdef FEAT_OSFILETYPE
9486 /* Find out how much of the string is the filetype check */
9487 if (*pat == '<')
9488 {
9489 /* Count chars until the next '>' */
9490 for (p = pat + 1; p < pat_end && *p != '>'; p++)
9491 ;
9492 if (p < pat_end)
9493 {
9494 /* Pattern is of the form <.*>.* */
9495 check_length = p - pat + 1;
9496 if (p + 1 >= pat_end)
9497 {
9498 /* The 'pattern' is a filetype check ONLY */
9499 reg_pat = (char_u *)alloc(check_length + 1);
9500 if (reg_pat != NULL)
9501 {
9502 mch_memmove(reg_pat, pat, (size_t)check_length);
9503 reg_pat[check_length] = NUL;
9504 }
9505 return reg_pat;
9506 }
9507 }
9508 /* else: there was no closing '>' - assume it was a normal pattern */
9509
9510 }
9511 pat += check_length;
9512 size = 2 + check_length;
9513#else
9514 size = 2; /* '^' at start, '$' at end */
9515#endif
9516
9517 for (p = pat; p < pat_end; p++)
9518 {
9519 switch (*p)
9520 {
9521 case '*':
9522 case '.':
9523 case ',':
9524 case '{':
9525 case '}':
9526 case '~':
9527 size += 2; /* extra backslash */
9528 break;
9529#ifdef BACKSLASH_IN_FILENAME
9530 case '\\':
9531 case '/':
9532 size += 4; /* could become "[\/]" */
9533 break;
9534#endif
9535 default:
9536 size++;
9537# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009538 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009539 {
9540 ++p;
9541 ++size;
9542 }
9543# endif
9544 break;
9545 }
9546 }
9547 reg_pat = alloc(size + 1);
9548 if (reg_pat == NULL)
9549 return NULL;
9550
9551#ifdef FEAT_OSFILETYPE
9552 /* Copy the type check in to the start. */
9553 if (check_length)
9554 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
9555 i = check_length;
9556#else
9557 i = 0;
9558#endif
9559
9560 if (pat[0] == '*')
9561 while (pat[0] == '*' && pat < pat_end - 1)
9562 pat++;
9563 else
9564 reg_pat[i++] = '^';
9565 endp = pat_end - 1;
9566 if (*endp == '*')
9567 {
9568 while (endp - pat > 0 && *endp == '*')
9569 endp--;
9570 add_dollar = FALSE;
9571 }
9572 for (p = pat; *p && nested >= 0 && p <= endp; p++)
9573 {
9574 switch (*p)
9575 {
9576 case '*':
9577 reg_pat[i++] = '.';
9578 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +00009579 while (p[1] == '*') /* "**" matches like "*" */
9580 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581 break;
9582 case '.':
9583#ifdef RISCOS
9584 if (allow_dirs != NULL)
9585 *allow_dirs = TRUE;
9586 /* FALLTHROUGH */
9587#endif
9588 case '~':
9589 reg_pat[i++] = '\\';
9590 reg_pat[i++] = *p;
9591 break;
9592 case '?':
9593#ifdef RISCOS
9594 case '#':
9595#endif
9596 reg_pat[i++] = '.';
9597 break;
9598 case '\\':
9599 if (p[1] == NUL)
9600 break;
9601#ifdef BACKSLASH_IN_FILENAME
9602 if (!no_bslash)
9603 {
9604 /* translate:
9605 * "\x" to "\\x" e.g., "dir\file"
9606 * "\*" to "\\.*" e.g., "dir\*.c"
9607 * "\?" to "\\." e.g., "dir\??.c"
9608 * "\+" to "\+" e.g., "fileX\+.c"
9609 */
9610 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
9611 && p[1] != '+')
9612 {
9613 reg_pat[i++] = '[';
9614 reg_pat[i++] = '\\';
9615 reg_pat[i++] = '/';
9616 reg_pat[i++] = ']';
9617 if (allow_dirs != NULL)
9618 *allow_dirs = TRUE;
9619 break;
9620 }
9621 }
9622#endif
9623 if (*++p == '?'
9624#ifdef BACKSLASH_IN_FILENAME
9625 && no_bslash
9626#endif
9627 )
9628 reg_pat[i++] = '?';
9629 else
9630 if (*p == ',')
9631 reg_pat[i++] = ',';
9632 else
9633 {
9634 if (allow_dirs != NULL && vim_ispathsep(*p)
9635#ifdef BACKSLASH_IN_FILENAME
9636 && (!no_bslash || *p != '\\')
9637#endif
9638 )
9639 *allow_dirs = TRUE;
9640 reg_pat[i++] = '\\';
9641 reg_pat[i++] = *p;
9642 }
9643 break;
9644#ifdef BACKSLASH_IN_FILENAME
9645 case '/':
9646 reg_pat[i++] = '[';
9647 reg_pat[i++] = '\\';
9648 reg_pat[i++] = '/';
9649 reg_pat[i++] = ']';
9650 if (allow_dirs != NULL)
9651 *allow_dirs = TRUE;
9652 break;
9653#endif
9654 case '{':
9655 reg_pat[i++] = '\\';
9656 reg_pat[i++] = '(';
9657 nested++;
9658 break;
9659 case '}':
9660 reg_pat[i++] = '\\';
9661 reg_pat[i++] = ')';
9662 --nested;
9663 break;
9664 case ',':
9665 if (nested)
9666 {
9667 reg_pat[i++] = '\\';
9668 reg_pat[i++] = '|';
9669 }
9670 else
9671 reg_pat[i++] = ',';
9672 break;
9673 default:
9674# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009675 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009676 reg_pat[i++] = *p++;
9677 else
9678# endif
9679 if (allow_dirs != NULL && vim_ispathsep(*p))
9680 *allow_dirs = TRUE;
9681 reg_pat[i++] = *p;
9682 break;
9683 }
9684 }
9685 if (add_dollar)
9686 reg_pat[i++] = '$';
9687 reg_pat[i] = NUL;
9688 if (nested != 0)
9689 {
9690 if (nested < 0)
9691 EMSG(_("E219: Missing {."));
9692 else
9693 EMSG(_("E220: Missing }."));
9694 vim_free(reg_pat);
9695 reg_pat = NULL;
9696 }
9697 return reg_pat;
9698}