blob: aad76170efab77e91bdd1599618f1b17f0432f4f [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
14#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
Bram Moolenaar362e1a32006-03-06 23:29:24 +000015# include "vimio.h" /* for lseek(), must be before vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +000016#endif
17
18#if defined __EMX__
Bram Moolenaar362e1a32006-03-06 23:29:24 +000019# include "vimio.h" /* for mktemp(), CJW 1997-12-03 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000020#endif
21
22#include "vim.h"
23
Bram Moolenaarf4888d02009-12-02 12:31:27 +000024#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000025# include <limits.h> /* for SSIZE_MAX */
26#endif
27
28#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
29# include <utime.h> /* for struct utimbuf */
30#endif
31
32#define BUFSIZE 8192 /* size of normal write buffer */
33#define SMBUFSIZE 256 /* size of emergency write buffer */
34
35#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020036/* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */
Bram Moolenaarf50a2532010-05-21 15:36:08 +020037static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
38static char crypt_magic_head[] = "VimCrypt~";
39# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
Bram Moolenaar80794b12010-06-13 05:20:42 +020040
41/* For blowfish, after the magic header, we store 8 bytes of salt and then 8
42 * bytes of seed (initialisation vector). */
43static int crypt_salt_len[] = {0, 8};
Bram Moolenaarf50a2532010-05-21 15:36:08 +020044static int crypt_seed_len[] = {0, 8};
Bram Moolenaar80794b12010-06-13 05:20:42 +020045#define CRYPT_SALT_LEN_MAX 8
Bram Moolenaar40e6a712010-05-16 22:32:54 +020046#define CRYPT_SEED_LEN_MAX 8
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#endif
48
49/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000050#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000051
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000052#if defined(sun) && defined(S_ISCHR)
53# define OPEN_CHR_FILES
54static int is_dev_fd_file(char_u *fname);
55#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000056#ifdef FEAT_MBYTE
57static char_u *next_fenc __ARGS((char_u **pp));
58# ifdef FEAT_EVAL
59static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
60# endif
61#endif
62#ifdef FEAT_VIMINFO
63static void check_marks_read __ARGS((void));
64#endif
65#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020066static int get_crypt_method __ARGS((char *ptr, int len));
Bram Moolenaar914703b2010-05-31 21:59:46 +020067static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep, int newfile, int *did_ask));
Bram Moolenaar071d4272004-06-13 20:20:40 +000068#endif
69#ifdef UNIX
70static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
71#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000072static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000073static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000074static void msg_add_eol __ARGS((void));
75static int check_mtime __ARGS((buf_T *buf, struct stat *s));
76static int time_differs __ARGS((long t1, long t2));
77#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000078static 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 +000079static int au_find_group __ARGS((char_u *name));
80
81# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000082# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000083# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000084#endif
85
86#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
87# define HAS_BW_FLAGS
88# define FIO_LATIN1 0x01 /* convert Latin1 */
89# define FIO_UTF8 0x02 /* convert UTF-8 */
90# define FIO_UCS2 0x04 /* convert UCS-2 */
91# define FIO_UCS4 0x08 /* convert UCS-4 */
92# define FIO_UTF16 0x10 /* convert UTF-16 */
93# ifdef WIN3264
94# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
95# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
96# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
97# endif
98# ifdef MACOS_X
99# define FIO_MACROMAN 0x20 /* convert MacRoman */
100# endif
101# define FIO_ENDIAN_L 0x80 /* little endian */
102# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
103# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
104# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
105# define FIO_ALL -1 /* allow all formats */
106#endif
107
108/* When converting, a read() or write() may leave some bytes to be converted
109 * for the next call. The value is guessed... */
110#define CONV_RESTLEN 30
111
112/* We have to guess how much a sequence of bytes may expand when converting
113 * with iconv() to be able to allocate a buffer. */
114#define ICONV_MULT 8
115
116/*
117 * Structure to pass arguments from buf_write() to buf_write_bytes().
118 */
119struct bw_info
120{
121 int bw_fd; /* file descriptor */
122 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000123 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124#ifdef HAS_BW_FLAGS
125 int bw_flags; /* FIO_ flags */
126#endif
127#ifdef FEAT_MBYTE
128 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
129 int bw_restlen; /* nr of bytes in bw_rest[] */
130 int bw_first; /* first write call */
131 char_u *bw_conv_buf; /* buffer for writing converted chars */
132 int bw_conv_buflen; /* size of bw_conv_buf */
133 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000134 linenr_T bw_conv_error_lnum; /* first line with error or zero */
135 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136# ifdef USE_ICONV
137 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
138# endif
139#endif
140};
141
142static int buf_write_bytes __ARGS((struct bw_info *ip));
143
144#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000145static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000147static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148static int get_fio_flags __ARGS((char_u *ptr));
149static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
150static int make_bom __ARGS((char_u *buf, char_u *name));
151# ifdef WIN3264
152static int get_win_fio_flags __ARGS((char_u *ptr));
153# endif
154# ifdef MACOS_X
155static int get_mac_fio_flags __ARGS((char_u *ptr));
156# endif
157#endif
158static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000159#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000160static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000161#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000162#ifdef FEAT_AUTOCMD
163static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
164#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166 void
167filemess(buf, name, s, attr)
168 buf_T *buf;
169 char_u *name;
170 char_u *s;
171 int attr;
172{
173 int msg_scroll_save;
174
175 if (msg_silent != 0)
176 return;
177 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
178 /* If it's extremely long, truncate it. */
179 if (STRLEN(IObuff) > IOSIZE - 80)
180 IObuff[IOSIZE - 80] = NUL;
181 STRCAT(IObuff, s);
182 /*
183 * For the first message may have to start a new line.
184 * For further ones overwrite the previous one, reset msg_scroll before
185 * calling filemess().
186 */
187 msg_scroll_save = msg_scroll;
188 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
189 msg_scroll = FALSE;
190 if (!msg_scroll) /* wait a bit when overwriting an error msg */
191 check_for_delay(FALSE);
192 msg_start();
193 msg_scroll = msg_scroll_save;
194 msg_scrolled_ign = TRUE;
195 /* may truncate the message to avoid a hit-return prompt */
196 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
197 msg_clr_eos();
198 out_flush();
199 msg_scrolled_ign = FALSE;
200}
201
202/*
203 * Read lines from file "fname" into the buffer after line "from".
204 *
205 * 1. We allocate blocks with lalloc, as big as possible.
206 * 2. Each block is filled with characters from the file with a single read().
207 * 3. The lines are inserted in the buffer with ml_append().
208 *
209 * (caller must check that fname != NULL, unless READ_STDIN is used)
210 *
211 * "lines_to_skip" is the number of lines that must be skipped
212 * "lines_to_read" is the number of lines that are appended
213 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
214 *
215 * flags:
216 * READ_NEW starting to edit a new buffer
217 * READ_FILTER reading filter output
218 * READ_STDIN read from stdin instead of a file
219 * READ_BUFFER read from curbuf instead of a file (converting after reading
220 * stdin)
221 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
222 *
223 * return FAIL for failure, OK otherwise
224 */
225 int
226readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
227 char_u *fname;
228 char_u *sfname;
229 linenr_T from;
230 linenr_T lines_to_skip;
231 linenr_T lines_to_read;
232 exarg_T *eap; /* can be NULL! */
233 int flags;
234{
235 int fd = 0;
236 int newfile = (flags & READ_NEW);
237 int check_readonly;
238 int filtering = (flags & READ_FILTER);
239 int read_stdin = (flags & READ_STDIN);
240 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000241 int set_options = newfile || read_buffer
242 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
244 colnr_T read_buf_col = 0; /* next char to read from this line */
245 char_u c;
246 linenr_T lnum = from;
247 char_u *ptr = NULL; /* pointer into read buffer */
248 char_u *buffer = NULL; /* read buffer */
249 char_u *new_buffer = NULL; /* init to shut up gcc */
250 char_u *line_start = NULL; /* init to shut up gcc */
251 int wasempty; /* buffer was empty before reading */
252 colnr_T len;
253 long size = 0;
254 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200255 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256 int skip_read = FALSE;
257#ifdef FEAT_CRYPT
258 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200259 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200261#ifdef FEAT_PERSISTENT_UNDO
262 context_sha256_T sha_ctx;
263 int read_undo_file = FALSE;
264#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265 int split = 0; /* number of split lines */
266#define UNKNOWN 0x0fffffff /* file size is unknown */
267 linenr_T linecnt;
268 int error = FALSE; /* errors encountered */
269 int ff_error = EOL_UNKNOWN; /* file format with errors */
270 long linerest = 0; /* remaining chars in line */
271#ifdef UNIX
272 int perm = 0;
273 int swap_mode = -1; /* protection bits for swap file */
274#else
275 int perm;
276#endif
277 int fileformat = 0; /* end-of-line format */
278 int keep_fileformat = FALSE;
279 struct stat st;
280 int file_readonly;
281 linenr_T skip_count = 0;
282 linenr_T read_count = 0;
283 int msg_save = msg_scroll;
284 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
285 * last read was missing the eol */
286 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
287 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
288 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
289 int file_rewind = FALSE;
290#ifdef FEAT_MBYTE
291 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000292 linenr_T conv_error = 0; /* line nr with conversion error */
293 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
295 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000296 int bad_char_behavior = BAD_REPLACE;
297 /* BAD_KEEP, BAD_DROP or character to
298 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000299 char_u *tmpname = NULL; /* name of 'charconvert' output file */
300 int fio_flags = 0;
301 char_u *fenc; /* fileencoding to use */
302 int fenc_alloced; /* fenc_next is in allocated memory */
303 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
304 int advance_fenc = FALSE;
305 long real_size = 0;
306# ifdef USE_ICONV
307 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
308# ifdef FEAT_EVAL
309 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
310 'charconvert' next */
311# endif
312# endif
313 int converted = FALSE; /* TRUE if conversion done */
314 int notconverted = FALSE; /* TRUE if conversion wanted but it
315 wasn't possible */
316 char_u conv_rest[CONV_RESTLEN];
317 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
318#endif
319
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000320#ifdef FEAT_AUTOCMD
321 /* Remember the initial values of curbuf, curbuf->b_ffname and
322 * curbuf->b_fname to detect whether they are altered as a result of
323 * executing nasty autocommands. Also check if "fname" and "sfname"
324 * point to one of these values. */
325 buf_T *old_curbuf = curbuf;
326 char_u *old_b_ffname = curbuf->b_ffname;
327 char_u *old_b_fname = curbuf->b_fname;
328 int using_b_ffname = (fname == curbuf->b_ffname)
329 || (sfname == curbuf->b_ffname);
330 int using_b_fname = (fname == curbuf->b_fname)
331 || (sfname == curbuf->b_fname);
332#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000333 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334
335 /*
336 * If there is no file name yet, use the one for the read file.
337 * BF_NOTEDITED is set to reflect this.
338 * Don't do this for a read from a filter.
339 * Only do this when 'cpoptions' contains the 'f' flag.
340 */
341 if (curbuf->b_ffname == NULL
342 && !filtering
343 && fname != NULL
344 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
345 && !(flags & READ_DUMMY))
346 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000347 if (set_rw_fname(fname, sfname) == FAIL)
348 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 }
350
Bram Moolenaardf177f62005-02-22 08:39:57 +0000351 /* After reading a file the cursor line changes but we don't want to
352 * display the line. */
353 ex_no_reprint = TRUE;
354
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000355 /* don't display the file info for another buffer now */
356 need_fileinfo = FALSE;
357
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 /*
359 * For Unix: Use the short file name whenever possible.
360 * Avoids problems with networks and when directory names are changed.
361 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
362 * another directory, which we don't detect.
363 */
364 if (sfname == NULL)
365 sfname = fname;
366#if defined(UNIX) || defined(__EMX__)
367 fname = sfname;
368#endif
369
370#ifdef FEAT_AUTOCMD
371 /*
372 * The BufReadCmd and FileReadCmd events intercept the reading process by
373 * executing the associated commands instead.
374 */
375 if (!filtering && !read_stdin && !read_buffer)
376 {
377 pos_T pos;
378
379 pos = curbuf->b_op_start;
380
381 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
382 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
383 curbuf->b_op_start.col = 0;
384
385 if (newfile)
386 {
387 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
388 FALSE, curbuf, eap))
389#ifdef FEAT_EVAL
390 return aborting() ? FAIL : OK;
391#else
392 return OK;
393#endif
394 }
395 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
396 FALSE, NULL, eap))
397#ifdef FEAT_EVAL
398 return aborting() ? FAIL : OK;
399#else
400 return OK;
401#endif
402
403 curbuf->b_op_start = pos;
404 }
405#endif
406
407 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
408 msg_scroll = FALSE; /* overwrite previous file message */
409 else
410 msg_scroll = TRUE; /* don't overwrite previous file message */
411
412 /*
413 * If the name ends in a path separator, we can't open it. Check here,
414 * because reading the file may actually work, but then creating the swap
415 * file may destroy it! Reported on MS-DOS and Win 95.
416 * If the name is too long we might crash further on, quit here.
417 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000418 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000420 p = fname + STRLEN(fname);
421 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000422 {
423 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
424 msg_end();
425 msg_scroll = msg_save;
426 return FAIL;
427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 }
429
430#ifdef UNIX
431 /*
432 * On Unix it is possible to read a directory, so we have to
433 * check for it before the mch_open().
434 */
435 if (!read_stdin && !read_buffer)
436 {
437 perm = mch_getperm(fname);
438 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
439# ifdef S_ISFIFO
440 && !S_ISFIFO(perm) /* ... or fifo */
441# endif
442# ifdef S_ISSOCK
443 && !S_ISSOCK(perm) /* ... or socket */
444# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000445# ifdef OPEN_CHR_FILES
446 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
447 /* ... or a character special file named /dev/fd/<n> */
448# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 )
450 {
451 if (S_ISDIR(perm))
452 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
453 else
454 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
455 msg_end();
456 msg_scroll = msg_save;
457 return FAIL;
458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000460# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
461 /*
462 * MS-Windows allows opening a device, but we will probably get stuck
463 * trying to read it.
464 */
465 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
466 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000467 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468 msg_end();
469 msg_scroll = msg_save;
470 return FAIL;
471 }
472# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000473 }
474#endif
475
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
479 if (eap != NULL && eap->force_ff != 0)
480 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
481 else if (*p_ffs != NUL)
482 set_fileformat(default_fileformat(), OPT_LOCAL);
483 }
484
485 /* set or reset 'binary' */
486 if (eap != NULL && eap->force_bin != 0)
487 {
488 int oldval = curbuf->b_p_bin;
489
490 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
491 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
492 }
493
494 /*
495 * When opening a new file we take the readonly flag from the file.
496 * Default is r/w, can be set to r/o below.
497 * Don't reset it when in readonly mode
498 * Only set/reset b_p_ro when BF_CHECK_RO is set.
499 */
500 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000501 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 curbuf->b_p_ro = FALSE;
503
504 if (newfile && !read_stdin && !read_buffer)
505 {
506 /* Remember time of file.
507 * For RISCOS, also remember the filetype.
508 */
509 if (mch_stat((char *)fname, &st) >= 0)
510 {
511 buf_store_time(curbuf, &st, fname);
512 curbuf->b_mtime_read = curbuf->b_mtime;
513
514#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
515 /* Read the filetype into the buffer local filetype option. */
516 mch_read_filetype(fname);
517#endif
518#ifdef UNIX
519 /*
520 * Use the protection bits of the original file for the swap file.
521 * This makes it possible for others to read the name of the
522 * edited file from the swapfile, but only if they can read the
523 * edited file.
524 * Remove the "write" and "execute" bits for group and others
525 * (they must not write the swapfile).
526 * Add the "read" and "write" bits for the user, otherwise we may
527 * not be able to write to the file ourselves.
528 * Setting the bits is done below, after creating the swap file.
529 */
530 swap_mode = (st.st_mode & 0644) | 0600;
531#endif
532#ifdef FEAT_CW_EDITOR
533 /* Get the FSSpec on MacOS
534 * TODO: Update it properly when the buffer name changes
535 */
536 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
537#endif
538#ifdef VMS
539 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000540 curbuf->b_fab_rat = st.st_fab_rat;
541 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542#endif
543 }
544 else
545 {
546 curbuf->b_mtime = 0;
547 curbuf->b_mtime_read = 0;
548 curbuf->b_orig_size = 0;
549 curbuf->b_orig_mode = 0;
550 }
551
552 /* Reset the "new file" flag. It will be set again below when the
553 * file doesn't exist. */
554 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
555 }
556
557/*
558 * for UNIX: check readonly with perm and mch_access()
559 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
560 * for MSDOS and Amiga: check readonly by trying to open the file for writing
561 */
562 file_readonly = FALSE;
563 if (read_stdin)
564 {
565#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
566 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
567 setmode(0, O_BINARY);
568#endif
569 }
570 else if (!read_buffer)
571 {
572#ifdef USE_MCH_ACCESS
573 if (
574# ifdef UNIX
575 !(perm & 0222) ||
576# endif
577 mch_access((char *)fname, W_OK))
578 file_readonly = TRUE;
579 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
580#else
581 if (!newfile
582 || readonlymode
583 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
584 {
585 file_readonly = TRUE;
586 /* try to open ro */
587 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
588 }
589#endif
590 }
591
592 if (fd < 0) /* cannot open at all */
593 {
594#ifndef UNIX
595 int isdir_f;
596#endif
597 msg_scroll = msg_save;
598#ifndef UNIX
599 /*
600 * On MSDOS and Amiga we can't open a directory, check here.
601 */
602 isdir_f = (mch_isdir(fname));
603 perm = mch_getperm(fname); /* check if the file exists */
604 if (isdir_f)
605 {
606 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
607 curbuf->b_p_ro = TRUE; /* must use "w!" now */
608 }
609 else
610#endif
611 if (newfile)
612 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200613 if (perm < 0
614#ifdef ENOENT
615 && errno == ENOENT
616#endif
617 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 {
619 /*
620 * Set the 'new-file' flag, so that when the file has
621 * been created by someone else, a ":w" will complain.
622 */
623 curbuf->b_flags |= BF_NEW;
624
625 /* Create a swap file now, so that other Vims are warned
626 * that we are editing this file. Don't do this for a
627 * "nofile" or "nowrite" buffer type. */
628#ifdef FEAT_QUICKFIX
629 if (!bt_dontwrite(curbuf))
630#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000631 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000633#ifdef FEAT_AUTOCMD
634 /* SwapExists autocommand may mess things up */
635 if (curbuf != old_curbuf
636 || (using_b_ffname
637 && (old_b_ffname != curbuf->b_ffname))
638 || (using_b_fname
639 && (old_b_fname != curbuf->b_fname)))
640 {
641 EMSG(_(e_auchangedbuf));
642 return FAIL;
643 }
644#endif
645 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000646 if (dir_of_file_exists(fname))
647 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
648 else
649 filemess(curbuf, sfname,
650 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651#ifdef FEAT_VIMINFO
652 /* Even though this is a new file, it might have been
653 * edited before and deleted. Get the old marks. */
654 check_marks_read();
655#endif
656#ifdef FEAT_MBYTE
657 if (eap != NULL && eap->force_enc != 0)
658 {
659 /* set forced 'fileencoding' */
660 fenc = enc_canonize(eap->cmd + eap->force_enc);
661 if (fenc != NULL)
662 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000663 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 vim_free(fenc);
665 }
666#endif
667#ifdef FEAT_AUTOCMD
668 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
669 FALSE, curbuf, eap);
670#endif
671 /* remember the current fileformat */
672 save_file_ff(curbuf);
673
674#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
675 if (aborting()) /* autocmds may abort script processing */
676 return FAIL;
677#endif
678 return OK; /* a new file is not an error */
679 }
680 else
681 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000682 filemess(curbuf, sfname, (char_u *)(
683# ifdef EFBIG
684 (errno == EFBIG) ? _("[File too big]") :
685# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200686# ifdef EOVERFLOW
687 (errno == EOVERFLOW) ? _("[File too big]") :
688# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000689 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 curbuf->b_p_ro = TRUE; /* must use "w!" now */
691 }
692 }
693
694 return FAIL;
695 }
696
697 /*
698 * Only set the 'ro' flag for readonly files the first time they are
699 * loaded. Help files always get readonly mode
700 */
701 if ((check_readonly && file_readonly) || curbuf->b_help)
702 curbuf->b_p_ro = TRUE;
703
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000704 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000706 /* Don't change 'eol' if reading from buffer as it will already be
707 * correctly set when reading stdin. */
708 if (!read_buffer)
709 {
710 curbuf->b_p_eol = TRUE;
711 curbuf->b_start_eol = TRUE;
712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713#ifdef FEAT_MBYTE
714 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000715 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716#endif
717 }
718
719 /* Create a swap file now, so that other Vims are warned that we are
720 * editing this file.
721 * Don't do this for a "nofile" or "nowrite" buffer type. */
722#ifdef FEAT_QUICKFIX
723 if (!bt_dontwrite(curbuf))
724#endif
725 {
726 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000727#ifdef FEAT_AUTOCMD
728 if (!read_stdin && (curbuf != old_curbuf
729 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
730 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
731 {
732 EMSG(_(e_auchangedbuf));
733 if (!read_buffer)
734 close(fd);
735 return FAIL;
736 }
737#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738#ifdef UNIX
739 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000740 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
741 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
743#endif
744 }
745
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000746#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 /* If "Quit" selected at ATTENTION dialog, don't load the file */
748 if (swap_exists_action == SEA_QUIT)
749 {
750 if (!read_buffer && !read_stdin)
751 close(fd);
752 return FAIL;
753 }
754#endif
755
756 ++no_wait_return; /* don't wait for return yet */
757
758 /*
759 * Set '[ mark to the line above where the lines go (line 1 if zero).
760 */
761 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
762 curbuf->b_op_start.col = 0;
763
764#ifdef FEAT_AUTOCMD
765 if (!read_buffer)
766 {
767 int m = msg_scroll;
768 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769
770 /*
771 * The file must be closed again, the autocommands may want to change
772 * the file before reading it.
773 */
774 if (!read_stdin)
775 close(fd); /* ignore errors */
776
777 /*
778 * The output from the autocommands should not overwrite anything and
779 * should not be overwritten: Set msg_scroll, restore its value if no
780 * output was done.
781 */
782 msg_scroll = TRUE;
783 if (filtering)
784 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
785 FALSE, curbuf, eap);
786 else if (read_stdin)
787 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
788 FALSE, curbuf, eap);
789 else if (newfile)
790 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
791 FALSE, curbuf, eap);
792 else
793 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
794 FALSE, NULL, eap);
795 if (msg_scrolled == n)
796 msg_scroll = m;
797
798#ifdef FEAT_EVAL
799 if (aborting()) /* autocmds may abort script processing */
800 {
801 --no_wait_return;
802 msg_scroll = msg_save;
803 curbuf->b_p_ro = TRUE; /* must use "w!" now */
804 return FAIL;
805 }
806#endif
807 /*
808 * Don't allow the autocommands to change the current buffer.
809 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000810 *
811 * Don't allow the autocommands to change the buffer name either
812 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 */
814 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000815 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
816 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
818 {
819 --no_wait_return;
820 msg_scroll = msg_save;
821 if (fd < 0)
822 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
823 else
824 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
825 curbuf->b_p_ro = TRUE; /* must use "w!" now */
826 return FAIL;
827 }
828 }
829#endif /* FEAT_AUTOCMD */
830
831 /* Autocommands may add lines to the file, need to check if it is empty */
832 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
833
834 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
835 {
836 /*
837 * Show the user that we are busy reading the input. Sometimes this
838 * may take a while. When reading from stdin another program may
839 * still be running, don't move the cursor to the last line, unless
840 * always using the GUI.
841 */
842 if (read_stdin)
843 {
844#ifndef ALWAYS_USE_GUI
845 mch_msg(_("Vim: Reading from stdin...\n"));
846#endif
847#ifdef FEAT_GUI
848 /* Also write a message in the GUI window, if there is one. */
849 if (gui.in_use && !gui.dying && !gui.starting)
850 {
851 p = (char_u *)_("Reading from stdin...");
852 gui_write(p, (int)STRLEN(p));
853 }
854#endif
855 }
856 else if (!read_buffer)
857 filemess(curbuf, sfname, (char_u *)"", 0);
858 }
859
860 msg_scroll = FALSE; /* overwrite the file message */
861
862 /*
863 * Set linecnt now, before the "retry" caused by a wrong guess for
864 * fileformat, and after the autocommands, which may change them.
865 */
866 linecnt = curbuf->b_ml.ml_line_count;
867
868#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000869 /* "++bad=" argument. */
870 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000871 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000873 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000874 curbuf->b_bad_char = eap->bad_char;
875 }
876 else
877 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000878
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 */
882 if (eap != NULL && eap->force_enc != 0)
883 {
884 fenc = enc_canonize(eap->cmd + eap->force_enc);
885 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000886 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 }
888 else if (curbuf->b_p_bin)
889 {
890 fenc = (char_u *)""; /* binary: don't convert */
891 fenc_alloced = FALSE;
892 }
893 else if (curbuf->b_help)
894 {
895 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000896 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897
898 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
899 * fails it must be latin1.
900 * Always do this when 'encoding' is "utf-8". Otherwise only do
901 * this when needed to avoid [converted] remarks all the time.
902 * It is needed when the first line contains non-ASCII characters.
903 * That is only in *.??x files. */
904 fenc = (char_u *)"latin1";
905 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000906 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000908 fc = fname[STRLEN(fname) - 1];
909 if (TOLOWER_ASC(fc) == 'x')
910 {
911 /* Read the first line (and a bit more). Immediately rewind to
912 * the start of the file. If the read() fails "len" is -1. */
913 len = vim_read(fd, firstline, 80);
914 lseek(fd, (off_t)0L, SEEK_SET);
915 for (p = firstline; p < firstline + len; ++p)
916 if (*p >= 0x80)
917 {
918 c = TRUE;
919 break;
920 }
921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 }
923
924 if (c)
925 {
926 fenc_next = fenc;
927 fenc = (char_u *)"utf-8";
928
929 /* When the file is utf-8 but a character doesn't fit in
930 * 'encoding' don't retry. In help text editing utf-8 bytes
931 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000932 if (!enc_utf8)
933 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 }
935 fenc_alloced = FALSE;
936 }
937 else if (*p_fencs == NUL)
938 {
939 fenc = curbuf->b_p_fenc; /* use format from buffer */
940 fenc_alloced = FALSE;
941 }
942 else
943 {
944 fenc_next = p_fencs; /* try items in 'fileencodings' */
945 fenc = next_fenc(&fenc_next);
946 fenc_alloced = TRUE;
947 }
948#endif
949
950 /*
951 * Jump back here to retry reading the file in different ways.
952 * Reasons to retry:
953 * - encoding conversion failed: try another one from "fenc_next"
954 * - BOM detected and fenc was set, need to setup conversion
955 * - "fileformat" check failed: try another
956 *
957 * Variables set for special retry actions:
958 * "file_rewind" Rewind the file to start reading it again.
959 * "advance_fenc" Advance "fenc" using "fenc_next".
960 * "skip_read" Re-use already read bytes (BOM detected).
961 * "did_iconv" iconv() conversion failed, try 'charconvert'.
962 * "keep_fileformat" Don't reset "fileformat".
963 *
964 * Other status indicators:
965 * "tmpname" When != NULL did conversion with 'charconvert'.
966 * Output file has to be deleted afterwards.
967 * "iconv_fd" When != -1 did conversion with iconv().
968 */
969retry:
970
971 if (file_rewind)
972 {
973 if (read_buffer)
974 {
975 read_buf_lnum = 1;
976 read_buf_col = 0;
977 }
978 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
979 {
980 /* Can't rewind the file, give up. */
981 error = TRUE;
982 goto failed;
983 }
984 /* Delete the previously read lines. */
985 while (lnum > from)
986 ml_delete(lnum--, FALSE);
987 file_rewind = FALSE;
988#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000989 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000990 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000992 curbuf->b_start_bomb = FALSE;
993 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000994 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995#endif
996 }
997
998 /*
999 * When retrying with another "fenc" and the first time "fileformat"
1000 * will be reset.
1001 */
1002 if (keep_fileformat)
1003 keep_fileformat = FALSE;
1004 else
1005 {
1006 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001007 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001009 try_unix = try_dos = try_mac = FALSE;
1010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011 else if (curbuf->b_p_bin)
1012 fileformat = EOL_UNIX; /* binary: use Unix format */
1013 else if (*p_ffs == NUL)
1014 fileformat = get_fileformat(curbuf);/* use format from buffer */
1015 else
1016 fileformat = EOL_UNKNOWN; /* detect from file */
1017 }
1018
1019#ifdef FEAT_MBYTE
1020# ifdef USE_ICONV
1021 if (iconv_fd != (iconv_t)-1)
1022 {
1023 /* aborted conversion with iconv(), close the descriptor */
1024 iconv_close(iconv_fd);
1025 iconv_fd = (iconv_t)-1;
1026 }
1027# endif
1028
1029 if (advance_fenc)
1030 {
1031 /*
1032 * Try the next entry in 'fileencodings'.
1033 */
1034 advance_fenc = FALSE;
1035
1036 if (eap != NULL && eap->force_enc != 0)
1037 {
1038 /* Conversion given with "++cc=" wasn't possible, read
1039 * without conversion. */
1040 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001041 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 if (fenc_alloced)
1043 vim_free(fenc);
1044 fenc = (char_u *)"";
1045 fenc_alloced = FALSE;
1046 }
1047 else
1048 {
1049 if (fenc_alloced)
1050 vim_free(fenc);
1051 if (fenc_next != NULL)
1052 {
1053 fenc = next_fenc(&fenc_next);
1054 fenc_alloced = (fenc_next != NULL);
1055 }
1056 else
1057 {
1058 fenc = (char_u *)"";
1059 fenc_alloced = FALSE;
1060 }
1061 }
1062 if (tmpname != NULL)
1063 {
1064 mch_remove(tmpname); /* delete converted file */
1065 vim_free(tmpname);
1066 tmpname = NULL;
1067 }
1068 }
1069
1070 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001071 * Conversion may be required when the encoding of the file is different
1072 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 */
1074 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001075 converted = need_conversion(fenc);
1076 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077 {
1078
1079 /* "ucs-bom" means we need to check the first bytes of the file
1080 * for a BOM. */
1081 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1082 fio_flags = FIO_UCSBOM;
1083
1084 /*
1085 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1086 * done. This is handled below after read(). Prepare the
1087 * fio_flags to avoid having to parse the string each time.
1088 * Also check for Unicode to Latin1 conversion, because iconv()
1089 * appears not to handle this correctly. This works just like
1090 * conversion to UTF-8 except how the resulting character is put in
1091 * the buffer.
1092 */
1093 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1094 fio_flags = get_fio_flags(fenc);
1095
1096# ifdef WIN3264
1097 /*
1098 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1099 * is handled with MultiByteToWideChar().
1100 */
1101 if (fio_flags == 0)
1102 fio_flags = get_win_fio_flags(fenc);
1103# endif
1104
1105# ifdef MACOS_X
1106 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1107 if (fio_flags == 0)
1108 fio_flags = get_mac_fio_flags(fenc);
1109# endif
1110
1111# ifdef USE_ICONV
1112 /*
1113 * Try using iconv() if we can't convert internally.
1114 */
1115 if (fio_flags == 0
1116# ifdef FEAT_EVAL
1117 && !did_iconv
1118# endif
1119 )
1120 iconv_fd = (iconv_t)my_iconv_open(
1121 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1122# endif
1123
1124# ifdef FEAT_EVAL
1125 /*
1126 * Use the 'charconvert' expression when conversion is required
1127 * and we can't do it internally or with iconv().
1128 */
1129 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1130# ifdef USE_ICONV
1131 && iconv_fd == (iconv_t)-1
1132# endif
1133 )
1134 {
1135# ifdef USE_ICONV
1136 did_iconv = FALSE;
1137# endif
1138 /* Skip conversion when it's already done (retry for wrong
1139 * "fileformat"). */
1140 if (tmpname == NULL)
1141 {
1142 tmpname = readfile_charconvert(fname, fenc, &fd);
1143 if (tmpname == NULL)
1144 {
1145 /* Conversion failed. Try another one. */
1146 advance_fenc = TRUE;
1147 if (fd < 0)
1148 {
1149 /* Re-opening the original file failed! */
1150 EMSG(_("E202: Conversion made file unreadable!"));
1151 error = TRUE;
1152 goto failed;
1153 }
1154 goto retry;
1155 }
1156 }
1157 }
1158 else
1159# endif
1160 {
1161 if (fio_flags == 0
1162# ifdef USE_ICONV
1163 && iconv_fd == (iconv_t)-1
1164# endif
1165 )
1166 {
1167 /* Conversion wanted but we can't.
1168 * Try the next conversion in 'fileencodings' */
1169 advance_fenc = TRUE;
1170 goto retry;
1171 }
1172 }
1173 }
1174
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001175 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001177 * stdin or fixed at a specific encoding. */
1178 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179#endif
1180
1181 if (!skip_read)
1182 {
1183 linerest = 0;
1184 filesize = 0;
1185 skip_count = lines_to_skip;
1186 read_count = lines_to_read;
1187#ifdef FEAT_MBYTE
1188 conv_restlen = 0;
1189#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001190#ifdef FEAT_PERSISTENT_UNDO
1191 read_undo_file = (newfile && curbuf->b_ffname != NULL && curbuf->b_p_udf
1192 && !filtering && !read_stdin && !read_buffer);
1193 if (read_undo_file)
1194 sha256_start(&sha_ctx);
1195#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196 }
1197
1198 while (!error && !got_int)
1199 {
1200 /*
1201 * We allocate as much space for the file as we can get, plus
1202 * space for the old line plus room for one terminating NUL.
1203 * The amount is limited by the fact that read() only can read
1204 * upto max_unsigned characters (and other things).
1205 */
1206#if SIZEOF_INT <= 2
1207 if (linerest >= 0x7ff0)
1208 {
1209 ++split;
1210 *ptr = NL; /* split line by inserting a NL */
1211 size = 1;
1212 }
1213 else
1214#endif
1215 {
1216 if (!skip_read)
1217 {
1218#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001219# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 size = SSIZE_MAX; /* use max I/O size, 52K */
1221# else
1222 size = 0x10000L; /* use buffer >= 64K */
1223# endif
1224#else
1225 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1226#endif
1227
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001228 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 {
1230 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1231 FALSE)) != NULL)
1232 break;
1233 }
1234 if (new_buffer == NULL)
1235 {
1236 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1237 error = TRUE;
1238 break;
1239 }
1240 if (linerest) /* copy characters from the previous buffer */
1241 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1242 vim_free(buffer);
1243 buffer = new_buffer;
1244 ptr = buffer + linerest;
1245 line_start = buffer;
1246
1247#ifdef FEAT_MBYTE
1248 /* May need room to translate into.
1249 * For iconv() we don't really know the required space, use a
1250 * factor ICONV_MULT.
1251 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1252 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1253 * become up to 4 bytes, size must be multiple of 2
1254 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1255 * multiple of 2
1256 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1257 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001258 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259# ifdef USE_ICONV
1260 if (iconv_fd != (iconv_t)-1)
1261 size = size / ICONV_MULT;
1262 else
1263# endif
1264 if (fio_flags & FIO_LATIN1)
1265 size = size / 2;
1266 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1267 size = (size * 2 / 3) & ~1;
1268 else if (fio_flags & FIO_UCS4)
1269 size = (size * 2 / 3) & ~3;
1270 else if (fio_flags == FIO_UCSBOM)
1271 size = size / ICONV_MULT; /* worst case */
1272# ifdef WIN3264
1273 else if (fio_flags & FIO_CODEPAGE)
1274 size = size / ICONV_MULT; /* also worst case */
1275# endif
1276# ifdef MACOS_X
1277 else if (fio_flags & FIO_MACROMAN)
1278 size = size / ICONV_MULT; /* also worst case */
1279# endif
1280#endif
1281
1282#ifdef FEAT_MBYTE
1283 if (conv_restlen > 0)
1284 {
1285 /* Insert unconverted bytes from previous line. */
1286 mch_memmove(ptr, conv_rest, conv_restlen);
1287 ptr += conv_restlen;
1288 size -= conv_restlen;
1289 }
1290#endif
1291
1292 if (read_buffer)
1293 {
1294 /*
1295 * Read bytes from curbuf. Used for converting text read
1296 * from stdin.
1297 */
1298 if (read_buf_lnum > from)
1299 size = 0;
1300 else
1301 {
1302 int n, ni;
1303 long tlen;
1304
1305 tlen = 0;
1306 for (;;)
1307 {
1308 p = ml_get(read_buf_lnum) + read_buf_col;
1309 n = (int)STRLEN(p);
1310 if ((int)tlen + n + 1 > size)
1311 {
1312 /* Filled up to "size", append partial line.
1313 * Change NL to NUL to reverse the effect done
1314 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001315 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 for (ni = 0; ni < n; ++ni)
1317 {
1318 if (p[ni] == NL)
1319 ptr[tlen++] = NUL;
1320 else
1321 ptr[tlen++] = p[ni];
1322 }
1323 read_buf_col += n;
1324 break;
1325 }
1326 else
1327 {
1328 /* Append whole line and new-line. Change NL
1329 * to NUL to reverse the effect done below. */
1330 for (ni = 0; ni < n; ++ni)
1331 {
1332 if (p[ni] == NL)
1333 ptr[tlen++] = NUL;
1334 else
1335 ptr[tlen++] = p[ni];
1336 }
1337 ptr[tlen++] = NL;
1338 read_buf_col = 0;
1339 if (++read_buf_lnum > from)
1340 {
1341 /* When the last line didn't have an
1342 * end-of-line don't add it now either. */
1343 if (!curbuf->b_p_eol)
1344 --tlen;
1345 size = tlen;
1346 break;
1347 }
1348 }
1349 }
1350 }
1351 }
1352 else
1353 {
1354 /*
1355 * Read bytes from the file.
1356 */
1357 size = vim_read(fd, ptr, size);
1358 }
1359
1360 if (size <= 0)
1361 {
1362 if (size < 0) /* read error */
1363 error = TRUE;
1364#ifdef FEAT_MBYTE
1365 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001366 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001367 /*
1368 * Reached end-of-file but some trailing bytes could
1369 * not be converted. Truncated file?
1370 */
1371
1372 /* When we did a conversion report an error. */
1373 if (fio_flags != 0
1374# ifdef USE_ICONV
1375 || iconv_fd != (iconv_t)-1
1376# endif
1377 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001378 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001379 if (conv_error == 0)
1380 conv_error = curbuf->b_ml.ml_line_count
1381 - linecnt + 1;
1382 }
1383 /* Remember the first linenr with an illegal byte */
1384 else if (illegal_byte == 0)
1385 illegal_byte = curbuf->b_ml.ml_line_count
1386 - linecnt + 1;
1387 if (bad_char_behavior == BAD_DROP)
1388 {
1389 *(ptr - conv_restlen) = NUL;
1390 conv_restlen = 0;
1391 }
1392 else
1393 {
1394 /* Replace the trailing bytes with the replacement
1395 * character if we were converting; if we weren't,
1396 * leave the UTF8 checking code to do it, as it
1397 * works slightly differently. */
1398 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1399# ifdef USE_ICONV
1400 || iconv_fd != (iconv_t)-1
1401# endif
1402 ))
1403 {
1404 while (conv_restlen > 0)
1405 {
1406 *(--ptr) = bad_char_behavior;
1407 --conv_restlen;
1408 }
1409 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001410 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001411# ifdef USE_ICONV
1412 if (iconv_fd != (iconv_t)-1)
1413 {
1414 iconv_close(iconv_fd);
1415 iconv_fd = (iconv_t)-1;
1416 }
1417# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001418 }
1419 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420#endif
1421 }
1422
1423#ifdef FEAT_CRYPT
1424 /*
1425 * At start of file: Check for magic number of encryption.
1426 */
1427 if (filesize == 0)
1428 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaarf50a2532010-05-21 15:36:08 +02001429 &filesize, newfile, &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 /*
1431 * Decrypt the read bytes.
1432 */
1433 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001434 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435#endif
1436 }
1437 skip_read = FALSE;
1438
1439#ifdef FEAT_MBYTE
1440 /*
1441 * At start of file (or after crypt magic number): Check for BOM.
1442 * Also check for a BOM for other Unicode encodings, but not after
1443 * converting with 'charconvert' or when a BOM has already been
1444 * found.
1445 */
1446 if ((filesize == 0
1447# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001448 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001449 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001450 + crypt_seed_len[use_crypt_method])
1451 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452# endif
1453 )
1454 && (fio_flags == FIO_UCSBOM
1455 || (!curbuf->b_p_bomb
1456 && tmpname == NULL
1457 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1458 {
1459 char_u *ccname;
1460 int blen;
1461
1462 /* no BOM detection in a short file or in binary mode */
1463 if (size < 2 || curbuf->b_p_bin)
1464 ccname = NULL;
1465 else
1466 ccname = check_for_bom(ptr, size, &blen,
1467 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1468 if (ccname != NULL)
1469 {
1470 /* Remove BOM from the text */
1471 filesize += blen;
1472 size -= blen;
1473 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001474 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001475 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001477 curbuf->b_start_bomb = TRUE;
1478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 }
1480
1481 if (fio_flags == FIO_UCSBOM)
1482 {
1483 if (ccname == NULL)
1484 {
1485 /* No BOM detected: retry with next encoding. */
1486 advance_fenc = TRUE;
1487 }
1488 else
1489 {
1490 /* BOM detected: set "fenc" and jump back */
1491 if (fenc_alloced)
1492 vim_free(fenc);
1493 fenc = ccname;
1494 fenc_alloced = FALSE;
1495 }
1496 /* retry reading without getting new bytes or rewinding */
1497 skip_read = TRUE;
1498 goto retry;
1499 }
1500 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001501
1502 /* Include not converted bytes. */
1503 ptr -= conv_restlen;
1504 size += conv_restlen;
1505 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506#endif
1507 /*
1508 * Break here for a read error or end-of-file.
1509 */
1510 if (size <= 0)
1511 break;
1512
1513#ifdef FEAT_MBYTE
1514
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515# ifdef USE_ICONV
1516 if (iconv_fd != (iconv_t)-1)
1517 {
1518 /*
1519 * Attempt conversion of the read bytes to 'encoding' using
1520 * iconv().
1521 */
1522 const char *fromp;
1523 char *top;
1524 size_t from_size;
1525 size_t to_size;
1526
1527 fromp = (char *)ptr;
1528 from_size = size;
1529 ptr += size;
1530 top = (char *)ptr;
1531 to_size = real_size - size;
1532
1533 /*
1534 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001535 * another conversion. Except for when there is no
1536 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001538 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1539 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1541 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001542 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001543 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001544 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001545 if (conv_error == 0)
1546 conv_error = readfile_linenr(linecnt,
1547 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001548
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001549 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001550 ++fromp;
1551 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001552 if (bad_char_behavior == BAD_KEEP)
1553 {
1554 *top++ = *(fromp - 1);
1555 --to_size;
1556 }
1557 else if (bad_char_behavior != BAD_DROP)
1558 {
1559 *top++ = bad_char_behavior;
1560 --to_size;
1561 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563
1564 if (from_size > 0)
1565 {
1566 /* Some remaining characters, keep them for the next
1567 * round. */
1568 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1569 conv_restlen = (int)from_size;
1570 }
1571
1572 /* move the linerest to before the converted characters */
1573 line_start = ptr - linerest;
1574 mch_memmove(line_start, buffer, (size_t)linerest);
1575 size = (long)((char_u *)top - ptr);
1576 }
1577# endif
1578
1579# ifdef WIN3264
1580 if (fio_flags & FIO_CODEPAGE)
1581 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001582 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001583 WCHAR ucs2buf[3];
1584 int ucs2len;
1585 int codepage = FIO_GET_CP(fio_flags);
1586 int bytelen;
1587 int found_bad;
1588 char replstr[2];
1589
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 /*
1591 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001592 * a codepage, using standard MS-Windows functions. This
1593 * requires two steps:
1594 * 1. convert from 'fileencoding' to ucs-2
1595 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001597 * Because there may be illegal bytes AND an incomplete byte
1598 * sequence at the end, we may have to do the conversion one
1599 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001602 /* Replacement string for WideCharToMultiByte(). */
1603 if (bad_char_behavior > 0)
1604 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001606 replstr[0] = '?';
1607 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
1609 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 * Move the bytes to the end of the buffer, so that we have
1611 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001613 src = ptr + real_size - size;
1614 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001616 /*
1617 * Do the conversion.
1618 */
1619 dst = ptr;
1620 size = size;
1621 while (size > 0)
1622 {
1623 found_bad = FALSE;
1624
1625# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1626 if (codepage == CP_UTF8)
1627 {
1628 /* Handle CP_UTF8 input ourselves to be able to handle
1629 * trailing bytes properly.
1630 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001631 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001632 if (bytelen > size)
1633 {
1634 /* Only got some bytes of a character. Normally
1635 * it's put in "conv_rest", but if it's too long
1636 * deal with it as if they were illegal bytes. */
1637 if (bytelen <= CONV_RESTLEN)
1638 break;
1639
1640 /* weird overlong byte sequence */
1641 bytelen = size;
1642 found_bad = TRUE;
1643 }
1644 else
1645 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001646 int u8c = utf_ptr2char(src);
1647
Bram Moolenaar86e01082005-12-29 22:45:34 +00001648 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001649 found_bad = TRUE;
1650 ucs2buf[0] = u8c;
1651 ucs2len = 1;
1652 }
1653 }
1654 else
1655# endif
1656 {
1657 /* We don't know how long the byte sequence is, try
1658 * from one to three bytes. */
1659 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1660 ++bytelen)
1661 {
1662 ucs2len = MultiByteToWideChar(codepage,
1663 MB_ERR_INVALID_CHARS,
1664 (LPCSTR)src, bytelen,
1665 ucs2buf, 3);
1666 if (ucs2len > 0)
1667 break;
1668 }
1669 if (ucs2len == 0)
1670 {
1671 /* If we have only one byte then it's probably an
1672 * incomplete byte sequence. Otherwise discard
1673 * one byte as a bad character. */
1674 if (size == 1)
1675 break;
1676 found_bad = TRUE;
1677 bytelen = 1;
1678 }
1679 }
1680
1681 if (!found_bad)
1682 {
1683 int i;
1684
1685 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1686 if (enc_utf8)
1687 {
1688 /* From UCS-2 to UTF-8. Cannot fail. */
1689 for (i = 0; i < ucs2len; ++i)
1690 dst += utf_char2bytes(ucs2buf[i], dst);
1691 }
1692 else
1693 {
1694 BOOL bad = FALSE;
1695 int dstlen;
1696
1697 /* From UCS-2 to "enc_codepage". If the
1698 * conversion uses the default character "?",
1699 * the data doesn't fit in this encoding. */
1700 dstlen = WideCharToMultiByte(enc_codepage, 0,
1701 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001702 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001703 replstr, &bad);
1704 if (bad)
1705 found_bad = TRUE;
1706 else
1707 dst += dstlen;
1708 }
1709 }
1710
1711 if (found_bad)
1712 {
1713 /* Deal with bytes we can't convert. */
1714 if (can_retry)
1715 goto rewind_retry;
1716 if (conv_error == 0)
1717 conv_error = readfile_linenr(linecnt, ptr, dst);
1718 if (bad_char_behavior != BAD_DROP)
1719 {
1720 if (bad_char_behavior == BAD_KEEP)
1721 {
1722 mch_memmove(dst, src, bytelen);
1723 dst += bytelen;
1724 }
1725 else
1726 *dst++ = bad_char_behavior;
1727 }
1728 }
1729
1730 src += bytelen;
1731 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001733
1734 if (size > 0)
1735 {
1736 /* An incomplete byte sequence remaining. */
1737 mch_memmove(conv_rest, src, size);
1738 conv_restlen = size;
1739 }
1740
1741 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001742 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 }
1744 else
1745# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001746# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 if (fio_flags & FIO_MACROMAN)
1748 {
1749 /*
1750 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001751 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001753 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 }
1756 else
1757# endif
1758 if (fio_flags != 0)
1759 {
1760 int u8c;
1761 char_u *dest;
1762 char_u *tail = NULL;
1763
1764 /*
1765 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1766 * "enc_utf8" not set: Convert Unicode to Latin1.
1767 * Go from end to start through the buffer, because the number
1768 * of bytes may increase.
1769 * "dest" points to after where the UTF-8 bytes go, "p" points
1770 * to after the next character to convert.
1771 */
1772 dest = ptr + real_size;
1773 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1774 {
1775 p = ptr + size;
1776 if (fio_flags == FIO_UTF8)
1777 {
1778 /* Check for a trailing incomplete UTF-8 sequence */
1779 tail = ptr + size - 1;
1780 while (tail > ptr && (*tail & 0xc0) == 0x80)
1781 --tail;
1782 if (tail + utf_byte2len(*tail) <= ptr + size)
1783 tail = NULL;
1784 else
1785 p = tail;
1786 }
1787 }
1788 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1789 {
1790 /* Check for a trailing byte */
1791 p = ptr + (size & ~1);
1792 if (size & 1)
1793 tail = p;
1794 if ((fio_flags & FIO_UTF16) && p > ptr)
1795 {
1796 /* Check for a trailing leading word */
1797 if (fio_flags & FIO_ENDIAN_L)
1798 {
1799 u8c = (*--p << 8);
1800 u8c += *--p;
1801 }
1802 else
1803 {
1804 u8c = *--p;
1805 u8c += (*--p << 8);
1806 }
1807 if (u8c >= 0xd800 && u8c <= 0xdbff)
1808 tail = p;
1809 else
1810 p += 2;
1811 }
1812 }
1813 else /* FIO_UCS4 */
1814 {
1815 /* Check for trailing 1, 2 or 3 bytes */
1816 p = ptr + (size & ~3);
1817 if (size & 3)
1818 tail = p;
1819 }
1820
1821 /* If there is a trailing incomplete sequence move it to
1822 * conv_rest[]. */
1823 if (tail != NULL)
1824 {
1825 conv_restlen = (int)((ptr + size) - tail);
1826 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1827 size -= conv_restlen;
1828 }
1829
1830
1831 while (p > ptr)
1832 {
1833 if (fio_flags & FIO_LATIN1)
1834 u8c = *--p;
1835 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1836 {
1837 if (fio_flags & FIO_ENDIAN_L)
1838 {
1839 u8c = (*--p << 8);
1840 u8c += *--p;
1841 }
1842 else
1843 {
1844 u8c = *--p;
1845 u8c += (*--p << 8);
1846 }
1847 if ((fio_flags & FIO_UTF16)
1848 && u8c >= 0xdc00 && u8c <= 0xdfff)
1849 {
1850 int u16c;
1851
1852 if (p == ptr)
1853 {
1854 /* Missing leading word. */
1855 if (can_retry)
1856 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001857 if (conv_error == 0)
1858 conv_error = readfile_linenr(linecnt,
1859 ptr, p);
1860 if (bad_char_behavior == BAD_DROP)
1861 continue;
1862 if (bad_char_behavior != BAD_KEEP)
1863 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864 }
1865
1866 /* found second word of double-word, get the first
1867 * word and compute the resulting character */
1868 if (fio_flags & FIO_ENDIAN_L)
1869 {
1870 u16c = (*--p << 8);
1871 u16c += *--p;
1872 }
1873 else
1874 {
1875 u16c = *--p;
1876 u16c += (*--p << 8);
1877 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001878 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1879 + (u8c & 0x3ff);
1880
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 /* Check if the word is indeed a leading word. */
1882 if (u16c < 0xd800 || u16c > 0xdbff)
1883 {
1884 if (can_retry)
1885 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001886 if (conv_error == 0)
1887 conv_error = readfile_linenr(linecnt,
1888 ptr, p);
1889 if (bad_char_behavior == BAD_DROP)
1890 continue;
1891 if (bad_char_behavior != BAD_KEEP)
1892 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 }
1895 }
1896 else if (fio_flags & FIO_UCS4)
1897 {
1898 if (fio_flags & FIO_ENDIAN_L)
1899 {
1900 u8c = (*--p << 24);
1901 u8c += (*--p << 16);
1902 u8c += (*--p << 8);
1903 u8c += *--p;
1904 }
1905 else /* big endian */
1906 {
1907 u8c = *--p;
1908 u8c += (*--p << 8);
1909 u8c += (*--p << 16);
1910 u8c += (*--p << 24);
1911 }
1912 }
1913 else /* UTF-8 */
1914 {
1915 if (*--p < 0x80)
1916 u8c = *p;
1917 else
1918 {
1919 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001920 p -= len;
1921 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 if (len == 0)
1923 {
1924 /* Not a valid UTF-8 character, retry with
1925 * another fenc when possible, otherwise just
1926 * report the error. */
1927 if (can_retry)
1928 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001929 if (conv_error == 0)
1930 conv_error = readfile_linenr(linecnt,
1931 ptr, p);
1932 if (bad_char_behavior == BAD_DROP)
1933 continue;
1934 if (bad_char_behavior != BAD_KEEP)
1935 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 }
1938 }
1939 if (enc_utf8) /* produce UTF-8 */
1940 {
1941 dest -= utf_char2len(u8c);
1942 (void)utf_char2bytes(u8c, dest);
1943 }
1944 else /* produce Latin1 */
1945 {
1946 --dest;
1947 if (u8c >= 0x100)
1948 {
1949 /* character doesn't fit in latin1, retry with
1950 * another fenc when possible, otherwise just
1951 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001952 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001954 if (conv_error == 0)
1955 conv_error = readfile_linenr(linecnt, ptr, p);
1956 if (bad_char_behavior == BAD_DROP)
1957 ++dest;
1958 else if (bad_char_behavior == BAD_KEEP)
1959 *dest = u8c;
1960 else if (eap != NULL && eap->bad_char != 0)
1961 *dest = bad_char_behavior;
1962 else
1963 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
1965 else
1966 *dest = u8c;
1967 }
1968 }
1969
1970 /* move the linerest to before the converted characters */
1971 line_start = dest - linerest;
1972 mch_memmove(line_start, buffer, (size_t)linerest);
1973 size = (long)((ptr + real_size) - dest);
1974 ptr = dest;
1975 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001976 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001978 int incomplete_tail = FALSE;
1979
1980 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1981 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001983 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001984 int l;
1985
1986 if (todo <= 0)
1987 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 if (*p >= 0x80)
1989 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 /* A length of 1 means it's an illegal byte. Accept
1991 * an incomplete character at the end though, the next
1992 * read() will get the next bytes, we'll check it
1993 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001994 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001995 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001997 /* Avoid retrying with a different encoding when
1998 * a truncated file is more likely, or attempting
1999 * to read the rest of an incomplete sequence when
2000 * we have already done so. */
2001 if (p > ptr || filesize > 0)
2002 incomplete_tail = TRUE;
2003 /* Incomplete byte sequence, move it to conv_rest[]
2004 * and try to read the rest of it, unless we've
2005 * already done so. */
2006 if (p > ptr)
2007 {
2008 conv_restlen = todo;
2009 mch_memmove(conv_rest, p, conv_restlen);
2010 size -= conv_restlen;
2011 break;
2012 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002014 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002015 {
2016 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002017 * do that, unless at EOF where a truncated
2018 * file is more likely than a conversion error. */
2019 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002020 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002021# ifdef USE_ICONV
2022 /* When we did a conversion report an error. */
2023 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2024 conv_error = readfile_linenr(linecnt, ptr, p);
2025# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002026 /* Remember the first linenr with an illegal byte */
2027 if (conv_error == 0 && illegal_byte == 0)
2028 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002029
2030 /* Drop, keep or replace the bad byte. */
2031 if (bad_char_behavior == BAD_DROP)
2032 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002033 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002034 --p;
2035 --size;
2036 }
2037 else if (bad_char_behavior != BAD_KEEP)
2038 *p = bad_char_behavior;
2039 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002040 else
2041 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 }
2043 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002044 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 {
2046 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002048 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002050 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2051 /* iconv() failed, try 'charconvert' */
2052 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 else
2054# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002055 /* use next item from 'fileencodings' */
2056 advance_fenc = TRUE;
2057 file_rewind = TRUE;
2058 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 }
2060 }
2061#endif
2062
2063 /* count the number of characters (after conversion!) */
2064 filesize += size;
2065
2066 /*
2067 * when reading the first part of a file: guess EOL type
2068 */
2069 if (fileformat == EOL_UNKNOWN)
2070 {
2071 /* First try finding a NL, for Dos and Unix */
2072 if (try_dos || try_unix)
2073 {
2074 for (p = ptr; p < ptr + size; ++p)
2075 {
2076 if (*p == NL)
2077 {
2078 if (!try_unix
2079 || (try_dos && p > ptr && p[-1] == CAR))
2080 fileformat = EOL_DOS;
2081 else
2082 fileformat = EOL_UNIX;
2083 break;
2084 }
2085 }
2086
2087 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2088 if (fileformat == EOL_UNIX && try_mac)
2089 {
2090 /* Need to reset the counters when retrying fenc. */
2091 try_mac = 1;
2092 try_unix = 1;
2093 for (; p >= ptr && *p != CAR; p--)
2094 ;
2095 if (p >= ptr)
2096 {
2097 for (p = ptr; p < ptr + size; ++p)
2098 {
2099 if (*p == NL)
2100 try_unix++;
2101 else if (*p == CAR)
2102 try_mac++;
2103 }
2104 if (try_mac > try_unix)
2105 fileformat = EOL_MAC;
2106 }
2107 }
2108 }
2109
2110 /* No NL found: may use Mac format */
2111 if (fileformat == EOL_UNKNOWN && try_mac)
2112 fileformat = EOL_MAC;
2113
2114 /* Still nothing found? Use first format in 'ffs' */
2115 if (fileformat == EOL_UNKNOWN)
2116 fileformat = default_fileformat();
2117
2118 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002119 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 set_fileformat(fileformat, OPT_LOCAL);
2121 }
2122 }
2123
2124 /*
2125 * This loop is executed once for every character read.
2126 * Keep it fast!
2127 */
2128 if (fileformat == EOL_MAC)
2129 {
2130 --ptr;
2131 while (++ptr, --size >= 0)
2132 {
2133 /* catch most common case first */
2134 if ((c = *ptr) != NUL && c != CAR && c != NL)
2135 continue;
2136 if (c == NUL)
2137 *ptr = NL; /* NULs are replaced by newlines! */
2138 else if (c == NL)
2139 *ptr = CAR; /* NLs are replaced by CRs! */
2140 else
2141 {
2142 if (skip_count == 0)
2143 {
2144 *ptr = NUL; /* end of line */
2145 len = (colnr_T) (ptr - line_start + 1);
2146 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2147 {
2148 error = TRUE;
2149 break;
2150 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002151#ifdef FEAT_PERSISTENT_UNDO
2152 if (read_undo_file)
2153 sha256_update(&sha_ctx, line_start, len);
2154#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 ++lnum;
2156 if (--read_count == 0)
2157 {
2158 error = TRUE; /* break loop */
2159 line_start = ptr; /* nothing left to write */
2160 break;
2161 }
2162 }
2163 else
2164 --skip_count;
2165 line_start = ptr + 1;
2166 }
2167 }
2168 }
2169 else
2170 {
2171 --ptr;
2172 while (++ptr, --size >= 0)
2173 {
2174 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2175 continue;
2176 if (c == NUL)
2177 *ptr = NL; /* NULs are replaced by newlines! */
2178 else
2179 {
2180 if (skip_count == 0)
2181 {
2182 *ptr = NUL; /* end of line */
2183 len = (colnr_T)(ptr - line_start + 1);
2184 if (fileformat == EOL_DOS)
2185 {
2186 if (ptr[-1] == CAR) /* remove CR */
2187 {
2188 ptr[-1] = NUL;
2189 --len;
2190 }
2191 /*
2192 * Reading in Dos format, but no CR-LF found!
2193 * When 'fileformats' includes "unix", delete all
2194 * the lines read so far and start all over again.
2195 * Otherwise give an error message later.
2196 */
2197 else if (ff_error != EOL_DOS)
2198 {
2199 if ( try_unix
2200 && !read_stdin
2201 && (read_buffer
2202 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2203 {
2204 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002205 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 set_fileformat(EOL_UNIX, OPT_LOCAL);
2207 file_rewind = TRUE;
2208 keep_fileformat = TRUE;
2209 goto retry;
2210 }
2211 ff_error = EOL_DOS;
2212 }
2213 }
2214 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2215 {
2216 error = TRUE;
2217 break;
2218 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002219#ifdef FEAT_PERSISTENT_UNDO
2220 if (read_undo_file)
2221 sha256_update(&sha_ctx, line_start, len);
2222#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223 ++lnum;
2224 if (--read_count == 0)
2225 {
2226 error = TRUE; /* break loop */
2227 line_start = ptr; /* nothing left to write */
2228 break;
2229 }
2230 }
2231 else
2232 --skip_count;
2233 line_start = ptr + 1;
2234 }
2235 }
2236 }
2237 linerest = (long)(ptr - line_start);
2238 ui_breakcheck();
2239 }
2240
2241failed:
2242 /* not an error, max. number of lines reached */
2243 if (error && read_count == 0)
2244 error = FALSE;
2245
2246 /*
2247 * If we get EOF in the middle of a line, note the fact and
2248 * complete the line ourselves.
2249 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2250 */
2251 if (!error
2252 && !got_int
2253 && linerest != 0
2254 && !(!curbuf->b_p_bin
2255 && fileformat == EOL_DOS
2256 && *line_start == Ctrl_Z
2257 && ptr == line_start + 1))
2258 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002259 /* remember for when writing */
2260 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 curbuf->b_p_eol = FALSE;
2262 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002263 len = (colnr_T)(ptr - line_start + 1);
2264 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 error = TRUE;
2266 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002267 {
2268#ifdef FEAT_PERSISTENT_UNDO
2269 if (read_undo_file)
2270 sha256_update(&sha_ctx, line_start, len);
2271#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002273 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 }
2275
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002276 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 save_file_ff(curbuf); /* remember the current file format */
2278
2279#ifdef FEAT_CRYPT
2280 if (cryptkey != curbuf->b_p_key)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002281 free_crypt_key(cryptkey);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282#endif
2283
2284#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002285 /* If editing a new file: set 'fenc' for the current buffer.
2286 * Also for ":read ++edit file". */
2287 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002289 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 if (fenc_alloced)
2291 vim_free(fenc);
2292# ifdef USE_ICONV
2293 if (iconv_fd != (iconv_t)-1)
2294 {
2295 iconv_close(iconv_fd);
2296 iconv_fd = (iconv_t)-1;
2297 }
2298# endif
2299#endif
2300
2301 if (!read_buffer && !read_stdin)
2302 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002303#ifdef HAVE_FD_CLOEXEC
2304 else
2305 {
2306 int fdflags = fcntl(fd, F_GETFD);
2307 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2308 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2309 }
2310#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311 vim_free(buffer);
2312
2313#ifdef HAVE_DUP
2314 if (read_stdin)
2315 {
2316 /* Use stderr for stdin, makes shell commands work. */
2317 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002318 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 }
2320#endif
2321
2322#ifdef FEAT_MBYTE
2323 if (tmpname != NULL)
2324 {
2325 mch_remove(tmpname); /* delete converted file */
2326 vim_free(tmpname);
2327 }
2328#endif
2329 --no_wait_return; /* may wait for return now */
2330
2331 /*
2332 * In recovery mode everything but autocommands is skipped.
2333 */
2334 if (!recoverymode)
2335 {
2336 /* need to delete the last line, which comes from the empty buffer */
2337 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2338 {
2339#ifdef FEAT_NETBEANS_INTG
2340 netbeansFireChanges = 0;
2341#endif
2342 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2343#ifdef FEAT_NETBEANS_INTG
2344 netbeansFireChanges = 1;
2345#endif
2346 --linecnt;
2347 }
2348 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2349 if (filesize == 0)
2350 linecnt = 0;
2351 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002352 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002354#ifdef FEAT_DIFF
2355 /* After reading the text into the buffer the diff info needs to
2356 * be updated. */
2357 diff_invalidate(curbuf);
2358#endif
2359#ifdef FEAT_FOLDING
2360 /* All folds in the window are invalid now. Mark them for update
2361 * before triggering autocommands. */
2362 foldUpdateAll(curwin);
2363#endif
2364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 else if (linecnt) /* appended at least one line */
2366 appended_lines_mark(from, linecnt);
2367
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368#ifndef ALWAYS_USE_GUI
2369 /*
2370 * If we were reading from the same terminal as where messages go,
2371 * the screen will have been messed up.
2372 * Switch on raw mode now and clear the screen.
2373 */
2374 if (read_stdin)
2375 {
2376 settmode(TMODE_RAW); /* set to raw mode */
2377 starttermcap();
2378 screenclear();
2379 }
2380#endif
2381
2382 if (got_int)
2383 {
2384 if (!(flags & READ_DUMMY))
2385 {
2386 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2387 if (newfile)
2388 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2389 }
2390 msg_scroll = msg_save;
2391#ifdef FEAT_VIMINFO
2392 check_marks_read();
2393#endif
2394 return OK; /* an interrupt isn't really an error */
2395 }
2396
2397 if (!filtering && !(flags & READ_DUMMY))
2398 {
2399 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2400 c = FALSE;
2401
2402#ifdef UNIX
2403# ifdef S_ISFIFO
2404 if (S_ISFIFO(perm)) /* fifo or socket */
2405 {
2406 STRCAT(IObuff, _("[fifo/socket]"));
2407 c = TRUE;
2408 }
2409# else
2410# ifdef S_IFIFO
2411 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2412 {
2413 STRCAT(IObuff, _("[fifo]"));
2414 c = TRUE;
2415 }
2416# endif
2417# ifdef S_IFSOCK
2418 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2419 {
2420 STRCAT(IObuff, _("[socket]"));
2421 c = TRUE;
2422 }
2423# endif
2424# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002425# ifdef OPEN_CHR_FILES
2426 if (S_ISCHR(perm)) /* or character special */
2427 {
2428 STRCAT(IObuff, _("[character special]"));
2429 c = TRUE;
2430 }
2431# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432#endif
2433 if (curbuf->b_p_ro)
2434 {
2435 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2436 c = TRUE;
2437 }
2438 if (read_no_eol_lnum)
2439 {
2440 msg_add_eol();
2441 c = TRUE;
2442 }
2443 if (ff_error == EOL_DOS)
2444 {
2445 STRCAT(IObuff, _("[CR missing]"));
2446 c = TRUE;
2447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 if (split)
2449 {
2450 STRCAT(IObuff, _("[long lines split]"));
2451 c = TRUE;
2452 }
2453#ifdef FEAT_MBYTE
2454 if (notconverted)
2455 {
2456 STRCAT(IObuff, _("[NOT converted]"));
2457 c = TRUE;
2458 }
2459 else if (converted)
2460 {
2461 STRCAT(IObuff, _("[converted]"));
2462 c = TRUE;
2463 }
2464#endif
2465#ifdef FEAT_CRYPT
2466 if (cryptkey != NULL)
2467 {
2468 STRCAT(IObuff, _("[crypted]"));
2469 c = TRUE;
2470 }
2471#endif
2472#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002473 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002475 sprintf((char *)IObuff + STRLEN(IObuff),
2476 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 c = TRUE;
2478 }
2479 else if (illegal_byte > 0)
2480 {
2481 sprintf((char *)IObuff + STRLEN(IObuff),
2482 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2483 c = TRUE;
2484 }
2485 else
2486#endif
2487 if (error)
2488 {
2489 STRCAT(IObuff, _("[READ ERRORS]"));
2490 c = TRUE;
2491 }
2492 if (msg_add_fileformat(fileformat))
2493 c = TRUE;
2494#ifdef FEAT_CRYPT
2495 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002496 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002497 - CRYPT_MAGIC_LEN
2498 - crypt_salt_len[use_crypt_method]
2499 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 else
2501#endif
2502 msg_add_lines(c, (long)linecnt, filesize);
2503
2504 vim_free(keep_msg);
2505 keep_msg = NULL;
2506 msg_scrolled_ign = TRUE;
2507#ifdef ALWAYS_USE_GUI
2508 /* Don't show the message when reading stdin, it would end up in a
2509 * message box (which might be shown when exiting!) */
2510 if (read_stdin || read_buffer)
2511 p = msg_may_trunc(FALSE, IObuff);
2512 else
2513#endif
2514 p = msg_trunc_attr(IObuff, FALSE, 0);
2515 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002516 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 /* Need to repeat the message after redrawing when:
2518 * - When reading from stdin (the screen will be cleared next).
2519 * - When restart_edit is set (otherwise there will be a delay
2520 * before redrawing).
2521 * - When the screen was scrolled but there is no wait-return
2522 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002523 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 msg_scrolled_ign = FALSE;
2525 }
2526
2527 /* with errors writing the file requires ":w!" */
2528 if (newfile && (error
2529#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002530 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002531 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532#endif
2533 ))
2534 curbuf->b_p_ro = TRUE;
2535
2536 u_clearline(); /* cannot use "U" command after adding lines */
2537
2538 /*
2539 * In Ex mode: cursor at last new line.
2540 * Otherwise: cursor at first new line.
2541 */
2542 if (exmode_active)
2543 curwin->w_cursor.lnum = from + linecnt;
2544 else
2545 curwin->w_cursor.lnum = from + 1;
2546 check_cursor_lnum();
2547 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2548
2549 /*
2550 * Set '[ and '] marks to the newly read lines.
2551 */
2552 curbuf->b_op_start.lnum = from + 1;
2553 curbuf->b_op_start.col = 0;
2554 curbuf->b_op_end.lnum = from + linecnt;
2555 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002556
2557#ifdef WIN32
2558 /*
2559 * Work around a weird problem: When a file has two links (only
2560 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002561 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002562 * It's correct again after reading the file, thus reset the timestamp
2563 * here.
2564 */
2565 if (newfile && !read_stdin && !read_buffer
2566 && mch_stat((char *)fname, &st) >= 0)
2567 {
2568 buf_store_time(curbuf, &st, fname);
2569 curbuf->b_mtime_read = curbuf->b_mtime;
2570 }
2571#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 }
2573 msg_scroll = msg_save;
2574
2575#ifdef FEAT_VIMINFO
2576 /*
2577 * Get the marks before executing autocommands, so they can be used there.
2578 */
2579 check_marks_read();
2580#endif
2581
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 /*
2583 * Trick: We remember if the last line of the read didn't have
2584 * an eol for when writing it again. This is required for
2585 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2586 */
2587 write_no_eol_lnum = read_no_eol_lnum;
2588
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002589#ifdef FEAT_PERSISTENT_UNDO
2590 /*
2591 * When opening a new file locate undo info and read it.
2592 */
2593 if (read_undo_file)
2594 {
2595 char_u hash[UNDO_HASH_SIZE];
2596
2597 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002598 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002599 }
2600#endif
2601
Bram Moolenaardf177f62005-02-22 08:39:57 +00002602#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 if (!read_stdin && !read_buffer)
2604 {
2605 int m = msg_scroll;
2606 int n = msg_scrolled;
2607
2608 /* Save the fileformat now, otherwise the buffer will be considered
2609 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002610 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 save_file_ff(curbuf);
2612
2613 /*
2614 * The output from the autocommands should not overwrite anything and
2615 * should not be overwritten: Set msg_scroll, restore its value if no
2616 * output was done.
2617 */
2618 msg_scroll = TRUE;
2619 if (filtering)
2620 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2621 FALSE, curbuf, eap);
2622 else if (newfile)
2623 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2624 FALSE, curbuf, eap);
2625 else
2626 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2627 FALSE, NULL, eap);
2628 if (msg_scrolled == n)
2629 msg_scroll = m;
2630#ifdef FEAT_EVAL
2631 if (aborting()) /* autocmds may abort script processing */
2632 return FAIL;
2633#endif
2634 }
2635#endif
2636
2637 if (recoverymode && error)
2638 return FAIL;
2639 return OK;
2640}
2641
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002642#ifdef OPEN_CHR_FILES
2643/*
2644 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2645 * which is the name of files used for process substitution output by
2646 * some shells on some operating systems, e.g., bash on SunOS.
2647 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2648 */
2649 static int
2650is_dev_fd_file(fname)
2651 char_u *fname;
2652{
2653 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2654 && VIM_ISDIGIT(fname[8])
2655 && *skipdigits(fname + 9) == NUL
2656 && (fname[9] != NUL
2657 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2658}
2659#endif
2660
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002661#ifdef FEAT_MBYTE
2662
2663/*
2664 * From the current line count and characters read after that, estimate the
2665 * line number where we are now.
2666 * Used for error messages that include a line number.
2667 */
2668 static linenr_T
2669readfile_linenr(linecnt, p, endp)
2670 linenr_T linecnt; /* line count before reading more bytes */
2671 char_u *p; /* start of more bytes read */
2672 char_u *endp; /* end of more bytes read */
2673{
2674 char_u *s;
2675 linenr_T lnum;
2676
2677 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2678 for (s = p; s < endp; ++s)
2679 if (*s == '\n')
2680 ++lnum;
2681 return lnum;
2682}
2683#endif
2684
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002686 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2687 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 * Returns OK or FAIL.
2689 */
2690 int
2691prep_exarg(eap, buf)
2692 exarg_T *eap;
2693 buf_T *buf;
2694{
2695 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2696#ifdef FEAT_MBYTE
2697 + STRLEN(buf->b_p_fenc)
2698#endif
2699 + 15));
2700 if (eap->cmd == NULL)
2701 return FAIL;
2702
2703#ifdef FEAT_MBYTE
2704 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2705 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002706 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707#else
2708 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2709#endif
2710 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002711
2712 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002713 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002714 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 return OK;
2716}
2717
2718#ifdef FEAT_MBYTE
2719/*
2720 * Find next fileencoding to use from 'fileencodings'.
2721 * "pp" points to fenc_next. It's advanced to the next item.
2722 * When there are no more items, an empty string is returned and *pp is set to
2723 * NULL.
2724 * When *pp is not set to NULL, the result is in allocated memory.
2725 */
2726 static char_u *
2727next_fenc(pp)
2728 char_u **pp;
2729{
2730 char_u *p;
2731 char_u *r;
2732
2733 if (**pp == NUL)
2734 {
2735 *pp = NULL;
2736 return (char_u *)"";
2737 }
2738 p = vim_strchr(*pp, ',');
2739 if (p == NULL)
2740 {
2741 r = enc_canonize(*pp);
2742 *pp += STRLEN(*pp);
2743 }
2744 else
2745 {
2746 r = vim_strnsave(*pp, (int)(p - *pp));
2747 *pp = p + 1;
2748 if (r != NULL)
2749 {
2750 p = enc_canonize(r);
2751 vim_free(r);
2752 r = p;
2753 }
2754 }
2755 if (r == NULL) /* out of memory */
2756 {
2757 r = (char_u *)"";
2758 *pp = NULL;
2759 }
2760 return r;
2761}
2762
2763# ifdef FEAT_EVAL
2764/*
2765 * Convert a file with the 'charconvert' expression.
2766 * This closes the file which is to be read, converts it and opens the
2767 * resulting file for reading.
2768 * Returns name of the resulting converted file (the caller should delete it
2769 * after reading it).
2770 * Returns NULL if the conversion failed ("*fdp" is not set) .
2771 */
2772 static char_u *
2773readfile_charconvert(fname, fenc, fdp)
2774 char_u *fname; /* name of input file */
2775 char_u *fenc; /* converted from */
2776 int *fdp; /* in/out: file descriptor of file */
2777{
2778 char_u *tmpname;
2779 char_u *errmsg = NULL;
2780
2781 tmpname = vim_tempname('r');
2782 if (tmpname == NULL)
2783 errmsg = (char_u *)_("Can't find temp file for conversion");
2784 else
2785 {
2786 close(*fdp); /* close the input file, ignore errors */
2787 *fdp = -1;
2788 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2789 fname, tmpname) == FAIL)
2790 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2791 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2792 O_RDONLY | O_EXTRA, 0)) < 0)
2793 errmsg = (char_u *)_("can't read output of 'charconvert'");
2794 }
2795
2796 if (errmsg != NULL)
2797 {
2798 /* Don't use emsg(), it breaks mappings, the retry with
2799 * another type of conversion might still work. */
2800 MSG(errmsg);
2801 if (tmpname != NULL)
2802 {
2803 mch_remove(tmpname); /* delete converted file */
2804 vim_free(tmpname);
2805 tmpname = NULL;
2806 }
2807 }
2808
2809 /* If the input file is closed, open it (caller should check for error). */
2810 if (*fdp < 0)
2811 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2812
2813 return tmpname;
2814}
2815# endif
2816
2817#endif
2818
2819#ifdef FEAT_VIMINFO
2820/*
2821 * Read marks for the current buffer from the viminfo file, when we support
2822 * buffer marks and the buffer has a name.
2823 */
2824 static void
2825check_marks_read()
2826{
2827 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2828 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002829 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830
2831 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2832 * the ' parameter after opening a buffer. */
2833 curbuf->b_marks_read = TRUE;
2834}
2835#endif
2836
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002837#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002839 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2840 * start of the file.
2841 * Returns -1 when no encryption used.
2842 */
2843 static int
2844get_crypt_method(ptr, len)
2845 char *ptr;
2846 int len;
2847{
2848 int i;
2849
2850 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2851 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002852 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002853 continue;
2854 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2855 return i;
2856 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002857
Bram Moolenaar442b4222010-05-24 21:34:22 +02002858 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002859 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2860 EMSG(_("E821: File is encrypted with unknown method"));
2861
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002862 return -1;
2863}
2864
2865/*
2866 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2868 * *filesizep are updated.
2869 * Return the (new) encryption key, NULL for no encryption.
2870 */
2871 static char_u *
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002872check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 char_u *cryptkey; /* previous encryption key or NULL */
2874 char_u *ptr; /* pointer to read bytes */
2875 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002876 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 int newfile; /* editing a new buffer */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002878 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002879{
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002880 int method = get_crypt_method((char *)ptr, *sizep);
2881
2882 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002884 curbuf->b_p_cm = method;
2885 use_crypt_method = method;
2886 if (method > 0)
2887 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002888 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 {
2890 if (*curbuf->b_p_key)
2891 cryptkey = curbuf->b_p_key;
2892 else
2893 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002894 /* When newfile is TRUE, store the typed key in the 'key'
2895 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002896 * Don't ask for the key again when first time Enter was hit.
2897 * Happens when retrying to detect encoding. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002899 *did_ask = TRUE;
2900
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 /* check if empty key entered */
2902 if (cryptkey != NULL && *cryptkey == NUL)
2903 {
2904 if (cryptkey != curbuf->b_p_key)
2905 vim_free(cryptkey);
2906 cryptkey = NULL;
2907 }
2908 }
2909 }
2910
2911 if (cryptkey != NULL)
2912 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002913 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002914 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002915
2916 if (method == 0)
2917 crypt_init_keys(cryptkey);
2918 else
2919 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002920 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2921 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923
2924 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002925 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2926 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
2927 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len, (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 }
2929 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002930 /* When starting to edit a new file which does not have encryption, clear
2931 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 else if (newfile && *curbuf->b_p_key && !starting)
2933 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2934
2935 return cryptkey;
2936}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002937
2938/*
2939 * Check for magic number used for encryption. Applies to the current buffer.
2940 * If found and decryption is possible returns OK;
2941 */
2942 int
2943prepare_crypt_read(fp)
2944 FILE *fp;
2945{
2946 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002947 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2948 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002949
2950 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2951 return FAIL;
2952 method = get_crypt_method((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002953 CRYPT_MAGIC_LEN +
2954 CRYPT_SEED_LEN_MAX +
2955 CRYPT_SALT_LEN_MAX);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002956 if (method < 0 || method != curbuf->b_p_cm)
2957 return FAIL;
2958
2959 if (method == 0)
2960 crypt_init_keys(curbuf->b_p_key);
2961 else
2962 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002963 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002964 int seed_len = crypt_seed_len[method];
2965
Bram Moolenaar80794b12010-06-13 05:20:42 +02002966 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002967 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002968 bf_key_init(curbuf->b_p_key, buffer, salt_len);
2969 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002970 }
2971 return OK;
2972}
2973
2974/*
2975 * Prepare for writing encrypted bytes for buffer "buf".
2976 * Returns a pointer to an allocated header of length "*lenp".
2977 */
2978 char_u *
2979prepare_crypt_write(buf, lenp)
2980 buf_T *buf;
2981 int *lenp;
2982{
2983 char_u *header;
2984 int seed_len = crypt_seed_len[buf->b_p_cm];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002985 int salt_len = crypt_salt_len[buf->b_p_cm];
2986 char_u *salt;
2987 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002988
Bram Moolenaar80794b12010-06-13 05:20:42 +02002989 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2990 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002991 if (header != NULL)
2992 {
2993 use_crypt_method = buf->b_p_cm; /* select pkzip or blowfish */
2994 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
2995 CRYPT_MAGIC_LEN);
2996 if (buf->b_p_cm == 0)
2997 crypt_init_keys(buf->b_p_key);
2998 else
2999 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003000 /* Using blowfish, add salt and seed. */
3001 salt = header + CRYPT_MAGIC_LEN;
3002 seed = salt + salt_len;
3003 sha2_seed(salt, salt_len, seed, seed_len);
3004 bf_key_init(buf->b_p_key, salt, salt_len);
3005 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003006 }
3007 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003008 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003009 return header;
3010}
3011
Bram Moolenaar80794b12010-06-13 05:20:42 +02003012#endif /* FEAT_CRYPT */
3013
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014#ifdef UNIX
3015 static void
3016set_file_time(fname, atime, mtime)
3017 char_u *fname;
3018 time_t atime; /* access time */
3019 time_t mtime; /* modification time */
3020{
3021# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3022 struct utimbuf buf;
3023
3024 buf.actime = atime;
3025 buf.modtime = mtime;
3026 (void)utime((char *)fname, &buf);
3027# else
3028# if defined(HAVE_UTIMES)
3029 struct timeval tvp[2];
3030
3031 tvp[0].tv_sec = atime;
3032 tvp[0].tv_usec = 0;
3033 tvp[1].tv_sec = mtime;
3034 tvp[1].tv_usec = 0;
3035# ifdef NeXT
3036 (void)utimes((char *)fname, tvp);
3037# else
3038 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3039# endif
3040# endif
3041# endif
3042}
3043#endif /* UNIX */
3044
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003045#if defined(VMS) && !defined(MIN)
3046/* Older DECC compiler for VAX doesn't define MIN() */
3047# define MIN(a, b) ((a) < (b) ? (a) : (b))
3048#endif
3049
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003051 * Return TRUE if a file appears to be read-only from the file permissions.
3052 */
3053 int
3054check_file_readonly(fname, perm)
3055 char_u *fname; /* full path to file */
3056 int perm; /* known permissions on file */
3057{
3058#ifndef USE_MCH_ACCESS
3059 int fd = 0;
3060#endif
3061
3062 return (
3063#ifdef USE_MCH_ACCESS
3064# ifdef UNIX
3065 (perm & 0222) == 0 ||
3066# endif
3067 mch_access((char *)fname, W_OK)
3068#else
3069 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3070 ? TRUE : (close(fd), FALSE)
3071#endif
3072 );
3073}
3074
3075
3076/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003077 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 *
3079 * We do our own buffering here because fwrite() is so slow.
3080 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003081 * If "forceit" is true, we don't care for errors when attempting backups.
3082 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003083 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003084 *
3085 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3086 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087 *
3088 * This function must NOT use NameBuff (because it's called by autowrite()).
3089 *
3090 * return FAIL for failure, OK otherwise
3091 */
3092 int
3093buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3094 reset_changed, filtering)
3095 buf_T *buf;
3096 char_u *fname;
3097 char_u *sfname;
3098 linenr_T start, end;
3099 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3100 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003101 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 int forceit;
3103 int reset_changed;
3104 int filtering;
3105{
3106 int fd;
3107 char_u *backup = NULL;
3108 int backup_copy = FALSE; /* copy the original file? */
3109 int dobackup;
3110 char_u *ffname;
3111 char_u *wfname = NULL; /* name of file to write to */
3112 char_u *s;
3113 char_u *ptr;
3114 char_u c;
3115 int len;
3116 linenr_T lnum;
3117 long nchars;
3118 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003119 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 char_u *errnum = NULL;
3121 char_u *buffer;
3122 char_u smallbuf[SMBUFSIZE];
3123 char_u *backup_ext;
3124 int bufsize;
3125 long perm; /* file permissions */
3126 int retval = OK;
3127 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3128 int msg_save = msg_scroll;
3129 int overwriting; /* TRUE if writing over original */
3130 int no_eol = FALSE; /* no end-of-line written */
3131 int device = FALSE; /* writing to a device */
3132 struct stat st_old;
3133 int prev_got_int = got_int;
3134 int file_readonly = FALSE; /* overwritten file is read-only */
3135 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3136#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3137 int made_writable = FALSE; /* 'w' bit has been set */
3138#endif
3139 /* writing everything */
3140 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3141#ifdef FEAT_AUTOCMD
3142 linenr_T old_line_count = buf->b_ml.ml_line_count;
3143#endif
3144 int attr;
3145 int fileformat;
3146 int write_bin;
3147 struct bw_info write_info; /* info for buf_write_bytes() */
3148#ifdef FEAT_MBYTE
3149 int converted = FALSE;
3150 int notconverted = FALSE;
3151 char_u *fenc; /* effective 'fileencoding' */
3152 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3153#endif
3154#ifdef HAS_BW_FLAGS
3155 int wb_flags = 0;
3156#endif
3157#ifdef HAVE_ACL
3158 vim_acl_T acl = NULL; /* ACL copied from original file to
3159 backup or new file */
3160#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003161#ifdef FEAT_PERSISTENT_UNDO
3162 int write_undo_file = FALSE;
3163 context_sha256_T sha_ctx;
3164#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165
3166 if (fname == NULL || *fname == NUL) /* safety check */
3167 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003168 if (buf->b_ml.ml_mfp == NULL)
3169 {
3170 /* This can happen during startup when there is a stray "w" in the
3171 * vimrc file. */
3172 EMSG(_(e_emptybuf));
3173 return FAIL;
3174 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175
3176 /*
3177 * Disallow writing from .exrc and .vimrc in current directory for
3178 * security reasons.
3179 */
3180 if (check_secure())
3181 return FAIL;
3182
3183 /* Avoid a crash for a long name. */
3184 if (STRLEN(fname) >= MAXPATHL)
3185 {
3186 EMSG(_(e_longname));
3187 return FAIL;
3188 }
3189
3190#ifdef FEAT_MBYTE
3191 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3192 write_info.bw_conv_buf = NULL;
3193 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003194 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 write_info.bw_restlen = 0;
3196# ifdef USE_ICONV
3197 write_info.bw_iconv_fd = (iconv_t)-1;
3198# endif
3199#endif
3200
Bram Moolenaardf177f62005-02-22 08:39:57 +00003201 /* After writing a file changedtick changes but we don't want to display
3202 * the line. */
3203 ex_no_reprint = TRUE;
3204
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205 /*
3206 * If there is no file name yet, use the one for the written file.
3207 * BF_NOTEDITED is set to reflect this (in case the write fails).
3208 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003209 * Don't do this when appending.
3210 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003212 if (buf->b_ffname == NULL
3213 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 && whole
3215 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003216#ifdef FEAT_QUICKFIX
3217 && !bt_nofile(buf)
3218#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003220 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3222 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003223 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003225 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 }
3227
3228 if (sfname == NULL)
3229 sfname = fname;
3230 /*
3231 * For Unix: Use the short file name whenever possible.
3232 * Avoids problems with networks and when directory names are changed.
3233 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3234 * another directory, which we don't detect
3235 */
3236 ffname = fname; /* remember full fname */
3237#ifdef UNIX
3238 fname = sfname;
3239#endif
3240
3241 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3242 overwriting = TRUE;
3243 else
3244 overwriting = FALSE;
3245
3246 if (exiting)
3247 settmode(TMODE_COOK); /* when exiting allow typahead now */
3248
3249 ++no_wait_return; /* don't wait for return yet */
3250
3251 /*
3252 * Set '[ and '] marks to the lines to be written.
3253 */
3254 buf->b_op_start.lnum = start;
3255 buf->b_op_start.col = 0;
3256 buf->b_op_end.lnum = end;
3257 buf->b_op_end.col = 0;
3258
3259#ifdef FEAT_AUTOCMD
3260 {
3261 aco_save_T aco;
3262 int buf_ffname = FALSE;
3263 int buf_sfname = FALSE;
3264 int buf_fname_f = FALSE;
3265 int buf_fname_s = FALSE;
3266 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003267 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003268 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270 /*
3271 * Apply PRE aucocommands.
3272 * Set curbuf to the buffer to be written.
3273 * Careful: The autocommands may call buf_write() recursively!
3274 */
3275 if (ffname == buf->b_ffname)
3276 buf_ffname = TRUE;
3277 if (sfname == buf->b_sfname)
3278 buf_sfname = TRUE;
3279 if (fname == buf->b_ffname)
3280 buf_fname_f = TRUE;
3281 if (fname == buf->b_sfname)
3282 buf_fname_s = TRUE;
3283
3284 /* set curwin/curbuf to buf and save a few things */
3285 aucmd_prepbuf(&aco, buf);
3286
3287 if (append)
3288 {
3289 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3290 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003291 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003292#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003293 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003294 nofile_err = TRUE;
3295 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003296#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003297 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003299 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300 }
3301 else if (filtering)
3302 {
3303 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3304 NULL, sfname, FALSE, curbuf, eap);
3305 }
3306 else if (reset_changed && whole)
3307 {
3308 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3309 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003310 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003311#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003312 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003313 nofile_err = TRUE;
3314 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003315#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003316 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003319 }
3320 else
3321 {
3322 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3323 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003324 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003325#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003326 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003327 nofile_err = TRUE;
3328 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003329#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003330 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003332 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333 }
3334
3335 /* restore curwin/curbuf and a few other things */
3336 aucmd_restbuf(&aco);
3337
3338 /*
3339 * In three situations we return here and don't write the file:
3340 * 1. the autocommands deleted or unloaded the buffer.
3341 * 2. The autocommands abort script processing.
3342 * 3. If one of the "Cmd" autocommands was executed.
3343 */
3344 if (!buf_valid(buf))
3345 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003346 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003347 || did_cmd || nofile_err
3348#ifdef FEAT_EVAL
3349 || aborting()
3350#endif
3351 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 {
3353 --no_wait_return;
3354 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003355 if (nofile_err)
3356 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3357
Bram Moolenaar1e015462005-09-25 22:16:38 +00003358 if (nofile_err
3359#ifdef FEAT_EVAL
3360 || aborting()
3361#endif
3362 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 /* An aborting error, interrupt or exception in the
3364 * autocommands. */
3365 return FAIL;
3366 if (did_cmd)
3367 {
3368 if (buf == NULL)
3369 /* The buffer was deleted. We assume it was written
3370 * (can't retry anyway). */
3371 return OK;
3372 if (overwriting)
3373 {
3374 /* Assume the buffer was written, update the timestamp. */
3375 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003376 if (append)
3377 buf->b_flags &= ~BF_NEW;
3378 else
3379 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003381 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003382 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383 /* Buffer still changed, the autocommands didn't work
3384 * properly. */
3385 return FAIL;
3386 return OK;
3387 }
3388#ifdef FEAT_EVAL
3389 if (!aborting())
3390#endif
3391 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3392 return FAIL;
3393 }
3394
3395 /*
3396 * The autocommands may have changed the number of lines in the file.
3397 * When writing the whole file, adjust the end.
3398 * When writing part of the file, assume that the autocommands only
3399 * changed the number of lines that are to be written (tricky!).
3400 */
3401 if (buf->b_ml.ml_line_count != old_line_count)
3402 {
3403 if (whole) /* write all */
3404 end = buf->b_ml.ml_line_count;
3405 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3406 end += buf->b_ml.ml_line_count - old_line_count;
3407 else /* less lines */
3408 {
3409 end -= old_line_count - buf->b_ml.ml_line_count;
3410 if (end < start)
3411 {
3412 --no_wait_return;
3413 msg_scroll = msg_save;
3414 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3415 return FAIL;
3416 }
3417 }
3418 }
3419
3420 /*
3421 * The autocommands may have changed the name of the buffer, which may
3422 * be kept in fname, ffname and sfname.
3423 */
3424 if (buf_ffname)
3425 ffname = buf->b_ffname;
3426 if (buf_sfname)
3427 sfname = buf->b_sfname;
3428 if (buf_fname_f)
3429 fname = buf->b_ffname;
3430 if (buf_fname_s)
3431 fname = buf->b_sfname;
3432 }
3433#endif
3434
3435#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003436 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 {
3438 if (whole)
3439 {
3440 /*
3441 * b_changed can be 0 after an undo, but we still need to write
3442 * the buffer to NetBeans.
3443 */
3444 if (buf->b_changed || isNetbeansModified(buf))
3445 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003446 --no_wait_return; /* may wait for return now */
3447 msg_scroll = msg_save;
3448 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449 return retval;
3450 }
3451 else
3452 {
3453 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003454 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455 buffer = NULL;
3456 goto fail;
3457 }
3458 }
3459 else
3460 {
3461 errnum = (char_u *)"E657: ";
3462 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3463 buffer = NULL;
3464 goto fail;
3465 }
3466 }
3467#endif
3468
3469 if (shortmess(SHM_OVER) && !exiting)
3470 msg_scroll = FALSE; /* overwrite previous file message */
3471 else
3472 msg_scroll = TRUE; /* don't overwrite previous file message */
3473 if (!filtering)
3474 filemess(buf,
3475#ifndef UNIX
3476 sfname,
3477#else
3478 fname,
3479#endif
3480 (char_u *)"", 0); /* show that we are busy */
3481 msg_scroll = FALSE; /* always overwrite the file message now */
3482
3483 buffer = alloc(BUFSIZE);
3484 if (buffer == NULL) /* can't allocate big buffer, use small
3485 * one (to be able to write when out of
3486 * memory) */
3487 {
3488 buffer = smallbuf;
3489 bufsize = SMBUFSIZE;
3490 }
3491 else
3492 bufsize = BUFSIZE;
3493
3494 /*
3495 * Get information about original file (if there is one).
3496 */
3497#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003498 st_old.st_dev = 0;
3499 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 perm = -1;
3501 if (mch_stat((char *)fname, &st_old) < 0)
3502 newfile = TRUE;
3503 else
3504 {
3505 perm = st_old.st_mode;
3506 if (!S_ISREG(st_old.st_mode)) /* not a file */
3507 {
3508 if (S_ISDIR(st_old.st_mode))
3509 {
3510 errnum = (char_u *)"E502: ";
3511 errmsg = (char_u *)_("is a directory");
3512 goto fail;
3513 }
3514 if (mch_nodetype(fname) != NODE_WRITABLE)
3515 {
3516 errnum = (char_u *)"E503: ";
3517 errmsg = (char_u *)_("is not a file or writable device");
3518 goto fail;
3519 }
3520 /* It's a device of some kind (or a fifo) which we can write to
3521 * but for which we can't make a backup. */
3522 device = TRUE;
3523 newfile = TRUE;
3524 perm = -1;
3525 }
3526 }
3527#else /* !UNIX */
3528 /*
3529 * Check for a writable device name.
3530 */
3531 c = mch_nodetype(fname);
3532 if (c == NODE_OTHER)
3533 {
3534 errnum = (char_u *)"E503: ";
3535 errmsg = (char_u *)_("is not a file or writable device");
3536 goto fail;
3537 }
3538 if (c == NODE_WRITABLE)
3539 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003540# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3541 /* MS-Windows allows opening a device, but we will probably get stuck
3542 * trying to write to it. */
3543 if (!p_odev)
3544 {
3545 errnum = (char_u *)"E796: ";
3546 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3547 goto fail;
3548 }
3549# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 device = TRUE;
3551 newfile = TRUE;
3552 perm = -1;
3553 }
3554 else
3555 {
3556 perm = mch_getperm(fname);
3557 if (perm < 0)
3558 newfile = TRUE;
3559 else if (mch_isdir(fname))
3560 {
3561 errnum = (char_u *)"E502: ";
3562 errmsg = (char_u *)_("is a directory");
3563 goto fail;
3564 }
3565 if (overwriting)
3566 (void)mch_stat((char *)fname, &st_old);
3567 }
3568#endif /* !UNIX */
3569
3570 if (!device && !newfile)
3571 {
3572 /*
3573 * Check if the file is really writable (when renaming the file to
3574 * make a backup we won't discover it later).
3575 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003576 file_readonly = check_file_readonly(fname, (int)perm);
3577
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 if (!forceit && file_readonly)
3579 {
3580 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3581 {
3582 errnum = (char_u *)"E504: ";
3583 errmsg = (char_u *)_(err_readonly);
3584 }
3585 else
3586 {
3587 errnum = (char_u *)"E505: ";
3588 errmsg = (char_u *)_("is read-only (add ! to override)");
3589 }
3590 goto fail;
3591 }
3592
3593 /*
3594 * Check if the timestamp hasn't changed since reading the file.
3595 */
3596 if (overwriting)
3597 {
3598 retval = check_mtime(buf, &st_old);
3599 if (retval == FAIL)
3600 goto fail;
3601 }
3602 }
3603
3604#ifdef HAVE_ACL
3605 /*
3606 * For systems that support ACL: get the ACL from the original file.
3607 */
3608 if (!newfile)
3609 acl = mch_get_acl(fname);
3610#endif
3611
3612 /*
3613 * If 'backupskip' is not empty, don't make a backup for some files.
3614 */
3615 dobackup = (p_wb || p_bk || *p_pm != NUL);
3616#ifdef FEAT_WILDIGN
3617 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3618 dobackup = FALSE;
3619#endif
3620
3621 /*
3622 * Save the value of got_int and reset it. We don't want a previous
3623 * interruption cancel writing, only hitting CTRL-C while writing should
3624 * abort it.
3625 */
3626 prev_got_int = got_int;
3627 got_int = FALSE;
3628
3629 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3630 buf->b_saving = TRUE;
3631
3632 /*
3633 * If we are not appending or filtering, the file exists, and the
3634 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3635 * When 'patchmode' is set also make a backup when appending.
3636 *
3637 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3638 * off. This helps when editing large files on almost-full disks.
3639 */
3640 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3641 {
3642#if defined(UNIX) || defined(WIN32)
3643 struct stat st;
3644#endif
3645
3646 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3647 backup_copy = TRUE;
3648#if defined(UNIX) || defined(WIN32)
3649 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3650 {
3651 int i;
3652
3653# ifdef UNIX
3654 /*
3655 * Don't rename the file when:
3656 * - it's a hard link
3657 * - it's a symbolic link
3658 * - we don't have write permission in the directory
3659 * - we can't set the owner/group of the new file
3660 */
3661 if (st_old.st_nlink > 1
3662 || mch_lstat((char *)fname, &st) < 0
3663 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003664 || st.st_ino != st_old.st_ino
3665# ifndef HAVE_FCHOWN
3666 || st.st_uid != st_old.st_uid
3667 || st.st_gid != st_old.st_gid
3668# endif
3669 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 backup_copy = TRUE;
3671 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003672# else
3673# ifdef WIN32
3674 /* On NTFS file systems hard links are possible. */
3675 if (mch_is_linked(fname))
3676 backup_copy = TRUE;
3677 else
3678# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679# endif
3680 {
3681 /*
3682 * Check if we can create a file and set the owner/group to
3683 * the ones from the original file.
3684 * First find a file name that doesn't exist yet (use some
3685 * arbitrary numbers).
3686 */
3687 STRCPY(IObuff, fname);
3688 for (i = 4913; ; i += 123)
3689 {
3690 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003691 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 break;
3693 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003694 fd = mch_open((char *)IObuff,
3695 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 if (fd < 0) /* can't write in directory */
3697 backup_copy = TRUE;
3698 else
3699 {
3700# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003701# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003702 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003703# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 if (mch_stat((char *)IObuff, &st) < 0
3705 || st.st_uid != st_old.st_uid
3706 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003707 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 backup_copy = TRUE;
3709# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003710 /* Close the file before removing it, on MS-Windows we
3711 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003712 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003713 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714 }
3715 }
3716 }
3717
3718# ifdef UNIX
3719 /*
3720 * Break symlinks and/or hardlinks if we've been asked to.
3721 */
3722 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3723 {
3724 int lstat_res;
3725
3726 lstat_res = mch_lstat((char *)fname, &st);
3727
3728 /* Symlinks. */
3729 if ((bkc_flags & BKC_BREAKSYMLINK)
3730 && lstat_res == 0
3731 && st.st_ino != st_old.st_ino)
3732 backup_copy = FALSE;
3733
3734 /* Hardlinks. */
3735 if ((bkc_flags & BKC_BREAKHARDLINK)
3736 && st_old.st_nlink > 1
3737 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3738 backup_copy = FALSE;
3739 }
3740#endif
3741
3742#endif
3743
3744 /* make sure we have a valid backup extension to use */
3745 if (*p_bex == NUL)
3746 {
3747#ifdef RISCOS
3748 backup_ext = (char_u *)"/bak";
3749#else
3750 backup_ext = (char_u *)".bak";
3751#endif
3752 }
3753 else
3754 backup_ext = p_bex;
3755
3756 if (backup_copy
3757 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3758 {
3759 int bfd;
3760 char_u *copybuf, *wp;
3761 int some_error = FALSE;
3762 struct stat st_new;
3763 char_u *dirp;
3764 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003765#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 int did_set_shortname;
3767#endif
3768
3769 copybuf = alloc(BUFSIZE + 1);
3770 if (copybuf == NULL)
3771 {
3772 some_error = TRUE; /* out of memory */
3773 goto nobackup;
3774 }
3775
3776 /*
3777 * Try to make the backup in each directory in the 'bdir' option.
3778 *
3779 * Unix semantics has it, that we may have a writable file,
3780 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3781 * - the directory is not writable,
3782 * - the file may be a symbolic link,
3783 * - the file may belong to another user/group, etc.
3784 *
3785 * For these reasons, the existing writable file must be truncated
3786 * and reused. Creation of a backup COPY will be attempted.
3787 */
3788 dirp = p_bdir;
3789 while (*dirp)
3790 {
3791#ifdef UNIX
3792 st_new.st_ino = 0;
3793 st_new.st_dev = 0;
3794 st_new.st_gid = 0;
3795#endif
3796
3797 /*
3798 * Isolate one directory name, using an entry in 'bdir'.
3799 */
3800 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3801 rootname = get_file_in_dir(fname, copybuf);
3802 if (rootname == NULL)
3803 {
3804 some_error = TRUE; /* out of memory */
3805 goto nobackup;
3806 }
3807
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003808#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 did_set_shortname = FALSE;
3810#endif
3811
3812 /*
3813 * May try twice if 'shortname' not set.
3814 */
3815 for (;;)
3816 {
3817 /*
3818 * Make backup file name.
3819 */
3820 backup = buf_modname(
3821#ifdef SHORT_FNAME
3822 TRUE,
3823#else
3824 (buf->b_p_sn || buf->b_shortname),
3825#endif
3826 rootname, backup_ext, FALSE);
3827 if (backup == NULL)
3828 {
3829 vim_free(rootname);
3830 some_error = TRUE; /* out of memory */
3831 goto nobackup;
3832 }
3833
3834 /*
3835 * Check if backup file already exists.
3836 */
3837 if (mch_stat((char *)backup, &st_new) >= 0)
3838 {
3839#ifdef UNIX
3840 /*
3841 * Check if backup file is same as original file.
3842 * May happen when modname() gave the same file back.
3843 * E.g. silly link, or file name-length reached.
3844 * If we don't check here, we either ruin the file
3845 * when copying or erase it after writing. jw.
3846 */
3847 if (st_new.st_dev == st_old.st_dev
3848 && st_new.st_ino == st_old.st_ino)
3849 {
3850 vim_free(backup);
3851 backup = NULL; /* no backup file to delete */
3852# ifndef SHORT_FNAME
3853 /*
3854 * may try again with 'shortname' set
3855 */
3856 if (!(buf->b_shortname || buf->b_p_sn))
3857 {
3858 buf->b_shortname = TRUE;
3859 did_set_shortname = TRUE;
3860 continue;
3861 }
3862 /* setting shortname didn't help */
3863 if (did_set_shortname)
3864 buf->b_shortname = FALSE;
3865# endif
3866 break;
3867 }
3868#endif
3869
3870 /*
3871 * If we are not going to keep the backup file, don't
3872 * delete an existing one, try to use another name.
3873 * Change one character, just before the extension.
3874 */
3875 if (!p_bk)
3876 {
3877 wp = backup + STRLEN(backup) - 1
3878 - STRLEN(backup_ext);
3879 if (wp < backup) /* empty file name ??? */
3880 wp = backup;
3881 *wp = 'z';
3882 while (*wp > 'a'
3883 && mch_stat((char *)backup, &st_new) >= 0)
3884 --*wp;
3885 /* They all exist??? Must be something wrong. */
3886 if (*wp == 'a')
3887 {
3888 vim_free(backup);
3889 backup = NULL;
3890 }
3891 }
3892 }
3893 break;
3894 }
3895 vim_free(rootname);
3896
3897 /*
3898 * Try to create the backup file
3899 */
3900 if (backup != NULL)
3901 {
3902 /* remove old backup, if present */
3903 mch_remove(backup);
3904 /* Open with O_EXCL to avoid the file being created while
3905 * we were sleeping (symlink hacker attack?) */
3906 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003907 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3908 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 if (bfd < 0)
3910 {
3911 vim_free(backup);
3912 backup = NULL;
3913 }
3914 else
3915 {
3916 /* set file protection same as original file, but
3917 * strip s-bit */
3918 (void)mch_setperm(backup, perm & 0777);
3919
3920#ifdef UNIX
3921 /*
3922 * Try to set the group of the backup same as the
3923 * original file. If this fails, set the protection
3924 * bits for the group same as the protection bits for
3925 * others.
3926 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003927 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003929 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003930# endif
3931 )
3932 mch_setperm(backup,
3933 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003934# ifdef HAVE_SELINUX
3935 mch_copy_sec(fname, backup);
3936# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937#endif
3938
3939 /*
3940 * copy the file.
3941 */
3942 write_info.bw_fd = bfd;
3943 write_info.bw_buf = copybuf;
3944#ifdef HAS_BW_FLAGS
3945 write_info.bw_flags = FIO_NOCONVERT;
3946#endif
3947 while ((write_info.bw_len = vim_read(fd, copybuf,
3948 BUFSIZE)) > 0)
3949 {
3950 if (buf_write_bytes(&write_info) == FAIL)
3951 {
3952 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3953 break;
3954 }
3955 ui_breakcheck();
3956 if (got_int)
3957 {
3958 errmsg = (char_u *)_(e_interr);
3959 break;
3960 }
3961 }
3962
3963 if (close(bfd) < 0 && errmsg == NULL)
3964 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3965 if (write_info.bw_len < 0)
3966 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3967#ifdef UNIX
3968 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3969#endif
3970#ifdef HAVE_ACL
3971 mch_set_acl(backup, acl);
3972#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003973#ifdef HAVE_SELINUX
3974 mch_copy_sec(fname, backup);
3975#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976 break;
3977 }
3978 }
3979 }
3980 nobackup:
3981 close(fd); /* ignore errors for closing read file */
3982 vim_free(copybuf);
3983
3984 if (backup == NULL && errmsg == NULL)
3985 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3986 /* ignore errors when forceit is TRUE */
3987 if ((some_error || errmsg != NULL) && !forceit)
3988 {
3989 retval = FAIL;
3990 goto fail;
3991 }
3992 errmsg = NULL;
3993 }
3994 else
3995 {
3996 char_u *dirp;
3997 char_u *p;
3998 char_u *rootname;
3999
4000 /*
4001 * Make a backup by renaming the original file.
4002 */
4003 /*
4004 * If 'cpoptions' includes the "W" flag, we don't want to
4005 * overwrite a read-only file. But rename may be possible
4006 * anyway, thus we need an extra check here.
4007 */
4008 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4009 {
4010 errnum = (char_u *)"E504: ";
4011 errmsg = (char_u *)_(err_readonly);
4012 goto fail;
4013 }
4014
4015 /*
4016 *
4017 * Form the backup file name - change path/fo.o.h to
4018 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4019 * that works is used.
4020 */
4021 dirp = p_bdir;
4022 while (*dirp)
4023 {
4024 /*
4025 * Isolate one directory name and make the backup file name.
4026 */
4027 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4028 rootname = get_file_in_dir(fname, IObuff);
4029 if (rootname == NULL)
4030 backup = NULL;
4031 else
4032 {
4033 backup = buf_modname(
4034#ifdef SHORT_FNAME
4035 TRUE,
4036#else
4037 (buf->b_p_sn || buf->b_shortname),
4038#endif
4039 rootname, backup_ext, FALSE);
4040 vim_free(rootname);
4041 }
4042
4043 if (backup != NULL)
4044 {
4045 /*
4046 * If we are not going to keep the backup file, don't
4047 * delete an existing one, try to use another name.
4048 * Change one character, just before the extension.
4049 */
4050 if (!p_bk && mch_getperm(backup) >= 0)
4051 {
4052 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4053 if (p < backup) /* empty file name ??? */
4054 p = backup;
4055 *p = 'z';
4056 while (*p > 'a' && mch_getperm(backup) >= 0)
4057 --*p;
4058 /* They all exist??? Must be something wrong! */
4059 if (*p == 'a')
4060 {
4061 vim_free(backup);
4062 backup = NULL;
4063 }
4064 }
4065 }
4066 if (backup != NULL)
4067 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004069 * Delete any existing backup and move the current version
4070 * to the backup. For safety, we don't remove the backup
4071 * until the write has finished successfully. And if the
4072 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 */
4074 /*
4075 * If the renaming of the original file to the backup file
4076 * works, quit here.
4077 */
4078 if (vim_rename(fname, backup) == 0)
4079 break;
4080
4081 vim_free(backup); /* don't do the rename below */
4082 backup = NULL;
4083 }
4084 }
4085 if (backup == NULL && !forceit)
4086 {
4087 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4088 goto fail;
4089 }
4090 }
4091 }
4092
4093#if defined(UNIX) && !defined(ARCHIE)
4094 /* When using ":w!" and the file was read-only: make it writable */
4095 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4096 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4097 {
4098 perm |= 0200;
4099 (void)mch_setperm(fname, perm);
4100 made_writable = TRUE;
4101 }
4102#endif
4103
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004104 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004105 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4106 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 {
4108 buf->b_p_ro = FALSE;
4109#ifdef FEAT_TITLE
4110 need_maketitle = TRUE; /* set window title later */
4111#endif
4112#ifdef FEAT_WINDOWS
4113 status_redraw_all(); /* redraw status lines later */
4114#endif
4115 }
4116
4117 if (end > buf->b_ml.ml_line_count)
4118 end = buf->b_ml.ml_line_count;
4119 if (buf->b_ml.ml_flags & ML_EMPTY)
4120 start = end + 1;
4121
4122 /*
4123 * If the original file is being overwritten, there is a small chance that
4124 * we crash in the middle of writing. Therefore the file is preserved now.
4125 * This makes all block numbers positive so that recovery does not need
4126 * the original file.
4127 * Don't do this if there is a backup file and we are exiting.
4128 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004129 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 && !(exiting && backup != NULL))
4131 {
4132 ml_preserve(buf, FALSE);
4133 if (got_int)
4134 {
4135 errmsg = (char_u *)_(e_interr);
4136 goto restore_backup;
4137 }
4138 }
4139
4140#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4141 /*
4142 * Before risking to lose the original file verify if there's
4143 * a resource fork to preserve, and if cannot be done warn
4144 * the users. This happens when overwriting without backups.
4145 */
4146 if (backup == NULL && overwriting && !append)
4147 if (mch_has_resource_fork(fname))
4148 {
4149 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4150 goto restore_backup;
4151 }
4152#endif
4153
4154#ifdef VMS
4155 vms_remove_version(fname); /* remove version */
4156#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004157 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 * multi-byte conversion. */
4159 wfname = fname;
4160
4161#ifdef FEAT_MBYTE
4162 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4163 if (eap != NULL && eap->force_enc != 0)
4164 {
4165 fenc = eap->cmd + eap->force_enc;
4166 fenc = enc_canonize(fenc);
4167 fenc_tofree = fenc;
4168 }
4169 else
4170 fenc = buf->b_p_fenc;
4171
4172 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004173 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004175 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176
4177 /*
4178 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4179 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4180 * Prepare the flags for it and allocate bw_conv_buf when needed.
4181 */
4182 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4183 {
4184 wb_flags = get_fio_flags(fenc);
4185 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4186 {
4187 /* Need to allocate a buffer to translate into. */
4188 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4189 write_info.bw_conv_buflen = bufsize * 2;
4190 else /* FIO_UCS4 */
4191 write_info.bw_conv_buflen = bufsize * 4;
4192 write_info.bw_conv_buf
4193 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4194 if (write_info.bw_conv_buf == NULL)
4195 end = 0;
4196 }
4197 }
4198
4199# ifdef WIN3264
4200 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4201 {
4202 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4203 write_info.bw_conv_buflen = bufsize * 4;
4204 write_info.bw_conv_buf
4205 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4206 if (write_info.bw_conv_buf == NULL)
4207 end = 0;
4208 }
4209# endif
4210
4211# ifdef MACOS_X
4212 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4213 {
4214 write_info.bw_conv_buflen = bufsize * 3;
4215 write_info.bw_conv_buf
4216 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4217 if (write_info.bw_conv_buf == NULL)
4218 end = 0;
4219 }
4220# endif
4221
4222# if defined(FEAT_EVAL) || defined(USE_ICONV)
4223 if (converted && wb_flags == 0)
4224 {
4225# ifdef USE_ICONV
4226 /*
4227 * Use iconv() conversion when conversion is needed and it's not done
4228 * internally.
4229 */
4230 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4231 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4232 if (write_info.bw_iconv_fd != (iconv_t)-1)
4233 {
4234 /* We're going to use iconv(), allocate a buffer to convert in. */
4235 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4236 write_info.bw_conv_buf
4237 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4238 if (write_info.bw_conv_buf == NULL)
4239 end = 0;
4240 write_info.bw_first = TRUE;
4241 }
4242# ifdef FEAT_EVAL
4243 else
4244# endif
4245# endif
4246
4247# ifdef FEAT_EVAL
4248 /*
4249 * When the file needs to be converted with 'charconvert' after
4250 * writing, write to a temp file instead and let the conversion
4251 * overwrite the original file.
4252 */
4253 if (*p_ccv != NUL)
4254 {
4255 wfname = vim_tempname('w');
4256 if (wfname == NULL) /* Can't write without a tempfile! */
4257 {
4258 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4259 goto restore_backup;
4260 }
4261 }
4262# endif
4263 }
4264# endif
4265 if (converted && wb_flags == 0
4266# ifdef USE_ICONV
4267 && write_info.bw_iconv_fd == (iconv_t)-1
4268# endif
4269# ifdef FEAT_EVAL
4270 && wfname == fname
4271# endif
4272 )
4273 {
4274 if (!forceit)
4275 {
4276 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4277 goto restore_backup;
4278 }
4279 notconverted = TRUE;
4280 }
4281#endif
4282
4283 /*
4284 * Open the file "wfname" for writing.
4285 * We may try to open the file twice: If we can't write to the
4286 * file and forceit is TRUE we delete the existing file and try to create
4287 * a new one. If this still fails we may have lost the original file!
4288 * (this may happen when the user reached his quotum for number of files).
4289 * Appending will fail if the file does not exist and forceit is FALSE.
4290 */
4291 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4292 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4293 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004294 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 {
4296 /*
4297 * A forced write will try to create a new file if the old one is
4298 * still readonly. This may also happen when the directory is
4299 * read-only. In that case the mch_remove() will fail.
4300 */
4301 if (errmsg == NULL)
4302 {
4303#ifdef UNIX
4304 struct stat st;
4305
4306 /* Don't delete the file when it's a hard or symbolic link. */
4307 if ((!newfile && st_old.st_nlink > 1)
4308 || (mch_lstat((char *)fname, &st) == 0
4309 && (st.st_dev != st_old.st_dev
4310 || st.st_ino != st_old.st_ino)))
4311 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4312 else
4313#endif
4314 {
4315 errmsg = (char_u *)_("E212: Can't open file for writing");
4316 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4317 && perm >= 0)
4318 {
4319#ifdef UNIX
4320 /* we write to the file, thus it should be marked
4321 writable after all */
4322 if (!(perm & 0200))
4323 made_writable = TRUE;
4324 perm |= 0200;
4325 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4326 perm &= 0777;
4327#endif
4328 if (!append) /* don't remove when appending */
4329 mch_remove(wfname);
4330 continue;
4331 }
4332 }
4333 }
4334
4335restore_backup:
4336 {
4337 struct stat st;
4338
4339 /*
4340 * If we failed to open the file, we don't need a backup. Throw it
4341 * away. If we moved or removed the original file try to put the
4342 * backup in its place.
4343 */
4344 if (backup != NULL && wfname == fname)
4345 {
4346 if (backup_copy)
4347 {
4348 /*
4349 * There is a small chance that we removed the original,
4350 * try to move the copy in its place.
4351 * This may not work if the vim_rename() fails.
4352 * In that case we leave the copy around.
4353 */
4354 /* If file does not exist, put the copy in its place */
4355 if (mch_stat((char *)fname, &st) < 0)
4356 vim_rename(backup, fname);
4357 /* if original file does exist throw away the copy */
4358 if (mch_stat((char *)fname, &st) >= 0)
4359 mch_remove(backup);
4360 }
4361 else
4362 {
4363 /* try to put the original file back */
4364 vim_rename(backup, fname);
4365 }
4366 }
4367
4368 /* if original file no longer exists give an extra warning */
4369 if (!newfile && mch_stat((char *)fname, &st) < 0)
4370 end = 0;
4371 }
4372
4373#ifdef FEAT_MBYTE
4374 if (wfname != fname)
4375 vim_free(wfname);
4376#endif
4377 goto fail;
4378 }
4379 errmsg = NULL;
4380
4381#if defined(MACOS_CLASSIC) || defined(WIN3264)
4382 /* TODO: Is it need for MACOS_X? (Dany) */
4383 /*
4384 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004385 * This is done in order to preserve the resource fork and the
4386 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387 */
4388 if (backup != NULL && overwriting && !append)
4389 {
4390 if (backup_copy)
4391 (void)mch_copy_file_attribute(wfname, backup);
4392 else
4393 (void)mch_copy_file_attribute(backup, wfname);
4394 }
4395
4396 if (!overwriting && !append)
4397 {
4398 if (buf->b_ffname != NULL)
4399 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004400 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 }
4402#endif
4403
4404 write_info.bw_fd = fd;
4405
4406#ifdef FEAT_CRYPT
4407 if (*buf->b_p_key && !filtering)
4408 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004409 char_u *header;
4410 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004411
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004412 header = prepare_crypt_write(buf, &header_len);
4413 if (header == NULL)
4414 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004415 else
4416 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004417 /* Write magic number, so that Vim knows that this file is
4418 * encrypted when reading it again. This also undergoes utf-8 to
4419 * ucs-2/4 conversion when needed. */
4420 write_info.bw_buf = header;
4421 write_info.bw_len = header_len;
4422 write_info.bw_flags = FIO_NOCONVERT;
4423 if (buf_write_bytes(&write_info) == FAIL)
4424 end = 0;
4425 wb_flags |= FIO_ENCRYPTED;
4426 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428 }
4429#endif
4430
4431 write_info.bw_buf = buffer;
4432 nchars = 0;
4433
4434 /* use "++bin", "++nobin" or 'binary' */
4435 if (eap != NULL && eap->force_bin != 0)
4436 write_bin = (eap->force_bin == FORCE_BIN);
4437 else
4438 write_bin = buf->b_p_bin;
4439
4440#ifdef FEAT_MBYTE
4441 /*
4442 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004443 * Skip it when appending and the file already existed, the BOM only makes
4444 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004446 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 {
4448 write_info.bw_len = make_bom(buffer, fenc);
4449 if (write_info.bw_len > 0)
4450 {
4451 /* don't convert, do encryption */
4452 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4453 if (buf_write_bytes(&write_info) == FAIL)
4454 end = 0;
4455 else
4456 nchars += write_info.bw_len;
4457 }
4458 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004459 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460#endif
4461
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004462#ifdef FEAT_PERSISTENT_UNDO
4463 write_undo_file = (buf->b_p_udf && overwriting && !append
4464 && !filtering && reset_changed);
4465 if (write_undo_file)
4466 /* Prepare for computing the hash value of the text. */
4467 sha256_start(&sha_ctx);
4468#endif
4469
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 write_info.bw_len = bufsize;
4471#ifdef HAS_BW_FLAGS
4472 write_info.bw_flags = wb_flags;
4473#endif
4474 fileformat = get_fileformat_force(buf, eap);
4475 s = buffer;
4476 len = 0;
4477 for (lnum = start; lnum <= end; ++lnum)
4478 {
4479 /*
4480 * The next while loop is done once for each character written.
4481 * Keep it fast!
4482 */
4483 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004484#ifdef FEAT_PERSISTENT_UNDO
4485 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004486 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488 while ((c = *++ptr) != NUL)
4489 {
4490 if (c == NL)
4491 *s = NUL; /* replace newlines with NULs */
4492 else if (c == CAR && fileformat == EOL_MAC)
4493 *s = NL; /* Mac: replace CRs with NLs */
4494 else
4495 *s = c;
4496 ++s;
4497 if (++len != bufsize)
4498 continue;
4499 if (buf_write_bytes(&write_info) == FAIL)
4500 {
4501 end = 0; /* write error: break loop */
4502 break;
4503 }
4504 nchars += bufsize;
4505 s = buffer;
4506 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004507#ifdef FEAT_MBYTE
4508 write_info.bw_start_lnum = lnum;
4509#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004510 }
4511 /* write failed or last line has no EOL: stop here */
4512 if (end == 0
4513 || (lnum == end
4514 && write_bin
4515 && (lnum == write_no_eol_lnum
4516 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4517 {
4518 ++lnum; /* written the line, count it */
4519 no_eol = TRUE;
4520 break;
4521 }
4522 if (fileformat == EOL_UNIX)
4523 *s++ = NL;
4524 else
4525 {
4526 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4527 if (fileformat == EOL_DOS) /* write CR-NL */
4528 {
4529 if (++len == bufsize)
4530 {
4531 if (buf_write_bytes(&write_info) == FAIL)
4532 {
4533 end = 0; /* write error: break loop */
4534 break;
4535 }
4536 nchars += bufsize;
4537 s = buffer;
4538 len = 0;
4539 }
4540 *s++ = NL;
4541 }
4542 }
4543 if (++len == bufsize && end)
4544 {
4545 if (buf_write_bytes(&write_info) == FAIL)
4546 {
4547 end = 0; /* write error: break loop */
4548 break;
4549 }
4550 nchars += bufsize;
4551 s = buffer;
4552 len = 0;
4553
4554 ui_breakcheck();
4555 if (got_int)
4556 {
4557 end = 0; /* Interrupted, break loop */
4558 break;
4559 }
4560 }
4561#ifdef VMS
4562 /*
4563 * On VMS there is a problem: newlines get added when writing blocks
4564 * at a time. Fix it by writing a line at a time.
4565 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004566 * Explanation: VAX/DECC RTL insists that records in some RMS
4567 * structures end with a newline (carriage return) character, and if
4568 * they don't it adds one.
4569 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004571 if (buf->b_fab_rfm == FAB$C_VFC
4572 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004574 int b2write;
4575
4576 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4577 ? MIN(4096, bufsize)
4578 : MIN(buf->b_fab_mrs, bufsize));
4579
4580 b2write = len;
4581 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004583 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4584 if (buf_write_bytes(&write_info) == FAIL)
4585 {
4586 end = 0;
4587 break;
4588 }
4589 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590 }
4591 write_info.bw_len = bufsize;
4592 nchars += len;
4593 s = buffer;
4594 len = 0;
4595 }
4596#endif
4597 }
4598 if (len > 0 && end > 0)
4599 {
4600 write_info.bw_len = len;
4601 if (buf_write_bytes(&write_info) == FAIL)
4602 end = 0; /* write error */
4603 nchars += len;
4604 }
4605
4606#if defined(UNIX) && defined(HAVE_FSYNC)
4607 /* On many journalling file systems there is a bug that causes both the
4608 * original and the backup file to be lost when halting the system right
4609 * after writing the file. That's because only the meta-data is
4610 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004611 * been written to disk and we don't lose it.
4612 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004613 * (could be a pipe).
4614 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4615 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 {
4617 errmsg = (char_u *)_("E667: Fsync failed");
4618 end = 0;
4619 }
4620#endif
4621
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004622#ifdef HAVE_SELINUX
4623 /* Probably need to set the security context. */
4624 if (!backup_copy)
4625 mch_copy_sec(backup, wfname);
4626#endif
4627
Bram Moolenaara5792f52005-11-23 21:25:05 +00004628#ifdef UNIX
4629 /* When creating a new file, set its owner/group to that of the original
4630 * file. Get the new device and inode number. */
4631 if (backup != NULL && !backup_copy)
4632 {
4633# ifdef HAVE_FCHOWN
4634 struct stat st;
4635
4636 /* don't change the owner when it's already OK, some systems remove
4637 * permission or ACL stuff */
4638 if (mch_stat((char *)wfname, &st) < 0
4639 || st.st_uid != st_old.st_uid
4640 || st.st_gid != st_old.st_gid)
4641 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004642 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004643 if (perm >= 0) /* set permission again, may have changed */
4644 (void)mch_setperm(wfname, perm);
4645 }
4646# endif
4647 buf_setino(buf);
4648 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004649 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004650 /* Set the inode when creating a new file. */
4651 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004652#endif
4653
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 if (close(fd) != 0)
4655 {
4656 errmsg = (char_u *)_("E512: Close failed");
4657 end = 0;
4658 }
4659
4660#ifdef UNIX
4661 if (made_writable)
4662 perm &= ~0200; /* reset 'w' bit for security reasons */
4663#endif
4664 if (perm >= 0) /* set perm. of new file same as old file */
4665 (void)mch_setperm(wfname, perm);
4666#ifdef RISCOS
4667 if (!append && !filtering)
4668 /* Set the filetype after writing the file. */
4669 mch_set_filetype(wfname, buf->b_p_oft);
4670#endif
4671#ifdef HAVE_ACL
4672 /* Probably need to set the ACL before changing the user (can't set the
4673 * ACL on a file the user doesn't own). */
4674 if (!backup_copy)
4675 mch_set_acl(wfname, acl);
4676#endif
4677
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678
4679#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4680 if (wfname != fname)
4681 {
4682 /*
4683 * The file was written to a temp file, now it needs to be converted
4684 * with 'charconvert' to (overwrite) the output file.
4685 */
4686 if (end != 0)
4687 {
4688 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4689 wfname, fname) == FAIL)
4690 {
4691 write_info.bw_conv_error = TRUE;
4692 end = 0;
4693 }
4694 }
4695 mch_remove(wfname);
4696 vim_free(wfname);
4697 }
4698#endif
4699
4700 if (end == 0)
4701 {
4702 if (errmsg == NULL)
4703 {
4704#ifdef FEAT_MBYTE
4705 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004706 {
4707 if (write_info.bw_conv_error_lnum == 0)
4708 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4709 else
4710 {
4711 errmsg_allocated = TRUE;
4712 errmsg = alloc(300);
4713 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4714 (long)write_info.bw_conv_error_lnum);
4715 }
4716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 else
4718#endif
4719 if (got_int)
4720 errmsg = (char_u *)_(e_interr);
4721 else
4722 errmsg = (char_u *)_("E514: write error (file system full?)");
4723 }
4724
4725 /*
4726 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004727 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728 * original file when trying to make a backup when writing the file a
4729 * second time.
4730 * When "backup_copy" is set we need to copy the backup over the new
4731 * file. Otherwise rename the backup file.
4732 * If this is OK, don't give the extra warning message.
4733 */
4734 if (backup != NULL)
4735 {
4736 if (backup_copy)
4737 {
4738 /* This may take a while, if we were interrupted let the user
4739 * know we got the message. */
4740 if (got_int)
4741 {
4742 MSG(_(e_interr));
4743 out_flush();
4744 }
4745 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4746 {
4747 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004748 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4749 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750 {
4751 /* copy the file. */
4752 write_info.bw_buf = smallbuf;
4753#ifdef HAS_BW_FLAGS
4754 write_info.bw_flags = FIO_NOCONVERT;
4755#endif
4756 while ((write_info.bw_len = vim_read(fd, smallbuf,
4757 SMBUFSIZE)) > 0)
4758 if (buf_write_bytes(&write_info) == FAIL)
4759 break;
4760
4761 if (close(write_info.bw_fd) >= 0
4762 && write_info.bw_len == 0)
4763 end = 1; /* success */
4764 }
4765 close(fd); /* ignore errors for closing read file */
4766 }
4767 }
4768 else
4769 {
4770 if (vim_rename(backup, fname) == 0)
4771 end = 1;
4772 }
4773 }
4774 goto fail;
4775 }
4776
4777 lnum -= start; /* compute number of written lines */
4778 --no_wait_return; /* may wait for return now */
4779
4780#if !(defined(UNIX) || defined(VMS))
4781 fname = sfname; /* use shortname now, for the messages */
4782#endif
4783 if (!filtering)
4784 {
4785 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4786 c = FALSE;
4787#ifdef FEAT_MBYTE
4788 if (write_info.bw_conv_error)
4789 {
4790 STRCAT(IObuff, _(" CONVERSION ERROR"));
4791 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004792 if (write_info.bw_conv_error_lnum != 0)
4793 {
Bram Moolenaarc0662022009-09-11 13:04:24 +00004794 size_t l = STRLEN(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004795 vim_snprintf((char *)IObuff + l, IOSIZE - l, _(" in line %ld;"),
4796 (long)write_info.bw_conv_error_lnum);
4797 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 }
4799 else if (notconverted)
4800 {
4801 STRCAT(IObuff, _("[NOT converted]"));
4802 c = TRUE;
4803 }
4804 else if (converted)
4805 {
4806 STRCAT(IObuff, _("[converted]"));
4807 c = TRUE;
4808 }
4809#endif
4810 if (device)
4811 {
4812 STRCAT(IObuff, _("[Device]"));
4813 c = TRUE;
4814 }
4815 else if (newfile)
4816 {
4817 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4818 c = TRUE;
4819 }
4820 if (no_eol)
4821 {
4822 msg_add_eol();
4823 c = TRUE;
4824 }
4825 /* may add [unix/dos/mac] */
4826 if (msg_add_fileformat(fileformat))
4827 c = TRUE;
4828#ifdef FEAT_CRYPT
4829 if (wb_flags & FIO_ENCRYPTED)
4830 {
4831 STRCAT(IObuff, _("[crypted]"));
4832 c = TRUE;
4833 }
4834#endif
4835 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4836 if (!shortmess(SHM_WRITE))
4837 {
4838 if (append)
4839 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4840 else
4841 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4842 }
4843
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004844 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845 }
4846
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004847 /* When written everything correctly: reset 'modified'. Unless not
4848 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004849 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850#ifdef FEAT_MBYTE
4851 && !write_info.bw_conv_error
4852#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004853 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4854 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 {
4856 unchanged(buf, TRUE);
4857 u_unchanged(buf);
4858 }
4859
4860 /*
4861 * If written to the current file, update the timestamp of the swap file
4862 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4863 */
4864 if (overwriting)
4865 {
4866 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004867 if (append)
4868 buf->b_flags &= ~BF_NEW;
4869 else
4870 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 }
4872
4873 /*
4874 * If we kept a backup until now, and we are in patch mode, then we make
4875 * the backup file our 'original' file.
4876 */
4877 if (*p_pm && dobackup)
4878 {
4879 char *org = (char *)buf_modname(
4880#ifdef SHORT_FNAME
4881 TRUE,
4882#else
4883 (buf->b_p_sn || buf->b_shortname),
4884#endif
4885 fname, p_pm, FALSE);
4886
4887 if (backup != NULL)
4888 {
4889 struct stat st;
4890
4891 /*
4892 * If the original file does not exist yet
4893 * the current backup file becomes the original file
4894 */
4895 if (org == NULL)
4896 EMSG(_("E205: Patchmode: can't save original file"));
4897 else if (mch_stat(org, &st) < 0)
4898 {
4899 vim_rename(backup, (char_u *)org);
4900 vim_free(backup); /* don't delete the file */
4901 backup = NULL;
4902#ifdef UNIX
4903 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4904#endif
4905 }
4906 }
4907 /*
4908 * If there is no backup file, remember that a (new) file was
4909 * created.
4910 */
4911 else
4912 {
4913 int empty_fd;
4914
4915 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004916 || (empty_fd = mch_open(org,
4917 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004918 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 EMSG(_("E206: patchmode: can't touch empty original file"));
4920 else
4921 close(empty_fd);
4922 }
4923 if (org != NULL)
4924 {
4925 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4926 vim_free(org);
4927 }
4928 }
4929
4930 /*
4931 * Remove the backup unless 'backup' option is set
4932 */
4933 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4934 EMSG(_("E207: Can't delete backup file"));
4935
4936#ifdef FEAT_SUN_WORKSHOP
4937 if (usingSunWorkShop)
4938 workshop_file_saved((char *) ffname);
4939#endif
4940
4941 goto nofail;
4942
4943 /*
4944 * Finish up. We get here either after failure or success.
4945 */
4946fail:
4947 --no_wait_return; /* may wait for return now */
4948nofail:
4949
4950 /* Done saving, we accept changed buffer warnings again */
4951 buf->b_saving = FALSE;
4952
4953 vim_free(backup);
4954 if (buffer != smallbuf)
4955 vim_free(buffer);
4956#ifdef FEAT_MBYTE
4957 vim_free(fenc_tofree);
4958 vim_free(write_info.bw_conv_buf);
4959# ifdef USE_ICONV
4960 if (write_info.bw_iconv_fd != (iconv_t)-1)
4961 {
4962 iconv_close(write_info.bw_iconv_fd);
4963 write_info.bw_iconv_fd = (iconv_t)-1;
4964 }
4965# endif
4966#endif
4967#ifdef HAVE_ACL
4968 mch_free_acl(acl);
4969#endif
4970
4971 if (errmsg != NULL)
4972 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004973 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974
4975 attr = hl_attr(HLF_E); /* set highlight for error messages */
4976 msg_add_fname(buf,
4977#ifndef UNIX
4978 sfname
4979#else
4980 fname
4981#endif
4982 ); /* put file name in IObuff with quotes */
4983 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
4984 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
4985 /* If the error message has the form "is ...", put the error number in
4986 * front of the file name. */
4987 if (errnum != NULL)
4988 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004989 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 mch_memmove(IObuff, errnum, (size_t)numlen);
4991 }
4992 STRCAT(IObuff, errmsg);
4993 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004994 if (errmsg_allocated)
4995 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996
4997 retval = FAIL;
4998 if (end == 0)
4999 {
5000 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5001 attr | MSG_HIST);
5002 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5003 attr | MSG_HIST);
5004
5005 /* Update the timestamp to avoid an "overwrite changed file"
5006 * prompt when writing again. */
5007 if (mch_stat((char *)fname, &st_old) >= 0)
5008 {
5009 buf_store_time(buf, &st_old, fname);
5010 buf->b_mtime_read = buf->b_mtime;
5011 }
5012 }
5013 }
5014 msg_scroll = msg_save;
5015
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005016#ifdef FEAT_PERSISTENT_UNDO
5017 /*
5018 * When writing the whole file and 'undofile' is set, also write the undo
5019 * file.
5020 */
5021 if (retval == OK && write_undo_file)
5022 {
5023 char_u hash[UNDO_HASH_SIZE];
5024
5025 sha256_finish(&sha_ctx, hash);
5026 u_write_undo(NULL, FALSE, buf, hash);
5027 }
5028#endif
5029
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030#ifdef FEAT_AUTOCMD
5031#ifdef FEAT_EVAL
5032 if (!should_abort(retval))
5033#else
5034 if (!got_int)
5035#endif
5036 {
5037 aco_save_T aco;
5038
5039 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5040
5041 /*
5042 * Apply POST autocommands.
5043 * Careful: The autocommands may call buf_write() recursively!
5044 */
5045 aucmd_prepbuf(&aco, buf);
5046
5047 if (append)
5048 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5049 FALSE, curbuf, eap);
5050 else if (filtering)
5051 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5052 FALSE, curbuf, eap);
5053 else if (reset_changed && whole)
5054 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5055 FALSE, curbuf, eap);
5056 else
5057 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5058 FALSE, curbuf, eap);
5059
5060 /* restore curwin/curbuf and a few other things */
5061 aucmd_restbuf(&aco);
5062
5063#ifdef FEAT_EVAL
5064 if (aborting()) /* autocmds may abort script processing */
5065 retval = FALSE;
5066#endif
5067 }
5068#endif
5069
5070 got_int |= prev_got_int;
5071
5072#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5073 /* Update machine specific information. */
5074 mch_post_buffer_write(buf);
5075#endif
5076 return retval;
5077}
5078
5079/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005080 * Set the name of the current buffer. Use when the buffer doesn't have a
5081 * name and a ":r" or ":w" command with a file name is used.
5082 */
5083 static int
5084set_rw_fname(fname, sfname)
5085 char_u *fname;
5086 char_u *sfname;
5087{
5088#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005089 buf_T *buf = curbuf;
5090
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005091 /* It's like the unnamed buffer is deleted.... */
5092 if (curbuf->b_p_bl)
5093 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5094 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5095# ifdef FEAT_EVAL
5096 if (aborting()) /* autocmds may abort script processing */
5097 return FAIL;
5098# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005099 if (curbuf != buf)
5100 {
5101 /* We are in another buffer now, don't do the renaming. */
5102 EMSG(_(e_auchangedbuf));
5103 return FAIL;
5104 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005105#endif
5106
5107 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5108 curbuf->b_flags |= BF_NOTEDITED;
5109
5110#ifdef FEAT_AUTOCMD
5111 /* ....and a new named one is created */
5112 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5113 if (curbuf->b_p_bl)
5114 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5115# ifdef FEAT_EVAL
5116 if (aborting()) /* autocmds may abort script processing */
5117 return FAIL;
5118# endif
5119
5120 /* Do filetype detection now if 'filetype' is empty. */
5121 if (*curbuf->b_p_ft == NUL)
5122 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005123 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005124 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005125 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005126 }
5127#endif
5128
5129 return OK;
5130}
5131
5132/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005133 * Put file name into IObuff with quotes.
5134 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005135 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136msg_add_fname(buf, fname)
5137 buf_T *buf;
5138 char_u *fname;
5139{
5140 if (fname == NULL)
5141 fname = (char_u *)"-stdin-";
5142 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5143 IObuff[0] = '"';
5144 STRCAT(IObuff, "\" ");
5145}
5146
5147/*
5148 * Append message for text mode to IObuff.
5149 * Return TRUE if something appended.
5150 */
5151 static int
5152msg_add_fileformat(eol_type)
5153 int eol_type;
5154{
5155#ifndef USE_CRNL
5156 if (eol_type == EOL_DOS)
5157 {
5158 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5159 return TRUE;
5160 }
5161#endif
5162#ifndef USE_CR
5163 if (eol_type == EOL_MAC)
5164 {
5165 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5166 return TRUE;
5167 }
5168#endif
5169#if defined(USE_CRNL) || defined(USE_CR)
5170 if (eol_type == EOL_UNIX)
5171 {
5172 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5173 return TRUE;
5174 }
5175#endif
5176 return FALSE;
5177}
5178
5179/*
5180 * Append line and character count to IObuff.
5181 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005182 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183msg_add_lines(insert_space, lnum, nchars)
5184 int insert_space;
5185 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005186 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187{
5188 char_u *p;
5189
5190 p = IObuff + STRLEN(IObuff);
5191
5192 if (insert_space)
5193 *p++ = ' ';
5194 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005195 sprintf((char *)p,
5196#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005197 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005198#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005199 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5200 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005201#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005202 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 else
5204 {
5205 if (lnum == 1)
5206 STRCPY(p, _("1 line, "));
5207 else
5208 sprintf((char *)p, _("%ld lines, "), lnum);
5209 p += STRLEN(p);
5210 if (nchars == 1)
5211 STRCPY(p, _("1 character"));
5212 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005213 sprintf((char *)p,
5214#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005215 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005216#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005217 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5218 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005219#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005220 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221 }
5222}
5223
5224/*
5225 * Append message for missing line separator to IObuff.
5226 */
5227 static void
5228msg_add_eol()
5229{
5230 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5231}
5232
5233/*
5234 * Check modification time of file, before writing to it.
5235 * The size isn't checked, because using a tool like "gzip" takes care of
5236 * using the same timestamp but can't set the size.
5237 */
5238 static int
5239check_mtime(buf, st)
5240 buf_T *buf;
5241 struct stat *st;
5242{
5243 if (buf->b_mtime_read != 0
5244 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5245 {
5246 msg_scroll = TRUE; /* don't overwrite messages here */
5247 msg_silent = 0; /* must give this prompt */
5248 /* don't use emsg() here, don't want to flush the buffers */
5249 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5250 hl_attr(HLF_E));
5251 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5252 TRUE) == 'n')
5253 return FAIL;
5254 msg_scroll = FALSE; /* always overwrite the file message now */
5255 }
5256 return OK;
5257}
5258
5259 static int
5260time_differs(t1, t2)
5261 long t1, t2;
5262{
5263#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5264 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5265 * the seconds. Since the roundoff is done when flushing the inode, the
5266 * time may change unexpectedly by one second!!! */
5267 return (t1 - t2 > 1 || t2 - t1 > 1);
5268#else
5269 return (t1 != t2);
5270#endif
5271}
5272
5273/*
5274 * Call write() to write a number of bytes to the file.
5275 * Also handles encryption and 'encoding' conversion.
5276 *
5277 * Return FAIL for failure, OK otherwise.
5278 */
5279 static int
5280buf_write_bytes(ip)
5281 struct bw_info *ip;
5282{
5283 int wlen;
5284 char_u *buf = ip->bw_buf; /* data to write */
5285 int len = ip->bw_len; /* length of data */
5286#ifdef HAS_BW_FLAGS
5287 int flags = ip->bw_flags; /* extra flags */
5288#endif
5289
5290#ifdef FEAT_MBYTE
5291 /*
5292 * Skip conversion when writing the crypt magic number or the BOM.
5293 */
5294 if (!(flags & FIO_NOCONVERT))
5295 {
5296 char_u *p;
5297 unsigned c;
5298 int n;
5299
5300 if (flags & FIO_UTF8)
5301 {
5302 /*
5303 * Convert latin1 in the buffer to UTF-8 in the file.
5304 */
5305 p = ip->bw_conv_buf; /* translate to buffer */
5306 for (wlen = 0; wlen < len; ++wlen)
5307 p += utf_char2bytes(buf[wlen], p);
5308 buf = ip->bw_conv_buf;
5309 len = (int)(p - ip->bw_conv_buf);
5310 }
5311 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5312 {
5313 /*
5314 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5315 * Latin1 chars in the file.
5316 */
5317 if (flags & FIO_LATIN1)
5318 p = buf; /* translate in-place (can only get shorter) */
5319 else
5320 p = ip->bw_conv_buf; /* translate to buffer */
5321 for (wlen = 0; wlen < len; wlen += n)
5322 {
5323 if (wlen == 0 && ip->bw_restlen != 0)
5324 {
5325 int l;
5326
5327 /* Use remainder of previous call. Append the start of
5328 * buf[] to get a full sequence. Might still be too
5329 * short! */
5330 l = CONV_RESTLEN - ip->bw_restlen;
5331 if (l > len)
5332 l = len;
5333 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005334 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335 if (n > ip->bw_restlen + len)
5336 {
5337 /* We have an incomplete byte sequence at the end to
5338 * be written. We can't convert it without the
5339 * remaining bytes. Keep them for the next call. */
5340 if (ip->bw_restlen + len > CONV_RESTLEN)
5341 return FAIL;
5342 ip->bw_restlen += len;
5343 break;
5344 }
5345 if (n > 1)
5346 c = utf_ptr2char(ip->bw_rest);
5347 else
5348 c = ip->bw_rest[0];
5349 if (n >= ip->bw_restlen)
5350 {
5351 n -= ip->bw_restlen;
5352 ip->bw_restlen = 0;
5353 }
5354 else
5355 {
5356 ip->bw_restlen -= n;
5357 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5358 (size_t)ip->bw_restlen);
5359 n = 0;
5360 }
5361 }
5362 else
5363 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005364 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365 if (n > len - wlen)
5366 {
5367 /* We have an incomplete byte sequence at the end to
5368 * be written. We can't convert it without the
5369 * remaining bytes. Keep them for the next call. */
5370 if (len - wlen > CONV_RESTLEN)
5371 return FAIL;
5372 ip->bw_restlen = len - wlen;
5373 mch_memmove(ip->bw_rest, buf + wlen,
5374 (size_t)ip->bw_restlen);
5375 break;
5376 }
5377 if (n > 1)
5378 c = utf_ptr2char(buf + wlen);
5379 else
5380 c = buf[wlen];
5381 }
5382
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005383 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5384 {
5385 ip->bw_conv_error = TRUE;
5386 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5387 }
5388 if (c == NL)
5389 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 }
5391 if (flags & FIO_LATIN1)
5392 len = (int)(p - buf);
5393 else
5394 {
5395 buf = ip->bw_conv_buf;
5396 len = (int)(p - ip->bw_conv_buf);
5397 }
5398 }
5399
5400# ifdef WIN3264
5401 else if (flags & FIO_CODEPAGE)
5402 {
5403 /*
5404 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5405 * codepage.
5406 */
5407 char_u *from;
5408 size_t fromlen;
5409 char_u *to;
5410 int u8c;
5411 BOOL bad = FALSE;
5412 int needed;
5413
5414 if (ip->bw_restlen > 0)
5415 {
5416 /* Need to concatenate the remainder of the previous call and
5417 * the bytes of the current call. Use the end of the
5418 * conversion buffer for this. */
5419 fromlen = len + ip->bw_restlen;
5420 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5421 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5422 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5423 }
5424 else
5425 {
5426 from = buf;
5427 fromlen = len;
5428 }
5429
5430 to = ip->bw_conv_buf;
5431 if (enc_utf8)
5432 {
5433 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5434 * The buffer has been allocated to be big enough. */
5435 while (fromlen > 0)
5436 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005437 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438 if (n > (int)fromlen) /* incomplete byte sequence */
5439 break;
5440 u8c = utf_ptr2char(from);
5441 *to++ = (u8c & 0xff);
5442 *to++ = (u8c >> 8);
5443 fromlen -= n;
5444 from += n;
5445 }
5446
5447 /* Copy remainder to ip->bw_rest[] to be used for the next
5448 * call. */
5449 if (fromlen > CONV_RESTLEN)
5450 {
5451 /* weird overlong sequence */
5452 ip->bw_conv_error = TRUE;
5453 return FAIL;
5454 }
5455 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005456 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005457 }
5458 else
5459 {
5460 /* Convert from enc_codepage to UCS-2, to the start of the
5461 * buffer. The buffer has been allocated to be big enough. */
5462 ip->bw_restlen = 0;
5463 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005464 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465 NULL, 0);
5466 if (needed == 0)
5467 {
5468 /* When conversion fails there may be a trailing byte. */
5469 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005470 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 NULL, 0);
5472 if (needed == 0)
5473 {
5474 /* Conversion doesn't work. */
5475 ip->bw_conv_error = TRUE;
5476 return FAIL;
5477 }
5478 /* Save the trailing byte for the next call. */
5479 ip->bw_rest[0] = from[fromlen - 1];
5480 ip->bw_restlen = 1;
5481 }
5482 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005483 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484 (LPWSTR)to, needed);
5485 if (needed == 0)
5486 {
5487 /* Safety check: Conversion doesn't work. */
5488 ip->bw_conv_error = TRUE;
5489 return FAIL;
5490 }
5491 to += needed * 2;
5492 }
5493
5494 fromlen = to - ip->bw_conv_buf;
5495 buf = to;
5496# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5497 if (FIO_GET_CP(flags) == CP_UTF8)
5498 {
5499 /* Convert from UCS-2 to UTF-8, using the remainder of the
5500 * conversion buffer. Fails when out of space. */
5501 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5502 {
5503 u8c = *from++;
5504 u8c += (*from++ << 8);
5505 to += utf_char2bytes(u8c, to);
5506 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5507 {
5508 ip->bw_conv_error = TRUE;
5509 return FAIL;
5510 }
5511 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005512 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005513 }
5514 else
5515#endif
5516 {
5517 /* Convert from UCS-2 to the codepage, using the remainder of
5518 * the conversion buffer. If the conversion uses the default
5519 * character "0", the data doesn't fit in this encoding, so
5520 * fail. */
5521 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5522 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005523 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5524 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005525 if (bad)
5526 {
5527 ip->bw_conv_error = TRUE;
5528 return FAIL;
5529 }
5530 }
5531 }
5532# endif
5533
Bram Moolenaar56718732006-03-15 22:53:57 +00005534# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535 else if (flags & FIO_MACROMAN)
5536 {
5537 /*
5538 * Convert UTF-8 or latin1 to Apple MacRoman.
5539 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 char_u *from;
5541 size_t fromlen;
5542
5543 if (ip->bw_restlen > 0)
5544 {
5545 /* Need to concatenate the remainder of the previous call and
5546 * the bytes of the current call. Use the end of the
5547 * conversion buffer for this. */
5548 fromlen = len + ip->bw_restlen;
5549 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5550 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5551 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5552 }
5553 else
5554 {
5555 from = buf;
5556 fromlen = len;
5557 }
5558
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005559 if (enc2macroman(from, fromlen,
5560 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5561 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 {
5563 ip->bw_conv_error = TRUE;
5564 return FAIL;
5565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 }
5568# endif
5569
5570# ifdef USE_ICONV
5571 if (ip->bw_iconv_fd != (iconv_t)-1)
5572 {
5573 const char *from;
5574 size_t fromlen;
5575 char *to;
5576 size_t tolen;
5577
5578 /* Convert with iconv(). */
5579 if (ip->bw_restlen > 0)
5580 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005581 char *fp;
5582
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 /* Need to concatenate the remainder of the previous call and
5584 * the bytes of the current call. Use the end of the
5585 * conversion buffer for this. */
5586 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005587 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5588 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5589 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5590 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 tolen = ip->bw_conv_buflen - fromlen;
5592 }
5593 else
5594 {
5595 from = (const char *)buf;
5596 fromlen = len;
5597 tolen = ip->bw_conv_buflen;
5598 }
5599 to = (char *)ip->bw_conv_buf;
5600
5601 if (ip->bw_first)
5602 {
5603 size_t save_len = tolen;
5604
5605 /* output the initial shift state sequence */
5606 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5607
5608 /* There is a bug in iconv() on Linux (which appears to be
5609 * wide-spread) which sets "to" to NULL and messes up "tolen".
5610 */
5611 if (to == NULL)
5612 {
5613 to = (char *)ip->bw_conv_buf;
5614 tolen = save_len;
5615 }
5616 ip->bw_first = FALSE;
5617 }
5618
5619 /*
5620 * If iconv() has an error or there is not enough room, fail.
5621 */
5622 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5623 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5624 || fromlen > CONV_RESTLEN)
5625 {
5626 ip->bw_conv_error = TRUE;
5627 return FAIL;
5628 }
5629
5630 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5631 if (fromlen > 0)
5632 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5633 ip->bw_restlen = (int)fromlen;
5634
5635 buf = ip->bw_conv_buf;
5636 len = (int)((char_u *)to - ip->bw_conv_buf);
5637 }
5638# endif
5639 }
5640#endif /* FEAT_MBYTE */
5641
5642#ifdef FEAT_CRYPT
5643 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005644 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645#endif
5646
5647 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005648 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 {
5650 wlen = vim_write(ip->bw_fd, buf, len);
5651 if (wlen <= 0) /* error! */
5652 return FAIL;
5653 len -= wlen;
5654 buf += wlen;
5655 }
5656 return OK;
5657}
5658
5659#ifdef FEAT_MBYTE
5660/*
5661 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005662 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663 */
5664 static int
5665ucs2bytes(c, pp, flags)
5666 unsigned c; /* in: character */
5667 char_u **pp; /* in/out: pointer to result */
5668 int flags; /* FIO_ flags */
5669{
5670 char_u *p = *pp;
5671 int error = FALSE;
5672 int cc;
5673
5674
5675 if (flags & FIO_UCS4)
5676 {
5677 if (flags & FIO_ENDIAN_L)
5678 {
5679 *p++ = c;
5680 *p++ = (c >> 8);
5681 *p++ = (c >> 16);
5682 *p++ = (c >> 24);
5683 }
5684 else
5685 {
5686 *p++ = (c >> 24);
5687 *p++ = (c >> 16);
5688 *p++ = (c >> 8);
5689 *p++ = c;
5690 }
5691 }
5692 else if (flags & (FIO_UCS2 | FIO_UTF16))
5693 {
5694 if (c >= 0x10000)
5695 {
5696 if (flags & FIO_UTF16)
5697 {
5698 /* Make two words, ten bits of the character in each. First
5699 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5700 c -= 0x10000;
5701 if (c >= 0x100000)
5702 error = TRUE;
5703 cc = ((c >> 10) & 0x3ff) + 0xd800;
5704 if (flags & FIO_ENDIAN_L)
5705 {
5706 *p++ = cc;
5707 *p++ = ((unsigned)cc >> 8);
5708 }
5709 else
5710 {
5711 *p++ = ((unsigned)cc >> 8);
5712 *p++ = cc;
5713 }
5714 c = (c & 0x3ff) + 0xdc00;
5715 }
5716 else
5717 error = TRUE;
5718 }
5719 if (flags & FIO_ENDIAN_L)
5720 {
5721 *p++ = c;
5722 *p++ = (c >> 8);
5723 }
5724 else
5725 {
5726 *p++ = (c >> 8);
5727 *p++ = c;
5728 }
5729 }
5730 else /* Latin1 */
5731 {
5732 if (c >= 0x100)
5733 {
5734 error = TRUE;
5735 *p++ = 0xBF;
5736 }
5737 else
5738 *p++ = c;
5739 }
5740
5741 *pp = p;
5742 return error;
5743}
5744
5745/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005746 * Return TRUE if file encoding "fenc" requires conversion from or to
5747 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 */
5749 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005750need_conversion(fenc)
5751 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005753 int same_encoding;
5754 int enc_flags;
5755 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005757 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005758 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005759 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005760 fenc_flags = 0;
5761 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005762 else
5763 {
5764 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5765 * "ucs-4be", etc. */
5766 enc_flags = get_fio_flags(p_enc);
5767 fenc_flags = get_fio_flags(fenc);
5768 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5769 }
5770 if (same_encoding)
5771 {
5772 /* Specified encoding matches with 'encoding'. This requires
5773 * conversion when 'encoding' is Unicode but not UTF-8. */
5774 return enc_unicode != 0;
5775 }
5776
5777 /* Encodings differ. However, conversion is not needed when 'enc' is any
5778 * Unicode encoding and the file is UTF-8. */
5779 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780}
5781
5782/*
5783 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5784 * internal conversion.
5785 * if "ptr" is an empty string, use 'encoding'.
5786 */
5787 static int
5788get_fio_flags(ptr)
5789 char_u *ptr;
5790{
5791 int prop;
5792
5793 if (*ptr == NUL)
5794 ptr = p_enc;
5795
5796 prop = enc_canon_props(ptr);
5797 if (prop & ENC_UNICODE)
5798 {
5799 if (prop & ENC_2BYTE)
5800 {
5801 if (prop & ENC_ENDIAN_L)
5802 return FIO_UCS2 | FIO_ENDIAN_L;
5803 return FIO_UCS2;
5804 }
5805 if (prop & ENC_4BYTE)
5806 {
5807 if (prop & ENC_ENDIAN_L)
5808 return FIO_UCS4 | FIO_ENDIAN_L;
5809 return FIO_UCS4;
5810 }
5811 if (prop & ENC_2WORD)
5812 {
5813 if (prop & ENC_ENDIAN_L)
5814 return FIO_UTF16 | FIO_ENDIAN_L;
5815 return FIO_UTF16;
5816 }
5817 return FIO_UTF8;
5818 }
5819 if (prop & ENC_LATIN1)
5820 return FIO_LATIN1;
5821 /* must be ENC_DBCS, requires iconv() */
5822 return 0;
5823}
5824
5825#ifdef WIN3264
5826/*
5827 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5828 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5829 * Used for conversion between 'encoding' and 'fileencoding'.
5830 */
5831 static int
5832get_win_fio_flags(ptr)
5833 char_u *ptr;
5834{
5835 int cp;
5836
5837 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5838 if (!enc_utf8 && enc_codepage <= 0)
5839 return 0;
5840
5841 cp = encname2codepage(ptr);
5842 if (cp == 0)
5843 {
5844# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5845 if (STRCMP(ptr, "utf-8") == 0)
5846 cp = CP_UTF8;
5847 else
5848# endif
5849 return 0;
5850 }
5851 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5852}
5853#endif
5854
5855#ifdef MACOS_X
5856/*
5857 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5858 * needed for the internal conversion to/from utf-8 or latin1.
5859 */
5860 static int
5861get_mac_fio_flags(ptr)
5862 char_u *ptr;
5863{
5864 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5865 && (enc_canon_props(ptr) & ENC_MACROMAN))
5866 return FIO_MACROMAN;
5867 return 0;
5868}
5869#endif
5870
5871/*
5872 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5873 * "size" must be at least 2.
5874 * Return the name of the encoding and set "*lenp" to the length.
5875 * Returns NULL when no BOM found.
5876 */
5877 static char_u *
5878check_for_bom(p, size, lenp, flags)
5879 char_u *p;
5880 long size;
5881 int *lenp;
5882 int flags;
5883{
5884 char *name = NULL;
5885 int len = 2;
5886
5887 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005888 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889 {
5890 name = "utf-8"; /* EF BB BF */
5891 len = 3;
5892 }
5893 else if (p[0] == 0xff && p[1] == 0xfe)
5894 {
5895 if (size >= 4 && p[2] == 0 && p[3] == 0
5896 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5897 {
5898 name = "ucs-4le"; /* FF FE 00 00 */
5899 len = 4;
5900 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005901 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005903 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5904 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905 name = "utf-16le"; /* FF FE */
5906 }
5907 else if (p[0] == 0xfe && p[1] == 0xff
5908 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5909 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005910 /* Default to utf-16, it works also for ucs-2 text. */
5911 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005913 else
5914 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915 }
5916 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5917 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5918 {
5919 name = "ucs-4"; /* 00 00 FE FF */
5920 len = 4;
5921 }
5922
5923 *lenp = len;
5924 return (char_u *)name;
5925}
5926
5927/*
5928 * Generate a BOM in "buf[4]" for encoding "name".
5929 * Return the length of the BOM (zero when no BOM).
5930 */
5931 static int
5932make_bom(buf, name)
5933 char_u *buf;
5934 char_u *name;
5935{
5936 int flags;
5937 char_u *p;
5938
5939 flags = get_fio_flags(name);
5940
5941 /* Can't put a BOM in a non-Unicode file. */
5942 if (flags == FIO_LATIN1 || flags == 0)
5943 return 0;
5944
5945 if (flags == FIO_UTF8) /* UTF-8 */
5946 {
5947 buf[0] = 0xef;
5948 buf[1] = 0xbb;
5949 buf[2] = 0xbf;
5950 return 3;
5951 }
5952 p = buf;
5953 (void)ucs2bytes(0xfeff, &p, flags);
5954 return (int)(p - buf);
5955}
5956#endif
5957
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005958#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005959 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960/*
5961 * Try to find a shortname by comparing the fullname with the current
5962 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005963 * Returns "full_path" or pointer into "full_path" if shortened.
5964 */
5965 char_u *
5966shorten_fname1(full_path)
5967 char_u *full_path;
5968{
5969 char_u dirname[MAXPATHL];
5970 char_u *p = full_path;
5971
5972 if (mch_dirname(dirname, MAXPATHL) == OK)
5973 {
5974 p = shorten_fname(full_path, dirname);
5975 if (p == NULL || *p == NUL)
5976 p = full_path;
5977 }
5978 return p;
5979}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005980#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005981
5982/*
5983 * Try to find a shortname by comparing the fullname with the current
5984 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985 * Returns NULL if not shorter name possible, pointer into "full_path"
5986 * otherwise.
5987 */
5988 char_u *
5989shorten_fname(full_path, dir_name)
5990 char_u *full_path;
5991 char_u *dir_name;
5992{
5993 int len;
5994 char_u *p;
5995
5996 if (full_path == NULL)
5997 return NULL;
5998 len = (int)STRLEN(dir_name);
5999 if (fnamencmp(dir_name, full_path, len) == 0)
6000 {
6001 p = full_path + len;
6002#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6003 /*
6004 * MSDOS: when a file is in the root directory, dir_name will end in a
6005 * slash, since C: by itself does not define a specific dir. In this
6006 * case p may already be correct. <negri>
6007 */
6008 if (!((len > 2) && (*(p - 2) == ':')))
6009#endif
6010 {
6011 if (vim_ispathsep(*p))
6012 ++p;
6013#ifndef VMS /* the path separator is always part of the path */
6014 else
6015 p = NULL;
6016#endif
6017 }
6018 }
6019#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6020 /*
6021 * When using a file in the current drive, remove the drive name:
6022 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6023 * a floppy from "A:\dir" to "B:\dir".
6024 */
6025 else if (len > 3
6026 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6027 && full_path[1] == ':'
6028 && vim_ispathsep(full_path[2]))
6029 p = full_path + 2;
6030#endif
6031 else
6032 p = NULL;
6033 return p;
6034}
6035
6036/*
6037 * Shorten filenames for all buffers.
6038 * When "force" is TRUE: Use full path from now on for files currently being
6039 * edited, both for file name and swap file name. Try to shorten the file
6040 * names a bit, if safe to do so.
6041 * When "force" is FALSE: Only try to shorten absolute file names.
6042 * For buffers that have buftype "nofile" or "scratch": never change the file
6043 * name.
6044 */
6045 void
6046shorten_fnames(force)
6047 int force;
6048{
6049 char_u dirname[MAXPATHL];
6050 buf_T *buf;
6051 char_u *p;
6052
6053 mch_dirname(dirname, MAXPATHL);
6054 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6055 {
6056 if (buf->b_fname != NULL
6057#ifdef FEAT_QUICKFIX
6058 && !bt_nofile(buf)
6059#endif
6060 && !path_with_url(buf->b_fname)
6061 && (force
6062 || buf->b_sfname == NULL
6063 || mch_isFullName(buf->b_sfname)))
6064 {
6065 vim_free(buf->b_sfname);
6066 buf->b_sfname = NULL;
6067 p = shorten_fname(buf->b_ffname, dirname);
6068 if (p != NULL)
6069 {
6070 buf->b_sfname = vim_strsave(p);
6071 buf->b_fname = buf->b_sfname;
6072 }
6073 if (p == NULL || buf->b_fname == NULL)
6074 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006076
6077 /* Always make the swap file name a full path, a "nofile" buffer may
6078 * also have a swap file. */
6079 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 }
6081#ifdef FEAT_WINDOWS
6082 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006083 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084#endif
6085}
6086
6087#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6088 || defined(FEAT_GUI_MSWIN) \
6089 || defined(FEAT_GUI_MAC) \
6090 || defined(PROTO)
6091/*
6092 * Shorten all filenames in "fnames[count]" by current directory.
6093 */
6094 void
6095shorten_filenames(fnames, count)
6096 char_u **fnames;
6097 int count;
6098{
6099 int i;
6100 char_u dirname[MAXPATHL];
6101 char_u *p;
6102
6103 if (fnames == NULL || count < 1)
6104 return;
6105 mch_dirname(dirname, sizeof(dirname));
6106 for (i = 0; i < count; ++i)
6107 {
6108 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6109 {
6110 /* shorten_fname() returns pointer in given "fnames[i]". If free
6111 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6112 * "p" first then free fnames[i]. */
6113 p = vim_strsave(p);
6114 vim_free(fnames[i]);
6115 fnames[i] = p;
6116 }
6117 }
6118}
6119#endif
6120
6121/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006122 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123 * fo_o_h.ext for MSDOS or when shortname option set.
6124 *
6125 * Assumed that fname is a valid name found in the filesystem we assure that
6126 * the return value is a different name and ends in 'ext'.
6127 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6128 * characters otherwise.
6129 * Space for the returned name is allocated, must be freed later.
6130 * Returns NULL when out of memory.
6131 */
6132 char_u *
6133modname(fname, ext, prepend_dot)
6134 char_u *fname, *ext;
6135 int prepend_dot; /* may prepend a '.' to file name */
6136{
6137 return buf_modname(
6138#ifdef SHORT_FNAME
6139 TRUE,
6140#else
6141 (curbuf->b_p_sn || curbuf->b_shortname),
6142#endif
6143 fname, ext, prepend_dot);
6144}
6145
6146 char_u *
6147buf_modname(shortname, fname, ext, prepend_dot)
6148 int shortname; /* use 8.3 file name */
6149 char_u *fname, *ext;
6150 int prepend_dot; /* may prepend a '.' to file name */
6151{
6152 char_u *retval;
6153 char_u *s;
6154 char_u *e;
6155 char_u *ptr;
6156 int fnamelen, extlen;
6157
6158 extlen = (int)STRLEN(ext);
6159
6160 /*
6161 * If there is no file name we must get the name of the current directory
6162 * (we need the full path in case :cd is used).
6163 */
6164 if (fname == NULL || *fname == NUL)
6165 {
6166 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6167 if (retval == NULL)
6168 return NULL;
6169 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6170 (fnamelen = (int)STRLEN(retval)) == 0)
6171 {
6172 vim_free(retval);
6173 return NULL;
6174 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006175 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 {
6177 retval[fnamelen++] = PATHSEP;
6178 retval[fnamelen] = NUL;
6179 }
6180#ifndef SHORT_FNAME
6181 prepend_dot = FALSE; /* nothing to prepend a dot to */
6182#endif
6183 }
6184 else
6185 {
6186 fnamelen = (int)STRLEN(fname);
6187 retval = alloc((unsigned)(fnamelen + extlen + 3));
6188 if (retval == NULL)
6189 return NULL;
6190 STRCPY(retval, fname);
6191#ifdef VMS
6192 vms_remove_version(retval); /* we do not need versions here */
6193#endif
6194 }
6195
6196 /*
6197 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6198 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6199 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6200 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6201 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006202 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 {
6204#ifndef RISCOS
6205 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006206# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006208# else
6209# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006211# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 )
6214 if (*ptr == '.') /* replace '.' by '_' */
6215 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006216#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006218 {
6219 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006221 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223
6224 /* the file name has at most BASENAMELEN characters. */
6225#ifndef SHORT_FNAME
6226 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6227 ptr[BASENAMELEN] = '\0';
6228#endif
6229
6230 s = ptr + STRLEN(ptr);
6231
6232 /*
6233 * For 8.3 file names we may have to reduce the length.
6234 */
6235#ifdef USE_LONG_FNAME
6236 if (!USE_LONG_FNAME || shortname)
6237#else
6238# ifndef SHORT_FNAME
6239 if (shortname)
6240# endif
6241#endif
6242 {
6243 /*
6244 * If there is no file name, or the file name ends in '/', and the
6245 * extension starts with '.', put a '_' before the dot, because just
6246 * ".ext" is invalid.
6247 */
6248 if (fname == NULL || *fname == NUL
6249 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6250 {
6251#ifdef RISCOS
6252 if (*ext == '/')
6253#else
6254 if (*ext == '.')
6255#endif
6256 *s++ = '_';
6257 }
6258 /*
6259 * If the extension starts with '.', truncate the base name at 8
6260 * characters
6261 */
6262#ifdef RISCOS
6263 /* We normally use '/', but swap files are '_' */
6264 else if (*ext == '/' || *ext == '_')
6265#else
6266 else if (*ext == '.')
6267#endif
6268 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006269 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 {
6271 s = ptr + 8;
6272 *s = '\0';
6273 }
6274 }
6275 /*
6276 * If the extension doesn't start with '.', and the file name
6277 * doesn't have an extension yet, append a '.'
6278 */
6279#ifdef RISCOS
6280 else if ((e = vim_strchr(ptr, '/')) == NULL)
6281 *s++ = '/';
6282#else
6283 else if ((e = vim_strchr(ptr, '.')) == NULL)
6284 *s++ = '.';
6285#endif
6286 /*
6287 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006288 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 */
6290 else if ((int)STRLEN(e) + extlen > 4)
6291 s = e + 4 - extlen;
6292 }
6293#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6294 /*
6295 * If there is no file name, and the extension starts with '.', put a
6296 * '_' before the dot, because just ".ext" may be invalid if it's on a
6297 * FAT partition, and on HPFS it doesn't matter.
6298 */
6299 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6300 *s++ = '_';
6301#endif
6302
6303 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006304 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 * ext can start with '.' and cannot exceed 3 more characters.
6306 */
6307 STRCPY(s, ext);
6308
6309#ifndef SHORT_FNAME
6310 /*
6311 * Prepend the dot.
6312 */
6313 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6314#ifdef RISCOS
6315 '/'
6316#else
6317 '.'
6318#endif
6319#ifdef USE_LONG_FNAME
6320 && USE_LONG_FNAME
6321#endif
6322 )
6323 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006324 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325#ifdef RISCOS
6326 *e = '/';
6327#else
6328 *e = '.';
6329#endif
6330 }
6331#endif
6332
6333 /*
6334 * Check that, after appending the extension, the file name is really
6335 * different.
6336 */
6337 if (fname != NULL && STRCMP(fname, retval) == 0)
6338 {
6339 /* we search for a character that can be replaced by '_' */
6340 while (--s >= ptr)
6341 {
6342 if (*s != '_')
6343 {
6344 *s = '_';
6345 break;
6346 }
6347 }
6348 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6349 *ptr = 'v';
6350 }
6351 return retval;
6352}
6353
6354/*
6355 * Like fgets(), but if the file line is too long, it is truncated and the
6356 * rest of the line is thrown away. Returns TRUE for end-of-file.
6357 */
6358 int
6359vim_fgets(buf, size, fp)
6360 char_u *buf;
6361 int size;
6362 FILE *fp;
6363{
6364 char *eof;
6365#define FGETS_SIZE 200
6366 char tbuf[FGETS_SIZE];
6367
6368 buf[size - 2] = NUL;
6369#ifdef USE_CR
6370 eof = fgets_cr((char *)buf, size, fp);
6371#else
6372 eof = fgets((char *)buf, size, fp);
6373#endif
6374 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6375 {
6376 buf[size - 1] = NUL; /* Truncate the line */
6377
6378 /* Now throw away the rest of the line: */
6379 do
6380 {
6381 tbuf[FGETS_SIZE - 2] = NUL;
6382#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006383 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006385 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386#endif
6387 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6388 }
6389 return (eof == NULL);
6390}
6391
6392#if defined(USE_CR) || defined(PROTO)
6393/*
6394 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6395 * Returns TRUE for end-of-file.
6396 * Only used for the Mac, because it's much slower than vim_fgets().
6397 */
6398 int
6399tag_fgets(buf, size, fp)
6400 char_u *buf;
6401 int size;
6402 FILE *fp;
6403{
6404 int i = 0;
6405 int c;
6406 int eof = FALSE;
6407
6408 for (;;)
6409 {
6410 c = fgetc(fp);
6411 if (c == EOF)
6412 {
6413 eof = TRUE;
6414 break;
6415 }
6416 if (c == '\r')
6417 {
6418 /* Always store a NL for end-of-line. */
6419 if (i < size - 1)
6420 buf[i++] = '\n';
6421 c = fgetc(fp);
6422 if (c != '\n') /* Macintosh format: single CR. */
6423 ungetc(c, fp);
6424 break;
6425 }
6426 if (i < size - 1)
6427 buf[i++] = c;
6428 if (c == '\n')
6429 break;
6430 }
6431 buf[i] = NUL;
6432 return eof;
6433}
6434#endif
6435
6436/*
6437 * rename() only works if both files are on the same file system, this
6438 * function will (attempts to?) copy the file across if rename fails -- webb
6439 * Return -1 for failure, 0 for success.
6440 */
6441 int
6442vim_rename(from, to)
6443 char_u *from;
6444 char_u *to;
6445{
6446 int fd_in;
6447 int fd_out;
6448 int n;
6449 char *errmsg = NULL;
6450 char *buffer;
6451#ifdef AMIGA
6452 BPTR flock;
6453#endif
6454 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006455 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006456#ifdef HAVE_ACL
6457 vim_acl_T acl; /* ACL from original file */
6458#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006459#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6460 int use_tmp_file = FALSE;
6461#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462
6463 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006464 * When the names are identical, there is nothing to do. When they refer
6465 * to the same file (ignoring case and slash/backslash differences) but
6466 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 */
6468 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006469 {
6470#ifdef CASE_INSENSITIVE_FILENAME
6471 if (STRCMP(gettail(from), gettail(to)) != 0)
6472 use_tmp_file = TRUE;
6473 else
6474#endif
6475 return 0;
6476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477
6478 /*
6479 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6480 */
6481 if (mch_stat((char *)from, &st) < 0)
6482 return -1;
6483
Bram Moolenaar3576da72008-12-30 15:15:57 +00006484#ifdef UNIX
6485 {
6486 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006487
6488 /* It's possible for the source and destination to be the same file.
6489 * This happens when "from" and "to" differ in case and are on a FAT32
6490 * filesystem. In that case go through a temp file name. */
6491 if (mch_stat((char *)to, &st_to) >= 0
6492 && st.st_dev == st_to.st_dev
6493 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006494 use_tmp_file = TRUE;
6495 }
6496#endif
6497
6498#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6499 if (use_tmp_file)
6500 {
6501 char tempname[MAXPATHL + 1];
6502
6503 /*
6504 * Find a name that doesn't exist and is in the same directory.
6505 * Rename "from" to "tempname" and then rename "tempname" to "to".
6506 */
6507 if (STRLEN(from) >= MAXPATHL - 5)
6508 return -1;
6509 STRCPY(tempname, from);
6510 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006511 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006512 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6513 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006514 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006515 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006516 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006517 if (mch_rename(tempname, (char *)to) == 0)
6518 return 0;
6519 /* Strange, the second step failed. Try moving the
6520 * file back and return failure. */
6521 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006522 return -1;
6523 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006524 /* If it fails for one temp name it will most likely fail
6525 * for any temp name, give up. */
6526 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006527 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006528 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006529 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006530 }
6531#endif
6532
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 /*
6534 * Delete the "to" file, this is required on some systems to make the
6535 * mch_rename() work, on other systems it makes sure that we don't have
6536 * two files when the mch_rename() fails.
6537 */
6538
6539#ifdef AMIGA
6540 /*
6541 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6542 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006543 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 * deleting the "from" file (horror!) we lock it during the remove.
6545 *
6546 * When used for making a backup before writing the file: This should not
6547 * happen with ":w", because startscript() should detect this problem and
6548 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6549 * name. This problem does exist with ":w filename", but then the
6550 * original file will be somewhere else so the backup isn't really
6551 * important. If autoscripting is off the rename may fail.
6552 */
6553 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6554#endif
6555 mch_remove(to);
6556#ifdef AMIGA
6557 if (flock)
6558 UnLock(flock);
6559#endif
6560
6561 /*
6562 * First try a normal rename, return if it works.
6563 */
6564 if (mch_rename((char *)from, (char *)to) == 0)
6565 return 0;
6566
6567 /*
6568 * Rename() failed, try copying the file.
6569 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006570 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006571#ifdef HAVE_ACL
6572 /* For systems that support ACL: get the ACL from the original file. */
6573 acl = mch_get_acl(from);
6574#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6576 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006577 {
6578#ifdef HAVE_ACL
6579 mch_free_acl(acl);
6580#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006582 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006583
6584 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006585 fd_out = mch_open((char *)to,
6586 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 if (fd_out == -1)
6588 {
6589 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006590#ifdef HAVE_ACL
6591 mch_free_acl(acl);
6592#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 return -1;
6594 }
6595
6596 buffer = (char *)alloc(BUFSIZE);
6597 if (buffer == NULL)
6598 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006600 close(fd_in);
6601#ifdef HAVE_ACL
6602 mch_free_acl(acl);
6603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 return -1;
6605 }
6606
6607 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6608 if (vim_write(fd_out, buffer, n) != n)
6609 {
6610 errmsg = _("E208: Error writing to \"%s\"");
6611 break;
6612 }
6613
6614 vim_free(buffer);
6615 close(fd_in);
6616 if (close(fd_out) < 0)
6617 errmsg = _("E209: Error closing \"%s\"");
6618 if (n < 0)
6619 {
6620 errmsg = _("E210: Error reading \"%s\"");
6621 to = from;
6622 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006623#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006624 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006625#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006626#ifdef HAVE_ACL
6627 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006628 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006629#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 if (errmsg != NULL)
6631 {
6632 EMSG2(errmsg, to);
6633 return -1;
6634 }
6635 mch_remove(from);
6636 return 0;
6637}
6638
6639static int already_warned = FALSE;
6640
6641/*
6642 * Check if any not hidden buffer has been changed.
6643 * Postpone the check if there are characters in the stuff buffer, a global
6644 * command is being executed, a mapping is being executed or an autocommand is
6645 * busy.
6646 * Returns TRUE if some message was written (screen should be redrawn and
6647 * cursor positioned).
6648 */
6649 int
6650check_timestamps(focus)
6651 int focus; /* called for GUI focus event */
6652{
6653 buf_T *buf;
6654 int didit = 0;
6655 int n;
6656
6657 /* Don't check timestamps while system() or another low-level function may
6658 * cause us to lose and gain focus. */
6659 if (no_check_timestamps > 0)
6660 return FALSE;
6661
6662 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6663 * event and we would keep on checking if the file is steadily growing.
6664 * Do check again after typing something. */
6665 if (focus && did_check_timestamps)
6666 {
6667 need_check_timestamps = TRUE;
6668 return FALSE;
6669 }
6670
6671 if (!stuff_empty() || global_busy || !typebuf_typed()
6672#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006673 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674#endif
6675 )
6676 need_check_timestamps = TRUE; /* check later */
6677 else
6678 {
6679 ++no_wait_return;
6680 did_check_timestamps = TRUE;
6681 already_warned = FALSE;
6682 for (buf = firstbuf; buf != NULL; )
6683 {
6684 /* Only check buffers in a window. */
6685 if (buf->b_nwindows > 0)
6686 {
6687 n = buf_check_timestamp(buf, focus);
6688 if (didit < n)
6689 didit = n;
6690 if (n > 0 && !buf_valid(buf))
6691 {
6692 /* Autocommands have removed the buffer, start at the
6693 * first one again. */
6694 buf = firstbuf;
6695 continue;
6696 }
6697 }
6698 buf = buf->b_next;
6699 }
6700 --no_wait_return;
6701 need_check_timestamps = FALSE;
6702 if (need_wait_return && didit == 2)
6703 {
6704 /* make sure msg isn't overwritten */
6705 msg_puts((char_u *)"\n");
6706 out_flush();
6707 }
6708 }
6709 return didit;
6710}
6711
6712/*
6713 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6714 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6715 * empty.
6716 */
6717 static int
6718move_lines(frombuf, tobuf)
6719 buf_T *frombuf;
6720 buf_T *tobuf;
6721{
6722 buf_T *tbuf = curbuf;
6723 int retval = OK;
6724 linenr_T lnum;
6725 char_u *p;
6726
6727 /* Copy the lines in "frombuf" to "tobuf". */
6728 curbuf = tobuf;
6729 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6730 {
6731 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6732 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6733 {
6734 vim_free(p);
6735 retval = FAIL;
6736 break;
6737 }
6738 vim_free(p);
6739 }
6740
6741 /* Delete all the lines in "frombuf". */
6742 if (retval != FAIL)
6743 {
6744 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006745 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6746 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 {
6748 /* Oops! We could try putting back the saved lines, but that
6749 * might fail again... */
6750 retval = FAIL;
6751 break;
6752 }
6753 }
6754
6755 curbuf = tbuf;
6756 return retval;
6757}
6758
6759/*
6760 * Check if buffer "buf" has been changed.
6761 * Also check if the file for a new buffer unexpectedly appeared.
6762 * return 1 if a changed buffer was found.
6763 * return 2 if a message has been displayed.
6764 * return 0 otherwise.
6765 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766 int
6767buf_check_timestamp(buf, focus)
6768 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006769 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770{
6771 struct stat st;
6772 int stat_res;
6773 int retval = 0;
6774 char_u *path;
6775 char_u *tbuf;
6776 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006777 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 int helpmesg = FALSE;
6779 int reload = FALSE;
6780#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6781 int can_reload = FALSE;
6782#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006783 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 int orig_mode = buf->b_orig_mode;
6785#ifdef FEAT_GUI
6786 int save_mouse_correct = need_mouse_correct;
6787#endif
6788#ifdef FEAT_AUTOCMD
6789 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006790 int n;
6791 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006793 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794
6795 /* If there is no file name, the buffer is not loaded, 'buftype' is
6796 * set, we are in the middle of a save or being called recursively: ignore
6797 * this buffer. */
6798 if (buf->b_ffname == NULL
6799 || buf->b_ml.ml_mfp == NULL
6800#if defined(FEAT_QUICKFIX)
6801 || *buf->b_p_bt != NUL
6802#endif
6803 || buf->b_saving
6804#ifdef FEAT_AUTOCMD
6805 || busy
6806#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006807#ifdef FEAT_NETBEANS_INTG
6808 || isNetbeansBuffer(buf)
6809#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 )
6811 return 0;
6812
6813 if ( !(buf->b_flags & BF_NOTEDITED)
6814 && buf->b_mtime != 0
6815 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6816 || time_differs((long)st.st_mtime, buf->b_mtime)
6817#ifdef HAVE_ST_MODE
6818 || (int)st.st_mode != buf->b_orig_mode
6819#else
6820 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6821#endif
6822 ))
6823 {
6824 retval = 1;
6825
Bram Moolenaar316059c2006-01-14 21:18:42 +00006826 /* set b_mtime to stop further warnings (e.g., when executing
6827 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 if (stat_res < 0)
6829 {
6830 buf->b_mtime = 0;
6831 buf->b_orig_size = 0;
6832 buf->b_orig_mode = 0;
6833 }
6834 else
6835 buf_store_time(buf, &st, buf->b_ffname);
6836
6837 /* Don't do anything for a directory. Might contain the file
6838 * explorer. */
6839 if (mch_isdir(buf->b_fname))
6840 ;
6841
6842 /*
6843 * If 'autoread' is set, the buffer has no changes and the file still
6844 * exists, reload the buffer. Use the buffer-local option value if it
6845 * was set, the global option value otherwise.
6846 */
6847 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6848 && !bufIsChanged(buf) && stat_res >= 0)
6849 reload = TRUE;
6850 else
6851 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006852 if (stat_res < 0)
6853 reason = "deleted";
6854 else if (bufIsChanged(buf))
6855 reason = "conflict";
6856 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6857 reason = "changed";
6858 else if (orig_mode != buf->b_orig_mode)
6859 reason = "mode";
6860 else
6861 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006863#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 /*
6865 * Only give the warning if there are no FileChangedShell
6866 * autocommands.
6867 * Avoid being called recursively by setting "busy".
6868 */
6869 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006870# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006871 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6872 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006873# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006874 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6876 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006877 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 busy = FALSE;
6879 if (n)
6880 {
6881 if (!buf_valid(buf))
6882 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006883# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006884 s = get_vim_var_str(VV_FCS_CHOICE);
6885 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6886 reload = TRUE;
6887 else if (STRCMP(s, "ask") == 0)
6888 n = FALSE;
6889 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006890# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006891 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006893 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894#endif
6895 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006896 if (*reason == 'd')
6897 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 else
6899 {
6900 helpmesg = TRUE;
6901#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6902 can_reload = TRUE;
6903#endif
6904 /*
6905 * Check if the file contents really changed to avoid
6906 * giving a warning when only the timestamp was set (e.g.,
6907 * checked out of CVS). Always warn when the buffer was
6908 * changed.
6909 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006910 if (reason[2] == 'n')
6911 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006913 mesg2 = _("See \":help W12\" for more info.");
6914 }
6915 else if (reason[1] == 'h')
6916 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006918 mesg2 = _("See \":help W11\" for more info.");
6919 }
6920 else if (*reason == 'm')
6921 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006923 mesg2 = _("See \":help W16\" for more info.");
6924 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006925 else
6926 /* Only timestamp changed, store it to avoid a warning
6927 * in check_mtime() later. */
6928 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 }
6930 }
6931 }
6932
6933 }
6934 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6935 && vim_fexists(buf->b_ffname))
6936 {
6937 retval = 1;
6938 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6939 buf->b_flags |= BF_NEW_W;
6940#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6941 can_reload = TRUE;
6942#endif
6943 }
6944
6945 if (mesg != NULL)
6946 {
6947 path = home_replace_save(buf, buf->b_fname);
6948 if (path != NULL)
6949 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006950 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 mesg2 = "";
6952 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6953 + STRLEN(mesg2) + 2));
6954 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006955#ifdef FEAT_EVAL
6956 /* Set warningmsg here, before the unimportant and output-specific
6957 * mesg2 has been appended. */
6958 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6959#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6961 if (can_reload)
6962 {
6963 if (*mesg2 != NUL)
6964 {
6965 STRCAT(tbuf, "\n");
6966 STRCAT(tbuf, mesg2);
6967 }
6968 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6969 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6970 reload = TRUE;
6971 }
6972 else
6973#endif
6974 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6975 {
6976 if (*mesg2 != NUL)
6977 {
6978 STRCAT(tbuf, "; ");
6979 STRCAT(tbuf, mesg2);
6980 }
6981 EMSG(tbuf);
6982 retval = 2;
6983 }
6984 else
6985 {
Bram Moolenaared203462004-06-16 11:19:22 +00006986# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006988# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989 {
6990 msg_start();
6991 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6992 if (*mesg2 != NUL)
6993 msg_puts_attr((char_u *)mesg2,
6994 hl_attr(HLF_W) + MSG_HIST);
6995 msg_clr_eos();
6996 (void)msg_end();
6997 if (emsg_silent == 0)
6998 {
6999 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007000# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007002# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 /* give the user some time to think about it */
7004 ui_delay(1000L, TRUE);
7005
7006 /* don't redraw and erase the message */
7007 redraw_cmdline = FALSE;
7008 }
7009 }
7010 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 }
7012
7013 vim_free(path);
7014 vim_free(tbuf);
7015 }
7016 }
7017
7018 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007019 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007020 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021
Bram Moolenaar56718732006-03-15 22:53:57 +00007022#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007023 /* Trigger FileChangedShell when the file was changed in any way. */
7024 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007025 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7026 buf->b_fname, buf->b_fname, FALSE, buf);
7027#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028#ifdef FEAT_GUI
7029 /* restore this in case an autocommand has set it; it would break
7030 * 'mousefocus' */
7031 need_mouse_correct = save_mouse_correct;
7032#endif
7033
7034 return retval;
7035}
7036
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007037/*
7038 * Reload a buffer that is already loaded.
7039 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007040 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7041 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007042 */
7043 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007044buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007045 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007046 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007047{
7048 exarg_T ea;
7049 pos_T old_cursor;
7050 linenr_T old_topline;
7051 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007052 buf_T *savebuf;
7053 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007054 aco_save_T aco;
7055
7056 /* set curwin/curbuf for "buf" and save some things */
7057 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007058
7059 /* We only want to read the text from the file, not reset the syntax
7060 * highlighting, clear marks, diff status, etc. Force the fileformat
7061 * and encoding to be the same. */
7062 if (prep_exarg(&ea, buf) == OK)
7063 {
7064 old_cursor = curwin->w_cursor;
7065 old_topline = curwin->w_topline;
7066
7067 /*
7068 * To behave like when a new file is edited (matters for
7069 * BufReadPost autocommands) we first need to delete the current
7070 * buffer contents. But if reading the file fails we should keep
7071 * the old contents. Can't use memory only, the file might be
7072 * too big. Use a hidden buffer to move the buffer contents to.
7073 */
7074 if (bufempty())
7075 savebuf = NULL;
7076 else
7077 {
7078 /* Allocate a buffer without putting it in the buffer list. */
7079 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007080 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007081 {
7082 /* Open the memline. */
7083 curbuf = savebuf;
7084 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007085 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007086 curbuf = buf;
7087 curwin->w_buffer = buf;
7088 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007089 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007090 || move_lines(buf, savebuf) == FAIL)
7091 {
7092 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7093 buf->b_fname);
7094 saved = FAIL;
7095 }
7096 }
7097
7098 if (saved == OK)
7099 {
7100 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7101#ifdef FEAT_AUTOCMD
7102 keep_filetype = TRUE; /* don't detect 'filetype' */
7103#endif
7104 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7105 (linenr_T)0,
7106 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
7107 {
7108#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7109 if (!aborting())
7110#endif
7111 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007112 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007113 {
7114 /* Put the text back from the save buffer. First
7115 * delete any lines that readfile() added. */
7116 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007117 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007118 break;
7119 (void)move_lines(savebuf, buf);
7120 }
7121 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007122 else if (buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007123 {
7124 /* Mark the buffer as unmodified and free undo info. */
7125 unchanged(buf, TRUE);
7126 u_blockfree(buf);
7127 u_clearall(buf);
7128 }
7129 }
7130 vim_free(ea.cmd);
7131
Bram Moolenaar8424a622006-04-19 21:23:36 +00007132 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133 wipe_buffer(savebuf, FALSE);
7134
7135#ifdef FEAT_DIFF
7136 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007137 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138#endif
7139
7140 /* Restore the topline and cursor position and check it (lines may
7141 * have been removed). */
7142 if (old_topline > curbuf->b_ml.ml_line_count)
7143 curwin->w_topline = curbuf->b_ml.ml_line_count;
7144 else
7145 curwin->w_topline = old_topline;
7146 curwin->w_cursor = old_cursor;
7147 check_cursor();
7148 update_topline();
7149#ifdef FEAT_AUTOCMD
7150 keep_filetype = FALSE;
7151#endif
7152#ifdef FEAT_FOLDING
7153 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007154 win_T *wp;
7155 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007156
7157 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007158 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007159 if (wp->w_buffer == curwin->w_buffer
7160 && !foldmethodIsManual(wp))
7161 foldUpdateAll(wp);
7162 }
7163#endif
7164 /* If the mode didn't change and 'readonly' was set, keep the old
7165 * value; the user probably used the ":view" command. But don't
7166 * reset it, might have had a read error. */
7167 if (orig_mode == curbuf->b_orig_mode)
7168 curbuf->b_p_ro |= old_ro;
7169 }
7170
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007171 /* restore curwin/curbuf and a few other things */
7172 aucmd_restbuf(&aco);
7173 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007174}
7175
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176 void
7177buf_store_time(buf, st, fname)
7178 buf_T *buf;
7179 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007180 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181{
7182 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007183 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184#ifdef HAVE_ST_MODE
7185 buf->b_orig_mode = (int)st->st_mode;
7186#else
7187 buf->b_orig_mode = mch_getperm(fname);
7188#endif
7189}
7190
7191/*
7192 * Adjust the line with missing eol, used for the next write.
7193 * Used for do_filter(), when the input lines for the filter are deleted.
7194 */
7195 void
7196write_lnum_adjust(offset)
7197 linenr_T offset;
7198{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007199 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 write_no_eol_lnum += offset;
7201}
7202
7203#if defined(TEMPDIRNAMES) || defined(PROTO)
7204static long temp_count = 0; /* Temp filename counter. */
7205
7206/*
7207 * Delete the temp directory and all files it contains.
7208 */
7209 void
7210vim_deltempdir()
7211{
7212 char_u **files;
7213 int file_count;
7214 int i;
7215
7216 if (vim_tempdir != NULL)
7217 {
7218 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7219 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7220 EW_DIR|EW_FILE|EW_SILENT) == OK)
7221 {
7222 for (i = 0; i < file_count; ++i)
7223 mch_remove(files[i]);
7224 FreeWild(file_count, files);
7225 }
7226 gettail(NameBuff)[-1] = NUL;
7227 (void)mch_rmdir(NameBuff);
7228
7229 vim_free(vim_tempdir);
7230 vim_tempdir = NULL;
7231 }
7232}
7233#endif
7234
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007235#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007237 * Directory "tempdir" was created. Expand this name to a full path and put
7238 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7239 * "tempdir" must be no longer than MAXPATHL.
7240 */
7241 static void
7242vim_settempdir(tempdir)
7243 char_u *tempdir;
7244{
7245 char_u *buf;
7246
7247 buf = alloc((unsigned)MAXPATHL + 2);
7248 if (buf != NULL)
7249 {
7250 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7251 STRCPY(buf, tempdir);
7252# ifdef __EMX__
7253 if (vim_strchr(buf, '/') != NULL)
7254 STRCAT(buf, "/");
7255 else
7256# endif
7257 add_pathsep(buf);
7258 vim_tempdir = vim_strsave(buf);
7259 vim_free(buf);
7260 }
7261}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007262#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007263
7264/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265 * vim_tempname(): Return a unique name that can be used for a temp file.
7266 *
7267 * The temp file is NOT created.
7268 *
7269 * The returned pointer is to allocated memory.
7270 * The returned pointer is NULL if no valid name was found.
7271 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 char_u *
7273vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007274 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275{
7276#ifdef USE_TMPNAM
7277 char_u itmp[L_tmpnam]; /* use tmpnam() */
7278#else
7279 char_u itmp[TEMPNAMELEN];
7280#endif
7281
7282#ifdef TEMPDIRNAMES
7283 static char *(tempdirs[]) = {TEMPDIRNAMES};
7284 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285# ifndef EEXIST
7286 struct stat st;
7287# endif
7288
7289 /*
7290 * This will create a directory for private use by this instance of Vim.
7291 * This is done once, and the same directory is used for all temp files.
7292 * This method avoids security problems because of symlink attacks et al.
7293 * It's also a bit faster, because we only need to check for an existing
7294 * file when creating the directory and not for each temp file.
7295 */
7296 if (vim_tempdir == NULL)
7297 {
7298 /*
7299 * Try the entries in TEMPDIRNAMES to create the temp directory.
7300 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007301 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007303# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007304 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007305 long nr;
7306 long off;
7307# endif
7308
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309 /* expand $TMP, leave room for "/v1100000/999999999" */
7310 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7311 if (mch_isdir(itmp)) /* directory exists */
7312 {
7313# ifdef __EMX__
7314 /* If $TMP contains a forward slash (perhaps using bash or
7315 * tcsh), don't add a backslash, use a forward slash!
7316 * Adding 2 backslashes didn't work. */
7317 if (vim_strchr(itmp, '/') != NULL)
7318 STRCAT(itmp, "/");
7319 else
7320# endif
7321 add_pathsep(itmp);
7322
Bram Moolenaareaf03392009-11-17 11:08:52 +00007323# ifdef HAVE_MKDTEMP
7324 /* Leave room for filename */
7325 STRCAT(itmp, "vXXXXXX");
7326 if (mkdtemp((char *)itmp) != NULL)
7327 vim_settempdir(itmp);
7328# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 /* Get an arbitrary number of up to 6 digits. When it's
7330 * unlikely that it already exists it will be faster,
7331 * otherwise it doesn't matter. The use of mkdir() avoids any
7332 * security problems because of the predictable number. */
7333 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007334 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335
7336 /* Try up to 10000 different values until we find a name that
7337 * doesn't exist. */
7338 for (off = 0; off < 10000L; ++off)
7339 {
7340 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007341# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007343# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344
Bram Moolenaareaf03392009-11-17 11:08:52 +00007345 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7346# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347 /* If mkdir() does not set errno to EEXIST, check for
7348 * existing file here. There is a race condition then,
7349 * although it's fail-safe. */
7350 if (mch_stat((char *)itmp, &st) >= 0)
7351 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007352# endif
7353# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354 /* Make sure the umask doesn't remove the executable bit.
7355 * "repl" has been reported to use "177". */
7356 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007357# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007359# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362 if (r == 0)
7363 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007364 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365 break;
7366 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007367# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007368 /* If the mkdir() didn't fail because the file/dir exists,
7369 * we probably can't create any dir here, try another
7370 * place. */
7371 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007372# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 break;
7374 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007375# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376 if (vim_tempdir != NULL)
7377 break;
7378 }
7379 }
7380 }
7381
7382 if (vim_tempdir != NULL)
7383 {
7384 /* There is no need to check if the file exists, because we own the
7385 * directory and nobody else creates a file in it. */
7386 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7387 return vim_strsave(itmp);
7388 }
7389
7390 return NULL;
7391
7392#else /* TEMPDIRNAMES */
7393
7394# ifdef WIN3264
7395 char szTempFile[_MAX_PATH + 1];
7396 char buf4[4];
7397 char_u *retval;
7398 char_u *p;
7399
7400 STRCPY(itmp, "");
7401 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7402 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7403 strcpy(buf4, "VIM");
7404 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7405 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7406 return NULL;
7407 /* GetTempFileName() will create the file, we don't want that */
7408 (void)DeleteFile(itmp);
7409
7410 /* Backslashes in a temp file name cause problems when filtering with
7411 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7412 * didn't set 'shellslash'. */
7413 retval = vim_strsave(itmp);
7414 if (*p_shcf == '-' || p_ssl)
7415 for (p = retval; *p; ++p)
7416 if (*p == '\\')
7417 *p = '/';
7418 return retval;
7419
7420# else /* WIN3264 */
7421
7422# ifdef USE_TMPNAM
7423 /* tmpnam() will make its own name */
7424 if (*tmpnam((char *)itmp) == NUL)
7425 return NULL;
7426# else
7427 char_u *p;
7428
7429# ifdef VMS_TEMPNAM
7430 /* mktemp() is not working on VMS. It seems to be
7431 * a do-nothing function. Therefore we use tempnam().
7432 */
7433 sprintf((char *)itmp, "VIM%c", extra_char);
7434 p = (char_u *)tempnam("tmp:", (char *)itmp);
7435 if (p != NULL)
7436 {
7437 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7438 * and VIM will then be unable to find the file later */
7439 STRCPY(itmp, p);
7440 STRCAT(itmp, ".txt");
7441 free(p);
7442 }
7443 else
7444 return NULL;
7445# else
7446 STRCPY(itmp, TEMPNAME);
7447 if ((p = vim_strchr(itmp, '?')) != NULL)
7448 *p = extra_char;
7449 if (mktemp((char *)itmp) == NULL)
7450 return NULL;
7451# endif
7452# endif
7453
7454 return vim_strsave(itmp);
7455# endif /* WIN3264 */
7456#endif /* TEMPDIRNAMES */
7457}
7458
7459#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7460/*
7461 * Convert all backslashes in fname to forward slashes in-place.
7462 */
7463 void
7464forward_slash(fname)
7465 char_u *fname;
7466{
7467 char_u *p;
7468
7469 for (p = fname; *p != NUL; ++p)
7470# ifdef FEAT_MBYTE
7471 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007472 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007473 ++p;
7474 else
7475# endif
7476 if (*p == '\\')
7477 *p = '/';
7478}
7479#endif
7480
7481
7482/*
7483 * Code for automatic commands.
7484 *
7485 * Only included when "FEAT_AUTOCMD" has been defined.
7486 */
7487
7488#if defined(FEAT_AUTOCMD) || defined(PROTO)
7489
7490/*
7491 * The autocommands are stored in a list for each event.
7492 * Autocommands for the same pattern, that are consecutive, are joined
7493 * together, to avoid having to match the pattern too often.
7494 * The result is an array of Autopat lists, which point to AutoCmd lists:
7495 *
7496 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7497 * Autopat.cmds Autopat.cmds
7498 * | |
7499 * V V
7500 * AutoCmd.next AutoCmd.next
7501 * | |
7502 * V V
7503 * AutoCmd.next NULL
7504 * |
7505 * V
7506 * NULL
7507 *
7508 * first_autopat[1] --> Autopat.next --> NULL
7509 * Autopat.cmds
7510 * |
7511 * V
7512 * AutoCmd.next
7513 * |
7514 * V
7515 * NULL
7516 * etc.
7517 *
7518 * The order of AutoCmds is important, this is the order in which they were
7519 * defined and will have to be executed.
7520 */
7521typedef struct AutoCmd
7522{
7523 char_u *cmd; /* The command to be executed (NULL
7524 when command has been removed) */
7525 char nested; /* If autocommands nest here */
7526 char last; /* last command in list */
7527#ifdef FEAT_EVAL
7528 scid_T scriptID; /* script ID where defined */
7529#endif
7530 struct AutoCmd *next; /* Next AutoCmd in list */
7531} AutoCmd;
7532
7533typedef struct AutoPat
7534{
7535 int group; /* group ID */
7536 char_u *pat; /* pattern as typed (NULL when pattern
7537 has been removed) */
7538 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007539 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 char allow_dirs; /* Pattern may match whole path */
7541 char last; /* last pattern for apply_autocmds() */
7542 AutoCmd *cmds; /* list of commands to do */
7543 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007544 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545} AutoPat;
7546
7547static struct event_name
7548{
7549 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007550 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551} event_names[] =
7552{
7553 {"BufAdd", EVENT_BUFADD},
7554 {"BufCreate", EVENT_BUFADD},
7555 {"BufDelete", EVENT_BUFDELETE},
7556 {"BufEnter", EVENT_BUFENTER},
7557 {"BufFilePost", EVENT_BUFFILEPOST},
7558 {"BufFilePre", EVENT_BUFFILEPRE},
7559 {"BufHidden", EVENT_BUFHIDDEN},
7560 {"BufLeave", EVENT_BUFLEAVE},
7561 {"BufNew", EVENT_BUFNEW},
7562 {"BufNewFile", EVENT_BUFNEWFILE},
7563 {"BufRead", EVENT_BUFREADPOST},
7564 {"BufReadCmd", EVENT_BUFREADCMD},
7565 {"BufReadPost", EVENT_BUFREADPOST},
7566 {"BufReadPre", EVENT_BUFREADPRE},
7567 {"BufUnload", EVENT_BUFUNLOAD},
7568 {"BufWinEnter", EVENT_BUFWINENTER},
7569 {"BufWinLeave", EVENT_BUFWINLEAVE},
7570 {"BufWipeout", EVENT_BUFWIPEOUT},
7571 {"BufWrite", EVENT_BUFWRITEPRE},
7572 {"BufWritePost", EVENT_BUFWRITEPOST},
7573 {"BufWritePre", EVENT_BUFWRITEPRE},
7574 {"BufWriteCmd", EVENT_BUFWRITECMD},
7575 {"CmdwinEnter", EVENT_CMDWINENTER},
7576 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007577 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007578 {"CursorHold", EVENT_CURSORHOLD},
7579 {"CursorHoldI", EVENT_CURSORHOLDI},
7580 {"CursorMoved", EVENT_CURSORMOVED},
7581 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7583 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007584 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7585 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7586 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7587 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007588 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 {"FileChangedRO", EVENT_FILECHANGEDRO},
7590 {"FileReadPost", EVENT_FILEREADPOST},
7591 {"FileReadPre", EVENT_FILEREADPRE},
7592 {"FileReadCmd", EVENT_FILEREADCMD},
7593 {"FileType", EVENT_FILETYPE},
7594 {"FileWritePost", EVENT_FILEWRITEPOST},
7595 {"FileWritePre", EVENT_FILEWRITEPRE},
7596 {"FileWriteCmd", EVENT_FILEWRITECMD},
7597 {"FilterReadPost", EVENT_FILTERREADPOST},
7598 {"FilterReadPre", EVENT_FILTERREADPRE},
7599 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7600 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7601 {"FocusGained", EVENT_FOCUSGAINED},
7602 {"FocusLost", EVENT_FOCUSLOST},
7603 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7604 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007605 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007606 {"InsertChange", EVENT_INSERTCHANGE},
7607 {"InsertEnter", EVENT_INSERTENTER},
7608 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007609 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007610 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7611 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007613 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007614 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7615 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007616 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007617 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007618 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619 {"StdinReadPost", EVENT_STDINREADPOST},
7620 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007621 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007622 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007623 {"TabEnter", EVENT_TABENTER},
7624 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 {"TermChanged", EVENT_TERMCHANGED},
7626 {"TermResponse", EVENT_TERMRESPONSE},
7627 {"User", EVENT_USER},
7628 {"VimEnter", EVENT_VIMENTER},
7629 {"VimLeave", EVENT_VIMLEAVE},
7630 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7631 {"WinEnter", EVENT_WINENTER},
7632 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007633 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007634 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635};
7636
7637static AutoPat *first_autopat[NUM_EVENTS] =
7638{
7639 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7640 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7641 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7642 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007643 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7644 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645};
7646
7647/*
7648 * struct used to keep status while executing autocommands for an event.
7649 */
7650typedef struct AutoPatCmd
7651{
7652 AutoPat *curpat; /* next AutoPat to examine */
7653 AutoCmd *nextcmd; /* next AutoCmd to execute */
7654 int group; /* group being used */
7655 char_u *fname; /* fname to match with */
7656 char_u *sfname; /* sfname to match with */
7657 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007658 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007659 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7660 buf is deleted */
7661 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662} AutoPatCmd;
7663
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007664static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007665
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666/*
7667 * augroups stores a list of autocmd group names.
7668 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007669static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7671
7672/*
7673 * The ID of the current group. Group 0 is the default one.
7674 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675static int current_augroup = AUGROUP_DEFAULT;
7676
7677static int au_need_clean = FALSE; /* need to delete marked patterns */
7678
Bram Moolenaar754b5602006-02-09 23:53:20 +00007679static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680static void au_remove_pat __ARGS((AutoPat *ap));
7681static void au_remove_cmds __ARGS((AutoPat *ap));
7682static void au_cleanup __ARGS((void));
7683static int au_new_group __ARGS((char_u *name));
7684static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007685static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7686static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007688static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007690static 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 +00007691static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007692static 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 +00007693static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7694
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007695
Bram Moolenaar754b5602006-02-09 23:53:20 +00007696static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007698static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699
7700/*
7701 * Show the autocommands for one AutoPat.
7702 */
7703 static void
7704show_autocmd(ap, event)
7705 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007706 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707{
7708 AutoCmd *ac;
7709
7710 /* Check for "got_int" (here and at various places below), which is set
7711 * when "q" has been hit for the "--more--" prompt */
7712 if (got_int)
7713 return;
7714 if (ap->pat == NULL) /* pattern has been removed */
7715 return;
7716
7717 msg_putchar('\n');
7718 if (got_int)
7719 return;
7720 if (event != last_event || ap->group != last_group)
7721 {
7722 if (ap->group != AUGROUP_DEFAULT)
7723 {
7724 if (AUGROUP_NAME(ap->group) == NULL)
7725 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7726 else
7727 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7728 msg_puts((char_u *)" ");
7729 }
7730 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7731 last_event = event;
7732 last_group = ap->group;
7733 msg_putchar('\n');
7734 if (got_int)
7735 return;
7736 }
7737 msg_col = 4;
7738 msg_outtrans(ap->pat);
7739
7740 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7741 {
7742 if (ac->cmd != NULL) /* skip removed commands */
7743 {
7744 if (msg_col >= 14)
7745 msg_putchar('\n');
7746 msg_col = 14;
7747 if (got_int)
7748 return;
7749 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007750#ifdef FEAT_EVAL
7751 if (p_verbose > 0)
7752 last_set_msg(ac->scriptID);
7753#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754 if (got_int)
7755 return;
7756 if (ac->next != NULL)
7757 {
7758 msg_putchar('\n');
7759 if (got_int)
7760 return;
7761 }
7762 }
7763 }
7764}
7765
7766/*
7767 * Mark an autocommand pattern for deletion.
7768 */
7769 static void
7770au_remove_pat(ap)
7771 AutoPat *ap;
7772{
7773 vim_free(ap->pat);
7774 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007775 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776 au_need_clean = TRUE;
7777}
7778
7779/*
7780 * Mark all commands for a pattern for deletion.
7781 */
7782 static void
7783au_remove_cmds(ap)
7784 AutoPat *ap;
7785{
7786 AutoCmd *ac;
7787
7788 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7789 {
7790 vim_free(ac->cmd);
7791 ac->cmd = NULL;
7792 }
7793 au_need_clean = TRUE;
7794}
7795
7796/*
7797 * Cleanup autocommands and patterns that have been deleted.
7798 * This is only done when not executing autocommands.
7799 */
7800 static void
7801au_cleanup()
7802{
7803 AutoPat *ap, **prev_ap;
7804 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007805 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806
7807 if (autocmd_busy || !au_need_clean)
7808 return;
7809
7810 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007811 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7812 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813 {
7814 /* loop over all autocommand patterns */
7815 prev_ap = &(first_autopat[(int)event]);
7816 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7817 {
7818 /* loop over all commands for this pattern */
7819 prev_ac = &(ap->cmds);
7820 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7821 {
7822 /* remove the command if the pattern is to be deleted or when
7823 * the command has been marked for deletion */
7824 if (ap->pat == NULL || ac->cmd == NULL)
7825 {
7826 *prev_ac = ac->next;
7827 vim_free(ac->cmd);
7828 vim_free(ac);
7829 }
7830 else
7831 prev_ac = &(ac->next);
7832 }
7833
7834 /* remove the pattern if it has been marked for deletion */
7835 if (ap->pat == NULL)
7836 {
7837 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007838 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007839 vim_free(ap);
7840 }
7841 else
7842 prev_ap = &(ap->next);
7843 }
7844 }
7845
7846 au_need_clean = FALSE;
7847}
7848
7849/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007850 * Called when buffer is freed, to remove/invalidate related buffer-local
7851 * autocmds.
7852 */
7853 void
7854aubuflocal_remove(buf)
7855 buf_T *buf;
7856{
7857 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007858 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007859 AutoPatCmd *apc;
7860
7861 /* invalidate currently executing autocommands */
7862 for (apc = active_apc_list; apc; apc = apc->next)
7863 if (buf->b_fnum == apc->arg_bufnr)
7864 apc->arg_bufnr = 0;
7865
7866 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007867 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7868 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007869 /* loop over all autocommand patterns */
7870 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7871 if (ap->buflocal_nr == buf->b_fnum)
7872 {
7873 au_remove_pat(ap);
7874 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007875 {
7876 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007877 smsg((char_u *)
7878 _("auto-removing autocommand: %s <buffer=%d>"),
7879 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007880 verbose_leave();
7881 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007882 }
7883 au_cleanup();
7884}
7885
7886/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887 * Add an autocmd group name.
7888 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7889 */
7890 static int
7891au_new_group(name)
7892 char_u *name;
7893{
7894 int i;
7895
7896 i = au_find_group(name);
7897 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7898 {
7899 /* First try using a free entry. */
7900 for (i = 0; i < augroups.ga_len; ++i)
7901 if (AUGROUP_NAME(i) == NULL)
7902 break;
7903 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7904 return AUGROUP_ERROR;
7905
7906 AUGROUP_NAME(i) = vim_strsave(name);
7907 if (AUGROUP_NAME(i) == NULL)
7908 return AUGROUP_ERROR;
7909 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007910 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911 }
7912
7913 return i;
7914}
7915
7916 static void
7917au_del_group(name)
7918 char_u *name;
7919{
7920 int i;
7921
7922 i = au_find_group(name);
7923 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7924 EMSG2(_("E367: No such group: \"%s\""), name);
7925 else
7926 {
7927 vim_free(AUGROUP_NAME(i));
7928 AUGROUP_NAME(i) = NULL;
7929 }
7930}
7931
7932/*
7933 * Find the ID of an autocmd group name.
7934 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7935 */
7936 static int
7937au_find_group(name)
7938 char_u *name;
7939{
7940 int i;
7941
7942 for (i = 0; i < augroups.ga_len; ++i)
7943 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7944 return i;
7945 return AUGROUP_ERROR;
7946}
7947
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007948/*
7949 * Return TRUE if augroup "name" exists.
7950 */
7951 int
7952au_has_group(name)
7953 char_u *name;
7954{
7955 return au_find_group(name) != AUGROUP_ERROR;
7956}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007957
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958/*
7959 * ":augroup {name}".
7960 */
7961 void
7962do_augroup(arg, del_group)
7963 char_u *arg;
7964 int del_group;
7965{
7966 int i;
7967
7968 if (del_group)
7969 {
7970 if (*arg == NUL)
7971 EMSG(_(e_argreq));
7972 else
7973 au_del_group(arg);
7974 }
7975 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
7976 current_augroup = AUGROUP_DEFAULT;
7977 else if (*arg) /* ":aug xxx": switch to group xxx */
7978 {
7979 i = au_new_group(arg);
7980 if (i != AUGROUP_ERROR)
7981 current_augroup = i;
7982 }
7983 else /* ":aug": list the group names */
7984 {
7985 msg_start();
7986 for (i = 0; i < augroups.ga_len; ++i)
7987 {
7988 if (AUGROUP_NAME(i) != NULL)
7989 {
7990 msg_puts(AUGROUP_NAME(i));
7991 msg_puts((char_u *)" ");
7992 }
7993 }
7994 msg_clr_eos();
7995 msg_end();
7996 }
7997}
7998
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007999#if defined(EXITFREE) || defined(PROTO)
8000 void
8001free_all_autocmds()
8002{
8003 for (current_augroup = -1; current_augroup < augroups.ga_len;
8004 ++current_augroup)
8005 do_autocmd((char_u *)"", TRUE);
8006 ga_clear_strings(&augroups);
8007}
8008#endif
8009
Bram Moolenaar071d4272004-06-13 20:20:40 +00008010/*
8011 * Return the event number for event name "start".
8012 * Return NUM_EVENTS if the event name was not found.
8013 * Return a pointer to the next event name in "end".
8014 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008015 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016event_name2nr(start, end)
8017 char_u *start;
8018 char_u **end;
8019{
8020 char_u *p;
8021 int i;
8022 int len;
8023
8024 /* the event name ends with end of line, a blank or a comma */
8025 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8026 ;
8027 for (i = 0; event_names[i].name != NULL; ++i)
8028 {
8029 len = (int)STRLEN(event_names[i].name);
8030 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8031 break;
8032 }
8033 if (*p == ',')
8034 ++p;
8035 *end = p;
8036 if (event_names[i].name == NULL)
8037 return NUM_EVENTS;
8038 return event_names[i].event;
8039}
8040
8041/*
8042 * Return the name for event "event".
8043 */
8044 static char_u *
8045event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008046 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008047{
8048 int i;
8049
8050 for (i = 0; event_names[i].name != NULL; ++i)
8051 if (event_names[i].event == event)
8052 return (char_u *)event_names[i].name;
8053 return (char_u *)"Unknown";
8054}
8055
8056/*
8057 * Scan over the events. "*" stands for all events.
8058 */
8059 static char_u *
8060find_end_event(arg, have_group)
8061 char_u *arg;
8062 int have_group; /* TRUE when group name was found */
8063{
8064 char_u *pat;
8065 char_u *p;
8066
8067 if (*arg == '*')
8068 {
8069 if (arg[1] && !vim_iswhite(arg[1]))
8070 {
8071 EMSG2(_("E215: Illegal character after *: %s"), arg);
8072 return NULL;
8073 }
8074 pat = arg + 1;
8075 }
8076 else
8077 {
8078 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8079 {
8080 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8081 {
8082 if (have_group)
8083 EMSG2(_("E216: No such event: %s"), pat);
8084 else
8085 EMSG2(_("E216: No such group or event: %s"), pat);
8086 return NULL;
8087 }
8088 }
8089 }
8090 return pat;
8091}
8092
8093/*
8094 * Return TRUE if "event" is included in 'eventignore'.
8095 */
8096 static int
8097event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008098 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008099{
8100 char_u *p = p_ei;
8101
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008102 while (*p != NUL)
8103 {
8104 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8105 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008106 if (event_name2nr(p, &p) == event)
8107 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008108 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008109
8110 return FALSE;
8111}
8112
8113/*
8114 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8115 */
8116 int
8117check_ei()
8118{
8119 char_u *p = p_ei;
8120
Bram Moolenaar071d4272004-06-13 20:20:40 +00008121 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008122 {
8123 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8124 {
8125 p += 3;
8126 if (*p == ',')
8127 ++p;
8128 }
8129 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008130 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008131 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008132
8133 return OK;
8134}
8135
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008136# if defined(FEAT_SYN_HL) || defined(PROTO)
8137
8138/*
8139 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8140 * buffer loaded into the window. "what" must start with a comma.
8141 * Returns the old value of 'eventignore' in allocated memory.
8142 */
8143 char_u *
8144au_event_disable(what)
8145 char *what;
8146{
8147 char_u *new_ei;
8148 char_u *save_ei;
8149
8150 save_ei = vim_strsave(p_ei);
8151 if (save_ei != NULL)
8152 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008153 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008154 if (new_ei != NULL)
8155 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008156 if (*what == ',' && *p_ei == NUL)
8157 STRCPY(new_ei, what + 1);
8158 else
8159 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008160 set_string_option_direct((char_u *)"ei", -1, new_ei,
8161 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008162 vim_free(new_ei);
8163 }
8164 }
8165 return save_ei;
8166}
8167
8168 void
8169au_event_restore(old_ei)
8170 char_u *old_ei;
8171{
8172 if (old_ei != NULL)
8173 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008174 set_string_option_direct((char_u *)"ei", -1, old_ei,
8175 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008176 vim_free(old_ei);
8177 }
8178}
8179# endif /* FEAT_SYN_HL */
8180
Bram Moolenaar071d4272004-06-13 20:20:40 +00008181/*
8182 * do_autocmd() -- implements the :autocmd command. Can be used in the
8183 * following ways:
8184 *
8185 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8186 * will be automatically executed for <event>
8187 * when editing a file matching <pat>, in
8188 * the current group.
8189 * :autocmd <event> <pat> Show the auto-commands associated with
8190 * <event> and <pat>.
8191 * :autocmd <event> Show the auto-commands associated with
8192 * <event>.
8193 * :autocmd Show all auto-commands.
8194 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8195 * <event> and <pat>, and add the command
8196 * <cmd>, for the current group.
8197 * :autocmd! <event> <pat> Remove all auto-commands associated with
8198 * <event> and <pat> for the current group.
8199 * :autocmd! <event> Remove all auto-commands associated with
8200 * <event> for the current group.
8201 * :autocmd! Remove ALL auto-commands for the current
8202 * group.
8203 *
8204 * Multiple events and patterns may be given separated by commas. Here are
8205 * some examples:
8206 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8207 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8208 *
8209 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008210 *
8211 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008212 */
8213 void
8214do_autocmd(arg, forceit)
8215 char_u *arg;
8216 int forceit;
8217{
8218 char_u *pat;
8219 char_u *envpat = NULL;
8220 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008221 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008222 int need_free = FALSE;
8223 int nested = FALSE;
8224 int group;
8225
8226 /*
8227 * Check for a legal group name. If not, use AUGROUP_ALL.
8228 */
8229 group = au_get_grouparg(&arg);
8230 if (arg == NULL) /* out of memory */
8231 return;
8232
8233 /*
8234 * Scan over the events.
8235 * If we find an illegal name, return here, don't do anything.
8236 */
8237 pat = find_end_event(arg, group != AUGROUP_ALL);
8238 if (pat == NULL)
8239 return;
8240
8241 /*
8242 * Scan over the pattern. Put a NUL at the end.
8243 */
8244 pat = skipwhite(pat);
8245 cmd = pat;
8246 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8247 cmd++;
8248 if (*cmd)
8249 *cmd++ = NUL;
8250
8251 /* Expand environment variables in the pattern. Set 'shellslash', we want
8252 * forward slashes here. */
8253 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8254 {
8255#ifdef BACKSLASH_IN_FILENAME
8256 int p_ssl_save = p_ssl;
8257
8258 p_ssl = TRUE;
8259#endif
8260 envpat = expand_env_save(pat);
8261#ifdef BACKSLASH_IN_FILENAME
8262 p_ssl = p_ssl_save;
8263#endif
8264 if (envpat != NULL)
8265 pat = envpat;
8266 }
8267
8268 /*
8269 * Check for "nested" flag.
8270 */
8271 cmd = skipwhite(cmd);
8272 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8273 {
8274 nested = TRUE;
8275 cmd = skipwhite(cmd + 6);
8276 }
8277
8278 /*
8279 * Find the start of the commands.
8280 * Expand <sfile> in it.
8281 */
8282 if (*cmd != NUL)
8283 {
8284 cmd = expand_sfile(cmd);
8285 if (cmd == NULL) /* some error */
8286 return;
8287 need_free = TRUE;
8288 }
8289
8290 /*
8291 * Print header when showing autocommands.
8292 */
8293 if (!forceit && *cmd == NUL)
8294 {
8295 /* Highlight title */
8296 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8297 }
8298
8299 /*
8300 * Loop over the events.
8301 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008302 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303 last_group = AUGROUP_ERROR; /* for listing the group name */
8304 if (*arg == '*' || *arg == NUL)
8305 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008306 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8307 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 if (do_autocmd_event(event, pat,
8309 nested, cmd, forceit, group) == FAIL)
8310 break;
8311 }
8312 else
8313 {
8314 while (*arg && !vim_iswhite(*arg))
8315 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8316 nested, cmd, forceit, group) == FAIL)
8317 break;
8318 }
8319
8320 if (need_free)
8321 vim_free(cmd);
8322 vim_free(envpat);
8323}
8324
8325/*
8326 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8327 * The "argp" argument is advanced to the following argument.
8328 *
8329 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8330 */
8331 static int
8332au_get_grouparg(argp)
8333 char_u **argp;
8334{
8335 char_u *group_name;
8336 char_u *p;
8337 char_u *arg = *argp;
8338 int group = AUGROUP_ALL;
8339
8340 p = skiptowhite(arg);
8341 if (p > arg)
8342 {
8343 group_name = vim_strnsave(arg, (int)(p - arg));
8344 if (group_name == NULL) /* out of memory */
8345 return AUGROUP_ERROR;
8346 group = au_find_group(group_name);
8347 if (group == AUGROUP_ERROR)
8348 group = AUGROUP_ALL; /* no match, use all groups */
8349 else
8350 *argp = skipwhite(p); /* match, skip over group name */
8351 vim_free(group_name);
8352 }
8353 return group;
8354}
8355
8356/*
8357 * do_autocmd() for one event.
8358 * If *pat == NUL do for all patterns.
8359 * If *cmd == NUL show entries.
8360 * If forceit == TRUE delete entries.
8361 * If group is not AUGROUP_ALL, only use this group.
8362 */
8363 static int
8364do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008365 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008366 char_u *pat;
8367 int nested;
8368 char_u *cmd;
8369 int forceit;
8370 int group;
8371{
8372 AutoPat *ap;
8373 AutoPat **prev_ap;
8374 AutoCmd *ac;
8375 AutoCmd **prev_ac;
8376 int brace_level;
8377 char_u *endpat;
8378 int findgroup;
8379 int allgroups;
8380 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008381 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008382 int buflocal_nr;
8383 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384
8385 if (group == AUGROUP_ALL)
8386 findgroup = current_augroup;
8387 else
8388 findgroup = group;
8389 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8390
8391 /*
8392 * Show or delete all patterns for an event.
8393 */
8394 if (*pat == NUL)
8395 {
8396 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8397 {
8398 if (forceit) /* delete the AutoPat, if it's in the current group */
8399 {
8400 if (ap->group == findgroup)
8401 au_remove_pat(ap);
8402 }
8403 else if (group == AUGROUP_ALL || ap->group == group)
8404 show_autocmd(ap, event);
8405 }
8406 }
8407
8408 /*
8409 * Loop through all the specified patterns.
8410 */
8411 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8412 {
8413 /*
8414 * Find end of the pattern.
8415 * Watch out for a comma in braces, like "*.\{obj,o\}".
8416 */
8417 brace_level = 0;
8418 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8419 || endpat[-1] == '\\'); ++endpat)
8420 {
8421 if (*endpat == '{')
8422 brace_level++;
8423 else if (*endpat == '}')
8424 brace_level--;
8425 }
8426 if (pat == endpat) /* ignore single comma */
8427 continue;
8428 patlen = (int)(endpat - pat);
8429
8430 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008431 * detect special <buflocal[=X]> buffer-local patterns
8432 */
8433 is_buflocal = FALSE;
8434 buflocal_nr = 0;
8435
8436 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8437 && pat[patlen - 1] == '>')
8438 {
8439 /* Error will be printed only for addition. printing and removing
8440 * will proceed silently. */
8441 is_buflocal = TRUE;
8442 if (patlen == 8)
8443 buflocal_nr = curbuf->b_fnum;
8444 else if (patlen > 9 && pat[7] == '=')
8445 {
8446 /* <buffer=abuf> */
8447 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8448 buflocal_nr = autocmd_bufnr;
8449 /* <buffer=123> */
8450 else if (skipdigits(pat + 8) == pat + patlen - 1)
8451 buflocal_nr = atoi((char *)pat + 8);
8452 }
8453 }
8454
8455 if (is_buflocal)
8456 {
8457 /* normalize pat into standard "<buffer>#N" form */
8458 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8459 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008460 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008461 }
8462
8463 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008464 * Find AutoPat entries with this pattern.
8465 */
8466 prev_ap = &first_autopat[(int)event];
8467 while ((ap = *prev_ap) != NULL)
8468 {
8469 if (ap->pat != NULL)
8470 {
8471 /* Accept a pattern when:
8472 * - a group was specified and it's that group, or a group was
8473 * not specified and it's the current group, or a group was
8474 * not specified and we are listing
8475 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008476 * - the pattern matches.
8477 * For <buffer[=X]>, this condition works because we normalize
8478 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008479 */
8480 if ((allgroups || ap->group == findgroup)
8481 && ap->patlen == patlen
8482 && STRNCMP(pat, ap->pat, patlen) == 0)
8483 {
8484 /*
8485 * Remove existing autocommands.
8486 * If adding any new autocmd's for this AutoPat, don't
8487 * delete the pattern from the autopat list, append to
8488 * this list.
8489 */
8490 if (forceit)
8491 {
8492 if (*cmd != NUL && ap->next == NULL)
8493 {
8494 au_remove_cmds(ap);
8495 break;
8496 }
8497 au_remove_pat(ap);
8498 }
8499
8500 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008501 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008502 */
8503 else if (*cmd == NUL)
8504 show_autocmd(ap, event);
8505
8506 /*
8507 * Add autocmd to this autopat, if it's the last one.
8508 */
8509 else if (ap->next == NULL)
8510 break;
8511 }
8512 }
8513 prev_ap = &ap->next;
8514 }
8515
8516 /*
8517 * Add a new command.
8518 */
8519 if (*cmd != NUL)
8520 {
8521 /*
8522 * If the pattern we want to add a command to does appear at the
8523 * end of the list (or not is not in the list at all), add the
8524 * pattern at the end of the list.
8525 */
8526 if (ap == NULL)
8527 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008528 /* refuse to add buffer-local ap if buffer number is invalid */
8529 if (is_buflocal && (buflocal_nr == 0
8530 || buflist_findnr(buflocal_nr) == NULL))
8531 {
8532 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8533 buflocal_nr);
8534 return FAIL;
8535 }
8536
Bram Moolenaar071d4272004-06-13 20:20:40 +00008537 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8538 if (ap == NULL)
8539 return FAIL;
8540 ap->pat = vim_strnsave(pat, patlen);
8541 ap->patlen = patlen;
8542 if (ap->pat == NULL)
8543 {
8544 vim_free(ap);
8545 return FAIL;
8546 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008547
8548 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008549 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008550 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008551 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008552 }
8553 else
8554 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008555 char_u *reg_pat;
8556
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008557 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008558 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008559 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008560 if (reg_pat != NULL)
8561 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008562 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008563 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008564 {
8565 vim_free(ap->pat);
8566 vim_free(ap);
8567 return FAIL;
8568 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008569 }
8570 ap->cmds = NULL;
8571 *prev_ap = ap;
8572 ap->next = NULL;
8573 if (group == AUGROUP_ALL)
8574 ap->group = current_augroup;
8575 else
8576 ap->group = group;
8577 }
8578
8579 /*
8580 * Add the autocmd at the end of the AutoCmd list.
8581 */
8582 prev_ac = &(ap->cmds);
8583 while ((ac = *prev_ac) != NULL)
8584 prev_ac = &ac->next;
8585 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8586 if (ac == NULL)
8587 return FAIL;
8588 ac->cmd = vim_strsave(cmd);
8589#ifdef FEAT_EVAL
8590 ac->scriptID = current_SID;
8591#endif
8592 if (ac->cmd == NULL)
8593 {
8594 vim_free(ac);
8595 return FAIL;
8596 }
8597 ac->next = NULL;
8598 *prev_ac = ac;
8599 ac->nested = nested;
8600 }
8601 }
8602
8603 au_cleanup(); /* may really delete removed patterns/commands now */
8604 return OK;
8605}
8606
8607/*
8608 * Implementation of ":doautocmd [group] event [fname]".
8609 * Return OK for success, FAIL for failure;
8610 */
8611 int
8612do_doautocmd(arg, do_msg)
8613 char_u *arg;
8614 int do_msg; /* give message for no matching autocmds? */
8615{
8616 char_u *fname;
8617 int nothing_done = TRUE;
8618 int group;
8619
8620 /*
8621 * Check for a legal group name. If not, use AUGROUP_ALL.
8622 */
8623 group = au_get_grouparg(&arg);
8624 if (arg == NULL) /* out of memory */
8625 return FAIL;
8626
8627 if (*arg == '*')
8628 {
8629 EMSG(_("E217: Can't execute autocommands for ALL events"));
8630 return FAIL;
8631 }
8632
8633 /*
8634 * Scan over the events.
8635 * If we find an illegal name, return here, don't do anything.
8636 */
8637 fname = find_end_event(arg, group != AUGROUP_ALL);
8638 if (fname == NULL)
8639 return FAIL;
8640
8641 fname = skipwhite(fname);
8642
8643 /*
8644 * Loop over the events.
8645 */
8646 while (*arg && !vim_iswhite(*arg))
8647 if (apply_autocmds_group(event_name2nr(arg, &arg),
8648 fname, NULL, TRUE, group, curbuf, NULL))
8649 nothing_done = FALSE;
8650
8651 if (nothing_done && do_msg)
8652 MSG(_("No matching autocommands"));
8653
8654#ifdef FEAT_EVAL
8655 return aborting() ? FAIL : OK;
8656#else
8657 return OK;
8658#endif
8659}
8660
8661/*
8662 * ":doautoall": execute autocommands for each loaded buffer.
8663 */
8664 void
8665ex_doautoall(eap)
8666 exarg_T *eap;
8667{
8668 int retval;
8669 aco_save_T aco;
8670 buf_T *buf;
8671
8672 /*
8673 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8674 * equal to curbuf, but for some buffers there may not be a window.
8675 * So we change the buffer for the current window for a moment. This
8676 * gives problems when the autocommands make changes to the list of
8677 * buffers or windows...
8678 */
8679 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8680 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008681 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008682 {
8683 /* find a window for this buffer and save some values */
8684 aucmd_prepbuf(&aco, buf);
8685
8686 /* execute the autocommands for this buffer */
8687 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008688
8689 /* Execute the modeline settings, but don't set window-local
8690 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008691 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008692
8693 /* restore the current window */
8694 aucmd_restbuf(&aco);
8695
8696 /* stop if there is some error or buffer was deleted */
8697 if (retval == FAIL || !buf_valid(buf))
8698 break;
8699 }
8700 }
8701
8702 check_cursor(); /* just in case lines got deleted */
8703}
8704
8705/*
8706 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008707 * Search for a visible window containing the current buffer. If there isn't
8708 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008709 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008710 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008711 */
8712 void
8713aucmd_prepbuf(aco, buf)
8714 aco_save_T *aco; /* structure to save values in */
8715 buf_T *buf; /* new curbuf */
8716{
8717 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008718#ifdef FEAT_WINDOWS
8719 int save_ea;
8720#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008721
8722 /* Find a window that is for the new buffer */
8723 if (buf == curbuf) /* be quick when buf is curbuf */
8724 win = curwin;
8725 else
8726#ifdef FEAT_WINDOWS
8727 for (win = firstwin; win != NULL; win = win->w_next)
8728 if (win->w_buffer == buf)
8729 break;
8730#else
8731 win = NULL;
8732#endif
8733
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008734 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8735 * back to using the current window. */
8736 if (win == NULL && aucmd_win == NULL)
8737 {
8738 win_alloc_aucmd_win();
8739 if (aucmd_win == NULL)
8740 win = curwin;
8741 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008742 if (win == NULL && aucmd_win_used)
8743 /* Strange recursive autocommand, fall back to using the current
8744 * window. Expect a few side effects... */
8745 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008746
8747 aco->save_curwin = curwin;
8748 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008749 if (win != NULL)
8750 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008751 /* There is a window for "buf" in the current tab page, make it the
8752 * curwin. This is preferred, it has the least side effects (esp. if
8753 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008754 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008755 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008756 }
8757 else
8758 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008759 /* There is no window for "buf", use "aucmd_win". To minimize the side
8760 * effects, insert it in a the current tab page.
8761 * Anything related to a window (e.g., setting folds) may have
8762 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008763 aco->use_aucmd_win = TRUE;
8764 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008765 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008766 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008767 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008768 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008769 vim_free(aucmd_win->w_localdir);
8770 aucmd_win->w_localdir = NULL;
8771
8772 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8773 * win_enter_ext(). */
8774 aucmd_win->w_localdir = NULL;
8775 aco->globaldir = globaldir;
8776 globaldir = NULL;
8777
Bram Moolenaar071d4272004-06-13 20:20:40 +00008778
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008779#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008780 /* Split the current window, put the aucmd_win in the upper half.
8781 * We don't want the BufEnter or WinEnter autocommands. */
8782 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008783 make_snapshot(SNAP_AUCMD_IDX);
8784 save_ea = p_ea;
8785 p_ea = FALSE;
8786 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8787 (void)win_comp_pos(); /* recompute window positions */
8788 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008789 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008790#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008791 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008793 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008794 aco->new_curwin = curwin;
8795 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008796}
8797
8798/*
8799 * Cleanup after executing autocommands for a (hidden) buffer.
8800 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008801 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008802 */
8803 void
8804aucmd_restbuf(aco)
8805 aco_save_T *aco; /* structure holding saved values */
8806{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008807#ifdef FEAT_WINDOWS
8808 int dummy;
8809#endif
8810
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008811 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008812 {
8813 --curbuf->b_nwindows;
8814#ifdef FEAT_WINDOWS
8815 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008816 * page. Do not trigger autocommands here. */
8817 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008818 if (curwin != aucmd_win)
8819 {
8820 tabpage_T *tp;
8821 win_T *wp;
8822
8823 FOR_ALL_TAB_WINDOWS(tp, wp)
8824 {
8825 if (wp == aucmd_win)
8826 {
8827 if (tp != curtab)
8828 goto_tabpage_tp(tp);
8829 win_goto(aucmd_win);
8830 break;
8831 }
8832 }
8833 }
8834
8835 /* Remove the window and frame from the tree of frames. */
8836 (void)winframe_remove(curwin, &dummy, NULL);
8837 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008838 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008839 last_status(FALSE); /* may need to remove last status line */
8840 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8841 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008842 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008843
8844 if (win_valid(aco->save_curwin))
8845 curwin = aco->save_curwin;
8846 else
8847 /* Hmm, original window disappeared. Just use the first one. */
8848 curwin = firstwin;
8849# ifdef FEAT_EVAL
8850 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008851 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008852# endif
8853#else
8854 curwin = aco->save_curwin;
8855#endif
8856 curbuf = curwin->w_buffer;
8857
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008858 vim_free(globaldir);
8859 globaldir = aco->globaldir;
8860
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008861 /* the buffer contents may have changed */
8862 check_cursor();
8863 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8864 {
8865 curwin->w_topline = curbuf->b_ml.ml_line_count;
8866#ifdef FEAT_DIFF
8867 curwin->w_topfill = 0;
8868#endif
8869 }
8870#if defined(FEAT_GUI)
8871 /* Hide the scrollbars from the aucmd_win and update. */
8872 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8873 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8874 gui_may_update_scrollbars();
8875#endif
8876 }
8877 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008878 {
8879 /* restore curwin */
8880#ifdef FEAT_WINDOWS
8881 if (win_valid(aco->save_curwin))
8882#endif
8883 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008884 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008885 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008886 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008887 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008888 && curbuf != aco->new_curbuf
8889 && buf_valid(aco->new_curbuf)
8890 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008891 {
8892 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008893 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008894 curwin->w_buffer = curbuf;
8895 ++curbuf->b_nwindows;
8896 }
8897
8898 curwin = aco->save_curwin;
8899 curbuf = curwin->w_buffer;
8900 }
8901 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902}
8903
8904static int autocmd_nested = FALSE;
8905
8906/*
8907 * Execute autocommands for "event" and file name "fname".
8908 * Return TRUE if some commands were executed.
8909 */
8910 int
8911apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008912 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008913 char_u *fname; /* NULL or empty means use actual file name */
8914 char_u *fname_io; /* fname to use for <afile> on cmdline */
8915 int force; /* when TRUE, ignore autocmd_busy */
8916 buf_T *buf; /* buffer for <abuf> */
8917{
8918 return apply_autocmds_group(event, fname, fname_io, force,
8919 AUGROUP_ALL, buf, NULL);
8920}
8921
8922/*
8923 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8924 * setting v:filearg.
8925 */
8926 static int
8927apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008928 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929 char_u *fname;
8930 char_u *fname_io;
8931 int force;
8932 buf_T *buf;
8933 exarg_T *eap;
8934{
8935 return apply_autocmds_group(event, fname, fname_io, force,
8936 AUGROUP_ALL, buf, eap);
8937}
8938
8939/*
8940 * Like apply_autocmds(), but handles the caller's retval. If the script
8941 * processing is being aborted or if retval is FAIL when inside a try
8942 * conditional, no autocommands are executed. If otherwise the autocommands
8943 * cause the script to be aborted, retval is set to FAIL.
8944 */
8945 int
8946apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008947 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008948 char_u *fname; /* NULL or empty means use actual file name */
8949 char_u *fname_io; /* fname to use for <afile> on cmdline */
8950 int force; /* when TRUE, ignore autocmd_busy */
8951 buf_T *buf; /* buffer for <abuf> */
8952 int *retval; /* pointer to caller's retval */
8953{
8954 int did_cmd;
8955
Bram Moolenaar1e015462005-09-25 22:16:38 +00008956#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008957 if (should_abort(*retval))
8958 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00008959#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008960
8961 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8962 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008963 if (did_cmd
8964#ifdef FEAT_EVAL
8965 && aborting()
8966#endif
8967 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008968 *retval = FAIL;
8969 return did_cmd;
8970}
8971
Bram Moolenaard35f9712005-12-18 22:02:33 +00008972/*
8973 * Return TRUE when there is a CursorHold autocommand defined.
8974 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975 int
8976has_cursorhold()
8977{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008978 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
8979 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008980}
Bram Moolenaard35f9712005-12-18 22:02:33 +00008981
8982/*
8983 * Return TRUE if the CursorHold event can be triggered.
8984 */
8985 int
8986trigger_cursorhold()
8987{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008988 int state;
8989
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00008990 if (!did_cursorhold && has_cursorhold() && !Recording
8991#ifdef FEAT_INS_EXPAND
8992 && !ins_compl_active()
8993#endif
8994 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00008995 {
8996 state = get_real_state();
8997 if (state == NORMAL_BUSY || (state & INSERT) != 0)
8998 return TRUE;
8999 }
9000 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009001}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009002
9003/*
9004 * Return TRUE when there is a CursorMoved autocommand defined.
9005 */
9006 int
9007has_cursormoved()
9008{
9009 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9010}
9011
9012/*
9013 * Return TRUE when there is a CursorMovedI autocommand defined.
9014 */
9015 int
9016has_cursormovedI()
9017{
9018 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9019}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009020
9021 static int
9022apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009023 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009024 char_u *fname; /* NULL or empty means use actual file name */
9025 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9026 use fname */
9027 int force; /* when TRUE, ignore autocmd_busy */
9028 int group; /* group ID, or AUGROUP_ALL */
9029 buf_T *buf; /* buffer for <abuf> */
9030 exarg_T *eap; /* command arguments */
9031{
9032 char_u *sfname = NULL; /* short file name */
9033 char_u *tail;
9034 int save_changed;
9035 buf_T *old_curbuf;
9036 int retval = FALSE;
9037 char_u *save_sourcing_name;
9038 linenr_T save_sourcing_lnum;
9039 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009040 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009041 int save_autocmd_bufnr;
9042 char_u *save_autocmd_match;
9043 int save_autocmd_busy;
9044 int save_autocmd_nested;
9045 static int nesting = 0;
9046 AutoPatCmd patcmd;
9047 AutoPat *ap;
9048#ifdef FEAT_EVAL
9049 scid_T save_current_SID;
9050 void *save_funccalp;
9051 char_u *save_cmdarg;
9052 long save_cmdbang;
9053#endif
9054 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009055#ifdef FEAT_PROFILE
9056 proftime_T wait_time;
9057#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009058
9059 /*
9060 * Quickly return if there are no autocommands for this event or
9061 * autocommands are blocked.
9062 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009063 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009064 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009065
9066 /*
9067 * When autocommands are busy, new autocommands are only executed when
9068 * explicitly enabled with the "nested" flag.
9069 */
9070 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009071 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009072
9073#ifdef FEAT_EVAL
9074 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009075 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076 * occurred or an exception was thrown but not caught.
9077 */
9078 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009079 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080#endif
9081
9082 /*
9083 * FileChangedShell never nests, because it can create an endless loop.
9084 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009085 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9086 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009087 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088
9089 /*
9090 * Ignore events in 'eventignore'.
9091 */
9092 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009093 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009094
9095 /*
9096 * Allow nesting of autocommands, but restrict the depth, because it's
9097 * possible to create an endless loop.
9098 */
9099 if (nesting == 10)
9100 {
9101 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009102 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009103 }
9104
9105 /*
9106 * Check if these autocommands are disabled. Used when doing ":all" or
9107 * ":ball".
9108 */
9109 if ( (autocmd_no_enter
9110 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9111 || (autocmd_no_leave
9112 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009113 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009114
9115 /*
9116 * Save the autocmd_* variables and info about the current buffer.
9117 */
9118 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009119 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009120 save_autocmd_bufnr = autocmd_bufnr;
9121 save_autocmd_match = autocmd_match;
9122 save_autocmd_busy = autocmd_busy;
9123 save_autocmd_nested = autocmd_nested;
9124 save_changed = curbuf->b_changed;
9125 old_curbuf = curbuf;
9126
9127 /*
9128 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009129 * Make a copy to avoid that changing a buffer name or directory makes it
9130 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009131 */
9132 if (fname_io == NULL)
9133 {
9134 if (fname != NULL && *fname != NUL)
9135 autocmd_fname = fname;
9136 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009137 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009138 else
9139 autocmd_fname = NULL;
9140 }
9141 else
9142 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009143 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009144 autocmd_fname = vim_strsave(autocmd_fname);
9145 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146
9147 /*
9148 * Set the buffer number to be used for <abuf>.
9149 */
9150 if (buf == NULL)
9151 autocmd_bufnr = 0;
9152 else
9153 autocmd_bufnr = buf->b_fnum;
9154
9155 /*
9156 * When the file name is NULL or empty, use the file name of buffer "buf".
9157 * Always use the full path of the file name to match with, in case
9158 * "allow_dirs" is set.
9159 */
9160 if (fname == NULL || *fname == NUL)
9161 {
9162 if (buf == NULL)
9163 fname = NULL;
9164 else
9165 {
9166#ifdef FEAT_SYN_HL
9167 if (event == EVENT_SYNTAX)
9168 fname = buf->b_p_syn;
9169 else
9170#endif
9171 if (event == EVENT_FILETYPE)
9172 fname = buf->b_p_ft;
9173 else
9174 {
9175 if (buf->b_sfname != NULL)
9176 sfname = vim_strsave(buf->b_sfname);
9177 fname = buf->b_ffname;
9178 }
9179 }
9180 if (fname == NULL)
9181 fname = (char_u *)"";
9182 fname = vim_strsave(fname); /* make a copy, so we can change it */
9183 }
9184 else
9185 {
9186 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009187 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9188 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009189 if (event == EVENT_FILETYPE
9190 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009191 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009192 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009193 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009194 || event == EVENT_QUICKFIXCMDPRE
9195 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009196 fname = vim_strsave(fname);
9197 else
9198 fname = FullName_save(fname, FALSE);
9199 }
9200 if (fname == NULL) /* out of memory */
9201 {
9202 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009203 retval = FALSE;
9204 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 }
9206
9207#ifdef BACKSLASH_IN_FILENAME
9208 /*
9209 * Replace all backslashes with forward slashes. This makes the
9210 * autocommand patterns portable between Unix and MS-DOS.
9211 */
9212 if (sfname != NULL)
9213 forward_slash(sfname);
9214 forward_slash(fname);
9215#endif
9216
9217#ifdef VMS
9218 /* remove version for correct match */
9219 if (sfname != NULL)
9220 vms_remove_version(sfname);
9221 vms_remove_version(fname);
9222#endif
9223
9224 /*
9225 * Set the name to be used for <amatch>.
9226 */
9227 autocmd_match = fname;
9228
9229
9230 /* Don't redraw while doing auto commands. */
9231 ++RedrawingDisabled;
9232 save_sourcing_name = sourcing_name;
9233 sourcing_name = NULL; /* don't free this one */
9234 save_sourcing_lnum = sourcing_lnum;
9235 sourcing_lnum = 0; /* no line number here */
9236
9237#ifdef FEAT_EVAL
9238 save_current_SID = current_SID;
9239
Bram Moolenaar05159a02005-02-26 23:04:13 +00009240# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009241 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009242 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9243# endif
9244
Bram Moolenaar071d4272004-06-13 20:20:40 +00009245 /* Don't use local function variables, if called from a function */
9246 save_funccalp = save_funccal();
9247#endif
9248
9249 /*
9250 * When starting to execute autocommands, save the search patterns.
9251 */
9252 if (!autocmd_busy)
9253 {
9254 save_search_patterns();
9255 saveRedobuff();
9256 did_filetype = keep_filetype;
9257 }
9258
9259 /*
9260 * Note that we are applying autocmds. Some commands need to know.
9261 */
9262 autocmd_busy = TRUE;
9263 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9264 ++nesting; /* see matching decrement below */
9265
9266 /* Remember that FileType was triggered. Used for did_filetype(). */
9267 if (event == EVENT_FILETYPE)
9268 did_filetype = TRUE;
9269
9270 tail = gettail(fname);
9271
9272 /* Find first autocommand that matches */
9273 patcmd.curpat = first_autopat[(int)event];
9274 patcmd.nextcmd = NULL;
9275 patcmd.group = group;
9276 patcmd.fname = fname;
9277 patcmd.sfname = sfname;
9278 patcmd.tail = tail;
9279 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009280 patcmd.arg_bufnr = autocmd_bufnr;
9281 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009282 auto_next_pat(&patcmd, FALSE);
9283
9284 /* found one, start executing the autocommands */
9285 if (patcmd.curpat != NULL)
9286 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009287 /* add to active_apc_list */
9288 patcmd.next = active_apc_list;
9289 active_apc_list = &patcmd;
9290
Bram Moolenaar071d4272004-06-13 20:20:40 +00009291#ifdef FEAT_EVAL
9292 /* set v:cmdarg (only when there is a matching pattern) */
9293 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9294 if (eap != NULL)
9295 {
9296 save_cmdarg = set_cmdarg(eap, NULL);
9297 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9298 }
9299 else
9300 save_cmdarg = NULL; /* avoid gcc warning */
9301#endif
9302 retval = TRUE;
9303 /* mark the last pattern, to avoid an endless loop when more patterns
9304 * are added when executing autocommands */
9305 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9306 ap->last = FALSE;
9307 ap->last = TRUE;
9308 check_lnums(TRUE); /* make sure cursor and topline are valid */
9309 do_cmdline(NULL, getnextac, (void *)&patcmd,
9310 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9311#ifdef FEAT_EVAL
9312 if (eap != NULL)
9313 {
9314 (void)set_cmdarg(NULL, save_cmdarg);
9315 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9316 }
9317#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009318 /* delete from active_apc_list */
9319 if (active_apc_list == &patcmd) /* just in case */
9320 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009321 }
9322
9323 --RedrawingDisabled;
9324 autocmd_busy = save_autocmd_busy;
9325 filechangeshell_busy = FALSE;
9326 autocmd_nested = save_autocmd_nested;
9327 vim_free(sourcing_name);
9328 sourcing_name = save_sourcing_name;
9329 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009330 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009331 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009332 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009333 autocmd_bufnr = save_autocmd_bufnr;
9334 autocmd_match = save_autocmd_match;
9335#ifdef FEAT_EVAL
9336 current_SID = save_current_SID;
9337 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009338# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009339 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009340 prof_child_exit(&wait_time);
9341# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009342#endif
9343 vim_free(fname);
9344 vim_free(sfname);
9345 --nesting; /* see matching increment above */
9346
9347 /*
9348 * When stopping to execute autocommands, restore the search patterns and
9349 * the redo buffer.
9350 */
9351 if (!autocmd_busy)
9352 {
9353 restore_search_patterns();
9354 restoreRedobuff();
9355 did_filetype = FALSE;
9356 }
9357
9358 /*
9359 * Some events don't set or reset the Changed flag.
9360 * Check if still in the same buffer!
9361 */
9362 if (curbuf == old_curbuf
9363 && (event == EVENT_BUFREADPOST
9364 || event == EVENT_BUFWRITEPOST
9365 || event == EVENT_FILEAPPENDPOST
9366 || event == EVENT_VIMLEAVE
9367 || event == EVENT_VIMLEAVEPRE))
9368 {
9369#ifdef FEAT_TITLE
9370 if (curbuf->b_changed != save_changed)
9371 need_maketitle = TRUE;
9372#endif
9373 curbuf->b_changed = save_changed;
9374 }
9375
9376 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009377
9378BYPASS_AU:
9379 /* When wiping out a buffer make sure all its buffer-local autocommands
9380 * are deleted. */
9381 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9382 aubuflocal_remove(buf);
9383
Bram Moolenaar071d4272004-06-13 20:20:40 +00009384 return retval;
9385}
9386
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009387# ifdef FEAT_EVAL
9388static char_u *old_termresponse = NULL;
9389# endif
9390
9391/*
9392 * Block triggering autocommands until unblock_autocmd() is called.
9393 * Can be used recursively, so long as it's symmetric.
9394 */
9395 void
9396block_autocmds()
9397{
9398# ifdef FEAT_EVAL
9399 /* Remember the value of v:termresponse. */
9400 if (autocmd_blocked == 0)
9401 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9402# endif
9403 ++autocmd_blocked;
9404}
9405
9406 void
9407unblock_autocmds()
9408{
9409 --autocmd_blocked;
9410
9411# ifdef FEAT_EVAL
9412 /* When v:termresponse was set while autocommands were blocked, trigger
9413 * the autocommands now. Esp. useful when executing a shell command
9414 * during startup (vimdiff). */
9415 if (autocmd_blocked == 0
9416 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9417 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9418# endif
9419}
9420
Bram Moolenaar071d4272004-06-13 20:20:40 +00009421/*
9422 * Find next autocommand pattern that matches.
9423 */
9424 static void
9425auto_next_pat(apc, stop_at_last)
9426 AutoPatCmd *apc;
9427 int stop_at_last; /* stop when 'last' flag is set */
9428{
9429 AutoPat *ap;
9430 AutoCmd *cp;
9431 char_u *name;
9432 char *s;
9433
9434 vim_free(sourcing_name);
9435 sourcing_name = NULL;
9436
9437 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9438 {
9439 apc->curpat = NULL;
9440
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009441 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009442 * the group matches. For buffer-local autocommands only check the
9443 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009444 if (ap->pat != NULL && ap->cmds != NULL
9445 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9446 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009447 /* execution-condition */
9448 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009449 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9450 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009451 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009452 {
9453 name = event_nr2name(apc->event);
9454 s = _("%s Auto commands for \"%s\"");
9455 sourcing_name = alloc((unsigned)(STRLEN(s)
9456 + STRLEN(name) + ap->patlen + 1));
9457 if (sourcing_name != NULL)
9458 {
9459 sprintf((char *)sourcing_name, s,
9460 (char *)name, (char *)ap->pat);
9461 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009462 {
9463 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009464 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009465 verbose_leave();
9466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009467 }
9468
9469 apc->curpat = ap;
9470 apc->nextcmd = ap->cmds;
9471 /* mark last command */
9472 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9473 cp->last = FALSE;
9474 cp->last = TRUE;
9475 }
9476 line_breakcheck();
9477 if (apc->curpat != NULL) /* found a match */
9478 break;
9479 }
9480 if (stop_at_last && ap->last)
9481 break;
9482 }
9483}
9484
9485/*
9486 * Get next autocommand command.
9487 * Called by do_cmdline() to get the next line for ":if".
9488 * Returns allocated string, or NULL for end of autocommands.
9489 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009490 static char_u *
9491getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009492 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009493 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009494 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495{
9496 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9497 char_u *retval;
9498 AutoCmd *ac;
9499
9500 /* Can be called again after returning the last line. */
9501 if (acp->curpat == NULL)
9502 return NULL;
9503
9504 /* repeat until we find an autocommand to execute */
9505 for (;;)
9506 {
9507 /* skip removed commands */
9508 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9509 if (acp->nextcmd->last)
9510 acp->nextcmd = NULL;
9511 else
9512 acp->nextcmd = acp->nextcmd->next;
9513
9514 if (acp->nextcmd != NULL)
9515 break;
9516
9517 /* at end of commands, find next pattern that matches */
9518 if (acp->curpat->last)
9519 acp->curpat = NULL;
9520 else
9521 acp->curpat = acp->curpat->next;
9522 if (acp->curpat != NULL)
9523 auto_next_pat(acp, TRUE);
9524 if (acp->curpat == NULL)
9525 return NULL;
9526 }
9527
9528 ac = acp->nextcmd;
9529
9530 if (p_verbose >= 9)
9531 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009532 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009533 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009534 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009535 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009536 }
9537 retval = vim_strsave(ac->cmd);
9538 autocmd_nested = ac->nested;
9539#ifdef FEAT_EVAL
9540 current_SID = ac->scriptID;
9541#endif
9542 if (ac->last)
9543 acp->nextcmd = NULL;
9544 else
9545 acp->nextcmd = ac->next;
9546 return retval;
9547}
9548
9549/*
9550 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009551 * To account for buffer-local autocommands, function needs to know
9552 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009553 */
9554 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009555has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009556 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009557 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009558 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009559{
9560 AutoPat *ap;
9561 char_u *fname;
9562 char_u *tail = gettail(sfname);
9563 int retval = FALSE;
9564
9565 fname = FullName_save(sfname, FALSE);
9566 if (fname == NULL)
9567 return FALSE;
9568
9569#ifdef BACKSLASH_IN_FILENAME
9570 /*
9571 * Replace all backslashes with forward slashes. This makes the
9572 * autocommand patterns portable between Unix and MS-DOS.
9573 */
9574 sfname = vim_strsave(sfname);
9575 if (sfname != NULL)
9576 forward_slash(sfname);
9577 forward_slash(fname);
9578#endif
9579
9580 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9581 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009582 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009583 ? match_file_pat(NULL, ap->reg_prog,
9584 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009585 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009586 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009587 {
9588 retval = TRUE;
9589 break;
9590 }
9591
9592 vim_free(fname);
9593#ifdef BACKSLASH_IN_FILENAME
9594 vim_free(sfname);
9595#endif
9596
9597 return retval;
9598}
9599
9600#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9601/*
9602 * Function given to ExpandGeneric() to obtain the list of autocommand group
9603 * names.
9604 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009605 char_u *
9606get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009607 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009608 int idx;
9609{
9610 if (idx == augroups.ga_len) /* add "END" add the end */
9611 return (char_u *)"END";
9612 if (idx >= augroups.ga_len) /* end of list */
9613 return NULL;
9614 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9615 return (char_u *)"";
9616 return AUGROUP_NAME(idx); /* return a name */
9617}
9618
9619static int include_groups = FALSE;
9620
9621 char_u *
9622set_context_in_autocmd(xp, arg, doautocmd)
9623 expand_T *xp;
9624 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009625 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009626{
9627 char_u *p;
9628 int group;
9629
9630 /* check for a group name, skip it if present */
9631 include_groups = FALSE;
9632 p = arg;
9633 group = au_get_grouparg(&arg);
9634 if (group == AUGROUP_ERROR)
9635 return NULL;
9636 /* If there only is a group name that's what we expand. */
9637 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9638 {
9639 arg = p;
9640 group = AUGROUP_ALL;
9641 }
9642
9643 /* skip over event name */
9644 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9645 if (*p == ',')
9646 arg = p + 1;
9647 if (*p == NUL)
9648 {
9649 if (group == AUGROUP_ALL)
9650 include_groups = TRUE;
9651 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9652 xp->xp_pattern = arg;
9653 return NULL;
9654 }
9655
9656 /* skip over pattern */
9657 arg = skipwhite(p);
9658 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9659 arg++;
9660 if (*arg)
9661 return arg; /* expand (next) command */
9662
9663 if (doautocmd)
9664 xp->xp_context = EXPAND_FILES; /* expand file names */
9665 else
9666 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9667 return NULL;
9668}
9669
9670/*
9671 * Function given to ExpandGeneric() to obtain the list of event names.
9672 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009673 char_u *
9674get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009675 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009676 int idx;
9677{
9678 if (idx < augroups.ga_len) /* First list group names, if wanted */
9679 {
9680 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9681 return (char_u *)""; /* skip deleted entries */
9682 return AUGROUP_NAME(idx); /* return a name */
9683 }
9684 return (char_u *)event_names[idx - augroups.ga_len].name;
9685}
9686
9687#endif /* FEAT_CMDL_COMPL */
9688
9689/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009690 * Return TRUE if autocmd is supported.
9691 */
9692 int
9693autocmd_supported(name)
9694 char_u *name;
9695{
9696 char_u *p;
9697
9698 return (event_name2nr(name, &p) != NUM_EVENTS);
9699}
9700
9701/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009702 * Return TRUE if an autocommand is defined for a group, event and
9703 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9704 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9705 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9706 * Used for:
9707 * exists("#Group") or
9708 * exists("#Group#Event") or
9709 * exists("#Group#Event#pat") or
9710 * exists("#Event") or
9711 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009712 */
9713 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009714au_exists(arg)
9715 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009716{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009717 char_u *arg_save;
9718 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009719 char_u *event_name;
9720 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009721 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009722 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009723 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009724 int group;
9725 int retval = FALSE;
9726
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009727 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009728 arg_save = vim_strsave(arg);
9729 if (arg_save == NULL)
9730 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009731 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009732 if (p != NULL)
9733 *p++ = NUL;
9734
9735 /* First, look for an autocmd group name */
9736 group = au_find_group(arg_save);
9737 if (group == AUGROUP_ERROR)
9738 {
9739 /* Didn't match a group name, assume the first argument is an event. */
9740 group = AUGROUP_ALL;
9741 event_name = arg_save;
9742 }
9743 else
9744 {
9745 if (p == NULL)
9746 {
9747 /* "Group": group name is present and it's recognized */
9748 retval = TRUE;
9749 goto theend;
9750 }
9751
9752 /* Must be "Group#Event" or "Group#Event#pat". */
9753 event_name = p;
9754 p = vim_strchr(event_name, '#');
9755 if (p != NULL)
9756 *p++ = NUL; /* "Group#Event#pat" */
9757 }
9758
9759 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009760
9761 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009762 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009763
9764 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009765 if (event == NUM_EVENTS)
9766 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009767
9768 /* Find the first autocommand for this event.
9769 * If there isn't any, return FALSE;
9770 * If there is one and no pattern given, return TRUE; */
9771 ap = first_autopat[(int)event];
9772 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009773 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009774
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009775 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9776 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009777 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009778 buflocal_buf = curbuf;
9779
Bram Moolenaar071d4272004-06-13 20:20:40 +00009780 /* Check if there is an autocommand with the given pattern. */
9781 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009782 /* only use a pattern when it has not been removed and has commands. */
9783 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009784 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009785 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009786 && (pattern == NULL
9787 || (buflocal_buf == NULL
9788 ? fnamecmp(ap->pat, pattern) == 0
9789 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009790 {
9791 retval = TRUE;
9792 break;
9793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009794
Bram Moolenaar195d6352005-12-19 22:08:24 +00009795theend:
9796 vim_free(arg_save);
9797 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009798}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009799
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009800#else /* FEAT_AUTOCMD */
9801
9802/*
9803 * Prepare for executing commands for (hidden) buffer "buf".
9804 * This is the non-autocommand version, it simply saves "curbuf" and sets
9805 * "curbuf" and "curwin" to match "buf".
9806 */
9807 void
9808aucmd_prepbuf(aco, buf)
9809 aco_save_T *aco; /* structure to save values in */
9810 buf_T *buf; /* new curbuf */
9811{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009812 aco->save_curbuf = curbuf;
9813 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009814 curbuf = buf;
9815 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009816 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009817}
9818
9819/*
9820 * Restore after executing commands for a (hidden) buffer.
9821 * This is the non-autocommand version.
9822 */
9823 void
9824aucmd_restbuf(aco)
9825 aco_save_T *aco; /* structure holding saved values */
9826{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009827 --curbuf->b_nwindows;
9828 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009829 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009830 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009831}
9832
Bram Moolenaar071d4272004-06-13 20:20:40 +00009833#endif /* FEAT_AUTOCMD */
9834
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009835
Bram Moolenaar071d4272004-06-13 20:20:40 +00009836#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9837/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009838 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9839 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9840 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009841 * Used for autocommands and 'wildignore'.
9842 * Returns TRUE if there is a match, FALSE otherwise.
9843 */
9844 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009845match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009846 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009847 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009848 char_u *fname; /* full path of file name */
9849 char_u *sfname; /* short file name or NULL */
9850 char_u *tail; /* tail of path */
9851 int allow_dirs; /* allow matching with dir */
9852{
9853 regmatch_T regmatch;
9854 int result = FALSE;
9855#ifdef FEAT_OSFILETYPE
9856 int no_pattern = FALSE; /* TRUE if check is filetype only */
9857 char_u *type_start;
9858 char_u c;
9859 int match = FALSE;
9860#endif
9861
9862#ifdef CASE_INSENSITIVE_FILENAME
9863 regmatch.rm_ic = TRUE; /* Always ignore case */
9864#else
9865 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9866#endif
9867#ifdef FEAT_OSFILETYPE
9868 if (*pattern == '<')
9869 {
9870 /* There is a filetype condition specified with this pattern.
9871 * Check the filetype matches first. If not, don't bother with the
9872 * pattern (set regprog to NULL).
9873 * Always use magic for the regexp.
9874 */
9875
9876 for (type_start = pattern + 1; (c = *pattern); pattern++)
9877 {
9878 if ((c == ';' || c == '>') && match == FALSE)
9879 {
9880 *pattern = NUL; /* Terminate the string */
9881 match = mch_check_filetype(fname, type_start);
9882 *pattern = c; /* Restore the terminator */
9883 type_start = pattern + 1;
9884 }
9885 if (c == '>')
9886 break;
9887 }
9888
9889 /* (c should never be NUL, but check anyway) */
9890 if (match == FALSE || c == NUL)
9891 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9892 else if (*pattern == NUL)
9893 {
9894 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9895 no_pattern = TRUE; /* Always matches - don't check pat. */
9896 }
9897 else
9898 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9899 }
9900 else
9901#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009902 {
9903 if (prog != NULL)
9904 regmatch.regprog = prog;
9905 else
9906 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009908
9909 /*
9910 * Try for a match with the pattern with:
9911 * 1. the full file name, when the pattern has a '/'.
9912 * 2. the short file name, when the pattern has a '/'.
9913 * 3. the tail of the file name, when the pattern has no '/'.
9914 */
9915 if (
9916#ifdef FEAT_OSFILETYPE
9917 /* If the check is for a filetype only and we don't care
9918 * about the path then skip all the regexp stuff.
9919 */
9920 no_pattern ||
9921#endif
9922 (regmatch.regprog != NULL
9923 && ((allow_dirs
9924 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9925 || (sfname != NULL
9926 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9927 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9928 result = TRUE;
9929
Bram Moolenaar748bf032005-02-02 23:04:36 +00009930 if (prog == NULL)
9931 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009932 return result;
9933}
9934#endif
9935
9936#if defined(FEAT_WILDIGN) || defined(PROTO)
9937/*
9938 * Return TRUE if a file matches with a pattern in "list".
9939 * "list" is a comma-separated list of patterns, like 'wildignore'.
9940 * "sfname" is the short file name or NULL, "ffname" the long file name.
9941 */
9942 int
9943match_file_list(list, sfname, ffname)
9944 char_u *list;
9945 char_u *sfname;
9946 char_u *ffname;
9947{
9948 char_u buf[100];
9949 char_u *tail;
9950 char_u *regpat;
9951 char allow_dirs;
9952 int match;
9953 char_u *p;
9954
9955 tail = gettail(sfname);
9956
9957 /* try all patterns in 'wildignore' */
9958 p = list;
9959 while (*p)
9960 {
9961 copy_option_part(&p, buf, 100, ",");
9962 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9963 if (regpat == NULL)
9964 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00009965 match = match_file_pat(regpat, NULL, ffname, sfname,
9966 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009967 vim_free(regpat);
9968 if (match)
9969 return TRUE;
9970 }
9971 return FALSE;
9972}
9973#endif
9974
9975/*
9976 * Convert the given pattern "pat" which has shell style wildcards in it, into
9977 * a regular expression, and return the result in allocated memory. If there
9978 * is a directory path separator to be matched, then TRUE is put in
9979 * allow_dirs, otherwise FALSE is put there -- webb.
9980 * Handle backslashes before special characters, like "\*" and "\ ".
9981 *
9982 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
9983 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
9984 *
9985 * Returns NULL when out of memory.
9986 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987 char_u *
9988file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
9989 char_u *pat;
9990 char_u *pat_end; /* first char after pattern or NULL */
9991 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +00009992 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009993{
9994 int size;
9995 char_u *endp;
9996 char_u *reg_pat;
9997 char_u *p;
9998 int i;
9999 int nested = 0;
10000 int add_dollar = TRUE;
10001#ifdef FEAT_OSFILETYPE
10002 int check_length = 0;
10003#endif
10004
10005 if (allow_dirs != NULL)
10006 *allow_dirs = FALSE;
10007 if (pat_end == NULL)
10008 pat_end = pat + STRLEN(pat);
10009
10010#ifdef FEAT_OSFILETYPE
10011 /* Find out how much of the string is the filetype check */
10012 if (*pat == '<')
10013 {
10014 /* Count chars until the next '>' */
10015 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10016 ;
10017 if (p < pat_end)
10018 {
10019 /* Pattern is of the form <.*>.* */
10020 check_length = p - pat + 1;
10021 if (p + 1 >= pat_end)
10022 {
10023 /* The 'pattern' is a filetype check ONLY */
10024 reg_pat = (char_u *)alloc(check_length + 1);
10025 if (reg_pat != NULL)
10026 {
10027 mch_memmove(reg_pat, pat, (size_t)check_length);
10028 reg_pat[check_length] = NUL;
10029 }
10030 return reg_pat;
10031 }
10032 }
10033 /* else: there was no closing '>' - assume it was a normal pattern */
10034
10035 }
10036 pat += check_length;
10037 size = 2 + check_length;
10038#else
10039 size = 2; /* '^' at start, '$' at end */
10040#endif
10041
10042 for (p = pat; p < pat_end; p++)
10043 {
10044 switch (*p)
10045 {
10046 case '*':
10047 case '.':
10048 case ',':
10049 case '{':
10050 case '}':
10051 case '~':
10052 size += 2; /* extra backslash */
10053 break;
10054#ifdef BACKSLASH_IN_FILENAME
10055 case '\\':
10056 case '/':
10057 size += 4; /* could become "[\/]" */
10058 break;
10059#endif
10060 default:
10061 size++;
10062# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010063 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010064 {
10065 ++p;
10066 ++size;
10067 }
10068# endif
10069 break;
10070 }
10071 }
10072 reg_pat = alloc(size + 1);
10073 if (reg_pat == NULL)
10074 return NULL;
10075
10076#ifdef FEAT_OSFILETYPE
10077 /* Copy the type check in to the start. */
10078 if (check_length)
10079 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10080 i = check_length;
10081#else
10082 i = 0;
10083#endif
10084
10085 if (pat[0] == '*')
10086 while (pat[0] == '*' && pat < pat_end - 1)
10087 pat++;
10088 else
10089 reg_pat[i++] = '^';
10090 endp = pat_end - 1;
10091 if (*endp == '*')
10092 {
10093 while (endp - pat > 0 && *endp == '*')
10094 endp--;
10095 add_dollar = FALSE;
10096 }
10097 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10098 {
10099 switch (*p)
10100 {
10101 case '*':
10102 reg_pat[i++] = '.';
10103 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010104 while (p[1] == '*') /* "**" matches like "*" */
10105 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010106 break;
10107 case '.':
10108#ifdef RISCOS
10109 if (allow_dirs != NULL)
10110 *allow_dirs = TRUE;
10111 /* FALLTHROUGH */
10112#endif
10113 case '~':
10114 reg_pat[i++] = '\\';
10115 reg_pat[i++] = *p;
10116 break;
10117 case '?':
10118#ifdef RISCOS
10119 case '#':
10120#endif
10121 reg_pat[i++] = '.';
10122 break;
10123 case '\\':
10124 if (p[1] == NUL)
10125 break;
10126#ifdef BACKSLASH_IN_FILENAME
10127 if (!no_bslash)
10128 {
10129 /* translate:
10130 * "\x" to "\\x" e.g., "dir\file"
10131 * "\*" to "\\.*" e.g., "dir\*.c"
10132 * "\?" to "\\." e.g., "dir\??.c"
10133 * "\+" to "\+" e.g., "fileX\+.c"
10134 */
10135 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10136 && p[1] != '+')
10137 {
10138 reg_pat[i++] = '[';
10139 reg_pat[i++] = '\\';
10140 reg_pat[i++] = '/';
10141 reg_pat[i++] = ']';
10142 if (allow_dirs != NULL)
10143 *allow_dirs = TRUE;
10144 break;
10145 }
10146 }
10147#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010148 /* Undo escaping from ExpandEscape():
10149 * foo\?bar -> foo?bar
10150 * foo\%bar -> foo%bar
10151 * foo\,bar -> foo,bar
10152 * foo\ bar -> foo bar
10153 * Don't unescape \, * and others that are also special in a
10154 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010155 if (*++p == '?'
10156#ifdef BACKSLASH_IN_FILENAME
10157 && no_bslash
10158#endif
10159 )
10160 reg_pat[i++] = '?';
10161 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010162 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10163 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010164 else
10165 {
10166 if (allow_dirs != NULL && vim_ispathsep(*p)
10167#ifdef BACKSLASH_IN_FILENAME
10168 && (!no_bslash || *p != '\\')
10169#endif
10170 )
10171 *allow_dirs = TRUE;
10172 reg_pat[i++] = '\\';
10173 reg_pat[i++] = *p;
10174 }
10175 break;
10176#ifdef BACKSLASH_IN_FILENAME
10177 case '/':
10178 reg_pat[i++] = '[';
10179 reg_pat[i++] = '\\';
10180 reg_pat[i++] = '/';
10181 reg_pat[i++] = ']';
10182 if (allow_dirs != NULL)
10183 *allow_dirs = TRUE;
10184 break;
10185#endif
10186 case '{':
10187 reg_pat[i++] = '\\';
10188 reg_pat[i++] = '(';
10189 nested++;
10190 break;
10191 case '}':
10192 reg_pat[i++] = '\\';
10193 reg_pat[i++] = ')';
10194 --nested;
10195 break;
10196 case ',':
10197 if (nested)
10198 {
10199 reg_pat[i++] = '\\';
10200 reg_pat[i++] = '|';
10201 }
10202 else
10203 reg_pat[i++] = ',';
10204 break;
10205 default:
10206# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010207 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010208 reg_pat[i++] = *p++;
10209 else
10210# endif
10211 if (allow_dirs != NULL && vim_ispathsep(*p))
10212 *allow_dirs = TRUE;
10213 reg_pat[i++] = *p;
10214 break;
10215 }
10216 }
10217 if (add_dollar)
10218 reg_pat[i++] = '$';
10219 reg_pat[i] = NUL;
10220 if (nested != 0)
10221 {
10222 if (nested < 0)
10223 EMSG(_("E219: Missing {."));
10224 else
10225 EMSG(_("E220: Missing }."));
10226 vim_free(reg_pat);
10227 reg_pat = NULL;
10228 }
10229 return reg_pat;
10230}