blob: 010d933a12693f79cbb091bd4a5bf383578753a0 [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
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
27#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020028/* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */
Bram Moolenaarf50a2532010-05-21 15:36:08 +020029static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
30static char crypt_magic_head[] = "VimCrypt~";
31# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
Bram Moolenaar80794b12010-06-13 05:20:42 +020032
33/* For blowfish, after the magic header, we store 8 bytes of salt and then 8
34 * bytes of seed (initialisation vector). */
35static int crypt_salt_len[] = {0, 8};
Bram Moolenaarf50a2532010-05-21 15:36:08 +020036static int crypt_seed_len[] = {0, 8};
Bram Moolenaar80794b12010-06-13 05:20:42 +020037#define CRYPT_SALT_LEN_MAX 8
Bram Moolenaar40e6a712010-05-16 22:32:54 +020038#define CRYPT_SEED_LEN_MAX 8
Bram Moolenaar071d4272004-06-13 20:20:40 +000039#endif
40
41/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000042#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000043
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000044#if defined(sun) && defined(S_ISCHR)
45# define OPEN_CHR_FILES
46static int is_dev_fd_file(char_u *fname);
47#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000048#ifdef FEAT_MBYTE
49static char_u *next_fenc __ARGS((char_u **pp));
50# ifdef FEAT_EVAL
51static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
52# endif
53#endif
54#ifdef FEAT_VIMINFO
55static void check_marks_read __ARGS((void));
56#endif
57#ifdef FEAT_CRYPT
Bram Moolenaar49771f42010-07-20 17:32:38 +020058static int crypt_method_from_magic __ARGS((char *ptr, int len));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020059static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep, int newfile, char_u *fname, int *did_ask));
Bram Moolenaar071d4272004-06-13 20:20:40 +000060#endif
61#ifdef UNIX
62static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
63#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000064static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000065static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000066static void msg_add_eol __ARGS((void));
67static int check_mtime __ARGS((buf_T *buf, struct stat *s));
68static int time_differs __ARGS((long t1, long t2));
69#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000070static 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 +000071static int au_find_group __ARGS((char_u *name));
72
73# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000074# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000075# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000076#endif
77
78#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
79# define HAS_BW_FLAGS
80# define FIO_LATIN1 0x01 /* convert Latin1 */
81# define FIO_UTF8 0x02 /* convert UTF-8 */
82# define FIO_UCS2 0x04 /* convert UCS-2 */
83# define FIO_UCS4 0x08 /* convert UCS-4 */
84# define FIO_UTF16 0x10 /* convert UTF-16 */
85# ifdef WIN3264
86# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
87# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
88# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
89# endif
90# ifdef MACOS_X
91# define FIO_MACROMAN 0x20 /* convert MacRoman */
92# endif
93# define FIO_ENDIAN_L 0x80 /* little endian */
94# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
95# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
96# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
97# define FIO_ALL -1 /* allow all formats */
98#endif
99
100/* When converting, a read() or write() may leave some bytes to be converted
101 * for the next call. The value is guessed... */
102#define CONV_RESTLEN 30
103
104/* We have to guess how much a sequence of bytes may expand when converting
105 * with iconv() to be able to allocate a buffer. */
106#define ICONV_MULT 8
107
108/*
109 * Structure to pass arguments from buf_write() to buf_write_bytes().
110 */
111struct bw_info
112{
113 int bw_fd; /* file descriptor */
114 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000115 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116#ifdef HAS_BW_FLAGS
117 int bw_flags; /* FIO_ flags */
118#endif
119#ifdef FEAT_MBYTE
120 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
121 int bw_restlen; /* nr of bytes in bw_rest[] */
122 int bw_first; /* first write call */
123 char_u *bw_conv_buf; /* buffer for writing converted chars */
124 int bw_conv_buflen; /* size of bw_conv_buf */
125 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000126 linenr_T bw_conv_error_lnum; /* first line with error or zero */
127 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128# ifdef USE_ICONV
129 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
130# endif
131#endif
132};
133
134static int buf_write_bytes __ARGS((struct bw_info *ip));
135
136#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000137static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000139static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static int get_fio_flags __ARGS((char_u *ptr));
141static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
142static int make_bom __ARGS((char_u *buf, char_u *name));
143# ifdef WIN3264
144static int get_win_fio_flags __ARGS((char_u *ptr));
145# endif
146# ifdef MACOS_X
147static int get_mac_fio_flags __ARGS((char_u *ptr));
148# endif
149#endif
150static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000151#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000152static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000153#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000154#ifdef FEAT_AUTOCMD
155static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
156#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000157
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158 void
159filemess(buf, name, s, attr)
160 buf_T *buf;
161 char_u *name;
162 char_u *s;
163 int attr;
164{
165 int msg_scroll_save;
166
167 if (msg_silent != 0)
168 return;
169 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
170 /* If it's extremely long, truncate it. */
171 if (STRLEN(IObuff) > IOSIZE - 80)
172 IObuff[IOSIZE - 80] = NUL;
173 STRCAT(IObuff, s);
174 /*
175 * For the first message may have to start a new line.
176 * For further ones overwrite the previous one, reset msg_scroll before
177 * calling filemess().
178 */
179 msg_scroll_save = msg_scroll;
180 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
181 msg_scroll = FALSE;
182 if (!msg_scroll) /* wait a bit when overwriting an error msg */
183 check_for_delay(FALSE);
184 msg_start();
185 msg_scroll = msg_scroll_save;
186 msg_scrolled_ign = TRUE;
187 /* may truncate the message to avoid a hit-return prompt */
188 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
189 msg_clr_eos();
190 out_flush();
191 msg_scrolled_ign = FALSE;
192}
193
194/*
195 * Read lines from file "fname" into the buffer after line "from".
196 *
197 * 1. We allocate blocks with lalloc, as big as possible.
198 * 2. Each block is filled with characters from the file with a single read().
199 * 3. The lines are inserted in the buffer with ml_append().
200 *
201 * (caller must check that fname != NULL, unless READ_STDIN is used)
202 *
203 * "lines_to_skip" is the number of lines that must be skipped
204 * "lines_to_read" is the number of lines that are appended
205 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
206 *
207 * flags:
208 * READ_NEW starting to edit a new buffer
209 * READ_FILTER reading filter output
210 * READ_STDIN read from stdin instead of a file
211 * READ_BUFFER read from curbuf instead of a file (converting after reading
212 * stdin)
213 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200214 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 *
216 * return FAIL for failure, OK otherwise
217 */
218 int
219readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
220 char_u *fname;
221 char_u *sfname;
222 linenr_T from;
223 linenr_T lines_to_skip;
224 linenr_T lines_to_read;
225 exarg_T *eap; /* can be NULL! */
226 int flags;
227{
228 int fd = 0;
229 int newfile = (flags & READ_NEW);
230 int check_readonly;
231 int filtering = (flags & READ_FILTER);
232 int read_stdin = (flags & READ_STDIN);
233 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000234 int set_options = newfile || read_buffer
235 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
237 colnr_T read_buf_col = 0; /* next char to read from this line */
238 char_u c;
239 linenr_T lnum = from;
240 char_u *ptr = NULL; /* pointer into read buffer */
241 char_u *buffer = NULL; /* read buffer */
242 char_u *new_buffer = NULL; /* init to shut up gcc */
243 char_u *line_start = NULL; /* init to shut up gcc */
244 int wasempty; /* buffer was empty before reading */
245 colnr_T len;
246 long size = 0;
247 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200248 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249 int skip_read = FALSE;
250#ifdef FEAT_CRYPT
251 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200252 int did_ask_for_key = FALSE;
Bram Moolenaar4cf35c22011-02-25 16:52:17 +0100253 int crypt_method_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200255#ifdef FEAT_PERSISTENT_UNDO
256 context_sha256_T sha_ctx;
257 int read_undo_file = FALSE;
258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000259 int split = 0; /* number of split lines */
260#define UNKNOWN 0x0fffffff /* file size is unknown */
261 linenr_T linecnt;
262 int error = FALSE; /* errors encountered */
263 int ff_error = EOL_UNKNOWN; /* file format with errors */
264 long linerest = 0; /* remaining chars in line */
265#ifdef UNIX
266 int perm = 0;
267 int swap_mode = -1; /* protection bits for swap file */
268#else
269 int perm;
270#endif
271 int fileformat = 0; /* end-of-line format */
272 int keep_fileformat = FALSE;
273 struct stat st;
274 int file_readonly;
275 linenr_T skip_count = 0;
276 linenr_T read_count = 0;
277 int msg_save = msg_scroll;
278 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
279 * last read was missing the eol */
280 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
281 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
282 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
283 int file_rewind = FALSE;
284#ifdef FEAT_MBYTE
285 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000286 linenr_T conv_error = 0; /* line nr with conversion error */
287 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
289 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000290 int bad_char_behavior = BAD_REPLACE;
291 /* BAD_KEEP, BAD_DROP or character to
292 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293 char_u *tmpname = NULL; /* name of 'charconvert' output file */
294 int fio_flags = 0;
295 char_u *fenc; /* fileencoding to use */
296 int fenc_alloced; /* fenc_next is in allocated memory */
297 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
298 int advance_fenc = FALSE;
299 long real_size = 0;
300# ifdef USE_ICONV
301 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
302# ifdef FEAT_EVAL
303 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
304 'charconvert' next */
305# endif
306# endif
307 int converted = FALSE; /* TRUE if conversion done */
308 int notconverted = FALSE; /* TRUE if conversion wanted but it
309 wasn't possible */
310 char_u conv_rest[CONV_RESTLEN];
311 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
312#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000313#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200314 buf_T *old_curbuf;
315 char_u *old_b_ffname;
316 char_u *old_b_fname;
317 int using_b_ffname;
318 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000319#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200320
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100321 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322
323 /*
324 * If there is no file name yet, use the one for the read file.
325 * BF_NOTEDITED is set to reflect this.
326 * Don't do this for a read from a filter.
327 * Only do this when 'cpoptions' contains the 'f' flag.
328 */
329 if (curbuf->b_ffname == NULL
330 && !filtering
331 && fname != NULL
332 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
333 && !(flags & READ_DUMMY))
334 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000335 if (set_rw_fname(fname, sfname) == FAIL)
336 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000337 }
338
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200339#ifdef FEAT_AUTOCMD
340 /* Remember the initial values of curbuf, curbuf->b_ffname and
341 * curbuf->b_fname to detect whether they are altered as a result of
342 * executing nasty autocommands. Also check if "fname" and "sfname"
343 * point to one of these values. */
344 old_curbuf = curbuf;
345 old_b_ffname = curbuf->b_ffname;
346 old_b_fname = curbuf->b_fname;
347 using_b_ffname = (fname == curbuf->b_ffname)
348 || (sfname == curbuf->b_ffname);
349 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
350#endif
351
Bram Moolenaardf177f62005-02-22 08:39:57 +0000352 /* After reading a file the cursor line changes but we don't want to
353 * display the line. */
354 ex_no_reprint = TRUE;
355
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000356 /* don't display the file info for another buffer now */
357 need_fileinfo = FALSE;
358
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359 /*
360 * For Unix: Use the short file name whenever possible.
361 * Avoids problems with networks and when directory names are changed.
362 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
363 * another directory, which we don't detect.
364 */
365 if (sfname == NULL)
366 sfname = fname;
367#if defined(UNIX) || defined(__EMX__)
368 fname = sfname;
369#endif
370
371#ifdef FEAT_AUTOCMD
372 /*
373 * The BufReadCmd and FileReadCmd events intercept the reading process by
374 * executing the associated commands instead.
375 */
376 if (!filtering && !read_stdin && !read_buffer)
377 {
378 pos_T pos;
379
380 pos = curbuf->b_op_start;
381
382 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
383 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
384 curbuf->b_op_start.col = 0;
385
386 if (newfile)
387 {
388 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
389 FALSE, curbuf, eap))
390#ifdef FEAT_EVAL
391 return aborting() ? FAIL : OK;
392#else
393 return OK;
394#endif
395 }
396 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
397 FALSE, NULL, eap))
398#ifdef FEAT_EVAL
399 return aborting() ? FAIL : OK;
400#else
401 return OK;
402#endif
403
404 curbuf->b_op_start = pos;
405 }
406#endif
407
408 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
409 msg_scroll = FALSE; /* overwrite previous file message */
410 else
411 msg_scroll = TRUE; /* don't overwrite previous file message */
412
413 /*
414 * If the name ends in a path separator, we can't open it. Check here,
415 * because reading the file may actually work, but then creating the swap
416 * file may destroy it! Reported on MS-DOS and Win 95.
417 * If the name is too long we might crash further on, quit here.
418 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000419 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000421 p = fname + STRLEN(fname);
422 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000423 {
424 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
425 msg_end();
426 msg_scroll = msg_save;
427 return FAIL;
428 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 }
430
431#ifdef UNIX
432 /*
433 * On Unix it is possible to read a directory, so we have to
434 * check for it before the mch_open().
435 */
436 if (!read_stdin && !read_buffer)
437 {
438 perm = mch_getperm(fname);
439 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
440# ifdef S_ISFIFO
441 && !S_ISFIFO(perm) /* ... or fifo */
442# endif
443# ifdef S_ISSOCK
444 && !S_ISSOCK(perm) /* ... or socket */
445# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000446# ifdef OPEN_CHR_FILES
447 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
448 /* ... or a character special file named /dev/fd/<n> */
449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 )
451 {
452 if (S_ISDIR(perm))
453 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
454 else
455 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
456 msg_end();
457 msg_scroll = msg_save;
458 return FAIL;
459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000461# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
462 /*
463 * MS-Windows allows opening a device, but we will probably get stuck
464 * trying to read it.
465 */
466 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
467 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000468 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000469 msg_end();
470 msg_scroll = msg_save;
471 return FAIL;
472 }
473# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000474 }
475#endif
476
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200477 /* Set default or forced 'fileformat' and 'binary'. */
478 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
480 /*
481 * When opening a new file we take the readonly flag from the file.
482 * Default is r/w, can be set to r/o below.
483 * Don't reset it when in readonly mode
484 * Only set/reset b_p_ro when BF_CHECK_RO is set.
485 */
486 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000487 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488 curbuf->b_p_ro = FALSE;
489
490 if (newfile && !read_stdin && !read_buffer)
491 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200492 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 if (mch_stat((char *)fname, &st) >= 0)
494 {
495 buf_store_time(curbuf, &st, fname);
496 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497#ifdef UNIX
498 /*
499 * Use the protection bits of the original file for the swap file.
500 * This makes it possible for others to read the name of the
501 * edited file from the swapfile, but only if they can read the
502 * edited file.
503 * Remove the "write" and "execute" bits for group and others
504 * (they must not write the swapfile).
505 * Add the "read" and "write" bits for the user, otherwise we may
506 * not be able to write to the file ourselves.
507 * Setting the bits is done below, after creating the swap file.
508 */
509 swap_mode = (st.st_mode & 0644) | 0600;
510#endif
511#ifdef FEAT_CW_EDITOR
512 /* Get the FSSpec on MacOS
513 * TODO: Update it properly when the buffer name changes
514 */
515 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
516#endif
517#ifdef VMS
518 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000519 curbuf->b_fab_rat = st.st_fab_rat;
520 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521#endif
522 }
523 else
524 {
525 curbuf->b_mtime = 0;
526 curbuf->b_mtime_read = 0;
527 curbuf->b_orig_size = 0;
528 curbuf->b_orig_mode = 0;
529 }
530
531 /* Reset the "new file" flag. It will be set again below when the
532 * file doesn't exist. */
533 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
534 }
535
536/*
537 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538 * for MSDOS and Amiga: check readonly by trying to open the file for writing
539 */
540 file_readonly = FALSE;
541 if (read_stdin)
542 {
543#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
544 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
545 setmode(0, O_BINARY);
546#endif
547 }
548 else if (!read_buffer)
549 {
550#ifdef USE_MCH_ACCESS
551 if (
552# ifdef UNIX
553 !(perm & 0222) ||
554# endif
555 mch_access((char *)fname, W_OK))
556 file_readonly = TRUE;
557 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
558#else
559 if (!newfile
560 || readonlymode
561 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
562 {
563 file_readonly = TRUE;
564 /* try to open ro */
565 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
566 }
567#endif
568 }
569
570 if (fd < 0) /* cannot open at all */
571 {
572#ifndef UNIX
573 int isdir_f;
574#endif
575 msg_scroll = msg_save;
576#ifndef UNIX
577 /*
578 * On MSDOS and Amiga we can't open a directory, check here.
579 */
580 isdir_f = (mch_isdir(fname));
581 perm = mch_getperm(fname); /* check if the file exists */
582 if (isdir_f)
583 {
584 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
585 curbuf->b_p_ro = TRUE; /* must use "w!" now */
586 }
587 else
588#endif
589 if (newfile)
590 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200591 if (perm < 0
592#ifdef ENOENT
593 && errno == ENOENT
594#endif
595 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596 {
597 /*
598 * Set the 'new-file' flag, so that when the file has
599 * been created by someone else, a ":w" will complain.
600 */
601 curbuf->b_flags |= BF_NEW;
602
603 /* Create a swap file now, so that other Vims are warned
604 * that we are editing this file. Don't do this for a
605 * "nofile" or "nowrite" buffer type. */
606#ifdef FEAT_QUICKFIX
607 if (!bt_dontwrite(curbuf))
608#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000609 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000611#ifdef FEAT_AUTOCMD
612 /* SwapExists autocommand may mess things up */
613 if (curbuf != old_curbuf
614 || (using_b_ffname
615 && (old_b_ffname != curbuf->b_ffname))
616 || (using_b_fname
617 && (old_b_fname != curbuf->b_fname)))
618 {
619 EMSG(_(e_auchangedbuf));
620 return FAIL;
621 }
622#endif
623 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000624 if (dir_of_file_exists(fname))
625 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
626 else
627 filemess(curbuf, sfname,
628 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629#ifdef FEAT_VIMINFO
630 /* Even though this is a new file, it might have been
631 * edited before and deleted. Get the old marks. */
632 check_marks_read();
633#endif
634#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200635 /* Set forced 'fileencoding'. */
636 if (eap != NULL)
637 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638#endif
639#ifdef FEAT_AUTOCMD
640 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
641 FALSE, curbuf, eap);
642#endif
643 /* remember the current fileformat */
644 save_file_ff(curbuf);
645
646#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
647 if (aborting()) /* autocmds may abort script processing */
648 return FAIL;
649#endif
650 return OK; /* a new file is not an error */
651 }
652 else
653 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000654 filemess(curbuf, sfname, (char_u *)(
655# ifdef EFBIG
656 (errno == EFBIG) ? _("[File too big]") :
657# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200658# ifdef EOVERFLOW
659 (errno == EOVERFLOW) ? _("[File too big]") :
660# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000661 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662 curbuf->b_p_ro = TRUE; /* must use "w!" now */
663 }
664 }
665
666 return FAIL;
667 }
668
669 /*
670 * Only set the 'ro' flag for readonly files the first time they are
671 * loaded. Help files always get readonly mode
672 */
673 if ((check_readonly && file_readonly) || curbuf->b_help)
674 curbuf->b_p_ro = TRUE;
675
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000676 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000678 /* Don't change 'eol' if reading from buffer as it will already be
679 * correctly set when reading stdin. */
680 if (!read_buffer)
681 {
682 curbuf->b_p_eol = TRUE;
683 curbuf->b_start_eol = TRUE;
684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685#ifdef FEAT_MBYTE
686 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000687 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688#endif
689 }
690
691 /* Create a swap file now, so that other Vims are warned that we are
692 * editing this file.
693 * Don't do this for a "nofile" or "nowrite" buffer type. */
694#ifdef FEAT_QUICKFIX
695 if (!bt_dontwrite(curbuf))
696#endif
697 {
698 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000699#ifdef FEAT_AUTOCMD
700 if (!read_stdin && (curbuf != old_curbuf
701 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
702 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
703 {
704 EMSG(_(e_auchangedbuf));
705 if (!read_buffer)
706 close(fd);
707 return FAIL;
708 }
709#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710#ifdef UNIX
711 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000712 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
713 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
715#endif
716 }
717
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000718#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 /* If "Quit" selected at ATTENTION dialog, don't load the file */
720 if (swap_exists_action == SEA_QUIT)
721 {
722 if (!read_buffer && !read_stdin)
723 close(fd);
724 return FAIL;
725 }
726#endif
727
728 ++no_wait_return; /* don't wait for return yet */
729
730 /*
731 * Set '[ mark to the line above where the lines go (line 1 if zero).
732 */
733 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
734 curbuf->b_op_start.col = 0;
735
736#ifdef FEAT_AUTOCMD
737 if (!read_buffer)
738 {
739 int m = msg_scroll;
740 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741
742 /*
743 * The file must be closed again, the autocommands may want to change
744 * the file before reading it.
745 */
746 if (!read_stdin)
747 close(fd); /* ignore errors */
748
749 /*
750 * The output from the autocommands should not overwrite anything and
751 * should not be overwritten: Set msg_scroll, restore its value if no
752 * output was done.
753 */
754 msg_scroll = TRUE;
755 if (filtering)
756 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
757 FALSE, curbuf, eap);
758 else if (read_stdin)
759 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
760 FALSE, curbuf, eap);
761 else if (newfile)
762 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
763 FALSE, curbuf, eap);
764 else
765 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
766 FALSE, NULL, eap);
767 if (msg_scrolled == n)
768 msg_scroll = m;
769
770#ifdef FEAT_EVAL
771 if (aborting()) /* autocmds may abort script processing */
772 {
773 --no_wait_return;
774 msg_scroll = msg_save;
775 curbuf->b_p_ro = TRUE; /* must use "w!" now */
776 return FAIL;
777 }
778#endif
779 /*
780 * Don't allow the autocommands to change the current buffer.
781 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000782 *
783 * Don't allow the autocommands to change the buffer name either
784 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785 */
786 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000787 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
788 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
790 {
791 --no_wait_return;
792 msg_scroll = msg_save;
793 if (fd < 0)
794 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
795 else
796 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
797 curbuf->b_p_ro = TRUE; /* must use "w!" now */
798 return FAIL;
799 }
800 }
801#endif /* FEAT_AUTOCMD */
802
803 /* Autocommands may add lines to the file, need to check if it is empty */
804 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
805
806 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
807 {
808 /*
809 * Show the user that we are busy reading the input. Sometimes this
810 * may take a while. When reading from stdin another program may
811 * still be running, don't move the cursor to the last line, unless
812 * always using the GUI.
813 */
814 if (read_stdin)
815 {
816#ifndef ALWAYS_USE_GUI
817 mch_msg(_("Vim: Reading from stdin...\n"));
818#endif
819#ifdef FEAT_GUI
820 /* Also write a message in the GUI window, if there is one. */
821 if (gui.in_use && !gui.dying && !gui.starting)
822 {
823 p = (char_u *)_("Reading from stdin...");
824 gui_write(p, (int)STRLEN(p));
825 }
826#endif
827 }
828 else if (!read_buffer)
829 filemess(curbuf, sfname, (char_u *)"", 0);
830 }
831
832 msg_scroll = FALSE; /* overwrite the file message */
833
834 /*
835 * Set linecnt now, before the "retry" caused by a wrong guess for
836 * fileformat, and after the autocommands, which may change them.
837 */
838 linecnt = curbuf->b_ml.ml_line_count;
839
840#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000841 /* "++bad=" argument. */
842 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000843 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000844 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000845 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000846 curbuf->b_bad_char = eap->bad_char;
847 }
848 else
849 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000850
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000852 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 */
854 if (eap != NULL && eap->force_enc != 0)
855 {
856 fenc = enc_canonize(eap->cmd + eap->force_enc);
857 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000858 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859 }
860 else if (curbuf->b_p_bin)
861 {
862 fenc = (char_u *)""; /* binary: don't convert */
863 fenc_alloced = FALSE;
864 }
865 else if (curbuf->b_help)
866 {
867 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000868 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869
870 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
871 * fails it must be latin1.
872 * Always do this when 'encoding' is "utf-8". Otherwise only do
873 * this when needed to avoid [converted] remarks all the time.
874 * It is needed when the first line contains non-ASCII characters.
875 * That is only in *.??x files. */
876 fenc = (char_u *)"latin1";
877 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000878 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000880 fc = fname[STRLEN(fname) - 1];
881 if (TOLOWER_ASC(fc) == 'x')
882 {
883 /* Read the first line (and a bit more). Immediately rewind to
884 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100885 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000886 lseek(fd, (off_t)0L, SEEK_SET);
887 for (p = firstline; p < firstline + len; ++p)
888 if (*p >= 0x80)
889 {
890 c = TRUE;
891 break;
892 }
893 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894 }
895
896 if (c)
897 {
898 fenc_next = fenc;
899 fenc = (char_u *)"utf-8";
900
901 /* When the file is utf-8 but a character doesn't fit in
902 * 'encoding' don't retry. In help text editing utf-8 bytes
903 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000904 if (!enc_utf8)
905 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906 }
907 fenc_alloced = FALSE;
908 }
909 else if (*p_fencs == NUL)
910 {
911 fenc = curbuf->b_p_fenc; /* use format from buffer */
912 fenc_alloced = FALSE;
913 }
914 else
915 {
916 fenc_next = p_fencs; /* try items in 'fileencodings' */
917 fenc = next_fenc(&fenc_next);
918 fenc_alloced = TRUE;
919 }
920#endif
921
922 /*
923 * Jump back here to retry reading the file in different ways.
924 * Reasons to retry:
925 * - encoding conversion failed: try another one from "fenc_next"
926 * - BOM detected and fenc was set, need to setup conversion
927 * - "fileformat" check failed: try another
928 *
929 * Variables set for special retry actions:
930 * "file_rewind" Rewind the file to start reading it again.
931 * "advance_fenc" Advance "fenc" using "fenc_next".
932 * "skip_read" Re-use already read bytes (BOM detected).
933 * "did_iconv" iconv() conversion failed, try 'charconvert'.
934 * "keep_fileformat" Don't reset "fileformat".
935 *
936 * Other status indicators:
937 * "tmpname" When != NULL did conversion with 'charconvert'.
938 * Output file has to be deleted afterwards.
939 * "iconv_fd" When != -1 did conversion with iconv().
940 */
941retry:
942
943 if (file_rewind)
944 {
945 if (read_buffer)
946 {
947 read_buf_lnum = 1;
948 read_buf_col = 0;
949 }
950 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
951 {
952 /* Can't rewind the file, give up. */
953 error = TRUE;
954 goto failed;
955 }
956 /* Delete the previously read lines. */
957 while (lnum > from)
958 ml_delete(lnum--, FALSE);
959 file_rewind = FALSE;
960#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000961 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000962 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000964 curbuf->b_start_bomb = FALSE;
965 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000966 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967#endif
968 }
969
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200970#ifdef FEAT_CRYPT
971 if (cryptkey != NULL)
972 /* Need to reset the state, but keep the key, don't want to ask for it
973 * again. */
974 crypt_pop_state();
975#endif
976
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977 /*
978 * When retrying with another "fenc" and the first time "fileformat"
979 * will be reset.
980 */
981 if (keep_fileformat)
982 keep_fileformat = FALSE;
983 else
984 {
985 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000986 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000988 try_unix = try_dos = try_mac = FALSE;
989 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990 else if (curbuf->b_p_bin)
991 fileformat = EOL_UNIX; /* binary: use Unix format */
992 else if (*p_ffs == NUL)
993 fileformat = get_fileformat(curbuf);/* use format from buffer */
994 else
995 fileformat = EOL_UNKNOWN; /* detect from file */
996 }
997
998#ifdef FEAT_MBYTE
999# ifdef USE_ICONV
1000 if (iconv_fd != (iconv_t)-1)
1001 {
1002 /* aborted conversion with iconv(), close the descriptor */
1003 iconv_close(iconv_fd);
1004 iconv_fd = (iconv_t)-1;
1005 }
1006# endif
1007
1008 if (advance_fenc)
1009 {
1010 /*
1011 * Try the next entry in 'fileencodings'.
1012 */
1013 advance_fenc = FALSE;
1014
1015 if (eap != NULL && eap->force_enc != 0)
1016 {
1017 /* Conversion given with "++cc=" wasn't possible, read
1018 * without conversion. */
1019 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001020 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021 if (fenc_alloced)
1022 vim_free(fenc);
1023 fenc = (char_u *)"";
1024 fenc_alloced = FALSE;
1025 }
1026 else
1027 {
1028 if (fenc_alloced)
1029 vim_free(fenc);
1030 if (fenc_next != NULL)
1031 {
1032 fenc = next_fenc(&fenc_next);
1033 fenc_alloced = (fenc_next != NULL);
1034 }
1035 else
1036 {
1037 fenc = (char_u *)"";
1038 fenc_alloced = FALSE;
1039 }
1040 }
1041 if (tmpname != NULL)
1042 {
1043 mch_remove(tmpname); /* delete converted file */
1044 vim_free(tmpname);
1045 tmpname = NULL;
1046 }
1047 }
1048
1049 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001050 * Conversion may be required when the encoding of the file is different
1051 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052 */
1053 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001054 converted = need_conversion(fenc);
1055 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056 {
1057
1058 /* "ucs-bom" means we need to check the first bytes of the file
1059 * for a BOM. */
1060 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1061 fio_flags = FIO_UCSBOM;
1062
1063 /*
1064 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1065 * done. This is handled below after read(). Prepare the
1066 * fio_flags to avoid having to parse the string each time.
1067 * Also check for Unicode to Latin1 conversion, because iconv()
1068 * appears not to handle this correctly. This works just like
1069 * conversion to UTF-8 except how the resulting character is put in
1070 * the buffer.
1071 */
1072 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1073 fio_flags = get_fio_flags(fenc);
1074
1075# ifdef WIN3264
1076 /*
1077 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1078 * is handled with MultiByteToWideChar().
1079 */
1080 if (fio_flags == 0)
1081 fio_flags = get_win_fio_flags(fenc);
1082# endif
1083
1084# ifdef MACOS_X
1085 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1086 if (fio_flags == 0)
1087 fio_flags = get_mac_fio_flags(fenc);
1088# endif
1089
1090# ifdef USE_ICONV
1091 /*
1092 * Try using iconv() if we can't convert internally.
1093 */
1094 if (fio_flags == 0
1095# ifdef FEAT_EVAL
1096 && !did_iconv
1097# endif
1098 )
1099 iconv_fd = (iconv_t)my_iconv_open(
1100 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1101# endif
1102
1103# ifdef FEAT_EVAL
1104 /*
1105 * Use the 'charconvert' expression when conversion is required
1106 * and we can't do it internally or with iconv().
1107 */
1108 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1109# ifdef USE_ICONV
1110 && iconv_fd == (iconv_t)-1
1111# endif
1112 )
1113 {
1114# ifdef USE_ICONV
1115 did_iconv = FALSE;
1116# endif
1117 /* Skip conversion when it's already done (retry for wrong
1118 * "fileformat"). */
1119 if (tmpname == NULL)
1120 {
1121 tmpname = readfile_charconvert(fname, fenc, &fd);
1122 if (tmpname == NULL)
1123 {
1124 /* Conversion failed. Try another one. */
1125 advance_fenc = TRUE;
1126 if (fd < 0)
1127 {
1128 /* Re-opening the original file failed! */
1129 EMSG(_("E202: Conversion made file unreadable!"));
1130 error = TRUE;
1131 goto failed;
1132 }
1133 goto retry;
1134 }
1135 }
1136 }
1137 else
1138# endif
1139 {
1140 if (fio_flags == 0
1141# ifdef USE_ICONV
1142 && iconv_fd == (iconv_t)-1
1143# endif
1144 )
1145 {
1146 /* Conversion wanted but we can't.
1147 * Try the next conversion in 'fileencodings' */
1148 advance_fenc = TRUE;
1149 goto retry;
1150 }
1151 }
1152 }
1153
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001154 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001156 * stdin or fixed at a specific encoding. */
1157 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158#endif
1159
1160 if (!skip_read)
1161 {
1162 linerest = 0;
1163 filesize = 0;
1164 skip_count = lines_to_skip;
1165 read_count = lines_to_read;
1166#ifdef FEAT_MBYTE
1167 conv_restlen = 0;
1168#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001169#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001170 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1171 && curbuf->b_ffname != NULL
1172 && curbuf->b_p_udf
1173 && !filtering
1174 && !read_stdin
1175 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001176 if (read_undo_file)
1177 sha256_start(&sha_ctx);
1178#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179 }
1180
1181 while (!error && !got_int)
1182 {
1183 /*
1184 * We allocate as much space for the file as we can get, plus
1185 * space for the old line plus room for one terminating NUL.
1186 * The amount is limited by the fact that read() only can read
1187 * upto max_unsigned characters (and other things).
1188 */
1189#if SIZEOF_INT <= 2
1190 if (linerest >= 0x7ff0)
1191 {
1192 ++split;
1193 *ptr = NL; /* split line by inserting a NL */
1194 size = 1;
1195 }
1196 else
1197#endif
1198 {
1199 if (!skip_read)
1200 {
1201#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001202# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 size = SSIZE_MAX; /* use max I/O size, 52K */
1204# else
1205 size = 0x10000L; /* use buffer >= 64K */
1206# endif
1207#else
1208 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1209#endif
1210
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001211 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212 {
1213 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1214 FALSE)) != NULL)
1215 break;
1216 }
1217 if (new_buffer == NULL)
1218 {
1219 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1220 error = TRUE;
1221 break;
1222 }
1223 if (linerest) /* copy characters from the previous buffer */
1224 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1225 vim_free(buffer);
1226 buffer = new_buffer;
1227 ptr = buffer + linerest;
1228 line_start = buffer;
1229
1230#ifdef FEAT_MBYTE
1231 /* May need room to translate into.
1232 * For iconv() we don't really know the required space, use a
1233 * factor ICONV_MULT.
1234 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1235 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1236 * become up to 4 bytes, size must be multiple of 2
1237 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1238 * multiple of 2
1239 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1240 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001241 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242# ifdef USE_ICONV
1243 if (iconv_fd != (iconv_t)-1)
1244 size = size / ICONV_MULT;
1245 else
1246# endif
1247 if (fio_flags & FIO_LATIN1)
1248 size = size / 2;
1249 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1250 size = (size * 2 / 3) & ~1;
1251 else if (fio_flags & FIO_UCS4)
1252 size = (size * 2 / 3) & ~3;
1253 else if (fio_flags == FIO_UCSBOM)
1254 size = size / ICONV_MULT; /* worst case */
1255# ifdef WIN3264
1256 else if (fio_flags & FIO_CODEPAGE)
1257 size = size / ICONV_MULT; /* also worst case */
1258# endif
1259# ifdef MACOS_X
1260 else if (fio_flags & FIO_MACROMAN)
1261 size = size / ICONV_MULT; /* also worst case */
1262# endif
1263#endif
1264
1265#ifdef FEAT_MBYTE
1266 if (conv_restlen > 0)
1267 {
1268 /* Insert unconverted bytes from previous line. */
1269 mch_memmove(ptr, conv_rest, conv_restlen);
1270 ptr += conv_restlen;
1271 size -= conv_restlen;
1272 }
1273#endif
1274
1275 if (read_buffer)
1276 {
1277 /*
1278 * Read bytes from curbuf. Used for converting text read
1279 * from stdin.
1280 */
1281 if (read_buf_lnum > from)
1282 size = 0;
1283 else
1284 {
1285 int n, ni;
1286 long tlen;
1287
1288 tlen = 0;
1289 for (;;)
1290 {
1291 p = ml_get(read_buf_lnum) + read_buf_col;
1292 n = (int)STRLEN(p);
1293 if ((int)tlen + n + 1 > size)
1294 {
1295 /* Filled up to "size", append partial line.
1296 * Change NL to NUL to reverse the effect done
1297 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001298 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299 for (ni = 0; ni < n; ++ni)
1300 {
1301 if (p[ni] == NL)
1302 ptr[tlen++] = NUL;
1303 else
1304 ptr[tlen++] = p[ni];
1305 }
1306 read_buf_col += n;
1307 break;
1308 }
1309 else
1310 {
1311 /* Append whole line and new-line. Change NL
1312 * to NUL to reverse the effect done below. */
1313 for (ni = 0; ni < n; ++ni)
1314 {
1315 if (p[ni] == NL)
1316 ptr[tlen++] = NUL;
1317 else
1318 ptr[tlen++] = p[ni];
1319 }
1320 ptr[tlen++] = NL;
1321 read_buf_col = 0;
1322 if (++read_buf_lnum > from)
1323 {
1324 /* When the last line didn't have an
1325 * end-of-line don't add it now either. */
1326 if (!curbuf->b_p_eol)
1327 --tlen;
1328 size = tlen;
1329 break;
1330 }
1331 }
1332 }
1333 }
1334 }
1335 else
1336 {
1337 /*
1338 * Read bytes from the file.
1339 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001340 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 }
1342
1343 if (size <= 0)
1344 {
1345 if (size < 0) /* read error */
1346 error = TRUE;
1347#ifdef FEAT_MBYTE
1348 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001349 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001350 /*
1351 * Reached end-of-file but some trailing bytes could
1352 * not be converted. Truncated file?
1353 */
1354
1355 /* When we did a conversion report an error. */
1356 if (fio_flags != 0
1357# ifdef USE_ICONV
1358 || iconv_fd != (iconv_t)-1
1359# endif
1360 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001361 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001362 if (can_retry)
1363 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001364 if (conv_error == 0)
1365 conv_error = curbuf->b_ml.ml_line_count
1366 - linecnt + 1;
1367 }
1368 /* Remember the first linenr with an illegal byte */
1369 else if (illegal_byte == 0)
1370 illegal_byte = curbuf->b_ml.ml_line_count
1371 - linecnt + 1;
1372 if (bad_char_behavior == BAD_DROP)
1373 {
1374 *(ptr - conv_restlen) = NUL;
1375 conv_restlen = 0;
1376 }
1377 else
1378 {
1379 /* Replace the trailing bytes with the replacement
1380 * character if we were converting; if we weren't,
1381 * leave the UTF8 checking code to do it, as it
1382 * works slightly differently. */
1383 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1384# ifdef USE_ICONV
1385 || iconv_fd != (iconv_t)-1
1386# endif
1387 ))
1388 {
1389 while (conv_restlen > 0)
1390 {
1391 *(--ptr) = bad_char_behavior;
1392 --conv_restlen;
1393 }
1394 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001395 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001396# ifdef USE_ICONV
1397 if (iconv_fd != (iconv_t)-1)
1398 {
1399 iconv_close(iconv_fd);
1400 iconv_fd = (iconv_t)-1;
1401 }
1402# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001403 }
1404 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405#endif
1406 }
1407
1408#ifdef FEAT_CRYPT
1409 /*
1410 * At start of file: Check for magic number of encryption.
1411 */
1412 if (filesize == 0)
1413 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001414 &filesize, newfile, sfname,
1415 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416 /*
1417 * Decrypt the read bytes.
1418 */
1419 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001420 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421#endif
1422 }
1423 skip_read = FALSE;
1424
1425#ifdef FEAT_MBYTE
1426 /*
1427 * At start of file (or after crypt magic number): Check for BOM.
1428 * Also check for a BOM for other Unicode encodings, but not after
1429 * converting with 'charconvert' or when a BOM has already been
1430 * found.
1431 */
1432 if ((filesize == 0
1433# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001434 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001435 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001436 + crypt_seed_len[use_crypt_method])
1437 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438# endif
1439 )
1440 && (fio_flags == FIO_UCSBOM
1441 || (!curbuf->b_p_bomb
1442 && tmpname == NULL
1443 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1444 {
1445 char_u *ccname;
1446 int blen;
1447
1448 /* no BOM detection in a short file or in binary mode */
1449 if (size < 2 || curbuf->b_p_bin)
1450 ccname = NULL;
1451 else
1452 ccname = check_for_bom(ptr, size, &blen,
1453 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1454 if (ccname != NULL)
1455 {
1456 /* Remove BOM from the text */
1457 filesize += blen;
1458 size -= blen;
1459 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001460 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001461 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001463 curbuf->b_start_bomb = TRUE;
1464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 }
1466
1467 if (fio_flags == FIO_UCSBOM)
1468 {
1469 if (ccname == NULL)
1470 {
1471 /* No BOM detected: retry with next encoding. */
1472 advance_fenc = TRUE;
1473 }
1474 else
1475 {
1476 /* BOM detected: set "fenc" and jump back */
1477 if (fenc_alloced)
1478 vim_free(fenc);
1479 fenc = ccname;
1480 fenc_alloced = FALSE;
1481 }
1482 /* retry reading without getting new bytes or rewinding */
1483 skip_read = TRUE;
1484 goto retry;
1485 }
1486 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001487
1488 /* Include not converted bytes. */
1489 ptr -= conv_restlen;
1490 size += conv_restlen;
1491 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492#endif
1493 /*
1494 * Break here for a read error or end-of-file.
1495 */
1496 if (size <= 0)
1497 break;
1498
1499#ifdef FEAT_MBYTE
1500
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501# ifdef USE_ICONV
1502 if (iconv_fd != (iconv_t)-1)
1503 {
1504 /*
1505 * Attempt conversion of the read bytes to 'encoding' using
1506 * iconv().
1507 */
1508 const char *fromp;
1509 char *top;
1510 size_t from_size;
1511 size_t to_size;
1512
1513 fromp = (char *)ptr;
1514 from_size = size;
1515 ptr += size;
1516 top = (char *)ptr;
1517 to_size = real_size - size;
1518
1519 /*
1520 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001521 * another conversion. Except for when there is no
1522 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001524 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1525 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1527 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001528 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001529 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001530 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001531 if (conv_error == 0)
1532 conv_error = readfile_linenr(linecnt,
1533 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001534
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001535 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001536 ++fromp;
1537 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001538 if (bad_char_behavior == BAD_KEEP)
1539 {
1540 *top++ = *(fromp - 1);
1541 --to_size;
1542 }
1543 else if (bad_char_behavior != BAD_DROP)
1544 {
1545 *top++ = bad_char_behavior;
1546 --to_size;
1547 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001548 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549
1550 if (from_size > 0)
1551 {
1552 /* Some remaining characters, keep them for the next
1553 * round. */
1554 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1555 conv_restlen = (int)from_size;
1556 }
1557
1558 /* move the linerest to before the converted characters */
1559 line_start = ptr - linerest;
1560 mch_memmove(line_start, buffer, (size_t)linerest);
1561 size = (long)((char_u *)top - ptr);
1562 }
1563# endif
1564
1565# ifdef WIN3264
1566 if (fio_flags & FIO_CODEPAGE)
1567 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001568 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001569 WCHAR ucs2buf[3];
1570 int ucs2len;
1571 int codepage = FIO_GET_CP(fio_flags);
1572 int bytelen;
1573 int found_bad;
1574 char replstr[2];
1575
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576 /*
1577 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001578 * a codepage, using standard MS-Windows functions. This
1579 * requires two steps:
1580 * 1. convert from 'fileencoding' to ucs-2
1581 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001583 * Because there may be illegal bytes AND an incomplete byte
1584 * sequence at the end, we may have to do the conversion one
1585 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001588 /* Replacement string for WideCharToMultiByte(). */
1589 if (bad_char_behavior > 0)
1590 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001592 replstr[0] = '?';
1593 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594
1595 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001596 * Move the bytes to the end of the buffer, so that we have
1597 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001599 src = ptr + real_size - size;
1600 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001602 /*
1603 * Do the conversion.
1604 */
1605 dst = ptr;
1606 size = size;
1607 while (size > 0)
1608 {
1609 found_bad = FALSE;
1610
1611# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1612 if (codepage == CP_UTF8)
1613 {
1614 /* Handle CP_UTF8 input ourselves to be able to handle
1615 * trailing bytes properly.
1616 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001617 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001618 if (bytelen > size)
1619 {
1620 /* Only got some bytes of a character. Normally
1621 * it's put in "conv_rest", but if it's too long
1622 * deal with it as if they were illegal bytes. */
1623 if (bytelen <= CONV_RESTLEN)
1624 break;
1625
1626 /* weird overlong byte sequence */
1627 bytelen = size;
1628 found_bad = TRUE;
1629 }
1630 else
1631 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001632 int u8c = utf_ptr2char(src);
1633
Bram Moolenaar86e01082005-12-29 22:45:34 +00001634 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001635 found_bad = TRUE;
1636 ucs2buf[0] = u8c;
1637 ucs2len = 1;
1638 }
1639 }
1640 else
1641# endif
1642 {
1643 /* We don't know how long the byte sequence is, try
1644 * from one to three bytes. */
1645 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1646 ++bytelen)
1647 {
1648 ucs2len = MultiByteToWideChar(codepage,
1649 MB_ERR_INVALID_CHARS,
1650 (LPCSTR)src, bytelen,
1651 ucs2buf, 3);
1652 if (ucs2len > 0)
1653 break;
1654 }
1655 if (ucs2len == 0)
1656 {
1657 /* If we have only one byte then it's probably an
1658 * incomplete byte sequence. Otherwise discard
1659 * one byte as a bad character. */
1660 if (size == 1)
1661 break;
1662 found_bad = TRUE;
1663 bytelen = 1;
1664 }
1665 }
1666
1667 if (!found_bad)
1668 {
1669 int i;
1670
1671 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1672 if (enc_utf8)
1673 {
1674 /* From UCS-2 to UTF-8. Cannot fail. */
1675 for (i = 0; i < ucs2len; ++i)
1676 dst += utf_char2bytes(ucs2buf[i], dst);
1677 }
1678 else
1679 {
1680 BOOL bad = FALSE;
1681 int dstlen;
1682
1683 /* From UCS-2 to "enc_codepage". If the
1684 * conversion uses the default character "?",
1685 * the data doesn't fit in this encoding. */
1686 dstlen = WideCharToMultiByte(enc_codepage, 0,
1687 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001688 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001689 replstr, &bad);
1690 if (bad)
1691 found_bad = TRUE;
1692 else
1693 dst += dstlen;
1694 }
1695 }
1696
1697 if (found_bad)
1698 {
1699 /* Deal with bytes we can't convert. */
1700 if (can_retry)
1701 goto rewind_retry;
1702 if (conv_error == 0)
1703 conv_error = readfile_linenr(linecnt, ptr, dst);
1704 if (bad_char_behavior != BAD_DROP)
1705 {
1706 if (bad_char_behavior == BAD_KEEP)
1707 {
1708 mch_memmove(dst, src, bytelen);
1709 dst += bytelen;
1710 }
1711 else
1712 *dst++ = bad_char_behavior;
1713 }
1714 }
1715
1716 src += bytelen;
1717 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001719
1720 if (size > 0)
1721 {
1722 /* An incomplete byte sequence remaining. */
1723 mch_memmove(conv_rest, src, size);
1724 conv_restlen = size;
1725 }
1726
1727 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001728 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 }
1730 else
1731# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001732# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 if (fio_flags & FIO_MACROMAN)
1734 {
1735 /*
1736 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001737 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001739 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 }
1742 else
1743# endif
1744 if (fio_flags != 0)
1745 {
1746 int u8c;
1747 char_u *dest;
1748 char_u *tail = NULL;
1749
1750 /*
1751 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1752 * "enc_utf8" not set: Convert Unicode to Latin1.
1753 * Go from end to start through the buffer, because the number
1754 * of bytes may increase.
1755 * "dest" points to after where the UTF-8 bytes go, "p" points
1756 * to after the next character to convert.
1757 */
1758 dest = ptr + real_size;
1759 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1760 {
1761 p = ptr + size;
1762 if (fio_flags == FIO_UTF8)
1763 {
1764 /* Check for a trailing incomplete UTF-8 sequence */
1765 tail = ptr + size - 1;
1766 while (tail > ptr && (*tail & 0xc0) == 0x80)
1767 --tail;
1768 if (tail + utf_byte2len(*tail) <= ptr + size)
1769 tail = NULL;
1770 else
1771 p = tail;
1772 }
1773 }
1774 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1775 {
1776 /* Check for a trailing byte */
1777 p = ptr + (size & ~1);
1778 if (size & 1)
1779 tail = p;
1780 if ((fio_flags & FIO_UTF16) && p > ptr)
1781 {
1782 /* Check for a trailing leading word */
1783 if (fio_flags & FIO_ENDIAN_L)
1784 {
1785 u8c = (*--p << 8);
1786 u8c += *--p;
1787 }
1788 else
1789 {
1790 u8c = *--p;
1791 u8c += (*--p << 8);
1792 }
1793 if (u8c >= 0xd800 && u8c <= 0xdbff)
1794 tail = p;
1795 else
1796 p += 2;
1797 }
1798 }
1799 else /* FIO_UCS4 */
1800 {
1801 /* Check for trailing 1, 2 or 3 bytes */
1802 p = ptr + (size & ~3);
1803 if (size & 3)
1804 tail = p;
1805 }
1806
1807 /* If there is a trailing incomplete sequence move it to
1808 * conv_rest[]. */
1809 if (tail != NULL)
1810 {
1811 conv_restlen = (int)((ptr + size) - tail);
1812 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1813 size -= conv_restlen;
1814 }
1815
1816
1817 while (p > ptr)
1818 {
1819 if (fio_flags & FIO_LATIN1)
1820 u8c = *--p;
1821 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1822 {
1823 if (fio_flags & FIO_ENDIAN_L)
1824 {
1825 u8c = (*--p << 8);
1826 u8c += *--p;
1827 }
1828 else
1829 {
1830 u8c = *--p;
1831 u8c += (*--p << 8);
1832 }
1833 if ((fio_flags & FIO_UTF16)
1834 && u8c >= 0xdc00 && u8c <= 0xdfff)
1835 {
1836 int u16c;
1837
1838 if (p == ptr)
1839 {
1840 /* Missing leading word. */
1841 if (can_retry)
1842 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001843 if (conv_error == 0)
1844 conv_error = readfile_linenr(linecnt,
1845 ptr, p);
1846 if (bad_char_behavior == BAD_DROP)
1847 continue;
1848 if (bad_char_behavior != BAD_KEEP)
1849 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 }
1851
1852 /* found second word of double-word, get the first
1853 * word and compute the resulting character */
1854 if (fio_flags & FIO_ENDIAN_L)
1855 {
1856 u16c = (*--p << 8);
1857 u16c += *--p;
1858 }
1859 else
1860 {
1861 u16c = *--p;
1862 u16c += (*--p << 8);
1863 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001864 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1865 + (u8c & 0x3ff);
1866
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 /* Check if the word is indeed a leading word. */
1868 if (u16c < 0xd800 || u16c > 0xdbff)
1869 {
1870 if (can_retry)
1871 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001872 if (conv_error == 0)
1873 conv_error = readfile_linenr(linecnt,
1874 ptr, p);
1875 if (bad_char_behavior == BAD_DROP)
1876 continue;
1877 if (bad_char_behavior != BAD_KEEP)
1878 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880 }
1881 }
1882 else if (fio_flags & FIO_UCS4)
1883 {
1884 if (fio_flags & FIO_ENDIAN_L)
1885 {
1886 u8c = (*--p << 24);
1887 u8c += (*--p << 16);
1888 u8c += (*--p << 8);
1889 u8c += *--p;
1890 }
1891 else /* big endian */
1892 {
1893 u8c = *--p;
1894 u8c += (*--p << 8);
1895 u8c += (*--p << 16);
1896 u8c += (*--p << 24);
1897 }
1898 }
1899 else /* UTF-8 */
1900 {
1901 if (*--p < 0x80)
1902 u8c = *p;
1903 else
1904 {
1905 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 p -= len;
1907 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 if (len == 0)
1909 {
1910 /* Not a valid UTF-8 character, retry with
1911 * another fenc when possible, otherwise just
1912 * report the error. */
1913 if (can_retry)
1914 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001915 if (conv_error == 0)
1916 conv_error = readfile_linenr(linecnt,
1917 ptr, p);
1918 if (bad_char_behavior == BAD_DROP)
1919 continue;
1920 if (bad_char_behavior != BAD_KEEP)
1921 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 }
1924 }
1925 if (enc_utf8) /* produce UTF-8 */
1926 {
1927 dest -= utf_char2len(u8c);
1928 (void)utf_char2bytes(u8c, dest);
1929 }
1930 else /* produce Latin1 */
1931 {
1932 --dest;
1933 if (u8c >= 0x100)
1934 {
1935 /* character doesn't fit in latin1, retry with
1936 * another fenc when possible, otherwise just
1937 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001938 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001940 if (conv_error == 0)
1941 conv_error = readfile_linenr(linecnt, ptr, p);
1942 if (bad_char_behavior == BAD_DROP)
1943 ++dest;
1944 else if (bad_char_behavior == BAD_KEEP)
1945 *dest = u8c;
1946 else if (eap != NULL && eap->bad_char != 0)
1947 *dest = bad_char_behavior;
1948 else
1949 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 }
1951 else
1952 *dest = u8c;
1953 }
1954 }
1955
1956 /* move the linerest to before the converted characters */
1957 line_start = dest - linerest;
1958 mch_memmove(line_start, buffer, (size_t)linerest);
1959 size = (long)((ptr + real_size) - dest);
1960 ptr = dest;
1961 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001962 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001964 int incomplete_tail = FALSE;
1965
1966 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1967 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001969 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001970 int l;
1971
1972 if (todo <= 0)
1973 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 if (*p >= 0x80)
1975 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 /* A length of 1 means it's an illegal byte. Accept
1977 * an incomplete character at the end though, the next
1978 * read() will get the next bytes, we'll check it
1979 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001980 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001981 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001983 /* Avoid retrying with a different encoding when
1984 * a truncated file is more likely, or attempting
1985 * to read the rest of an incomplete sequence when
1986 * we have already done so. */
1987 if (p > ptr || filesize > 0)
1988 incomplete_tail = TRUE;
1989 /* Incomplete byte sequence, move it to conv_rest[]
1990 * and try to read the rest of it, unless we've
1991 * already done so. */
1992 if (p > ptr)
1993 {
1994 conv_restlen = todo;
1995 mch_memmove(conv_rest, p, conv_restlen);
1996 size -= conv_restlen;
1997 break;
1998 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002000 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002001 {
2002 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002003 * do that, unless at EOF where a truncated
2004 * file is more likely than a conversion error. */
2005 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002006 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002007# ifdef USE_ICONV
2008 /* When we did a conversion report an error. */
2009 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2010 conv_error = readfile_linenr(linecnt, ptr, p);
2011# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002012 /* Remember the first linenr with an illegal byte */
2013 if (conv_error == 0 && illegal_byte == 0)
2014 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002015
2016 /* Drop, keep or replace the bad byte. */
2017 if (bad_char_behavior == BAD_DROP)
2018 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002019 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002020 --p;
2021 --size;
2022 }
2023 else if (bad_char_behavior != BAD_KEEP)
2024 *p = bad_char_behavior;
2025 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002026 else
2027 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 }
2029 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002030 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 {
2032 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002034 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002036 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2037 /* iconv() failed, try 'charconvert' */
2038 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 else
2040# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002041 /* use next item from 'fileencodings' */
2042 advance_fenc = TRUE;
2043 file_rewind = TRUE;
2044 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 }
2046 }
2047#endif
2048
2049 /* count the number of characters (after conversion!) */
2050 filesize += size;
2051
2052 /*
2053 * when reading the first part of a file: guess EOL type
2054 */
2055 if (fileformat == EOL_UNKNOWN)
2056 {
2057 /* First try finding a NL, for Dos and Unix */
2058 if (try_dos || try_unix)
2059 {
2060 for (p = ptr; p < ptr + size; ++p)
2061 {
2062 if (*p == NL)
2063 {
2064 if (!try_unix
2065 || (try_dos && p > ptr && p[-1] == CAR))
2066 fileformat = EOL_DOS;
2067 else
2068 fileformat = EOL_UNIX;
2069 break;
2070 }
2071 }
2072
2073 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2074 if (fileformat == EOL_UNIX && try_mac)
2075 {
2076 /* Need to reset the counters when retrying fenc. */
2077 try_mac = 1;
2078 try_unix = 1;
2079 for (; p >= ptr && *p != CAR; p--)
2080 ;
2081 if (p >= ptr)
2082 {
2083 for (p = ptr; p < ptr + size; ++p)
2084 {
2085 if (*p == NL)
2086 try_unix++;
2087 else if (*p == CAR)
2088 try_mac++;
2089 }
2090 if (try_mac > try_unix)
2091 fileformat = EOL_MAC;
2092 }
2093 }
2094 }
2095
2096 /* No NL found: may use Mac format */
2097 if (fileformat == EOL_UNKNOWN && try_mac)
2098 fileformat = EOL_MAC;
2099
2100 /* Still nothing found? Use first format in 'ffs' */
2101 if (fileformat == EOL_UNKNOWN)
2102 fileformat = default_fileformat();
2103
2104 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002105 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 set_fileformat(fileformat, OPT_LOCAL);
2107 }
2108 }
2109
2110 /*
2111 * This loop is executed once for every character read.
2112 * Keep it fast!
2113 */
2114 if (fileformat == EOL_MAC)
2115 {
2116 --ptr;
2117 while (++ptr, --size >= 0)
2118 {
2119 /* catch most common case first */
2120 if ((c = *ptr) != NUL && c != CAR && c != NL)
2121 continue;
2122 if (c == NUL)
2123 *ptr = NL; /* NULs are replaced by newlines! */
2124 else if (c == NL)
2125 *ptr = CAR; /* NLs are replaced by CRs! */
2126 else
2127 {
2128 if (skip_count == 0)
2129 {
2130 *ptr = NUL; /* end of line */
2131 len = (colnr_T) (ptr - line_start + 1);
2132 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2133 {
2134 error = TRUE;
2135 break;
2136 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002137#ifdef FEAT_PERSISTENT_UNDO
2138 if (read_undo_file)
2139 sha256_update(&sha_ctx, line_start, len);
2140#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141 ++lnum;
2142 if (--read_count == 0)
2143 {
2144 error = TRUE; /* break loop */
2145 line_start = ptr; /* nothing left to write */
2146 break;
2147 }
2148 }
2149 else
2150 --skip_count;
2151 line_start = ptr + 1;
2152 }
2153 }
2154 }
2155 else
2156 {
2157 --ptr;
2158 while (++ptr, --size >= 0)
2159 {
2160 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2161 continue;
2162 if (c == NUL)
2163 *ptr = NL; /* NULs are replaced by newlines! */
2164 else
2165 {
2166 if (skip_count == 0)
2167 {
2168 *ptr = NUL; /* end of line */
2169 len = (colnr_T)(ptr - line_start + 1);
2170 if (fileformat == EOL_DOS)
2171 {
2172 if (ptr[-1] == CAR) /* remove CR */
2173 {
2174 ptr[-1] = NUL;
2175 --len;
2176 }
2177 /*
2178 * Reading in Dos format, but no CR-LF found!
2179 * When 'fileformats' includes "unix", delete all
2180 * the lines read so far and start all over again.
2181 * Otherwise give an error message later.
2182 */
2183 else if (ff_error != EOL_DOS)
2184 {
2185 if ( try_unix
2186 && !read_stdin
2187 && (read_buffer
2188 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2189 {
2190 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002191 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 set_fileformat(EOL_UNIX, OPT_LOCAL);
2193 file_rewind = TRUE;
2194 keep_fileformat = TRUE;
2195 goto retry;
2196 }
2197 ff_error = EOL_DOS;
2198 }
2199 }
2200 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2201 {
2202 error = TRUE;
2203 break;
2204 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002205#ifdef FEAT_PERSISTENT_UNDO
2206 if (read_undo_file)
2207 sha256_update(&sha_ctx, line_start, len);
2208#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 ++lnum;
2210 if (--read_count == 0)
2211 {
2212 error = TRUE; /* break loop */
2213 line_start = ptr; /* nothing left to write */
2214 break;
2215 }
2216 }
2217 else
2218 --skip_count;
2219 line_start = ptr + 1;
2220 }
2221 }
2222 }
2223 linerest = (long)(ptr - line_start);
2224 ui_breakcheck();
2225 }
2226
2227failed:
2228 /* not an error, max. number of lines reached */
2229 if (error && read_count == 0)
2230 error = FALSE;
2231
2232 /*
2233 * If we get EOF in the middle of a line, note the fact and
2234 * complete the line ourselves.
2235 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2236 */
2237 if (!error
2238 && !got_int
2239 && linerest != 0
2240 && !(!curbuf->b_p_bin
2241 && fileformat == EOL_DOS
2242 && *line_start == Ctrl_Z
2243 && ptr == line_start + 1))
2244 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002245 /* remember for when writing */
2246 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 curbuf->b_p_eol = FALSE;
2248 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002249 len = (colnr_T)(ptr - line_start + 1);
2250 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 error = TRUE;
2252 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002253 {
2254#ifdef FEAT_PERSISTENT_UNDO
2255 if (read_undo_file)
2256 sha256_update(&sha_ctx, line_start, len);
2257#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002259 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 }
2261
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002262 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263 save_file_ff(curbuf); /* remember the current file format */
2264
2265#ifdef FEAT_CRYPT
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01002266 crypt_method_used = use_crypt_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002267 if (cryptkey != NULL)
2268 {
2269 crypt_pop_state();
2270 if (cryptkey != curbuf->b_p_key)
2271 free_crypt_key(cryptkey);
2272 /* don't set cryptkey to NULL, it's used below as a flag that
2273 * encryption was used */
2274 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275#endif
2276
2277#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002278 /* If editing a new file: set 'fenc' for the current buffer.
2279 * Also for ":read ++edit file". */
2280 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002282 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 if (fenc_alloced)
2284 vim_free(fenc);
2285# ifdef USE_ICONV
2286 if (iconv_fd != (iconv_t)-1)
2287 {
2288 iconv_close(iconv_fd);
2289 iconv_fd = (iconv_t)-1;
2290 }
2291# endif
2292#endif
2293
2294 if (!read_buffer && !read_stdin)
2295 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002296#ifdef HAVE_FD_CLOEXEC
2297 else
2298 {
2299 int fdflags = fcntl(fd, F_GETFD);
2300 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2301 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2302 }
2303#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 vim_free(buffer);
2305
2306#ifdef HAVE_DUP
2307 if (read_stdin)
2308 {
2309 /* Use stderr for stdin, makes shell commands work. */
2310 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002311 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 }
2313#endif
2314
2315#ifdef FEAT_MBYTE
2316 if (tmpname != NULL)
2317 {
2318 mch_remove(tmpname); /* delete converted file */
2319 vim_free(tmpname);
2320 }
2321#endif
2322 --no_wait_return; /* may wait for return now */
2323
2324 /*
2325 * In recovery mode everything but autocommands is skipped.
2326 */
2327 if (!recoverymode)
2328 {
2329 /* need to delete the last line, which comes from the empty buffer */
2330 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2331 {
2332#ifdef FEAT_NETBEANS_INTG
2333 netbeansFireChanges = 0;
2334#endif
2335 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2336#ifdef FEAT_NETBEANS_INTG
2337 netbeansFireChanges = 1;
2338#endif
2339 --linecnt;
2340 }
2341 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2342 if (filesize == 0)
2343 linecnt = 0;
2344 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002345 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002347#ifdef FEAT_DIFF
2348 /* After reading the text into the buffer the diff info needs to
2349 * be updated. */
2350 diff_invalidate(curbuf);
2351#endif
2352#ifdef FEAT_FOLDING
2353 /* All folds in the window are invalid now. Mark them for update
2354 * before triggering autocommands. */
2355 foldUpdateAll(curwin);
2356#endif
2357 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 else if (linecnt) /* appended at least one line */
2359 appended_lines_mark(from, linecnt);
2360
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361#ifndef ALWAYS_USE_GUI
2362 /*
2363 * If we were reading from the same terminal as where messages go,
2364 * the screen will have been messed up.
2365 * Switch on raw mode now and clear the screen.
2366 */
2367 if (read_stdin)
2368 {
2369 settmode(TMODE_RAW); /* set to raw mode */
2370 starttermcap();
2371 screenclear();
2372 }
2373#endif
2374
2375 if (got_int)
2376 {
2377 if (!(flags & READ_DUMMY))
2378 {
2379 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2380 if (newfile)
2381 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2382 }
2383 msg_scroll = msg_save;
2384#ifdef FEAT_VIMINFO
2385 check_marks_read();
2386#endif
2387 return OK; /* an interrupt isn't really an error */
2388 }
2389
2390 if (!filtering && !(flags & READ_DUMMY))
2391 {
2392 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2393 c = FALSE;
2394
2395#ifdef UNIX
2396# ifdef S_ISFIFO
2397 if (S_ISFIFO(perm)) /* fifo or socket */
2398 {
2399 STRCAT(IObuff, _("[fifo/socket]"));
2400 c = TRUE;
2401 }
2402# else
2403# ifdef S_IFIFO
2404 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2405 {
2406 STRCAT(IObuff, _("[fifo]"));
2407 c = TRUE;
2408 }
2409# endif
2410# ifdef S_IFSOCK
2411 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2412 {
2413 STRCAT(IObuff, _("[socket]"));
2414 c = TRUE;
2415 }
2416# endif
2417# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002418# ifdef OPEN_CHR_FILES
2419 if (S_ISCHR(perm)) /* or character special */
2420 {
2421 STRCAT(IObuff, _("[character special]"));
2422 c = TRUE;
2423 }
2424# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425#endif
2426 if (curbuf->b_p_ro)
2427 {
2428 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2429 c = TRUE;
2430 }
2431 if (read_no_eol_lnum)
2432 {
2433 msg_add_eol();
2434 c = TRUE;
2435 }
2436 if (ff_error == EOL_DOS)
2437 {
2438 STRCAT(IObuff, _("[CR missing]"));
2439 c = TRUE;
2440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 if (split)
2442 {
2443 STRCAT(IObuff, _("[long lines split]"));
2444 c = TRUE;
2445 }
2446#ifdef FEAT_MBYTE
2447 if (notconverted)
2448 {
2449 STRCAT(IObuff, _("[NOT converted]"));
2450 c = TRUE;
2451 }
2452 else if (converted)
2453 {
2454 STRCAT(IObuff, _("[converted]"));
2455 c = TRUE;
2456 }
2457#endif
2458#ifdef FEAT_CRYPT
2459 if (cryptkey != NULL)
2460 {
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01002461 if (crypt_method_used == 1)
2462 STRCAT(IObuff, _("[blowfish]"));
2463 else
2464 STRCAT(IObuff, _("[crypted]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 c = TRUE;
2466 }
2467#endif
2468#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002469 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002471 sprintf((char *)IObuff + STRLEN(IObuff),
2472 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 c = TRUE;
2474 }
2475 else if (illegal_byte > 0)
2476 {
2477 sprintf((char *)IObuff + STRLEN(IObuff),
2478 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2479 c = TRUE;
2480 }
2481 else
2482#endif
2483 if (error)
2484 {
2485 STRCAT(IObuff, _("[READ ERRORS]"));
2486 c = TRUE;
2487 }
2488 if (msg_add_fileformat(fileformat))
2489 c = TRUE;
2490#ifdef FEAT_CRYPT
2491 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002492 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002493 - CRYPT_MAGIC_LEN
2494 - crypt_salt_len[use_crypt_method]
2495 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 else
2497#endif
2498 msg_add_lines(c, (long)linecnt, filesize);
2499
2500 vim_free(keep_msg);
2501 keep_msg = NULL;
2502 msg_scrolled_ign = TRUE;
2503#ifdef ALWAYS_USE_GUI
2504 /* Don't show the message when reading stdin, it would end up in a
2505 * message box (which might be shown when exiting!) */
2506 if (read_stdin || read_buffer)
2507 p = msg_may_trunc(FALSE, IObuff);
2508 else
2509#endif
2510 p = msg_trunc_attr(IObuff, FALSE, 0);
2511 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002512 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 /* Need to repeat the message after redrawing when:
2514 * - When reading from stdin (the screen will be cleared next).
2515 * - When restart_edit is set (otherwise there will be a delay
2516 * before redrawing).
2517 * - When the screen was scrolled but there is no wait-return
2518 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002519 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 msg_scrolled_ign = FALSE;
2521 }
2522
2523 /* with errors writing the file requires ":w!" */
2524 if (newfile && (error
2525#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002526 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002527 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528#endif
2529 ))
2530 curbuf->b_p_ro = TRUE;
2531
2532 u_clearline(); /* cannot use "U" command after adding lines */
2533
2534 /*
2535 * In Ex mode: cursor at last new line.
2536 * Otherwise: cursor at first new line.
2537 */
2538 if (exmode_active)
2539 curwin->w_cursor.lnum = from + linecnt;
2540 else
2541 curwin->w_cursor.lnum = from + 1;
2542 check_cursor_lnum();
2543 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2544
2545 /*
2546 * Set '[ and '] marks to the newly read lines.
2547 */
2548 curbuf->b_op_start.lnum = from + 1;
2549 curbuf->b_op_start.col = 0;
2550 curbuf->b_op_end.lnum = from + linecnt;
2551 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002552
2553#ifdef WIN32
2554 /*
2555 * Work around a weird problem: When a file has two links (only
2556 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002557 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002558 * It's correct again after reading the file, thus reset the timestamp
2559 * here.
2560 */
2561 if (newfile && !read_stdin && !read_buffer
2562 && mch_stat((char *)fname, &st) >= 0)
2563 {
2564 buf_store_time(curbuf, &st, fname);
2565 curbuf->b_mtime_read = curbuf->b_mtime;
2566 }
2567#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 }
2569 msg_scroll = msg_save;
2570
2571#ifdef FEAT_VIMINFO
2572 /*
2573 * Get the marks before executing autocommands, so they can be used there.
2574 */
2575 check_marks_read();
2576#endif
2577
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 /*
2579 * Trick: We remember if the last line of the read didn't have
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002580 * an eol even when 'binary' is off, for when writing it again with
2581 * 'binary' on. This is required for
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2583 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002584 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002586 /* When reloading a buffer put the cursor at the first line that is
2587 * different. */
2588 if (flags & READ_KEEP_UNDO)
2589 u_find_first_changed();
2590
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002591#ifdef FEAT_PERSISTENT_UNDO
2592 /*
2593 * When opening a new file locate undo info and read it.
2594 */
2595 if (read_undo_file)
2596 {
2597 char_u hash[UNDO_HASH_SIZE];
2598
2599 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002600 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002601 }
2602#endif
2603
Bram Moolenaardf177f62005-02-22 08:39:57 +00002604#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 if (!read_stdin && !read_buffer)
2606 {
2607 int m = msg_scroll;
2608 int n = msg_scrolled;
2609
2610 /* Save the fileformat now, otherwise the buffer will be considered
2611 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002612 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 save_file_ff(curbuf);
2614
2615 /*
2616 * The output from the autocommands should not overwrite anything and
2617 * should not be overwritten: Set msg_scroll, restore its value if no
2618 * output was done.
2619 */
2620 msg_scroll = TRUE;
2621 if (filtering)
2622 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2623 FALSE, curbuf, eap);
2624 else if (newfile)
2625 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2626 FALSE, curbuf, eap);
2627 else
2628 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2629 FALSE, NULL, eap);
2630 if (msg_scrolled == n)
2631 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002632# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 if (aborting()) /* autocmds may abort script processing */
2634 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002635# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636 }
2637#endif
2638
2639 if (recoverymode && error)
2640 return FAIL;
2641 return OK;
2642}
2643
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002644#ifdef OPEN_CHR_FILES
2645/*
2646 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2647 * which is the name of files used for process substitution output by
2648 * some shells on some operating systems, e.g., bash on SunOS.
2649 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2650 */
2651 static int
2652is_dev_fd_file(fname)
2653 char_u *fname;
2654{
2655 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2656 && VIM_ISDIGIT(fname[8])
2657 && *skipdigits(fname + 9) == NUL
2658 && (fname[9] != NUL
2659 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2660}
2661#endif
2662
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002663#ifdef FEAT_MBYTE
2664
2665/*
2666 * From the current line count and characters read after that, estimate the
2667 * line number where we are now.
2668 * Used for error messages that include a line number.
2669 */
2670 static linenr_T
2671readfile_linenr(linecnt, p, endp)
2672 linenr_T linecnt; /* line count before reading more bytes */
2673 char_u *p; /* start of more bytes read */
2674 char_u *endp; /* end of more bytes read */
2675{
2676 char_u *s;
2677 linenr_T lnum;
2678
2679 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2680 for (s = p; s < endp; ++s)
2681 if (*s == '\n')
2682 ++lnum;
2683 return lnum;
2684}
2685#endif
2686
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002688 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2689 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 * Returns OK or FAIL.
2691 */
2692 int
2693prep_exarg(eap, buf)
2694 exarg_T *eap;
2695 buf_T *buf;
2696{
2697 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2698#ifdef FEAT_MBYTE
2699 + STRLEN(buf->b_p_fenc)
2700#endif
2701 + 15));
2702 if (eap->cmd == NULL)
2703 return FAIL;
2704
2705#ifdef FEAT_MBYTE
2706 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2707 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002708 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709#else
2710 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2711#endif
2712 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002713
2714 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002715 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002716 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 return OK;
2718}
2719
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002720/*
2721 * Set default or forced 'fileformat' and 'binary'.
2722 */
2723 void
2724set_file_options(set_options, eap)
2725 int set_options;
2726 exarg_T *eap;
2727{
2728 /* set default 'fileformat' */
2729 if (set_options)
2730 {
2731 if (eap != NULL && eap->force_ff != 0)
2732 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2733 else if (*p_ffs != NUL)
2734 set_fileformat(default_fileformat(), OPT_LOCAL);
2735 }
2736
2737 /* set or reset 'binary' */
2738 if (eap != NULL && eap->force_bin != 0)
2739 {
2740 int oldval = curbuf->b_p_bin;
2741
2742 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2743 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2744 }
2745}
2746
2747#if defined(FEAT_MBYTE) || defined(PROTO)
2748/*
2749 * Set forced 'fileencoding'.
2750 */
2751 void
2752set_forced_fenc(eap)
2753 exarg_T *eap;
2754{
2755 if (eap->force_enc != 0)
2756 {
2757 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2758
2759 if (fenc != NULL)
2760 set_string_option_direct((char_u *)"fenc", -1,
2761 fenc, OPT_FREE|OPT_LOCAL, 0);
2762 vim_free(fenc);
2763 }
2764}
2765
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766/*
2767 * Find next fileencoding to use from 'fileencodings'.
2768 * "pp" points to fenc_next. It's advanced to the next item.
2769 * When there are no more items, an empty string is returned and *pp is set to
2770 * NULL.
2771 * When *pp is not set to NULL, the result is in allocated memory.
2772 */
2773 static char_u *
2774next_fenc(pp)
2775 char_u **pp;
2776{
2777 char_u *p;
2778 char_u *r;
2779
2780 if (**pp == NUL)
2781 {
2782 *pp = NULL;
2783 return (char_u *)"";
2784 }
2785 p = vim_strchr(*pp, ',');
2786 if (p == NULL)
2787 {
2788 r = enc_canonize(*pp);
2789 *pp += STRLEN(*pp);
2790 }
2791 else
2792 {
2793 r = vim_strnsave(*pp, (int)(p - *pp));
2794 *pp = p + 1;
2795 if (r != NULL)
2796 {
2797 p = enc_canonize(r);
2798 vim_free(r);
2799 r = p;
2800 }
2801 }
2802 if (r == NULL) /* out of memory */
2803 {
2804 r = (char_u *)"";
2805 *pp = NULL;
2806 }
2807 return r;
2808}
2809
2810# ifdef FEAT_EVAL
2811/*
2812 * Convert a file with the 'charconvert' expression.
2813 * This closes the file which is to be read, converts it and opens the
2814 * resulting file for reading.
2815 * Returns name of the resulting converted file (the caller should delete it
2816 * after reading it).
2817 * Returns NULL if the conversion failed ("*fdp" is not set) .
2818 */
2819 static char_u *
2820readfile_charconvert(fname, fenc, fdp)
2821 char_u *fname; /* name of input file */
2822 char_u *fenc; /* converted from */
2823 int *fdp; /* in/out: file descriptor of file */
2824{
2825 char_u *tmpname;
2826 char_u *errmsg = NULL;
2827
2828 tmpname = vim_tempname('r');
2829 if (tmpname == NULL)
2830 errmsg = (char_u *)_("Can't find temp file for conversion");
2831 else
2832 {
2833 close(*fdp); /* close the input file, ignore errors */
2834 *fdp = -1;
2835 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2836 fname, tmpname) == FAIL)
2837 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2838 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2839 O_RDONLY | O_EXTRA, 0)) < 0)
2840 errmsg = (char_u *)_("can't read output of 'charconvert'");
2841 }
2842
2843 if (errmsg != NULL)
2844 {
2845 /* Don't use emsg(), it breaks mappings, the retry with
2846 * another type of conversion might still work. */
2847 MSG(errmsg);
2848 if (tmpname != NULL)
2849 {
2850 mch_remove(tmpname); /* delete converted file */
2851 vim_free(tmpname);
2852 tmpname = NULL;
2853 }
2854 }
2855
2856 /* If the input file is closed, open it (caller should check for error). */
2857 if (*fdp < 0)
2858 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2859
2860 return tmpname;
2861}
2862# endif
2863
2864#endif
2865
2866#ifdef FEAT_VIMINFO
2867/*
2868 * Read marks for the current buffer from the viminfo file, when we support
2869 * buffer marks and the buffer has a name.
2870 */
2871 static void
2872check_marks_read()
2873{
2874 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2875 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002876 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877
2878 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2879 * the ' parameter after opening a buffer. */
2880 curbuf->b_marks_read = TRUE;
2881}
2882#endif
2883
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002884#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002886 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2887 * start of the file.
2888 * Returns -1 when no encryption used.
2889 */
2890 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002891crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002892 char *ptr;
2893 int len;
2894{
2895 int i;
2896
2897 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2898 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002899 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002900 continue;
2901 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2902 return i;
2903 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002904
Bram Moolenaar442b4222010-05-24 21:34:22 +02002905 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002906 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2907 EMSG(_("E821: File is encrypted with unknown method"));
2908
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002909 return -1;
2910}
2911
2912/*
2913 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2915 * *filesizep are updated.
2916 * Return the (new) encryption key, NULL for no encryption.
2917 */
2918 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002919check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 char_u *cryptkey; /* previous encryption key or NULL */
2921 char_u *ptr; /* pointer to read bytes */
2922 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002923 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002925 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002926 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002928 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002929 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002930
2931 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002933 /* Mark the buffer as read-only until the decryption has taken place.
2934 * Avoids accidentally overwriting the file with garbage. */
2935 curbuf->b_p_ro = TRUE;
2936
Bram Moolenaar49771f42010-07-20 17:32:38 +02002937 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002938 if (method > 0)
2939 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002940 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 {
2942 if (*curbuf->b_p_key)
2943 cryptkey = curbuf->b_p_key;
2944 else
2945 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002946 /* When newfile is TRUE, store the typed key in the 'key'
2947 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002948 * Don't ask for the key again when first time Enter was hit.
2949 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002950 smsg((char_u *)_(need_key_msg), fname);
2951 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002953 *did_ask = TRUE;
2954
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 /* check if empty key entered */
2956 if (cryptkey != NULL && *cryptkey == NUL)
2957 {
2958 if (cryptkey != curbuf->b_p_key)
2959 vim_free(cryptkey);
2960 cryptkey = NULL;
2961 }
2962 }
2963 }
2964
2965 if (cryptkey != NULL)
2966 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002967 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002968 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002969
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002970 crypt_push_state();
2971 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002972 if (method == 0)
2973 crypt_init_keys(cryptkey);
2974 else
2975 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002976 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2977 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002978 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979
2980 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002981 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2982 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002983 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2984 (size_t)*sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002985 /* Restore the read-only flag. */
2986 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 }
2988 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002989 /* When starting to edit a new file which does not have encryption, clear
2990 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002991 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2993
2994 return cryptkey;
2995}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002996
2997/*
2998 * Check for magic number used for encryption. Applies to the current buffer.
2999 * If found and decryption is possible returns OK;
3000 */
3001 int
3002prepare_crypt_read(fp)
3003 FILE *fp;
3004{
3005 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02003006 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3007 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003008
3009 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
3010 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003011 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02003012 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003013 CRYPT_SEED_LEN_MAX +
3014 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003015 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003016 return FAIL;
3017
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003018 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003019 if (method == 0)
3020 crypt_init_keys(curbuf->b_p_key);
3021 else
3022 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003023 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003024 int seed_len = crypt_seed_len[method];
3025
Bram Moolenaar80794b12010-06-13 05:20:42 +02003026 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003027 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02003028 bf_key_init(curbuf->b_p_key, buffer, salt_len);
3029 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003030 }
3031 return OK;
3032}
3033
3034/*
3035 * Prepare for writing encrypted bytes for buffer "buf".
3036 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003037 * When out of memory returns NULL.
3038 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003039 */
3040 char_u *
3041prepare_crypt_write(buf, lenp)
3042 buf_T *buf;
3043 int *lenp;
3044{
3045 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003046 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3047 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003048 char_u *salt;
3049 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003050
Bram Moolenaar80794b12010-06-13 05:20:42 +02003051 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3052 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003053 if (header != NULL)
3054 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003055 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003056 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003057 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3058 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003059 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003060 crypt_init_keys(buf->b_p_key);
3061 else
3062 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003063 /* Using blowfish, add salt and seed. */
3064 salt = header + CRYPT_MAGIC_LEN;
3065 seed = salt + salt_len;
3066 sha2_seed(salt, salt_len, seed, seed_len);
3067 bf_key_init(buf->b_p_key, salt, salt_len);
3068 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003069 }
3070 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003071 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003072 return header;
3073}
3074
Bram Moolenaar80794b12010-06-13 05:20:42 +02003075#endif /* FEAT_CRYPT */
3076
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077#ifdef UNIX
3078 static void
3079set_file_time(fname, atime, mtime)
3080 char_u *fname;
3081 time_t atime; /* access time */
3082 time_t mtime; /* modification time */
3083{
3084# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3085 struct utimbuf buf;
3086
3087 buf.actime = atime;
3088 buf.modtime = mtime;
3089 (void)utime((char *)fname, &buf);
3090# else
3091# if defined(HAVE_UTIMES)
3092 struct timeval tvp[2];
3093
3094 tvp[0].tv_sec = atime;
3095 tvp[0].tv_usec = 0;
3096 tvp[1].tv_sec = mtime;
3097 tvp[1].tv_usec = 0;
3098# ifdef NeXT
3099 (void)utimes((char *)fname, tvp);
3100# else
3101 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3102# endif
3103# endif
3104# endif
3105}
3106#endif /* UNIX */
3107
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003108#if defined(VMS) && !defined(MIN)
3109/* Older DECC compiler for VAX doesn't define MIN() */
3110# define MIN(a, b) ((a) < (b) ? (a) : (b))
3111#endif
3112
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003114 * Return TRUE if a file appears to be read-only from the file permissions.
3115 */
3116 int
3117check_file_readonly(fname, perm)
3118 char_u *fname; /* full path to file */
3119 int perm; /* known permissions on file */
3120{
3121#ifndef USE_MCH_ACCESS
3122 int fd = 0;
3123#endif
3124
3125 return (
3126#ifdef USE_MCH_ACCESS
3127# ifdef UNIX
3128 (perm & 0222) == 0 ||
3129# endif
3130 mch_access((char *)fname, W_OK)
3131#else
3132 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3133 ? TRUE : (close(fd), FALSE)
3134#endif
3135 );
3136}
3137
3138
3139/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003140 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 *
3142 * We do our own buffering here because fwrite() is so slow.
3143 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003144 * If "forceit" is true, we don't care for errors when attempting backups.
3145 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003146 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003147 *
3148 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3149 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150 *
3151 * This function must NOT use NameBuff (because it's called by autowrite()).
3152 *
3153 * return FAIL for failure, OK otherwise
3154 */
3155 int
3156buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3157 reset_changed, filtering)
3158 buf_T *buf;
3159 char_u *fname;
3160 char_u *sfname;
3161 linenr_T start, end;
3162 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3163 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003164 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165 int forceit;
3166 int reset_changed;
3167 int filtering;
3168{
3169 int fd;
3170 char_u *backup = NULL;
3171 int backup_copy = FALSE; /* copy the original file? */
3172 int dobackup;
3173 char_u *ffname;
3174 char_u *wfname = NULL; /* name of file to write to */
3175 char_u *s;
3176 char_u *ptr;
3177 char_u c;
3178 int len;
3179 linenr_T lnum;
3180 long nchars;
3181 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003182 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 char_u *errnum = NULL;
3184 char_u *buffer;
3185 char_u smallbuf[SMBUFSIZE];
3186 char_u *backup_ext;
3187 int bufsize;
3188 long perm; /* file permissions */
3189 int retval = OK;
3190 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3191 int msg_save = msg_scroll;
3192 int overwriting; /* TRUE if writing over original */
3193 int no_eol = FALSE; /* no end-of-line written */
3194 int device = FALSE; /* writing to a device */
3195 struct stat st_old;
3196 int prev_got_int = got_int;
3197 int file_readonly = FALSE; /* overwritten file is read-only */
3198 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3199#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3200 int made_writable = FALSE; /* 'w' bit has been set */
3201#endif
3202 /* writing everything */
3203 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3204#ifdef FEAT_AUTOCMD
3205 linenr_T old_line_count = buf->b_ml.ml_line_count;
3206#endif
3207 int attr;
3208 int fileformat;
3209 int write_bin;
3210 struct bw_info write_info; /* info for buf_write_bytes() */
3211#ifdef FEAT_MBYTE
3212 int converted = FALSE;
3213 int notconverted = FALSE;
3214 char_u *fenc; /* effective 'fileencoding' */
3215 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3216#endif
3217#ifdef HAS_BW_FLAGS
3218 int wb_flags = 0;
3219#endif
3220#ifdef HAVE_ACL
3221 vim_acl_T acl = NULL; /* ACL copied from original file to
3222 backup or new file */
3223#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003224#ifdef FEAT_PERSISTENT_UNDO
3225 int write_undo_file = FALSE;
3226 context_sha256_T sha_ctx;
3227#endif
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01003228#ifdef FEAT_CRYPT
3229 int crypt_method_used;
3230#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231
3232 if (fname == NULL || *fname == NUL) /* safety check */
3233 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003234 if (buf->b_ml.ml_mfp == NULL)
3235 {
3236 /* This can happen during startup when there is a stray "w" in the
3237 * vimrc file. */
3238 EMSG(_(e_emptybuf));
3239 return FAIL;
3240 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241
3242 /*
3243 * Disallow writing from .exrc and .vimrc in current directory for
3244 * security reasons.
3245 */
3246 if (check_secure())
3247 return FAIL;
3248
3249 /* Avoid a crash for a long name. */
3250 if (STRLEN(fname) >= MAXPATHL)
3251 {
3252 EMSG(_(e_longname));
3253 return FAIL;
3254 }
3255
3256#ifdef FEAT_MBYTE
3257 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3258 write_info.bw_conv_buf = NULL;
3259 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003260 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 write_info.bw_restlen = 0;
3262# ifdef USE_ICONV
3263 write_info.bw_iconv_fd = (iconv_t)-1;
3264# endif
3265#endif
3266
Bram Moolenaardf177f62005-02-22 08:39:57 +00003267 /* After writing a file changedtick changes but we don't want to display
3268 * the line. */
3269 ex_no_reprint = TRUE;
3270
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 /*
3272 * If there is no file name yet, use the one for the written file.
3273 * BF_NOTEDITED is set to reflect this (in case the write fails).
3274 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003275 * Don't do this when appending.
3276 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003278 if (buf->b_ffname == NULL
3279 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 && whole
3281 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003282#ifdef FEAT_QUICKFIX
3283 && !bt_nofile(buf)
3284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003286 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3288 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003289 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003291 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 }
3293
3294 if (sfname == NULL)
3295 sfname = fname;
3296 /*
3297 * For Unix: Use the short file name whenever possible.
3298 * Avoids problems with networks and when directory names are changed.
3299 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3300 * another directory, which we don't detect
3301 */
3302 ffname = fname; /* remember full fname */
3303#ifdef UNIX
3304 fname = sfname;
3305#endif
3306
3307 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3308 overwriting = TRUE;
3309 else
3310 overwriting = FALSE;
3311
3312 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003313 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314
3315 ++no_wait_return; /* don't wait for return yet */
3316
3317 /*
3318 * Set '[ and '] marks to the lines to be written.
3319 */
3320 buf->b_op_start.lnum = start;
3321 buf->b_op_start.col = 0;
3322 buf->b_op_end.lnum = end;
3323 buf->b_op_end.col = 0;
3324
3325#ifdef FEAT_AUTOCMD
3326 {
3327 aco_save_T aco;
3328 int buf_ffname = FALSE;
3329 int buf_sfname = FALSE;
3330 int buf_fname_f = FALSE;
3331 int buf_fname_s = FALSE;
3332 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003334 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335
3336 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003337 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 * Set curbuf to the buffer to be written.
3339 * Careful: The autocommands may call buf_write() recursively!
3340 */
3341 if (ffname == buf->b_ffname)
3342 buf_ffname = TRUE;
3343 if (sfname == buf->b_sfname)
3344 buf_sfname = TRUE;
3345 if (fname == buf->b_ffname)
3346 buf_fname_f = TRUE;
3347 if (fname == buf->b_sfname)
3348 buf_fname_s = TRUE;
3349
3350 /* set curwin/curbuf to buf and save a few things */
3351 aucmd_prepbuf(&aco, buf);
3352
3353 if (append)
3354 {
3355 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3356 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003357 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003358#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003359 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003360 nofile_err = TRUE;
3361 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003362#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003363 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 }
3367 else if (filtering)
3368 {
3369 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3370 NULL, sfname, FALSE, curbuf, eap);
3371 }
3372 else if (reset_changed && whole)
3373 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003374 int was_changed = curbufIsChanged();
3375
3376 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3377 sfname, sfname, FALSE, curbuf, eap);
3378 if (did_cmd)
3379 {
3380 if (was_changed && !curbufIsChanged())
3381 {
3382 /* Written everything correctly and BufWriteCmd has reset
3383 * 'modified': Correct the undo information so that an
3384 * undo now sets 'modified'. */
3385 u_unchanged(curbuf);
3386 u_update_save_nr(curbuf);
3387 }
3388 }
3389 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003390 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003391#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003392 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003393 nofile_err = TRUE;
3394 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003395#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003396 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003398 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 }
3400 else
3401 {
3402 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3403 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003404 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003405#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003406 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003407 nofile_err = TRUE;
3408 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003409#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003410 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 }
3414
3415 /* restore curwin/curbuf and a few other things */
3416 aucmd_restbuf(&aco);
3417
3418 /*
3419 * In three situations we return here and don't write the file:
3420 * 1. the autocommands deleted or unloaded the buffer.
3421 * 2. The autocommands abort script processing.
3422 * 3. If one of the "Cmd" autocommands was executed.
3423 */
3424 if (!buf_valid(buf))
3425 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003426 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003427 || did_cmd || nofile_err
3428#ifdef FEAT_EVAL
3429 || aborting()
3430#endif
3431 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 {
3433 --no_wait_return;
3434 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003435 if (nofile_err)
3436 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3437
Bram Moolenaar1e015462005-09-25 22:16:38 +00003438 if (nofile_err
3439#ifdef FEAT_EVAL
3440 || aborting()
3441#endif
3442 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443 /* An aborting error, interrupt or exception in the
3444 * autocommands. */
3445 return FAIL;
3446 if (did_cmd)
3447 {
3448 if (buf == NULL)
3449 /* The buffer was deleted. We assume it was written
3450 * (can't retry anyway). */
3451 return OK;
3452 if (overwriting)
3453 {
3454 /* Assume the buffer was written, update the timestamp. */
3455 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003456 if (append)
3457 buf->b_flags &= ~BF_NEW;
3458 else
3459 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003461 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003462 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463 /* Buffer still changed, the autocommands didn't work
3464 * properly. */
3465 return FAIL;
3466 return OK;
3467 }
3468#ifdef FEAT_EVAL
3469 if (!aborting())
3470#endif
3471 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3472 return FAIL;
3473 }
3474
3475 /*
3476 * The autocommands may have changed the number of lines in the file.
3477 * When writing the whole file, adjust the end.
3478 * When writing part of the file, assume that the autocommands only
3479 * changed the number of lines that are to be written (tricky!).
3480 */
3481 if (buf->b_ml.ml_line_count != old_line_count)
3482 {
3483 if (whole) /* write all */
3484 end = buf->b_ml.ml_line_count;
3485 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3486 end += buf->b_ml.ml_line_count - old_line_count;
3487 else /* less lines */
3488 {
3489 end -= old_line_count - buf->b_ml.ml_line_count;
3490 if (end < start)
3491 {
3492 --no_wait_return;
3493 msg_scroll = msg_save;
3494 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3495 return FAIL;
3496 }
3497 }
3498 }
3499
3500 /*
3501 * The autocommands may have changed the name of the buffer, which may
3502 * be kept in fname, ffname and sfname.
3503 */
3504 if (buf_ffname)
3505 ffname = buf->b_ffname;
3506 if (buf_sfname)
3507 sfname = buf->b_sfname;
3508 if (buf_fname_f)
3509 fname = buf->b_ffname;
3510 if (buf_fname_s)
3511 fname = buf->b_sfname;
3512 }
3513#endif
3514
3515#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003516 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 {
3518 if (whole)
3519 {
3520 /*
3521 * b_changed can be 0 after an undo, but we still need to write
3522 * the buffer to NetBeans.
3523 */
3524 if (buf->b_changed || isNetbeansModified(buf))
3525 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003526 --no_wait_return; /* may wait for return now */
3527 msg_scroll = msg_save;
3528 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529 return retval;
3530 }
3531 else
3532 {
3533 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003534 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 buffer = NULL;
3536 goto fail;
3537 }
3538 }
3539 else
3540 {
3541 errnum = (char_u *)"E657: ";
3542 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3543 buffer = NULL;
3544 goto fail;
3545 }
3546 }
3547#endif
3548
3549 if (shortmess(SHM_OVER) && !exiting)
3550 msg_scroll = FALSE; /* overwrite previous file message */
3551 else
3552 msg_scroll = TRUE; /* don't overwrite previous file message */
3553 if (!filtering)
3554 filemess(buf,
3555#ifndef UNIX
3556 sfname,
3557#else
3558 fname,
3559#endif
3560 (char_u *)"", 0); /* show that we are busy */
3561 msg_scroll = FALSE; /* always overwrite the file message now */
3562
3563 buffer = alloc(BUFSIZE);
3564 if (buffer == NULL) /* can't allocate big buffer, use small
3565 * one (to be able to write when out of
3566 * memory) */
3567 {
3568 buffer = smallbuf;
3569 bufsize = SMBUFSIZE;
3570 }
3571 else
3572 bufsize = BUFSIZE;
3573
3574 /*
3575 * Get information about original file (if there is one).
3576 */
3577#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003578 st_old.st_dev = 0;
3579 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 perm = -1;
3581 if (mch_stat((char *)fname, &st_old) < 0)
3582 newfile = TRUE;
3583 else
3584 {
3585 perm = st_old.st_mode;
3586 if (!S_ISREG(st_old.st_mode)) /* not a file */
3587 {
3588 if (S_ISDIR(st_old.st_mode))
3589 {
3590 errnum = (char_u *)"E502: ";
3591 errmsg = (char_u *)_("is a directory");
3592 goto fail;
3593 }
3594 if (mch_nodetype(fname) != NODE_WRITABLE)
3595 {
3596 errnum = (char_u *)"E503: ";
3597 errmsg = (char_u *)_("is not a file or writable device");
3598 goto fail;
3599 }
3600 /* It's a device of some kind (or a fifo) which we can write to
3601 * but for which we can't make a backup. */
3602 device = TRUE;
3603 newfile = TRUE;
3604 perm = -1;
3605 }
3606 }
3607#else /* !UNIX */
3608 /*
3609 * Check for a writable device name.
3610 */
3611 c = mch_nodetype(fname);
3612 if (c == NODE_OTHER)
3613 {
3614 errnum = (char_u *)"E503: ";
3615 errmsg = (char_u *)_("is not a file or writable device");
3616 goto fail;
3617 }
3618 if (c == NODE_WRITABLE)
3619 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003620# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3621 /* MS-Windows allows opening a device, but we will probably get stuck
3622 * trying to write to it. */
3623 if (!p_odev)
3624 {
3625 errnum = (char_u *)"E796: ";
3626 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3627 goto fail;
3628 }
3629# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 device = TRUE;
3631 newfile = TRUE;
3632 perm = -1;
3633 }
3634 else
3635 {
3636 perm = mch_getperm(fname);
3637 if (perm < 0)
3638 newfile = TRUE;
3639 else if (mch_isdir(fname))
3640 {
3641 errnum = (char_u *)"E502: ";
3642 errmsg = (char_u *)_("is a directory");
3643 goto fail;
3644 }
3645 if (overwriting)
3646 (void)mch_stat((char *)fname, &st_old);
3647 }
3648#endif /* !UNIX */
3649
3650 if (!device && !newfile)
3651 {
3652 /*
3653 * Check if the file is really writable (when renaming the file to
3654 * make a backup we won't discover it later).
3655 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003656 file_readonly = check_file_readonly(fname, (int)perm);
3657
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658 if (!forceit && file_readonly)
3659 {
3660 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3661 {
3662 errnum = (char_u *)"E504: ";
3663 errmsg = (char_u *)_(err_readonly);
3664 }
3665 else
3666 {
3667 errnum = (char_u *)"E505: ";
3668 errmsg = (char_u *)_("is read-only (add ! to override)");
3669 }
3670 goto fail;
3671 }
3672
3673 /*
3674 * Check if the timestamp hasn't changed since reading the file.
3675 */
3676 if (overwriting)
3677 {
3678 retval = check_mtime(buf, &st_old);
3679 if (retval == FAIL)
3680 goto fail;
3681 }
3682 }
3683
3684#ifdef HAVE_ACL
3685 /*
3686 * For systems that support ACL: get the ACL from the original file.
3687 */
3688 if (!newfile)
3689 acl = mch_get_acl(fname);
3690#endif
3691
3692 /*
3693 * If 'backupskip' is not empty, don't make a backup for some files.
3694 */
3695 dobackup = (p_wb || p_bk || *p_pm != NUL);
3696#ifdef FEAT_WILDIGN
3697 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3698 dobackup = FALSE;
3699#endif
3700
3701 /*
3702 * Save the value of got_int and reset it. We don't want a previous
3703 * interruption cancel writing, only hitting CTRL-C while writing should
3704 * abort it.
3705 */
3706 prev_got_int = got_int;
3707 got_int = FALSE;
3708
3709 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3710 buf->b_saving = TRUE;
3711
3712 /*
3713 * If we are not appending or filtering, the file exists, and the
3714 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3715 * When 'patchmode' is set also make a backup when appending.
3716 *
3717 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3718 * off. This helps when editing large files on almost-full disks.
3719 */
3720 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3721 {
3722#if defined(UNIX) || defined(WIN32)
3723 struct stat st;
3724#endif
3725
3726 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3727 backup_copy = TRUE;
3728#if defined(UNIX) || defined(WIN32)
3729 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3730 {
3731 int i;
3732
3733# ifdef UNIX
3734 /*
3735 * Don't rename the file when:
3736 * - it's a hard link
3737 * - it's a symbolic link
3738 * - we don't have write permission in the directory
3739 * - we can't set the owner/group of the new file
3740 */
3741 if (st_old.st_nlink > 1
3742 || mch_lstat((char *)fname, &st) < 0
3743 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003744 || st.st_ino != st_old.st_ino
3745# ifndef HAVE_FCHOWN
3746 || st.st_uid != st_old.st_uid
3747 || st.st_gid != st_old.st_gid
3748# endif
3749 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 backup_copy = TRUE;
3751 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003752# else
3753# ifdef WIN32
3754 /* On NTFS file systems hard links are possible. */
3755 if (mch_is_linked(fname))
3756 backup_copy = TRUE;
3757 else
3758# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759# endif
3760 {
3761 /*
3762 * Check if we can create a file and set the owner/group to
3763 * the ones from the original file.
3764 * First find a file name that doesn't exist yet (use some
3765 * arbitrary numbers).
3766 */
3767 STRCPY(IObuff, fname);
3768 for (i = 4913; ; i += 123)
3769 {
3770 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003771 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 break;
3773 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003774 fd = mch_open((char *)IObuff,
3775 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776 if (fd < 0) /* can't write in directory */
3777 backup_copy = TRUE;
3778 else
3779 {
3780# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003781# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003782 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 if (mch_stat((char *)IObuff, &st) < 0
3785 || st.st_uid != st_old.st_uid
3786 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003787 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 backup_copy = TRUE;
3789# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003790 /* Close the file before removing it, on MS-Windows we
3791 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003792 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003793 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003794# ifdef MSWIN
3795 /* MS-Windows may trigger a virus scanner to open the
3796 * file, we can't delete it then. Keep trying for half a
3797 * second. */
3798 {
3799 int try;
3800
3801 for (try = 0; try < 10; ++try)
3802 {
3803 if (mch_lstat((char *)IObuff, &st) < 0)
3804 break;
3805 ui_delay(50L, TRUE); /* wait 50 msec */
3806 mch_remove(IObuff);
3807 }
3808 }
3809# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 }
3811 }
3812 }
3813
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 /*
3815 * Break symlinks and/or hardlinks if we've been asked to.
3816 */
3817 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3818 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003819# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 int lstat_res;
3821
3822 lstat_res = mch_lstat((char *)fname, &st);
3823
3824 /* Symlinks. */
3825 if ((bkc_flags & BKC_BREAKSYMLINK)
3826 && lstat_res == 0
3827 && st.st_ino != st_old.st_ino)
3828 backup_copy = FALSE;
3829
3830 /* Hardlinks. */
3831 if ((bkc_flags & BKC_BREAKHARDLINK)
3832 && st_old.st_nlink > 1
3833 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3834 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003835# else
3836# if defined(WIN32)
3837 /* Symlinks. */
3838 if ((bkc_flags & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
3839 backup_copy = FALSE;
3840
3841 /* Hardlinks. */
3842 if ((bkc_flags & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
3843 backup_copy = FALSE;
3844# endif
3845# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847
3848#endif
3849
3850 /* make sure we have a valid backup extension to use */
3851 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853 else
3854 backup_ext = p_bex;
3855
3856 if (backup_copy
3857 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3858 {
3859 int bfd;
3860 char_u *copybuf, *wp;
3861 int some_error = FALSE;
3862 struct stat st_new;
3863 char_u *dirp;
3864 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003865#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 int did_set_shortname;
3867#endif
3868
3869 copybuf = alloc(BUFSIZE + 1);
3870 if (copybuf == NULL)
3871 {
3872 some_error = TRUE; /* out of memory */
3873 goto nobackup;
3874 }
3875
3876 /*
3877 * Try to make the backup in each directory in the 'bdir' option.
3878 *
3879 * Unix semantics has it, that we may have a writable file,
3880 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3881 * - the directory is not writable,
3882 * - the file may be a symbolic link,
3883 * - the file may belong to another user/group, etc.
3884 *
3885 * For these reasons, the existing writable file must be truncated
3886 * and reused. Creation of a backup COPY will be attempted.
3887 */
3888 dirp = p_bdir;
3889 while (*dirp)
3890 {
3891#ifdef UNIX
3892 st_new.st_ino = 0;
3893 st_new.st_dev = 0;
3894 st_new.st_gid = 0;
3895#endif
3896
3897 /*
3898 * Isolate one directory name, using an entry in 'bdir'.
3899 */
3900 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3901 rootname = get_file_in_dir(fname, copybuf);
3902 if (rootname == NULL)
3903 {
3904 some_error = TRUE; /* out of memory */
3905 goto nobackup;
3906 }
3907
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003908#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 did_set_shortname = FALSE;
3910#endif
3911
3912 /*
3913 * May try twice if 'shortname' not set.
3914 */
3915 for (;;)
3916 {
3917 /*
3918 * Make backup file name.
3919 */
3920 backup = buf_modname(
3921#ifdef SHORT_FNAME
3922 TRUE,
3923#else
3924 (buf->b_p_sn || buf->b_shortname),
3925#endif
3926 rootname, backup_ext, FALSE);
3927 if (backup == NULL)
3928 {
3929 vim_free(rootname);
3930 some_error = TRUE; /* out of memory */
3931 goto nobackup;
3932 }
3933
3934 /*
3935 * Check if backup file already exists.
3936 */
3937 if (mch_stat((char *)backup, &st_new) >= 0)
3938 {
3939#ifdef UNIX
3940 /*
3941 * Check if backup file is same as original file.
3942 * May happen when modname() gave the same file back.
3943 * E.g. silly link, or file name-length reached.
3944 * If we don't check here, we either ruin the file
3945 * when copying or erase it after writing. jw.
3946 */
3947 if (st_new.st_dev == st_old.st_dev
3948 && st_new.st_ino == st_old.st_ino)
3949 {
3950 vim_free(backup);
3951 backup = NULL; /* no backup file to delete */
3952# ifndef SHORT_FNAME
3953 /*
3954 * may try again with 'shortname' set
3955 */
3956 if (!(buf->b_shortname || buf->b_p_sn))
3957 {
3958 buf->b_shortname = TRUE;
3959 did_set_shortname = TRUE;
3960 continue;
3961 }
3962 /* setting shortname didn't help */
3963 if (did_set_shortname)
3964 buf->b_shortname = FALSE;
3965# endif
3966 break;
3967 }
3968#endif
3969
3970 /*
3971 * If we are not going to keep the backup file, don't
3972 * delete an existing one, try to use another name.
3973 * Change one character, just before the extension.
3974 */
3975 if (!p_bk)
3976 {
3977 wp = backup + STRLEN(backup) - 1
3978 - STRLEN(backup_ext);
3979 if (wp < backup) /* empty file name ??? */
3980 wp = backup;
3981 *wp = 'z';
3982 while (*wp > 'a'
3983 && mch_stat((char *)backup, &st_new) >= 0)
3984 --*wp;
3985 /* They all exist??? Must be something wrong. */
3986 if (*wp == 'a')
3987 {
3988 vim_free(backup);
3989 backup = NULL;
3990 }
3991 }
3992 }
3993 break;
3994 }
3995 vim_free(rootname);
3996
3997 /*
3998 * Try to create the backup file
3999 */
4000 if (backup != NULL)
4001 {
4002 /* remove old backup, if present */
4003 mch_remove(backup);
4004 /* Open with O_EXCL to avoid the file being created while
4005 * we were sleeping (symlink hacker attack?) */
4006 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00004007 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
4008 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 if (bfd < 0)
4010 {
4011 vim_free(backup);
4012 backup = NULL;
4013 }
4014 else
4015 {
4016 /* set file protection same as original file, but
4017 * strip s-bit */
4018 (void)mch_setperm(backup, perm & 0777);
4019
4020#ifdef UNIX
4021 /*
4022 * Try to set the group of the backup same as the
4023 * original file. If this fails, set the protection
4024 * bits for the group same as the protection bits for
4025 * others.
4026 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004027 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004029 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030# endif
4031 )
4032 mch_setperm(backup,
4033 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004034# ifdef HAVE_SELINUX
4035 mch_copy_sec(fname, backup);
4036# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004037#endif
4038
4039 /*
4040 * copy the file.
4041 */
4042 write_info.bw_fd = bfd;
4043 write_info.bw_buf = copybuf;
4044#ifdef HAS_BW_FLAGS
4045 write_info.bw_flags = FIO_NOCONVERT;
4046#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004047 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048 BUFSIZE)) > 0)
4049 {
4050 if (buf_write_bytes(&write_info) == FAIL)
4051 {
4052 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4053 break;
4054 }
4055 ui_breakcheck();
4056 if (got_int)
4057 {
4058 errmsg = (char_u *)_(e_interr);
4059 break;
4060 }
4061 }
4062
4063 if (close(bfd) < 0 && errmsg == NULL)
4064 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4065 if (write_info.bw_len < 0)
4066 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4067#ifdef UNIX
4068 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4069#endif
4070#ifdef HAVE_ACL
4071 mch_set_acl(backup, acl);
4072#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004073#ifdef HAVE_SELINUX
4074 mch_copy_sec(fname, backup);
4075#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004076 break;
4077 }
4078 }
4079 }
4080 nobackup:
4081 close(fd); /* ignore errors for closing read file */
4082 vim_free(copybuf);
4083
4084 if (backup == NULL && errmsg == NULL)
4085 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4086 /* ignore errors when forceit is TRUE */
4087 if ((some_error || errmsg != NULL) && !forceit)
4088 {
4089 retval = FAIL;
4090 goto fail;
4091 }
4092 errmsg = NULL;
4093 }
4094 else
4095 {
4096 char_u *dirp;
4097 char_u *p;
4098 char_u *rootname;
4099
4100 /*
4101 * Make a backup by renaming the original file.
4102 */
4103 /*
4104 * If 'cpoptions' includes the "W" flag, we don't want to
4105 * overwrite a read-only file. But rename may be possible
4106 * anyway, thus we need an extra check here.
4107 */
4108 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4109 {
4110 errnum = (char_u *)"E504: ";
4111 errmsg = (char_u *)_(err_readonly);
4112 goto fail;
4113 }
4114
4115 /*
4116 *
4117 * Form the backup file name - change path/fo.o.h to
4118 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4119 * that works is used.
4120 */
4121 dirp = p_bdir;
4122 while (*dirp)
4123 {
4124 /*
4125 * Isolate one directory name and make the backup file name.
4126 */
4127 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4128 rootname = get_file_in_dir(fname, IObuff);
4129 if (rootname == NULL)
4130 backup = NULL;
4131 else
4132 {
4133 backup = buf_modname(
4134#ifdef SHORT_FNAME
4135 TRUE,
4136#else
4137 (buf->b_p_sn || buf->b_shortname),
4138#endif
4139 rootname, backup_ext, FALSE);
4140 vim_free(rootname);
4141 }
4142
4143 if (backup != NULL)
4144 {
4145 /*
4146 * If we are not going to keep the backup file, don't
4147 * delete an existing one, try to use another name.
4148 * Change one character, just before the extension.
4149 */
4150 if (!p_bk && mch_getperm(backup) >= 0)
4151 {
4152 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4153 if (p < backup) /* empty file name ??? */
4154 p = backup;
4155 *p = 'z';
4156 while (*p > 'a' && mch_getperm(backup) >= 0)
4157 --*p;
4158 /* They all exist??? Must be something wrong! */
4159 if (*p == 'a')
4160 {
4161 vim_free(backup);
4162 backup = NULL;
4163 }
4164 }
4165 }
4166 if (backup != NULL)
4167 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004169 * Delete any existing backup and move the current version
4170 * to the backup. For safety, we don't remove the backup
4171 * until the write has finished successfully. And if the
4172 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 */
4174 /*
4175 * If the renaming of the original file to the backup file
4176 * works, quit here.
4177 */
4178 if (vim_rename(fname, backup) == 0)
4179 break;
4180
4181 vim_free(backup); /* don't do the rename below */
4182 backup = NULL;
4183 }
4184 }
4185 if (backup == NULL && !forceit)
4186 {
4187 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4188 goto fail;
4189 }
4190 }
4191 }
4192
4193#if defined(UNIX) && !defined(ARCHIE)
4194 /* When using ":w!" and the file was read-only: make it writable */
4195 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4196 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4197 {
4198 perm |= 0200;
4199 (void)mch_setperm(fname, perm);
4200 made_writable = TRUE;
4201 }
4202#endif
4203
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004204 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004205 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4206 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 {
4208 buf->b_p_ro = FALSE;
4209#ifdef FEAT_TITLE
4210 need_maketitle = TRUE; /* set window title later */
4211#endif
4212#ifdef FEAT_WINDOWS
4213 status_redraw_all(); /* redraw status lines later */
4214#endif
4215 }
4216
4217 if (end > buf->b_ml.ml_line_count)
4218 end = buf->b_ml.ml_line_count;
4219 if (buf->b_ml.ml_flags & ML_EMPTY)
4220 start = end + 1;
4221
4222 /*
4223 * If the original file is being overwritten, there is a small chance that
4224 * we crash in the middle of writing. Therefore the file is preserved now.
4225 * This makes all block numbers positive so that recovery does not need
4226 * the original file.
4227 * Don't do this if there is a backup file and we are exiting.
4228 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004229 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 && !(exiting && backup != NULL))
4231 {
4232 ml_preserve(buf, FALSE);
4233 if (got_int)
4234 {
4235 errmsg = (char_u *)_(e_interr);
4236 goto restore_backup;
4237 }
4238 }
4239
4240#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4241 /*
4242 * Before risking to lose the original file verify if there's
4243 * a resource fork to preserve, and if cannot be done warn
4244 * the users. This happens when overwriting without backups.
4245 */
4246 if (backup == NULL && overwriting && !append)
4247 if (mch_has_resource_fork(fname))
4248 {
4249 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4250 goto restore_backup;
4251 }
4252#endif
4253
4254#ifdef VMS
4255 vms_remove_version(fname); /* remove version */
4256#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004257 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258 * multi-byte conversion. */
4259 wfname = fname;
4260
4261#ifdef FEAT_MBYTE
4262 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4263 if (eap != NULL && eap->force_enc != 0)
4264 {
4265 fenc = eap->cmd + eap->force_enc;
4266 fenc = enc_canonize(fenc);
4267 fenc_tofree = fenc;
4268 }
4269 else
4270 fenc = buf->b_p_fenc;
4271
4272 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004273 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004274 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004275 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276
4277 /*
4278 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4279 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4280 * Prepare the flags for it and allocate bw_conv_buf when needed.
4281 */
4282 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4283 {
4284 wb_flags = get_fio_flags(fenc);
4285 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4286 {
4287 /* Need to allocate a buffer to translate into. */
4288 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4289 write_info.bw_conv_buflen = bufsize * 2;
4290 else /* FIO_UCS4 */
4291 write_info.bw_conv_buflen = bufsize * 4;
4292 write_info.bw_conv_buf
4293 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4294 if (write_info.bw_conv_buf == NULL)
4295 end = 0;
4296 }
4297 }
4298
4299# ifdef WIN3264
4300 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4301 {
4302 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4303 write_info.bw_conv_buflen = bufsize * 4;
4304 write_info.bw_conv_buf
4305 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4306 if (write_info.bw_conv_buf == NULL)
4307 end = 0;
4308 }
4309# endif
4310
4311# ifdef MACOS_X
4312 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4313 {
4314 write_info.bw_conv_buflen = bufsize * 3;
4315 write_info.bw_conv_buf
4316 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4317 if (write_info.bw_conv_buf == NULL)
4318 end = 0;
4319 }
4320# endif
4321
4322# if defined(FEAT_EVAL) || defined(USE_ICONV)
4323 if (converted && wb_flags == 0)
4324 {
4325# ifdef USE_ICONV
4326 /*
4327 * Use iconv() conversion when conversion is needed and it's not done
4328 * internally.
4329 */
4330 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4331 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4332 if (write_info.bw_iconv_fd != (iconv_t)-1)
4333 {
4334 /* We're going to use iconv(), allocate a buffer to convert in. */
4335 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4336 write_info.bw_conv_buf
4337 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4338 if (write_info.bw_conv_buf == NULL)
4339 end = 0;
4340 write_info.bw_first = TRUE;
4341 }
4342# ifdef FEAT_EVAL
4343 else
4344# endif
4345# endif
4346
4347# ifdef FEAT_EVAL
4348 /*
4349 * When the file needs to be converted with 'charconvert' after
4350 * writing, write to a temp file instead and let the conversion
4351 * overwrite the original file.
4352 */
4353 if (*p_ccv != NUL)
4354 {
4355 wfname = vim_tempname('w');
4356 if (wfname == NULL) /* Can't write without a tempfile! */
4357 {
4358 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4359 goto restore_backup;
4360 }
4361 }
4362# endif
4363 }
4364# endif
4365 if (converted && wb_flags == 0
4366# ifdef USE_ICONV
4367 && write_info.bw_iconv_fd == (iconv_t)-1
4368# endif
4369# ifdef FEAT_EVAL
4370 && wfname == fname
4371# endif
4372 )
4373 {
4374 if (!forceit)
4375 {
4376 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4377 goto restore_backup;
4378 }
4379 notconverted = TRUE;
4380 }
4381#endif
4382
4383 /*
4384 * Open the file "wfname" for writing.
4385 * We may try to open the file twice: If we can't write to the
4386 * file and forceit is TRUE we delete the existing file and try to create
4387 * a new one. If this still fails we may have lost the original file!
4388 * (this may happen when the user reached his quotum for number of files).
4389 * Appending will fail if the file does not exist and forceit is FALSE.
4390 */
4391 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4392 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4393 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004394 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395 {
4396 /*
4397 * A forced write will try to create a new file if the old one is
4398 * still readonly. This may also happen when the directory is
4399 * read-only. In that case the mch_remove() will fail.
4400 */
4401 if (errmsg == NULL)
4402 {
4403#ifdef UNIX
4404 struct stat st;
4405
4406 /* Don't delete the file when it's a hard or symbolic link. */
4407 if ((!newfile && st_old.st_nlink > 1)
4408 || (mch_lstat((char *)fname, &st) == 0
4409 && (st.st_dev != st_old.st_dev
4410 || st.st_ino != st_old.st_ino)))
4411 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4412 else
4413#endif
4414 {
4415 errmsg = (char_u *)_("E212: Can't open file for writing");
4416 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4417 && perm >= 0)
4418 {
4419#ifdef UNIX
4420 /* we write to the file, thus it should be marked
4421 writable after all */
4422 if (!(perm & 0200))
4423 made_writable = TRUE;
4424 perm |= 0200;
4425 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4426 perm &= 0777;
4427#endif
4428 if (!append) /* don't remove when appending */
4429 mch_remove(wfname);
4430 continue;
4431 }
4432 }
4433 }
4434
4435restore_backup:
4436 {
4437 struct stat st;
4438
4439 /*
4440 * If we failed to open the file, we don't need a backup. Throw it
4441 * away. If we moved or removed the original file try to put the
4442 * backup in its place.
4443 */
4444 if (backup != NULL && wfname == fname)
4445 {
4446 if (backup_copy)
4447 {
4448 /*
4449 * There is a small chance that we removed the original,
4450 * try to move the copy in its place.
4451 * This may not work if the vim_rename() fails.
4452 * In that case we leave the copy around.
4453 */
4454 /* If file does not exist, put the copy in its place */
4455 if (mch_stat((char *)fname, &st) < 0)
4456 vim_rename(backup, fname);
4457 /* if original file does exist throw away the copy */
4458 if (mch_stat((char *)fname, &st) >= 0)
4459 mch_remove(backup);
4460 }
4461 else
4462 {
4463 /* try to put the original file back */
4464 vim_rename(backup, fname);
4465 }
4466 }
4467
4468 /* if original file no longer exists give an extra warning */
4469 if (!newfile && mch_stat((char *)fname, &st) < 0)
4470 end = 0;
4471 }
4472
4473#ifdef FEAT_MBYTE
4474 if (wfname != fname)
4475 vim_free(wfname);
4476#endif
4477 goto fail;
4478 }
4479 errmsg = NULL;
4480
4481#if defined(MACOS_CLASSIC) || defined(WIN3264)
4482 /* TODO: Is it need for MACOS_X? (Dany) */
4483 /*
4484 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004485 * This is done in order to preserve the resource fork and the
4486 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487 */
4488 if (backup != NULL && overwriting && !append)
4489 {
4490 if (backup_copy)
4491 (void)mch_copy_file_attribute(wfname, backup);
4492 else
4493 (void)mch_copy_file_attribute(backup, wfname);
4494 }
4495
4496 if (!overwriting && !append)
4497 {
4498 if (buf->b_ffname != NULL)
4499 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004500 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 }
4502#endif
4503
4504 write_info.bw_fd = fd;
4505
4506#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004507 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004509 char_u *header;
4510 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004511
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004512 header = prepare_crypt_write(buf, &header_len);
4513 if (header == NULL)
4514 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004515 else
4516 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004517 /* Write magic number, so that Vim knows that this file is
4518 * encrypted when reading it again. This also undergoes utf-8 to
4519 * ucs-2/4 conversion when needed. */
4520 write_info.bw_buf = header;
4521 write_info.bw_len = header_len;
4522 write_info.bw_flags = FIO_NOCONVERT;
4523 if (buf_write_bytes(&write_info) == FAIL)
4524 end = 0;
4525 wb_flags |= FIO_ENCRYPTED;
4526 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004527 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528 }
4529#endif
4530
4531 write_info.bw_buf = buffer;
4532 nchars = 0;
4533
4534 /* use "++bin", "++nobin" or 'binary' */
4535 if (eap != NULL && eap->force_bin != 0)
4536 write_bin = (eap->force_bin == FORCE_BIN);
4537 else
4538 write_bin = buf->b_p_bin;
4539
4540#ifdef FEAT_MBYTE
4541 /*
4542 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004543 * Skip it when appending and the file already existed, the BOM only makes
4544 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004546 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 {
4548 write_info.bw_len = make_bom(buffer, fenc);
4549 if (write_info.bw_len > 0)
4550 {
4551 /* don't convert, do encryption */
4552 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4553 if (buf_write_bytes(&write_info) == FAIL)
4554 end = 0;
4555 else
4556 nchars += write_info.bw_len;
4557 }
4558 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004559 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560#endif
4561
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004562#ifdef FEAT_PERSISTENT_UNDO
4563 write_undo_file = (buf->b_p_udf && overwriting && !append
4564 && !filtering && reset_changed);
4565 if (write_undo_file)
4566 /* Prepare for computing the hash value of the text. */
4567 sha256_start(&sha_ctx);
4568#endif
4569
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 write_info.bw_len = bufsize;
4571#ifdef HAS_BW_FLAGS
4572 write_info.bw_flags = wb_flags;
4573#endif
4574 fileformat = get_fileformat_force(buf, eap);
4575 s = buffer;
4576 len = 0;
4577 for (lnum = start; lnum <= end; ++lnum)
4578 {
4579 /*
4580 * The next while loop is done once for each character written.
4581 * Keep it fast!
4582 */
4583 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004584#ifdef FEAT_PERSISTENT_UNDO
4585 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004586 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004587#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004588 while ((c = *++ptr) != NUL)
4589 {
4590 if (c == NL)
4591 *s = NUL; /* replace newlines with NULs */
4592 else if (c == CAR && fileformat == EOL_MAC)
4593 *s = NL; /* Mac: replace CRs with NLs */
4594 else
4595 *s = c;
4596 ++s;
4597 if (++len != bufsize)
4598 continue;
4599 if (buf_write_bytes(&write_info) == FAIL)
4600 {
4601 end = 0; /* write error: break loop */
4602 break;
4603 }
4604 nchars += bufsize;
4605 s = buffer;
4606 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004607#ifdef FEAT_MBYTE
4608 write_info.bw_start_lnum = lnum;
4609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610 }
4611 /* write failed or last line has no EOL: stop here */
4612 if (end == 0
4613 || (lnum == end
4614 && write_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004615 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4617 {
4618 ++lnum; /* written the line, count it */
4619 no_eol = TRUE;
4620 break;
4621 }
4622 if (fileformat == EOL_UNIX)
4623 *s++ = NL;
4624 else
4625 {
4626 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4627 if (fileformat == EOL_DOS) /* write CR-NL */
4628 {
4629 if (++len == bufsize)
4630 {
4631 if (buf_write_bytes(&write_info) == FAIL)
4632 {
4633 end = 0; /* write error: break loop */
4634 break;
4635 }
4636 nchars += bufsize;
4637 s = buffer;
4638 len = 0;
4639 }
4640 *s++ = NL;
4641 }
4642 }
4643 if (++len == bufsize && end)
4644 {
4645 if (buf_write_bytes(&write_info) == FAIL)
4646 {
4647 end = 0; /* write error: break loop */
4648 break;
4649 }
4650 nchars += bufsize;
4651 s = buffer;
4652 len = 0;
4653
4654 ui_breakcheck();
4655 if (got_int)
4656 {
4657 end = 0; /* Interrupted, break loop */
4658 break;
4659 }
4660 }
4661#ifdef VMS
4662 /*
4663 * On VMS there is a problem: newlines get added when writing blocks
4664 * at a time. Fix it by writing a line at a time.
4665 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004666 * Explanation: VAX/DECC RTL insists that records in some RMS
4667 * structures end with a newline (carriage return) character, and if
4668 * they don't it adds one.
4669 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004670 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004671 if (buf->b_fab_rfm == FAB$C_VFC
4672 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004674 int b2write;
4675
4676 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4677 ? MIN(4096, bufsize)
4678 : MIN(buf->b_fab_mrs, bufsize));
4679
4680 b2write = len;
4681 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004682 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004683 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4684 if (buf_write_bytes(&write_info) == FAIL)
4685 {
4686 end = 0;
4687 break;
4688 }
4689 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690 }
4691 write_info.bw_len = bufsize;
4692 nchars += len;
4693 s = buffer;
4694 len = 0;
4695 }
4696#endif
4697 }
4698 if (len > 0 && end > 0)
4699 {
4700 write_info.bw_len = len;
4701 if (buf_write_bytes(&write_info) == FAIL)
4702 end = 0; /* write error */
4703 nchars += len;
4704 }
4705
4706#if defined(UNIX) && defined(HAVE_FSYNC)
4707 /* On many journalling file systems there is a bug that causes both the
4708 * original and the backup file to be lost when halting the system right
4709 * after writing the file. That's because only the meta-data is
4710 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004711 * been written to disk and we don't lose it.
4712 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004713 * (could be a pipe).
4714 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4715 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 {
4717 errmsg = (char_u *)_("E667: Fsync failed");
4718 end = 0;
4719 }
4720#endif
4721
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004722#ifdef HAVE_SELINUX
4723 /* Probably need to set the security context. */
4724 if (!backup_copy)
4725 mch_copy_sec(backup, wfname);
4726#endif
4727
Bram Moolenaara5792f52005-11-23 21:25:05 +00004728#ifdef UNIX
4729 /* When creating a new file, set its owner/group to that of the original
4730 * file. Get the new device and inode number. */
4731 if (backup != NULL && !backup_copy)
4732 {
4733# ifdef HAVE_FCHOWN
4734 struct stat st;
4735
4736 /* don't change the owner when it's already OK, some systems remove
4737 * permission or ACL stuff */
4738 if (mch_stat((char *)wfname, &st) < 0
4739 || st.st_uid != st_old.st_uid
4740 || st.st_gid != st_old.st_gid)
4741 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004742 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004743 if (perm >= 0) /* set permission again, may have changed */
4744 (void)mch_setperm(wfname, perm);
4745 }
4746# endif
4747 buf_setino(buf);
4748 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004749 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004750 /* Set the inode when creating a new file. */
4751 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004752#endif
4753
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 if (close(fd) != 0)
4755 {
4756 errmsg = (char_u *)_("E512: Close failed");
4757 end = 0;
4758 }
4759
4760#ifdef UNIX
4761 if (made_writable)
4762 perm &= ~0200; /* reset 'w' bit for security reasons */
4763#endif
4764 if (perm >= 0) /* set perm. of new file same as old file */
4765 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766#ifdef HAVE_ACL
4767 /* Probably need to set the ACL before changing the user (can't set the
4768 * ACL on a file the user doesn't own). */
4769 if (!backup_copy)
4770 mch_set_acl(wfname, acl);
4771#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004772#ifdef FEAT_CRYPT
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01004773 crypt_method_used = use_crypt_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004774 if (wb_flags & FIO_ENCRYPTED)
4775 crypt_pop_state();
4776#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778
4779#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4780 if (wfname != fname)
4781 {
4782 /*
4783 * The file was written to a temp file, now it needs to be converted
4784 * with 'charconvert' to (overwrite) the output file.
4785 */
4786 if (end != 0)
4787 {
4788 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4789 wfname, fname) == FAIL)
4790 {
4791 write_info.bw_conv_error = TRUE;
4792 end = 0;
4793 }
4794 }
4795 mch_remove(wfname);
4796 vim_free(wfname);
4797 }
4798#endif
4799
4800 if (end == 0)
4801 {
4802 if (errmsg == NULL)
4803 {
4804#ifdef FEAT_MBYTE
4805 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004806 {
4807 if (write_info.bw_conv_error_lnum == 0)
4808 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4809 else
4810 {
4811 errmsg_allocated = TRUE;
4812 errmsg = alloc(300);
4813 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4814 (long)write_info.bw_conv_error_lnum);
4815 }
4816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004817 else
4818#endif
4819 if (got_int)
4820 errmsg = (char_u *)_(e_interr);
4821 else
4822 errmsg = (char_u *)_("E514: write error (file system full?)");
4823 }
4824
4825 /*
4826 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004827 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 * original file when trying to make a backup when writing the file a
4829 * second time.
4830 * When "backup_copy" is set we need to copy the backup over the new
4831 * file. Otherwise rename the backup file.
4832 * If this is OK, don't give the extra warning message.
4833 */
4834 if (backup != NULL)
4835 {
4836 if (backup_copy)
4837 {
4838 /* This may take a while, if we were interrupted let the user
4839 * know we got the message. */
4840 if (got_int)
4841 {
4842 MSG(_(e_interr));
4843 out_flush();
4844 }
4845 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4846 {
4847 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004848 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4849 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 {
4851 /* copy the file. */
4852 write_info.bw_buf = smallbuf;
4853#ifdef HAS_BW_FLAGS
4854 write_info.bw_flags = FIO_NOCONVERT;
4855#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004856 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 SMBUFSIZE)) > 0)
4858 if (buf_write_bytes(&write_info) == FAIL)
4859 break;
4860
4861 if (close(write_info.bw_fd) >= 0
4862 && write_info.bw_len == 0)
4863 end = 1; /* success */
4864 }
4865 close(fd); /* ignore errors for closing read file */
4866 }
4867 }
4868 else
4869 {
4870 if (vim_rename(backup, fname) == 0)
4871 end = 1;
4872 }
4873 }
4874 goto fail;
4875 }
4876
4877 lnum -= start; /* compute number of written lines */
4878 --no_wait_return; /* may wait for return now */
4879
4880#if !(defined(UNIX) || defined(VMS))
4881 fname = sfname; /* use shortname now, for the messages */
4882#endif
4883 if (!filtering)
4884 {
4885 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4886 c = FALSE;
4887#ifdef FEAT_MBYTE
4888 if (write_info.bw_conv_error)
4889 {
4890 STRCAT(IObuff, _(" CONVERSION ERROR"));
4891 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004892 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004893 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004894 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 }
4896 else if (notconverted)
4897 {
4898 STRCAT(IObuff, _("[NOT converted]"));
4899 c = TRUE;
4900 }
4901 else if (converted)
4902 {
4903 STRCAT(IObuff, _("[converted]"));
4904 c = TRUE;
4905 }
4906#endif
4907 if (device)
4908 {
4909 STRCAT(IObuff, _("[Device]"));
4910 c = TRUE;
4911 }
4912 else if (newfile)
4913 {
4914 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4915 c = TRUE;
4916 }
4917 if (no_eol)
4918 {
4919 msg_add_eol();
4920 c = TRUE;
4921 }
4922 /* may add [unix/dos/mac] */
4923 if (msg_add_fileformat(fileformat))
4924 c = TRUE;
4925#ifdef FEAT_CRYPT
4926 if (wb_flags & FIO_ENCRYPTED)
4927 {
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01004928 if (crypt_method_used == 1)
4929 STRCAT(IObuff, _("[blowfish]"));
4930 else
4931 STRCAT(IObuff, _("[crypted]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 c = TRUE;
4933 }
4934#endif
4935 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4936 if (!shortmess(SHM_WRITE))
4937 {
4938 if (append)
4939 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4940 else
4941 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4942 }
4943
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004944 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945 }
4946
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004947 /* When written everything correctly: reset 'modified'. Unless not
4948 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004949 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950#ifdef FEAT_MBYTE
4951 && !write_info.bw_conv_error
4952#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004953 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4954 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955 {
4956 unchanged(buf, TRUE);
4957 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004958 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959 }
4960
4961 /*
4962 * If written to the current file, update the timestamp of the swap file
4963 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4964 */
4965 if (overwriting)
4966 {
4967 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004968 if (append)
4969 buf->b_flags &= ~BF_NEW;
4970 else
4971 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972 }
4973
4974 /*
4975 * If we kept a backup until now, and we are in patch mode, then we make
4976 * the backup file our 'original' file.
4977 */
4978 if (*p_pm && dobackup)
4979 {
4980 char *org = (char *)buf_modname(
4981#ifdef SHORT_FNAME
4982 TRUE,
4983#else
4984 (buf->b_p_sn || buf->b_shortname),
4985#endif
4986 fname, p_pm, FALSE);
4987
4988 if (backup != NULL)
4989 {
4990 struct stat st;
4991
4992 /*
4993 * If the original file does not exist yet
4994 * the current backup file becomes the original file
4995 */
4996 if (org == NULL)
4997 EMSG(_("E205: Patchmode: can't save original file"));
4998 else if (mch_stat(org, &st) < 0)
4999 {
5000 vim_rename(backup, (char_u *)org);
5001 vim_free(backup); /* don't delete the file */
5002 backup = NULL;
5003#ifdef UNIX
5004 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5005#endif
5006 }
5007 }
5008 /*
5009 * If there is no backup file, remember that a (new) file was
5010 * created.
5011 */
5012 else
5013 {
5014 int empty_fd;
5015
5016 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005017 || (empty_fd = mch_open(org,
5018 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005019 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020 EMSG(_("E206: patchmode: can't touch empty original file"));
5021 else
5022 close(empty_fd);
5023 }
5024 if (org != NULL)
5025 {
5026 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5027 vim_free(org);
5028 }
5029 }
5030
5031 /*
5032 * Remove the backup unless 'backup' option is set
5033 */
5034 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5035 EMSG(_("E207: Can't delete backup file"));
5036
5037#ifdef FEAT_SUN_WORKSHOP
5038 if (usingSunWorkShop)
5039 workshop_file_saved((char *) ffname);
5040#endif
5041
5042 goto nofail;
5043
5044 /*
5045 * Finish up. We get here either after failure or success.
5046 */
5047fail:
5048 --no_wait_return; /* may wait for return now */
5049nofail:
5050
5051 /* Done saving, we accept changed buffer warnings again */
5052 buf->b_saving = FALSE;
5053
5054 vim_free(backup);
5055 if (buffer != smallbuf)
5056 vim_free(buffer);
5057#ifdef FEAT_MBYTE
5058 vim_free(fenc_tofree);
5059 vim_free(write_info.bw_conv_buf);
5060# ifdef USE_ICONV
5061 if (write_info.bw_iconv_fd != (iconv_t)-1)
5062 {
5063 iconv_close(write_info.bw_iconv_fd);
5064 write_info.bw_iconv_fd = (iconv_t)-1;
5065 }
5066# endif
5067#endif
5068#ifdef HAVE_ACL
5069 mch_free_acl(acl);
5070#endif
5071
5072 if (errmsg != NULL)
5073 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005074 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005075
5076 attr = hl_attr(HLF_E); /* set highlight for error messages */
5077 msg_add_fname(buf,
5078#ifndef UNIX
5079 sfname
5080#else
5081 fname
5082#endif
5083 ); /* put file name in IObuff with quotes */
5084 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5085 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5086 /* If the error message has the form "is ...", put the error number in
5087 * front of the file name. */
5088 if (errnum != NULL)
5089 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005090 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091 mch_memmove(IObuff, errnum, (size_t)numlen);
5092 }
5093 STRCAT(IObuff, errmsg);
5094 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005095 if (errmsg_allocated)
5096 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005097
5098 retval = FAIL;
5099 if (end == 0)
5100 {
5101 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5102 attr | MSG_HIST);
5103 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5104 attr | MSG_HIST);
5105
5106 /* Update the timestamp to avoid an "overwrite changed file"
5107 * prompt when writing again. */
5108 if (mch_stat((char *)fname, &st_old) >= 0)
5109 {
5110 buf_store_time(buf, &st_old, fname);
5111 buf->b_mtime_read = buf->b_mtime;
5112 }
5113 }
5114 }
5115 msg_scroll = msg_save;
5116
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005117#ifdef FEAT_PERSISTENT_UNDO
5118 /*
5119 * When writing the whole file and 'undofile' is set, also write the undo
5120 * file.
5121 */
5122 if (retval == OK && write_undo_file)
5123 {
5124 char_u hash[UNDO_HASH_SIZE];
5125
5126 sha256_finish(&sha_ctx, hash);
5127 u_write_undo(NULL, FALSE, buf, hash);
5128 }
5129#endif
5130
Bram Moolenaar071d4272004-06-13 20:20:40 +00005131#ifdef FEAT_AUTOCMD
5132#ifdef FEAT_EVAL
5133 if (!should_abort(retval))
5134#else
5135 if (!got_int)
5136#endif
5137 {
5138 aco_save_T aco;
5139
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005140 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5141
Bram Moolenaar071d4272004-06-13 20:20:40 +00005142 /*
5143 * Apply POST autocommands.
5144 * Careful: The autocommands may call buf_write() recursively!
5145 */
5146 aucmd_prepbuf(&aco, buf);
5147
5148 if (append)
5149 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5150 FALSE, curbuf, eap);
5151 else if (filtering)
5152 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5153 FALSE, curbuf, eap);
5154 else if (reset_changed && whole)
5155 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5156 FALSE, curbuf, eap);
5157 else
5158 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5159 FALSE, curbuf, eap);
5160
5161 /* restore curwin/curbuf and a few other things */
5162 aucmd_restbuf(&aco);
5163
5164#ifdef FEAT_EVAL
5165 if (aborting()) /* autocmds may abort script processing */
5166 retval = FALSE;
5167#endif
5168 }
5169#endif
5170
5171 got_int |= prev_got_int;
5172
5173#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5174 /* Update machine specific information. */
5175 mch_post_buffer_write(buf);
5176#endif
5177 return retval;
5178}
5179
5180/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005181 * Set the name of the current buffer. Use when the buffer doesn't have a
5182 * name and a ":r" or ":w" command with a file name is used.
5183 */
5184 static int
5185set_rw_fname(fname, sfname)
5186 char_u *fname;
5187 char_u *sfname;
5188{
5189#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005190 buf_T *buf = curbuf;
5191
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005192 /* It's like the unnamed buffer is deleted.... */
5193 if (curbuf->b_p_bl)
5194 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5195 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5196# ifdef FEAT_EVAL
5197 if (aborting()) /* autocmds may abort script processing */
5198 return FAIL;
5199# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005200 if (curbuf != buf)
5201 {
5202 /* We are in another buffer now, don't do the renaming. */
5203 EMSG(_(e_auchangedbuf));
5204 return FAIL;
5205 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005206#endif
5207
5208 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5209 curbuf->b_flags |= BF_NOTEDITED;
5210
5211#ifdef FEAT_AUTOCMD
5212 /* ....and a new named one is created */
5213 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5214 if (curbuf->b_p_bl)
5215 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5216# ifdef FEAT_EVAL
5217 if (aborting()) /* autocmds may abort script processing */
5218 return FAIL;
5219# endif
5220
5221 /* Do filetype detection now if 'filetype' is empty. */
5222 if (*curbuf->b_p_ft == NUL)
5223 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005224 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005225 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005226 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005227 }
5228#endif
5229
5230 return OK;
5231}
5232
5233/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234 * Put file name into IObuff with quotes.
5235 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005236 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237msg_add_fname(buf, fname)
5238 buf_T *buf;
5239 char_u *fname;
5240{
5241 if (fname == NULL)
5242 fname = (char_u *)"-stdin-";
5243 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5244 IObuff[0] = '"';
5245 STRCAT(IObuff, "\" ");
5246}
5247
5248/*
5249 * Append message for text mode to IObuff.
5250 * Return TRUE if something appended.
5251 */
5252 static int
5253msg_add_fileformat(eol_type)
5254 int eol_type;
5255{
5256#ifndef USE_CRNL
5257 if (eol_type == EOL_DOS)
5258 {
5259 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5260 return TRUE;
5261 }
5262#endif
5263#ifndef USE_CR
5264 if (eol_type == EOL_MAC)
5265 {
5266 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5267 return TRUE;
5268 }
5269#endif
5270#if defined(USE_CRNL) || defined(USE_CR)
5271 if (eol_type == EOL_UNIX)
5272 {
5273 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5274 return TRUE;
5275 }
5276#endif
5277 return FALSE;
5278}
5279
5280/*
5281 * Append line and character count to IObuff.
5282 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005283 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005284msg_add_lines(insert_space, lnum, nchars)
5285 int insert_space;
5286 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005287 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288{
5289 char_u *p;
5290
5291 p = IObuff + STRLEN(IObuff);
5292
5293 if (insert_space)
5294 *p++ = ' ';
5295 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005296 sprintf((char *)p,
5297#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005298 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005299#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005300 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5301 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005302#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005303 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005304 else
5305 {
5306 if (lnum == 1)
5307 STRCPY(p, _("1 line, "));
5308 else
5309 sprintf((char *)p, _("%ld lines, "), lnum);
5310 p += STRLEN(p);
5311 if (nchars == 1)
5312 STRCPY(p, _("1 character"));
5313 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005314 sprintf((char *)p,
5315#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005316 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005317#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005318 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5319 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005320#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005321 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 }
5323}
5324
5325/*
5326 * Append message for missing line separator to IObuff.
5327 */
5328 static void
5329msg_add_eol()
5330{
5331 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5332}
5333
5334/*
5335 * Check modification time of file, before writing to it.
5336 * The size isn't checked, because using a tool like "gzip" takes care of
5337 * using the same timestamp but can't set the size.
5338 */
5339 static int
5340check_mtime(buf, st)
5341 buf_T *buf;
5342 struct stat *st;
5343{
5344 if (buf->b_mtime_read != 0
5345 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5346 {
5347 msg_scroll = TRUE; /* don't overwrite messages here */
5348 msg_silent = 0; /* must give this prompt */
5349 /* don't use emsg() here, don't want to flush the buffers */
5350 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5351 hl_attr(HLF_E));
5352 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5353 TRUE) == 'n')
5354 return FAIL;
5355 msg_scroll = FALSE; /* always overwrite the file message now */
5356 }
5357 return OK;
5358}
5359
5360 static int
5361time_differs(t1, t2)
5362 long t1, t2;
5363{
5364#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5365 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5366 * the seconds. Since the roundoff is done when flushing the inode, the
5367 * time may change unexpectedly by one second!!! */
5368 return (t1 - t2 > 1 || t2 - t1 > 1);
5369#else
5370 return (t1 != t2);
5371#endif
5372}
5373
5374/*
5375 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005376 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377 *
5378 * Return FAIL for failure, OK otherwise.
5379 */
5380 static int
5381buf_write_bytes(ip)
5382 struct bw_info *ip;
5383{
5384 int wlen;
5385 char_u *buf = ip->bw_buf; /* data to write */
5386 int len = ip->bw_len; /* length of data */
5387#ifdef HAS_BW_FLAGS
5388 int flags = ip->bw_flags; /* extra flags */
5389#endif
5390
5391#ifdef FEAT_MBYTE
5392 /*
5393 * Skip conversion when writing the crypt magic number or the BOM.
5394 */
5395 if (!(flags & FIO_NOCONVERT))
5396 {
5397 char_u *p;
5398 unsigned c;
5399 int n;
5400
5401 if (flags & FIO_UTF8)
5402 {
5403 /*
5404 * Convert latin1 in the buffer to UTF-8 in the file.
5405 */
5406 p = ip->bw_conv_buf; /* translate to buffer */
5407 for (wlen = 0; wlen < len; ++wlen)
5408 p += utf_char2bytes(buf[wlen], p);
5409 buf = ip->bw_conv_buf;
5410 len = (int)(p - ip->bw_conv_buf);
5411 }
5412 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5413 {
5414 /*
5415 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5416 * Latin1 chars in the file.
5417 */
5418 if (flags & FIO_LATIN1)
5419 p = buf; /* translate in-place (can only get shorter) */
5420 else
5421 p = ip->bw_conv_buf; /* translate to buffer */
5422 for (wlen = 0; wlen < len; wlen += n)
5423 {
5424 if (wlen == 0 && ip->bw_restlen != 0)
5425 {
5426 int l;
5427
5428 /* Use remainder of previous call. Append the start of
5429 * buf[] to get a full sequence. Might still be too
5430 * short! */
5431 l = CONV_RESTLEN - ip->bw_restlen;
5432 if (l > len)
5433 l = len;
5434 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005435 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005436 if (n > ip->bw_restlen + len)
5437 {
5438 /* We have an incomplete byte sequence at the end to
5439 * be written. We can't convert it without the
5440 * remaining bytes. Keep them for the next call. */
5441 if (ip->bw_restlen + len > CONV_RESTLEN)
5442 return FAIL;
5443 ip->bw_restlen += len;
5444 break;
5445 }
5446 if (n > 1)
5447 c = utf_ptr2char(ip->bw_rest);
5448 else
5449 c = ip->bw_rest[0];
5450 if (n >= ip->bw_restlen)
5451 {
5452 n -= ip->bw_restlen;
5453 ip->bw_restlen = 0;
5454 }
5455 else
5456 {
5457 ip->bw_restlen -= n;
5458 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5459 (size_t)ip->bw_restlen);
5460 n = 0;
5461 }
5462 }
5463 else
5464 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005465 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466 if (n > len - wlen)
5467 {
5468 /* We have an incomplete byte sequence at the end to
5469 * be written. We can't convert it without the
5470 * remaining bytes. Keep them for the next call. */
5471 if (len - wlen > CONV_RESTLEN)
5472 return FAIL;
5473 ip->bw_restlen = len - wlen;
5474 mch_memmove(ip->bw_rest, buf + wlen,
5475 (size_t)ip->bw_restlen);
5476 break;
5477 }
5478 if (n > 1)
5479 c = utf_ptr2char(buf + wlen);
5480 else
5481 c = buf[wlen];
5482 }
5483
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005484 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5485 {
5486 ip->bw_conv_error = TRUE;
5487 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5488 }
5489 if (c == NL)
5490 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491 }
5492 if (flags & FIO_LATIN1)
5493 len = (int)(p - buf);
5494 else
5495 {
5496 buf = ip->bw_conv_buf;
5497 len = (int)(p - ip->bw_conv_buf);
5498 }
5499 }
5500
5501# ifdef WIN3264
5502 else if (flags & FIO_CODEPAGE)
5503 {
5504 /*
5505 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5506 * codepage.
5507 */
5508 char_u *from;
5509 size_t fromlen;
5510 char_u *to;
5511 int u8c;
5512 BOOL bad = FALSE;
5513 int needed;
5514
5515 if (ip->bw_restlen > 0)
5516 {
5517 /* Need to concatenate the remainder of the previous call and
5518 * the bytes of the current call. Use the end of the
5519 * conversion buffer for this. */
5520 fromlen = len + ip->bw_restlen;
5521 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5522 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5523 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5524 }
5525 else
5526 {
5527 from = buf;
5528 fromlen = len;
5529 }
5530
5531 to = ip->bw_conv_buf;
5532 if (enc_utf8)
5533 {
5534 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5535 * The buffer has been allocated to be big enough. */
5536 while (fromlen > 0)
5537 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005538 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539 if (n > (int)fromlen) /* incomplete byte sequence */
5540 break;
5541 u8c = utf_ptr2char(from);
5542 *to++ = (u8c & 0xff);
5543 *to++ = (u8c >> 8);
5544 fromlen -= n;
5545 from += n;
5546 }
5547
5548 /* Copy remainder to ip->bw_rest[] to be used for the next
5549 * call. */
5550 if (fromlen > CONV_RESTLEN)
5551 {
5552 /* weird overlong sequence */
5553 ip->bw_conv_error = TRUE;
5554 return FAIL;
5555 }
5556 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005557 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 }
5559 else
5560 {
5561 /* Convert from enc_codepage to UCS-2, to the start of the
5562 * buffer. The buffer has been allocated to be big enough. */
5563 ip->bw_restlen = 0;
5564 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005565 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 NULL, 0);
5567 if (needed == 0)
5568 {
5569 /* When conversion fails there may be a trailing byte. */
5570 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005571 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005572 NULL, 0);
5573 if (needed == 0)
5574 {
5575 /* Conversion doesn't work. */
5576 ip->bw_conv_error = TRUE;
5577 return FAIL;
5578 }
5579 /* Save the trailing byte for the next call. */
5580 ip->bw_rest[0] = from[fromlen - 1];
5581 ip->bw_restlen = 1;
5582 }
5583 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005584 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 (LPWSTR)to, needed);
5586 if (needed == 0)
5587 {
5588 /* Safety check: Conversion doesn't work. */
5589 ip->bw_conv_error = TRUE;
5590 return FAIL;
5591 }
5592 to += needed * 2;
5593 }
5594
5595 fromlen = to - ip->bw_conv_buf;
5596 buf = to;
5597# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5598 if (FIO_GET_CP(flags) == CP_UTF8)
5599 {
5600 /* Convert from UCS-2 to UTF-8, using the remainder of the
5601 * conversion buffer. Fails when out of space. */
5602 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5603 {
5604 u8c = *from++;
5605 u8c += (*from++ << 8);
5606 to += utf_char2bytes(u8c, to);
5607 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5608 {
5609 ip->bw_conv_error = TRUE;
5610 return FAIL;
5611 }
5612 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005613 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 }
5615 else
5616#endif
5617 {
5618 /* Convert from UCS-2 to the codepage, using the remainder of
5619 * the conversion buffer. If the conversion uses the default
5620 * character "0", the data doesn't fit in this encoding, so
5621 * fail. */
5622 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5623 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005624 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5625 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 if (bad)
5627 {
5628 ip->bw_conv_error = TRUE;
5629 return FAIL;
5630 }
5631 }
5632 }
5633# endif
5634
Bram Moolenaar56718732006-03-15 22:53:57 +00005635# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 else if (flags & FIO_MACROMAN)
5637 {
5638 /*
5639 * Convert UTF-8 or latin1 to Apple MacRoman.
5640 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 char_u *from;
5642 size_t fromlen;
5643
5644 if (ip->bw_restlen > 0)
5645 {
5646 /* Need to concatenate the remainder of the previous call and
5647 * the bytes of the current call. Use the end of the
5648 * conversion buffer for this. */
5649 fromlen = len + ip->bw_restlen;
5650 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5651 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5652 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5653 }
5654 else
5655 {
5656 from = buf;
5657 fromlen = len;
5658 }
5659
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005660 if (enc2macroman(from, fromlen,
5661 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5662 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663 {
5664 ip->bw_conv_error = TRUE;
5665 return FAIL;
5666 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 }
5669# endif
5670
5671# ifdef USE_ICONV
5672 if (ip->bw_iconv_fd != (iconv_t)-1)
5673 {
5674 const char *from;
5675 size_t fromlen;
5676 char *to;
5677 size_t tolen;
5678
5679 /* Convert with iconv(). */
5680 if (ip->bw_restlen > 0)
5681 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005682 char *fp;
5683
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684 /* Need to concatenate the remainder of the previous call and
5685 * the bytes of the current call. Use the end of the
5686 * conversion buffer for this. */
5687 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005688 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5689 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5690 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5691 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 tolen = ip->bw_conv_buflen - fromlen;
5693 }
5694 else
5695 {
5696 from = (const char *)buf;
5697 fromlen = len;
5698 tolen = ip->bw_conv_buflen;
5699 }
5700 to = (char *)ip->bw_conv_buf;
5701
5702 if (ip->bw_first)
5703 {
5704 size_t save_len = tolen;
5705
5706 /* output the initial shift state sequence */
5707 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5708
5709 /* There is a bug in iconv() on Linux (which appears to be
5710 * wide-spread) which sets "to" to NULL and messes up "tolen".
5711 */
5712 if (to == NULL)
5713 {
5714 to = (char *)ip->bw_conv_buf;
5715 tolen = save_len;
5716 }
5717 ip->bw_first = FALSE;
5718 }
5719
5720 /*
5721 * If iconv() has an error or there is not enough room, fail.
5722 */
5723 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5724 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5725 || fromlen > CONV_RESTLEN)
5726 {
5727 ip->bw_conv_error = TRUE;
5728 return FAIL;
5729 }
5730
5731 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5732 if (fromlen > 0)
5733 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5734 ip->bw_restlen = (int)fromlen;
5735
5736 buf = ip->bw_conv_buf;
5737 len = (int)((char_u *)to - ip->bw_conv_buf);
5738 }
5739# endif
5740 }
5741#endif /* FEAT_MBYTE */
5742
5743#ifdef FEAT_CRYPT
5744 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005745 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746#endif
5747
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005748 wlen = write_eintr(ip->bw_fd, buf, len);
5749 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750}
5751
5752#ifdef FEAT_MBYTE
5753/*
5754 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005755 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756 */
5757 static int
5758ucs2bytes(c, pp, flags)
5759 unsigned c; /* in: character */
5760 char_u **pp; /* in/out: pointer to result */
5761 int flags; /* FIO_ flags */
5762{
5763 char_u *p = *pp;
5764 int error = FALSE;
5765 int cc;
5766
5767
5768 if (flags & FIO_UCS4)
5769 {
5770 if (flags & FIO_ENDIAN_L)
5771 {
5772 *p++ = c;
5773 *p++ = (c >> 8);
5774 *p++ = (c >> 16);
5775 *p++ = (c >> 24);
5776 }
5777 else
5778 {
5779 *p++ = (c >> 24);
5780 *p++ = (c >> 16);
5781 *p++ = (c >> 8);
5782 *p++ = c;
5783 }
5784 }
5785 else if (flags & (FIO_UCS2 | FIO_UTF16))
5786 {
5787 if (c >= 0x10000)
5788 {
5789 if (flags & FIO_UTF16)
5790 {
5791 /* Make two words, ten bits of the character in each. First
5792 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5793 c -= 0x10000;
5794 if (c >= 0x100000)
5795 error = TRUE;
5796 cc = ((c >> 10) & 0x3ff) + 0xd800;
5797 if (flags & FIO_ENDIAN_L)
5798 {
5799 *p++ = cc;
5800 *p++ = ((unsigned)cc >> 8);
5801 }
5802 else
5803 {
5804 *p++ = ((unsigned)cc >> 8);
5805 *p++ = cc;
5806 }
5807 c = (c & 0x3ff) + 0xdc00;
5808 }
5809 else
5810 error = TRUE;
5811 }
5812 if (flags & FIO_ENDIAN_L)
5813 {
5814 *p++ = c;
5815 *p++ = (c >> 8);
5816 }
5817 else
5818 {
5819 *p++ = (c >> 8);
5820 *p++ = c;
5821 }
5822 }
5823 else /* Latin1 */
5824 {
5825 if (c >= 0x100)
5826 {
5827 error = TRUE;
5828 *p++ = 0xBF;
5829 }
5830 else
5831 *p++ = c;
5832 }
5833
5834 *pp = p;
5835 return error;
5836}
5837
5838/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005839 * Return TRUE if file encoding "fenc" requires conversion from or to
5840 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841 */
5842 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005843need_conversion(fenc)
5844 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005846 int same_encoding;
5847 int enc_flags;
5848 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005850 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005851 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005852 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005853 fenc_flags = 0;
5854 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005855 else
5856 {
5857 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5858 * "ucs-4be", etc. */
5859 enc_flags = get_fio_flags(p_enc);
5860 fenc_flags = get_fio_flags(fenc);
5861 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5862 }
5863 if (same_encoding)
5864 {
5865 /* Specified encoding matches with 'encoding'. This requires
5866 * conversion when 'encoding' is Unicode but not UTF-8. */
5867 return enc_unicode != 0;
5868 }
5869
5870 /* Encodings differ. However, conversion is not needed when 'enc' is any
5871 * Unicode encoding and the file is UTF-8. */
5872 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873}
5874
5875/*
5876 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5877 * internal conversion.
5878 * if "ptr" is an empty string, use 'encoding'.
5879 */
5880 static int
5881get_fio_flags(ptr)
5882 char_u *ptr;
5883{
5884 int prop;
5885
5886 if (*ptr == NUL)
5887 ptr = p_enc;
5888
5889 prop = enc_canon_props(ptr);
5890 if (prop & ENC_UNICODE)
5891 {
5892 if (prop & ENC_2BYTE)
5893 {
5894 if (prop & ENC_ENDIAN_L)
5895 return FIO_UCS2 | FIO_ENDIAN_L;
5896 return FIO_UCS2;
5897 }
5898 if (prop & ENC_4BYTE)
5899 {
5900 if (prop & ENC_ENDIAN_L)
5901 return FIO_UCS4 | FIO_ENDIAN_L;
5902 return FIO_UCS4;
5903 }
5904 if (prop & ENC_2WORD)
5905 {
5906 if (prop & ENC_ENDIAN_L)
5907 return FIO_UTF16 | FIO_ENDIAN_L;
5908 return FIO_UTF16;
5909 }
5910 return FIO_UTF8;
5911 }
5912 if (prop & ENC_LATIN1)
5913 return FIO_LATIN1;
5914 /* must be ENC_DBCS, requires iconv() */
5915 return 0;
5916}
5917
5918#ifdef WIN3264
5919/*
5920 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5921 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5922 * Used for conversion between 'encoding' and 'fileencoding'.
5923 */
5924 static int
5925get_win_fio_flags(ptr)
5926 char_u *ptr;
5927{
5928 int cp;
5929
5930 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5931 if (!enc_utf8 && enc_codepage <= 0)
5932 return 0;
5933
5934 cp = encname2codepage(ptr);
5935 if (cp == 0)
5936 {
5937# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5938 if (STRCMP(ptr, "utf-8") == 0)
5939 cp = CP_UTF8;
5940 else
5941# endif
5942 return 0;
5943 }
5944 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5945}
5946#endif
5947
5948#ifdef MACOS_X
5949/*
5950 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5951 * needed for the internal conversion to/from utf-8 or latin1.
5952 */
5953 static int
5954get_mac_fio_flags(ptr)
5955 char_u *ptr;
5956{
5957 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5958 && (enc_canon_props(ptr) & ENC_MACROMAN))
5959 return FIO_MACROMAN;
5960 return 0;
5961}
5962#endif
5963
5964/*
5965 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5966 * "size" must be at least 2.
5967 * Return the name of the encoding and set "*lenp" to the length.
5968 * Returns NULL when no BOM found.
5969 */
5970 static char_u *
5971check_for_bom(p, size, lenp, flags)
5972 char_u *p;
5973 long size;
5974 int *lenp;
5975 int flags;
5976{
5977 char *name = NULL;
5978 int len = 2;
5979
5980 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005981 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982 {
5983 name = "utf-8"; /* EF BB BF */
5984 len = 3;
5985 }
5986 else if (p[0] == 0xff && p[1] == 0xfe)
5987 {
5988 if (size >= 4 && p[2] == 0 && p[3] == 0
5989 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5990 {
5991 name = "ucs-4le"; /* FF FE 00 00 */
5992 len = 4;
5993 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005994 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005996 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5997 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 name = "utf-16le"; /* FF FE */
5999 }
6000 else if (p[0] == 0xfe && p[1] == 0xff
6001 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6002 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006003 /* Default to utf-16, it works also for ucs-2 text. */
6004 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006006 else
6007 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 }
6009 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6010 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6011 {
6012 name = "ucs-4"; /* 00 00 FE FF */
6013 len = 4;
6014 }
6015
6016 *lenp = len;
6017 return (char_u *)name;
6018}
6019
6020/*
6021 * Generate a BOM in "buf[4]" for encoding "name".
6022 * Return the length of the BOM (zero when no BOM).
6023 */
6024 static int
6025make_bom(buf, name)
6026 char_u *buf;
6027 char_u *name;
6028{
6029 int flags;
6030 char_u *p;
6031
6032 flags = get_fio_flags(name);
6033
6034 /* Can't put a BOM in a non-Unicode file. */
6035 if (flags == FIO_LATIN1 || flags == 0)
6036 return 0;
6037
6038 if (flags == FIO_UTF8) /* UTF-8 */
6039 {
6040 buf[0] = 0xef;
6041 buf[1] = 0xbb;
6042 buf[2] = 0xbf;
6043 return 3;
6044 }
6045 p = buf;
6046 (void)ucs2bytes(0xfeff, &p, flags);
6047 return (int)(p - buf);
6048}
6049#endif
6050
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006051#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006052 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053/*
6054 * Try to find a shortname by comparing the fullname with the current
6055 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006056 * Returns "full_path" or pointer into "full_path" if shortened.
6057 */
6058 char_u *
6059shorten_fname1(full_path)
6060 char_u *full_path;
6061{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006062 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006063 char_u *p = full_path;
6064
Bram Moolenaard9462e32011-04-11 21:35:11 +02006065 dirname = alloc(MAXPATHL);
6066 if (dirname == NULL)
6067 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006068 if (mch_dirname(dirname, MAXPATHL) == OK)
6069 {
6070 p = shorten_fname(full_path, dirname);
6071 if (p == NULL || *p == NUL)
6072 p = full_path;
6073 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006074 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006075 return p;
6076}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006077#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006078
6079/*
6080 * Try to find a shortname by comparing the fullname with the current
6081 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082 * Returns NULL if not shorter name possible, pointer into "full_path"
6083 * otherwise.
6084 */
6085 char_u *
6086shorten_fname(full_path, dir_name)
6087 char_u *full_path;
6088 char_u *dir_name;
6089{
6090 int len;
6091 char_u *p;
6092
6093 if (full_path == NULL)
6094 return NULL;
6095 len = (int)STRLEN(dir_name);
6096 if (fnamencmp(dir_name, full_path, len) == 0)
6097 {
6098 p = full_path + len;
6099#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6100 /*
6101 * MSDOS: when a file is in the root directory, dir_name will end in a
6102 * slash, since C: by itself does not define a specific dir. In this
6103 * case p may already be correct. <negri>
6104 */
6105 if (!((len > 2) && (*(p - 2) == ':')))
6106#endif
6107 {
6108 if (vim_ispathsep(*p))
6109 ++p;
6110#ifndef VMS /* the path separator is always part of the path */
6111 else
6112 p = NULL;
6113#endif
6114 }
6115 }
6116#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6117 /*
6118 * When using a file in the current drive, remove the drive name:
6119 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6120 * a floppy from "A:\dir" to "B:\dir".
6121 */
6122 else if (len > 3
6123 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6124 && full_path[1] == ':'
6125 && vim_ispathsep(full_path[2]))
6126 p = full_path + 2;
6127#endif
6128 else
6129 p = NULL;
6130 return p;
6131}
6132
6133/*
6134 * Shorten filenames for all buffers.
6135 * When "force" is TRUE: Use full path from now on for files currently being
6136 * edited, both for file name and swap file name. Try to shorten the file
6137 * names a bit, if safe to do so.
6138 * When "force" is FALSE: Only try to shorten absolute file names.
6139 * For buffers that have buftype "nofile" or "scratch": never change the file
6140 * name.
6141 */
6142 void
6143shorten_fnames(force)
6144 int force;
6145{
6146 char_u dirname[MAXPATHL];
6147 buf_T *buf;
6148 char_u *p;
6149
6150 mch_dirname(dirname, MAXPATHL);
6151 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6152 {
6153 if (buf->b_fname != NULL
6154#ifdef FEAT_QUICKFIX
6155 && !bt_nofile(buf)
6156#endif
6157 && !path_with_url(buf->b_fname)
6158 && (force
6159 || buf->b_sfname == NULL
6160 || mch_isFullName(buf->b_sfname)))
6161 {
6162 vim_free(buf->b_sfname);
6163 buf->b_sfname = NULL;
6164 p = shorten_fname(buf->b_ffname, dirname);
6165 if (p != NULL)
6166 {
6167 buf->b_sfname = vim_strsave(p);
6168 buf->b_fname = buf->b_sfname;
6169 }
6170 if (p == NULL || buf->b_fname == NULL)
6171 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006173
6174 /* Always make the swap file name a full path, a "nofile" buffer may
6175 * also have a swap file. */
6176 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 }
6178#ifdef FEAT_WINDOWS
6179 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006180 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181#endif
6182}
6183
6184#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6185 || defined(FEAT_GUI_MSWIN) \
6186 || defined(FEAT_GUI_MAC) \
6187 || defined(PROTO)
6188/*
6189 * Shorten all filenames in "fnames[count]" by current directory.
6190 */
6191 void
6192shorten_filenames(fnames, count)
6193 char_u **fnames;
6194 int count;
6195{
6196 int i;
6197 char_u dirname[MAXPATHL];
6198 char_u *p;
6199
6200 if (fnames == NULL || count < 1)
6201 return;
6202 mch_dirname(dirname, sizeof(dirname));
6203 for (i = 0; i < count; ++i)
6204 {
6205 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6206 {
6207 /* shorten_fname() returns pointer in given "fnames[i]". If free
6208 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6209 * "p" first then free fnames[i]. */
6210 p = vim_strsave(p);
6211 vim_free(fnames[i]);
6212 fnames[i] = p;
6213 }
6214 }
6215}
6216#endif
6217
6218/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006219 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 * fo_o_h.ext for MSDOS or when shortname option set.
6221 *
6222 * Assumed that fname is a valid name found in the filesystem we assure that
6223 * the return value is a different name and ends in 'ext'.
6224 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6225 * characters otherwise.
6226 * Space for the returned name is allocated, must be freed later.
6227 * Returns NULL when out of memory.
6228 */
6229 char_u *
6230modname(fname, ext, prepend_dot)
6231 char_u *fname, *ext;
6232 int prepend_dot; /* may prepend a '.' to file name */
6233{
6234 return buf_modname(
6235#ifdef SHORT_FNAME
6236 TRUE,
6237#else
6238 (curbuf->b_p_sn || curbuf->b_shortname),
6239#endif
6240 fname, ext, prepend_dot);
6241}
6242
6243 char_u *
6244buf_modname(shortname, fname, ext, prepend_dot)
6245 int shortname; /* use 8.3 file name */
6246 char_u *fname, *ext;
6247 int prepend_dot; /* may prepend a '.' to file name */
6248{
6249 char_u *retval;
6250 char_u *s;
6251 char_u *e;
6252 char_u *ptr;
6253 int fnamelen, extlen;
6254
6255 extlen = (int)STRLEN(ext);
6256
6257 /*
6258 * If there is no file name we must get the name of the current directory
6259 * (we need the full path in case :cd is used).
6260 */
6261 if (fname == NULL || *fname == NUL)
6262 {
6263 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6264 if (retval == NULL)
6265 return NULL;
6266 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6267 (fnamelen = (int)STRLEN(retval)) == 0)
6268 {
6269 vim_free(retval);
6270 return NULL;
6271 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006272 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 {
6274 retval[fnamelen++] = PATHSEP;
6275 retval[fnamelen] = NUL;
6276 }
6277#ifndef SHORT_FNAME
6278 prepend_dot = FALSE; /* nothing to prepend a dot to */
6279#endif
6280 }
6281 else
6282 {
6283 fnamelen = (int)STRLEN(fname);
6284 retval = alloc((unsigned)(fnamelen + extlen + 3));
6285 if (retval == NULL)
6286 return NULL;
6287 STRCPY(retval, fname);
6288#ifdef VMS
6289 vms_remove_version(retval); /* we do not need versions here */
6290#endif
6291 }
6292
6293 /*
6294 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6295 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6296 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6297 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6298 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006299 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006302#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006304#else
6305# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 && shortname
6307# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02006308#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 )
6310 if (*ptr == '.') /* replace '.' by '_' */
6311 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006313 {
6314 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006316 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318
6319 /* the file name has at most BASENAMELEN characters. */
6320#ifndef SHORT_FNAME
6321 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6322 ptr[BASENAMELEN] = '\0';
6323#endif
6324
6325 s = ptr + STRLEN(ptr);
6326
6327 /*
6328 * For 8.3 file names we may have to reduce the length.
6329 */
6330#ifdef USE_LONG_FNAME
6331 if (!USE_LONG_FNAME || shortname)
6332#else
6333# ifndef SHORT_FNAME
6334 if (shortname)
6335# endif
6336#endif
6337 {
6338 /*
6339 * If there is no file name, or the file name ends in '/', and the
6340 * extension starts with '.', put a '_' before the dot, because just
6341 * ".ext" is invalid.
6342 */
6343 if (fname == NULL || *fname == NUL
6344 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6345 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 *s++ = '_';
6348 }
6349 /*
6350 * If the extension starts with '.', truncate the base name at 8
6351 * characters
6352 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006355 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356 {
6357 s = ptr + 8;
6358 *s = '\0';
6359 }
6360 }
6361 /*
6362 * If the extension doesn't start with '.', and the file name
6363 * doesn't have an extension yet, append a '.'
6364 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 else if ((e = vim_strchr(ptr, '.')) == NULL)
6366 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 /*
6368 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006369 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 */
6371 else if ((int)STRLEN(e) + extlen > 4)
6372 s = e + 4 - extlen;
6373 }
6374#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6375 /*
6376 * If there is no file name, and the extension starts with '.', put a
6377 * '_' before the dot, because just ".ext" may be invalid if it's on a
6378 * FAT partition, and on HPFS it doesn't matter.
6379 */
6380 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6381 *s++ = '_';
6382#endif
6383
6384 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006385 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386 * ext can start with '.' and cannot exceed 3 more characters.
6387 */
6388 STRCPY(s, ext);
6389
6390#ifndef SHORT_FNAME
6391 /*
6392 * Prepend the dot.
6393 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006394 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395#ifdef USE_LONG_FNAME
6396 && USE_LONG_FNAME
6397#endif
6398 )
6399 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006400 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 }
6403#endif
6404
6405 /*
6406 * Check that, after appending the extension, the file name is really
6407 * different.
6408 */
6409 if (fname != NULL && STRCMP(fname, retval) == 0)
6410 {
6411 /* we search for a character that can be replaced by '_' */
6412 while (--s >= ptr)
6413 {
6414 if (*s != '_')
6415 {
6416 *s = '_';
6417 break;
6418 }
6419 }
6420 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6421 *ptr = 'v';
6422 }
6423 return retval;
6424}
6425
6426/*
6427 * Like fgets(), but if the file line is too long, it is truncated and the
6428 * rest of the line is thrown away. Returns TRUE for end-of-file.
6429 */
6430 int
6431vim_fgets(buf, size, fp)
6432 char_u *buf;
6433 int size;
6434 FILE *fp;
6435{
6436 char *eof;
6437#define FGETS_SIZE 200
6438 char tbuf[FGETS_SIZE];
6439
6440 buf[size - 2] = NUL;
6441#ifdef USE_CR
6442 eof = fgets_cr((char *)buf, size, fp);
6443#else
6444 eof = fgets((char *)buf, size, fp);
6445#endif
6446 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6447 {
6448 buf[size - 1] = NUL; /* Truncate the line */
6449
6450 /* Now throw away the rest of the line: */
6451 do
6452 {
6453 tbuf[FGETS_SIZE - 2] = NUL;
6454#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006455 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006457 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458#endif
6459 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6460 }
6461 return (eof == NULL);
6462}
6463
6464#if defined(USE_CR) || defined(PROTO)
6465/*
6466 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6467 * Returns TRUE for end-of-file.
6468 * Only used for the Mac, because it's much slower than vim_fgets().
6469 */
6470 int
6471tag_fgets(buf, size, fp)
6472 char_u *buf;
6473 int size;
6474 FILE *fp;
6475{
6476 int i = 0;
6477 int c;
6478 int eof = FALSE;
6479
6480 for (;;)
6481 {
6482 c = fgetc(fp);
6483 if (c == EOF)
6484 {
6485 eof = TRUE;
6486 break;
6487 }
6488 if (c == '\r')
6489 {
6490 /* Always store a NL for end-of-line. */
6491 if (i < size - 1)
6492 buf[i++] = '\n';
6493 c = fgetc(fp);
6494 if (c != '\n') /* Macintosh format: single CR. */
6495 ungetc(c, fp);
6496 break;
6497 }
6498 if (i < size - 1)
6499 buf[i++] = c;
6500 if (c == '\n')
6501 break;
6502 }
6503 buf[i] = NUL;
6504 return eof;
6505}
6506#endif
6507
6508/*
6509 * rename() only works if both files are on the same file system, this
6510 * function will (attempts to?) copy the file across if rename fails -- webb
6511 * Return -1 for failure, 0 for success.
6512 */
6513 int
6514vim_rename(from, to)
6515 char_u *from;
6516 char_u *to;
6517{
6518 int fd_in;
6519 int fd_out;
6520 int n;
6521 char *errmsg = NULL;
6522 char *buffer;
6523#ifdef AMIGA
6524 BPTR flock;
6525#endif
6526 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006527 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006528#ifdef HAVE_ACL
6529 vim_acl_T acl; /* ACL from original file */
6530#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006531 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532
6533 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006534 * When the names are identical, there is nothing to do. When they refer
6535 * to the same file (ignoring case and slash/backslash differences) but
6536 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 */
6538 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006539 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006540 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006541 use_tmp_file = TRUE;
6542 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006543 return 0;
6544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545
6546 /*
6547 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6548 */
6549 if (mch_stat((char *)from, &st) < 0)
6550 return -1;
6551
Bram Moolenaar3576da72008-12-30 15:15:57 +00006552#ifdef UNIX
6553 {
6554 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006555
6556 /* It's possible for the source and destination to be the same file.
6557 * This happens when "from" and "to" differ in case and are on a FAT32
6558 * filesystem. In that case go through a temp file name. */
6559 if (mch_stat((char *)to, &st_to) >= 0
6560 && st.st_dev == st_to.st_dev
6561 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006562 use_tmp_file = TRUE;
6563 }
6564#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006565#ifdef WIN3264
6566 {
6567 BY_HANDLE_FILE_INFORMATION info1, info2;
6568
6569 /* It's possible for the source and destination to be the same file.
6570 * In that case go through a temp file name. This makes rename("foo",
6571 * "./foo") a no-op (in a complicated way). */
6572 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6573 && win32_fileinfo(to, &info2) == FILEINFO_OK
6574 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6575 && info1.nFileIndexHigh == info2.nFileIndexHigh
6576 && info1.nFileIndexLow == info2.nFileIndexLow)
6577 use_tmp_file = TRUE;
6578 }
6579#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006580
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006581 if (use_tmp_file)
6582 {
6583 char tempname[MAXPATHL + 1];
6584
6585 /*
6586 * Find a name that doesn't exist and is in the same directory.
6587 * Rename "from" to "tempname" and then rename "tempname" to "to".
6588 */
6589 if (STRLEN(from) >= MAXPATHL - 5)
6590 return -1;
6591 STRCPY(tempname, from);
6592 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006593 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006594 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6595 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006596 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006597 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006598 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006599 if (mch_rename(tempname, (char *)to) == 0)
6600 return 0;
6601 /* Strange, the second step failed. Try moving the
6602 * file back and return failure. */
6603 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006604 return -1;
6605 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006606 /* If it fails for one temp name it will most likely fail
6607 * for any temp name, give up. */
6608 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006609 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006610 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006611 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006612 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006613
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 /*
6615 * Delete the "to" file, this is required on some systems to make the
6616 * mch_rename() work, on other systems it makes sure that we don't have
6617 * two files when the mch_rename() fails.
6618 */
6619
6620#ifdef AMIGA
6621 /*
6622 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6623 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006624 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 * deleting the "from" file (horror!) we lock it during the remove.
6626 *
6627 * When used for making a backup before writing the file: This should not
6628 * happen with ":w", because startscript() should detect this problem and
6629 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6630 * name. This problem does exist with ":w filename", but then the
6631 * original file will be somewhere else so the backup isn't really
6632 * important. If autoscripting is off the rename may fail.
6633 */
6634 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6635#endif
6636 mch_remove(to);
6637#ifdef AMIGA
6638 if (flock)
6639 UnLock(flock);
6640#endif
6641
6642 /*
6643 * First try a normal rename, return if it works.
6644 */
6645 if (mch_rename((char *)from, (char *)to) == 0)
6646 return 0;
6647
6648 /*
6649 * Rename() failed, try copying the file.
6650 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006651 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006652#ifdef HAVE_ACL
6653 /* For systems that support ACL: get the ACL from the original file. */
6654 acl = mch_get_acl(from);
6655#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6657 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006658 {
6659#ifdef HAVE_ACL
6660 mch_free_acl(acl);
6661#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006663 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006664
6665 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006666 fd_out = mch_open((char *)to,
6667 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 if (fd_out == -1)
6669 {
6670 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006671#ifdef HAVE_ACL
6672 mch_free_acl(acl);
6673#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 return -1;
6675 }
6676
6677 buffer = (char *)alloc(BUFSIZE);
6678 if (buffer == NULL)
6679 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006681 close(fd_in);
6682#ifdef HAVE_ACL
6683 mch_free_acl(acl);
6684#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 return -1;
6686 }
6687
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006688 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6689 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 {
6691 errmsg = _("E208: Error writing to \"%s\"");
6692 break;
6693 }
6694
6695 vim_free(buffer);
6696 close(fd_in);
6697 if (close(fd_out) < 0)
6698 errmsg = _("E209: Error closing \"%s\"");
6699 if (n < 0)
6700 {
6701 errmsg = _("E210: Error reading \"%s\"");
6702 to = from;
6703 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006704#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006705 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006706#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006707#ifdef HAVE_ACL
6708 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006709 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006710#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 if (errmsg != NULL)
6712 {
6713 EMSG2(errmsg, to);
6714 return -1;
6715 }
6716 mch_remove(from);
6717 return 0;
6718}
6719
6720static int already_warned = FALSE;
6721
6722/*
6723 * Check if any not hidden buffer has been changed.
6724 * Postpone the check if there are characters in the stuff buffer, a global
6725 * command is being executed, a mapping is being executed or an autocommand is
6726 * busy.
6727 * Returns TRUE if some message was written (screen should be redrawn and
6728 * cursor positioned).
6729 */
6730 int
6731check_timestamps(focus)
6732 int focus; /* called for GUI focus event */
6733{
6734 buf_T *buf;
6735 int didit = 0;
6736 int n;
6737
6738 /* Don't check timestamps while system() or another low-level function may
6739 * cause us to lose and gain focus. */
6740 if (no_check_timestamps > 0)
6741 return FALSE;
6742
6743 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6744 * event and we would keep on checking if the file is steadily growing.
6745 * Do check again after typing something. */
6746 if (focus && did_check_timestamps)
6747 {
6748 need_check_timestamps = TRUE;
6749 return FALSE;
6750 }
6751
6752 if (!stuff_empty() || global_busy || !typebuf_typed()
6753#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006754 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755#endif
6756 )
6757 need_check_timestamps = TRUE; /* check later */
6758 else
6759 {
6760 ++no_wait_return;
6761 did_check_timestamps = TRUE;
6762 already_warned = FALSE;
6763 for (buf = firstbuf; buf != NULL; )
6764 {
6765 /* Only check buffers in a window. */
6766 if (buf->b_nwindows > 0)
6767 {
6768 n = buf_check_timestamp(buf, focus);
6769 if (didit < n)
6770 didit = n;
6771 if (n > 0 && !buf_valid(buf))
6772 {
6773 /* Autocommands have removed the buffer, start at the
6774 * first one again. */
6775 buf = firstbuf;
6776 continue;
6777 }
6778 }
6779 buf = buf->b_next;
6780 }
6781 --no_wait_return;
6782 need_check_timestamps = FALSE;
6783 if (need_wait_return && didit == 2)
6784 {
6785 /* make sure msg isn't overwritten */
6786 msg_puts((char_u *)"\n");
6787 out_flush();
6788 }
6789 }
6790 return didit;
6791}
6792
6793/*
6794 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6795 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6796 * empty.
6797 */
6798 static int
6799move_lines(frombuf, tobuf)
6800 buf_T *frombuf;
6801 buf_T *tobuf;
6802{
6803 buf_T *tbuf = curbuf;
6804 int retval = OK;
6805 linenr_T lnum;
6806 char_u *p;
6807
6808 /* Copy the lines in "frombuf" to "tobuf". */
6809 curbuf = tobuf;
6810 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6811 {
6812 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6813 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6814 {
6815 vim_free(p);
6816 retval = FAIL;
6817 break;
6818 }
6819 vim_free(p);
6820 }
6821
6822 /* Delete all the lines in "frombuf". */
6823 if (retval != FAIL)
6824 {
6825 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006826 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6827 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 {
6829 /* Oops! We could try putting back the saved lines, but that
6830 * might fail again... */
6831 retval = FAIL;
6832 break;
6833 }
6834 }
6835
6836 curbuf = tbuf;
6837 return retval;
6838}
6839
6840/*
6841 * Check if buffer "buf" has been changed.
6842 * Also check if the file for a new buffer unexpectedly appeared.
6843 * return 1 if a changed buffer was found.
6844 * return 2 if a message has been displayed.
6845 * return 0 otherwise.
6846 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847 int
6848buf_check_timestamp(buf, focus)
6849 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006850 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851{
6852 struct stat st;
6853 int stat_res;
6854 int retval = 0;
6855 char_u *path;
6856 char_u *tbuf;
6857 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006858 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006859 int helpmesg = FALSE;
6860 int reload = FALSE;
6861#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6862 int can_reload = FALSE;
6863#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006864 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865 int orig_mode = buf->b_orig_mode;
6866#ifdef FEAT_GUI
6867 int save_mouse_correct = need_mouse_correct;
6868#endif
6869#ifdef FEAT_AUTOCMD
6870 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006871 int n;
6872 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006874 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875
6876 /* If there is no file name, the buffer is not loaded, 'buftype' is
6877 * set, we are in the middle of a save or being called recursively: ignore
6878 * this buffer. */
6879 if (buf->b_ffname == NULL
6880 || buf->b_ml.ml_mfp == NULL
6881#if defined(FEAT_QUICKFIX)
6882 || *buf->b_p_bt != NUL
6883#endif
6884 || buf->b_saving
6885#ifdef FEAT_AUTOCMD
6886 || busy
6887#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006888#ifdef FEAT_NETBEANS_INTG
6889 || isNetbeansBuffer(buf)
6890#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 )
6892 return 0;
6893
6894 if ( !(buf->b_flags & BF_NOTEDITED)
6895 && buf->b_mtime != 0
6896 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6897 || time_differs((long)st.st_mtime, buf->b_mtime)
6898#ifdef HAVE_ST_MODE
6899 || (int)st.st_mode != buf->b_orig_mode
6900#else
6901 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6902#endif
6903 ))
6904 {
6905 retval = 1;
6906
Bram Moolenaar316059c2006-01-14 21:18:42 +00006907 /* set b_mtime to stop further warnings (e.g., when executing
6908 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 if (stat_res < 0)
6910 {
6911 buf->b_mtime = 0;
6912 buf->b_orig_size = 0;
6913 buf->b_orig_mode = 0;
6914 }
6915 else
6916 buf_store_time(buf, &st, buf->b_ffname);
6917
6918 /* Don't do anything for a directory. Might contain the file
6919 * explorer. */
6920 if (mch_isdir(buf->b_fname))
6921 ;
6922
6923 /*
6924 * If 'autoread' is set, the buffer has no changes and the file still
6925 * exists, reload the buffer. Use the buffer-local option value if it
6926 * was set, the global option value otherwise.
6927 */
6928 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6929 && !bufIsChanged(buf) && stat_res >= 0)
6930 reload = TRUE;
6931 else
6932 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006933 if (stat_res < 0)
6934 reason = "deleted";
6935 else if (bufIsChanged(buf))
6936 reason = "conflict";
6937 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6938 reason = "changed";
6939 else if (orig_mode != buf->b_orig_mode)
6940 reason = "mode";
6941 else
6942 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006944#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 /*
6946 * Only give the warning if there are no FileChangedShell
6947 * autocommands.
6948 * Avoid being called recursively by setting "busy".
6949 */
6950 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006951# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006952 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6953 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006954# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006955 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6957 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006958 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 busy = FALSE;
6960 if (n)
6961 {
6962 if (!buf_valid(buf))
6963 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006964# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006965 s = get_vim_var_str(VV_FCS_CHOICE);
6966 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6967 reload = TRUE;
6968 else if (STRCMP(s, "ask") == 0)
6969 n = FALSE;
6970 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006971# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006972 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006974 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975#endif
6976 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006977 if (*reason == 'd')
6978 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 else
6980 {
6981 helpmesg = TRUE;
6982#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6983 can_reload = TRUE;
6984#endif
6985 /*
6986 * Check if the file contents really changed to avoid
6987 * giving a warning when only the timestamp was set (e.g.,
6988 * checked out of CVS). Always warn when the buffer was
6989 * changed.
6990 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006991 if (reason[2] == 'n')
6992 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006994 mesg2 = _("See \":help W12\" for more info.");
6995 }
6996 else if (reason[1] == 'h')
6997 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006999 mesg2 = _("See \":help W11\" for more info.");
7000 }
7001 else if (*reason == 'm')
7002 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007004 mesg2 = _("See \":help W16\" for more info.");
7005 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007006 else
7007 /* Only timestamp changed, store it to avoid a warning
7008 * in check_mtime() later. */
7009 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 }
7011 }
7012 }
7013
7014 }
7015 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7016 && vim_fexists(buf->b_ffname))
7017 {
7018 retval = 1;
7019 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7020 buf->b_flags |= BF_NEW_W;
7021#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7022 can_reload = TRUE;
7023#endif
7024 }
7025
7026 if (mesg != NULL)
7027 {
7028 path = home_replace_save(buf, buf->b_fname);
7029 if (path != NULL)
7030 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007031 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 mesg2 = "";
7033 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7034 + STRLEN(mesg2) + 2));
7035 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007036#ifdef FEAT_EVAL
7037 /* Set warningmsg here, before the unimportant and output-specific
7038 * mesg2 has been appended. */
7039 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7040#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7042 if (can_reload)
7043 {
7044 if (*mesg2 != NUL)
7045 {
7046 STRCAT(tbuf, "\n");
7047 STRCAT(tbuf, mesg2);
7048 }
7049 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007050 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 reload = TRUE;
7052 }
7053 else
7054#endif
7055 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7056 {
7057 if (*mesg2 != NUL)
7058 {
7059 STRCAT(tbuf, "; ");
7060 STRCAT(tbuf, mesg2);
7061 }
7062 EMSG(tbuf);
7063 retval = 2;
7064 }
7065 else
7066 {
Bram Moolenaared203462004-06-16 11:19:22 +00007067# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007069# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 {
7071 msg_start();
7072 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7073 if (*mesg2 != NUL)
7074 msg_puts_attr((char_u *)mesg2,
7075 hl_attr(HLF_W) + MSG_HIST);
7076 msg_clr_eos();
7077 (void)msg_end();
7078 if (emsg_silent == 0)
7079 {
7080 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007081# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007083# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 /* give the user some time to think about it */
7085 ui_delay(1000L, TRUE);
7086
7087 /* don't redraw and erase the message */
7088 redraw_cmdline = FALSE;
7089 }
7090 }
7091 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 }
7093
7094 vim_free(path);
7095 vim_free(tbuf);
7096 }
7097 }
7098
7099 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007100 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007101 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007102 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007103#ifdef FEAT_PERSISTENT_UNDO
7104 if (buf->b_p_udf && buf->b_ffname != NULL)
7105 {
7106 char_u hash[UNDO_HASH_SIZE];
7107 buf_T *save_curbuf = curbuf;
7108
7109 /* Any existing undo file is unusable, write it now. */
7110 curbuf = buf;
7111 u_compute_hash(hash);
7112 u_write_undo(NULL, FALSE, buf, hash);
7113 curbuf = save_curbuf;
7114 }
7115#endif
7116 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117
Bram Moolenaar56718732006-03-15 22:53:57 +00007118#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007119 /* Trigger FileChangedShell when the file was changed in any way. */
7120 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007121 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7122 buf->b_fname, buf->b_fname, FALSE, buf);
7123#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124#ifdef FEAT_GUI
7125 /* restore this in case an autocommand has set it; it would break
7126 * 'mousefocus' */
7127 need_mouse_correct = save_mouse_correct;
7128#endif
7129
7130 return retval;
7131}
7132
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133/*
7134 * Reload a buffer that is already loaded.
7135 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007136 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7137 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 */
7139 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007140buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007141 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007142 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143{
7144 exarg_T ea;
7145 pos_T old_cursor;
7146 linenr_T old_topline;
7147 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007148 buf_T *savebuf;
7149 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007150 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007151 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007152
7153 /* set curwin/curbuf for "buf" and save some things */
7154 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007155
7156 /* We only want to read the text from the file, not reset the syntax
7157 * highlighting, clear marks, diff status, etc. Force the fileformat
7158 * and encoding to be the same. */
7159 if (prep_exarg(&ea, buf) == OK)
7160 {
7161 old_cursor = curwin->w_cursor;
7162 old_topline = curwin->w_topline;
7163
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007164 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007165 {
7166 /* Save all the text, so that the reload can be undone.
7167 * Sync first so that this is a separate undo-able action. */
7168 u_sync(FALSE);
7169 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7170 flags |= READ_KEEP_UNDO;
7171 }
7172
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007173 /*
7174 * To behave like when a new file is edited (matters for
7175 * BufReadPost autocommands) we first need to delete the current
7176 * buffer contents. But if reading the file fails we should keep
7177 * the old contents. Can't use memory only, the file might be
7178 * too big. Use a hidden buffer to move the buffer contents to.
7179 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007180 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007181 savebuf = NULL;
7182 else
7183 {
7184 /* Allocate a buffer without putting it in the buffer list. */
7185 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007186 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007187 {
7188 /* Open the memline. */
7189 curbuf = savebuf;
7190 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007191 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007192 curbuf = buf;
7193 curwin->w_buffer = buf;
7194 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007195 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007196 || move_lines(buf, savebuf) == FAIL)
7197 {
7198 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7199 buf->b_fname);
7200 saved = FAIL;
7201 }
7202 }
7203
7204 if (saved == OK)
7205 {
7206 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7207#ifdef FEAT_AUTOCMD
7208 keep_filetype = TRUE; /* don't detect 'filetype' */
7209#endif
7210 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7211 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007212 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213 {
7214#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7215 if (!aborting())
7216#endif
7217 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007218 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007219 {
7220 /* Put the text back from the save buffer. First
7221 * delete any lines that readfile() added. */
7222 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007223 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007224 break;
7225 (void)move_lines(savebuf, buf);
7226 }
7227 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007228 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007229 {
7230 /* Mark the buffer as unmodified and free undo info. */
7231 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007232 if ((flags & READ_KEEP_UNDO) == 0)
7233 {
7234 u_blockfree(buf);
7235 u_clearall(buf);
7236 }
7237 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007238 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007239 /* Mark all undo states as changed. */
7240 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007241 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007242 }
7243 }
7244 vim_free(ea.cmd);
7245
Bram Moolenaar8424a622006-04-19 21:23:36 +00007246 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007247 wipe_buffer(savebuf, FALSE);
7248
7249#ifdef FEAT_DIFF
7250 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007251 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007252#endif
7253
7254 /* Restore the topline and cursor position and check it (lines may
7255 * have been removed). */
7256 if (old_topline > curbuf->b_ml.ml_line_count)
7257 curwin->w_topline = curbuf->b_ml.ml_line_count;
7258 else
7259 curwin->w_topline = old_topline;
7260 curwin->w_cursor = old_cursor;
7261 check_cursor();
7262 update_topline();
7263#ifdef FEAT_AUTOCMD
7264 keep_filetype = FALSE;
7265#endif
7266#ifdef FEAT_FOLDING
7267 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007268 win_T *wp;
7269 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007270
7271 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007272 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007273 if (wp->w_buffer == curwin->w_buffer
7274 && !foldmethodIsManual(wp))
7275 foldUpdateAll(wp);
7276 }
7277#endif
7278 /* If the mode didn't change and 'readonly' was set, keep the old
7279 * value; the user probably used the ":view" command. But don't
7280 * reset it, might have had a read error. */
7281 if (orig_mode == curbuf->b_orig_mode)
7282 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007283
7284 /* Modelines must override settings done by autocommands. */
7285 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007286 }
7287
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007288 /* restore curwin/curbuf and a few other things */
7289 aucmd_restbuf(&aco);
7290 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007291}
7292
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 void
7294buf_store_time(buf, st, fname)
7295 buf_T *buf;
7296 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007297 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298{
7299 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007300 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301#ifdef HAVE_ST_MODE
7302 buf->b_orig_mode = (int)st->st_mode;
7303#else
7304 buf->b_orig_mode = mch_getperm(fname);
7305#endif
7306}
7307
7308/*
7309 * Adjust the line with missing eol, used for the next write.
7310 * Used for do_filter(), when the input lines for the filter are deleted.
7311 */
7312 void
7313write_lnum_adjust(offset)
7314 linenr_T offset;
7315{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007316 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7317 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318}
7319
7320#if defined(TEMPDIRNAMES) || defined(PROTO)
7321static long temp_count = 0; /* Temp filename counter. */
7322
7323/*
7324 * Delete the temp directory and all files it contains.
7325 */
7326 void
7327vim_deltempdir()
7328{
7329 char_u **files;
7330 int file_count;
7331 int i;
7332
7333 if (vim_tempdir != NULL)
7334 {
7335 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7336 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7337 EW_DIR|EW_FILE|EW_SILENT) == OK)
7338 {
7339 for (i = 0; i < file_count; ++i)
7340 mch_remove(files[i]);
7341 FreeWild(file_count, files);
7342 }
7343 gettail(NameBuff)[-1] = NUL;
7344 (void)mch_rmdir(NameBuff);
7345
7346 vim_free(vim_tempdir);
7347 vim_tempdir = NULL;
7348 }
7349}
7350#endif
7351
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007352#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007354 * Directory "tempdir" was created. Expand this name to a full path and put
7355 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7356 * "tempdir" must be no longer than MAXPATHL.
7357 */
7358 static void
7359vim_settempdir(tempdir)
7360 char_u *tempdir;
7361{
7362 char_u *buf;
7363
7364 buf = alloc((unsigned)MAXPATHL + 2);
7365 if (buf != NULL)
7366 {
7367 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7368 STRCPY(buf, tempdir);
7369# ifdef __EMX__
7370 if (vim_strchr(buf, '/') != NULL)
7371 STRCAT(buf, "/");
7372 else
7373# endif
7374 add_pathsep(buf);
7375 vim_tempdir = vim_strsave(buf);
7376 vim_free(buf);
7377 }
7378}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007379#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007380
7381/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382 * vim_tempname(): Return a unique name that can be used for a temp file.
7383 *
7384 * The temp file is NOT created.
7385 *
7386 * The returned pointer is to allocated memory.
7387 * The returned pointer is NULL if no valid name was found.
7388 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 char_u *
7390vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007391 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392{
7393#ifdef USE_TMPNAM
7394 char_u itmp[L_tmpnam]; /* use tmpnam() */
7395#else
7396 char_u itmp[TEMPNAMELEN];
7397#endif
7398
7399#ifdef TEMPDIRNAMES
7400 static char *(tempdirs[]) = {TEMPDIRNAMES};
7401 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402# ifndef EEXIST
7403 struct stat st;
7404# endif
7405
7406 /*
7407 * This will create a directory for private use by this instance of Vim.
7408 * This is done once, and the same directory is used for all temp files.
7409 * This method avoids security problems because of symlink attacks et al.
7410 * It's also a bit faster, because we only need to check for an existing
7411 * file when creating the directory and not for each temp file.
7412 */
7413 if (vim_tempdir == NULL)
7414 {
7415 /*
7416 * Try the entries in TEMPDIRNAMES to create the temp directory.
7417 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007418 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007421 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007422 long nr;
7423 long off;
7424# endif
7425
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 /* expand $TMP, leave room for "/v1100000/999999999" */
7427 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7428 if (mch_isdir(itmp)) /* directory exists */
7429 {
7430# ifdef __EMX__
7431 /* If $TMP contains a forward slash (perhaps using bash or
7432 * tcsh), don't add a backslash, use a forward slash!
7433 * Adding 2 backslashes didn't work. */
7434 if (vim_strchr(itmp, '/') != NULL)
7435 STRCAT(itmp, "/");
7436 else
7437# endif
7438 add_pathsep(itmp);
7439
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440# ifdef HAVE_MKDTEMP
7441 /* Leave room for filename */
7442 STRCAT(itmp, "vXXXXXX");
7443 if (mkdtemp((char *)itmp) != NULL)
7444 vim_settempdir(itmp);
7445# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 /* Get an arbitrary number of up to 6 digits. When it's
7447 * unlikely that it already exists it will be faster,
7448 * otherwise it doesn't matter. The use of mkdir() avoids any
7449 * security problems because of the predictable number. */
7450 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007451 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452
7453 /* Try up to 10000 different values until we find a name that
7454 * doesn't exist. */
7455 for (off = 0; off < 10000L; ++off)
7456 {
7457 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007458# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007460# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461
Bram Moolenaareaf03392009-11-17 11:08:52 +00007462 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7463# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 /* If mkdir() does not set errno to EEXIST, check for
7465 * existing file here. There is a race condition then,
7466 * although it's fail-safe. */
7467 if (mch_stat((char *)itmp, &st) >= 0)
7468 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007469# endif
7470# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 /* Make sure the umask doesn't remove the executable bit.
7472 * "repl" has been reported to use "177". */
7473 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007474# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007476# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007478# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479 if (r == 0)
7480 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007481 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 break;
7483 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007484# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 /* If the mkdir() didn't fail because the file/dir exists,
7486 * we probably can't create any dir here, try another
7487 * place. */
7488 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007489# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 break;
7491 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007492# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 if (vim_tempdir != NULL)
7494 break;
7495 }
7496 }
7497 }
7498
7499 if (vim_tempdir != NULL)
7500 {
7501 /* There is no need to check if the file exists, because we own the
7502 * directory and nobody else creates a file in it. */
7503 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7504 return vim_strsave(itmp);
7505 }
7506
7507 return NULL;
7508
7509#else /* TEMPDIRNAMES */
7510
7511# ifdef WIN3264
7512 char szTempFile[_MAX_PATH + 1];
7513 char buf4[4];
7514 char_u *retval;
7515 char_u *p;
7516
7517 STRCPY(itmp, "");
7518 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007519 {
7520 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7521 szTempFile[1] = NUL;
7522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523 strcpy(buf4, "VIM");
7524 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7525 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7526 return NULL;
7527 /* GetTempFileName() will create the file, we don't want that */
7528 (void)DeleteFile(itmp);
7529
7530 /* Backslashes in a temp file name cause problems when filtering with
7531 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7532 * didn't set 'shellslash'. */
7533 retval = vim_strsave(itmp);
7534 if (*p_shcf == '-' || p_ssl)
7535 for (p = retval; *p; ++p)
7536 if (*p == '\\')
7537 *p = '/';
7538 return retval;
7539
7540# else /* WIN3264 */
7541
7542# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007543 char_u *p;
7544
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007546 p = tmpnam((char *)itmp);
7547 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007548 return NULL;
7549# else
7550 char_u *p;
7551
7552# ifdef VMS_TEMPNAM
7553 /* mktemp() is not working on VMS. It seems to be
7554 * a do-nothing function. Therefore we use tempnam().
7555 */
7556 sprintf((char *)itmp, "VIM%c", extra_char);
7557 p = (char_u *)tempnam("tmp:", (char *)itmp);
7558 if (p != NULL)
7559 {
7560 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7561 * and VIM will then be unable to find the file later */
7562 STRCPY(itmp, p);
7563 STRCAT(itmp, ".txt");
7564 free(p);
7565 }
7566 else
7567 return NULL;
7568# else
7569 STRCPY(itmp, TEMPNAME);
7570 if ((p = vim_strchr(itmp, '?')) != NULL)
7571 *p = extra_char;
7572 if (mktemp((char *)itmp) == NULL)
7573 return NULL;
7574# endif
7575# endif
7576
7577 return vim_strsave(itmp);
7578# endif /* WIN3264 */
7579#endif /* TEMPDIRNAMES */
7580}
7581
7582#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7583/*
7584 * Convert all backslashes in fname to forward slashes in-place.
7585 */
7586 void
7587forward_slash(fname)
7588 char_u *fname;
7589{
7590 char_u *p;
7591
7592 for (p = fname; *p != NUL; ++p)
7593# ifdef FEAT_MBYTE
7594 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007595 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007596 ++p;
7597 else
7598# endif
7599 if (*p == '\\')
7600 *p = '/';
7601}
7602#endif
7603
7604
7605/*
7606 * Code for automatic commands.
7607 *
7608 * Only included when "FEAT_AUTOCMD" has been defined.
7609 */
7610
7611#if defined(FEAT_AUTOCMD) || defined(PROTO)
7612
7613/*
7614 * The autocommands are stored in a list for each event.
7615 * Autocommands for the same pattern, that are consecutive, are joined
7616 * together, to avoid having to match the pattern too often.
7617 * The result is an array of Autopat lists, which point to AutoCmd lists:
7618 *
7619 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7620 * Autopat.cmds Autopat.cmds
7621 * | |
7622 * V V
7623 * AutoCmd.next AutoCmd.next
7624 * | |
7625 * V V
7626 * AutoCmd.next NULL
7627 * |
7628 * V
7629 * NULL
7630 *
7631 * first_autopat[1] --> Autopat.next --> NULL
7632 * Autopat.cmds
7633 * |
7634 * V
7635 * AutoCmd.next
7636 * |
7637 * V
7638 * NULL
7639 * etc.
7640 *
7641 * The order of AutoCmds is important, this is the order in which they were
7642 * defined and will have to be executed.
7643 */
7644typedef struct AutoCmd
7645{
7646 char_u *cmd; /* The command to be executed (NULL
7647 when command has been removed) */
7648 char nested; /* If autocommands nest here */
7649 char last; /* last command in list */
7650#ifdef FEAT_EVAL
7651 scid_T scriptID; /* script ID where defined */
7652#endif
7653 struct AutoCmd *next; /* Next AutoCmd in list */
7654} AutoCmd;
7655
7656typedef struct AutoPat
7657{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658 char_u *pat; /* pattern as typed (NULL when pattern
7659 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007660 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007661 AutoCmd *cmds; /* list of commands to do */
7662 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007663 int group; /* group ID */
7664 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007665 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007666 char allow_dirs; /* Pattern may match whole path */
7667 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668} AutoPat;
7669
7670static struct event_name
7671{
7672 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007673 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674} event_names[] =
7675{
7676 {"BufAdd", EVENT_BUFADD},
7677 {"BufCreate", EVENT_BUFADD},
7678 {"BufDelete", EVENT_BUFDELETE},
7679 {"BufEnter", EVENT_BUFENTER},
7680 {"BufFilePost", EVENT_BUFFILEPOST},
7681 {"BufFilePre", EVENT_BUFFILEPRE},
7682 {"BufHidden", EVENT_BUFHIDDEN},
7683 {"BufLeave", EVENT_BUFLEAVE},
7684 {"BufNew", EVENT_BUFNEW},
7685 {"BufNewFile", EVENT_BUFNEWFILE},
7686 {"BufRead", EVENT_BUFREADPOST},
7687 {"BufReadCmd", EVENT_BUFREADCMD},
7688 {"BufReadPost", EVENT_BUFREADPOST},
7689 {"BufReadPre", EVENT_BUFREADPRE},
7690 {"BufUnload", EVENT_BUFUNLOAD},
7691 {"BufWinEnter", EVENT_BUFWINENTER},
7692 {"BufWinLeave", EVENT_BUFWINLEAVE},
7693 {"BufWipeout", EVENT_BUFWIPEOUT},
7694 {"BufWrite", EVENT_BUFWRITEPRE},
7695 {"BufWritePost", EVENT_BUFWRITEPOST},
7696 {"BufWritePre", EVENT_BUFWRITEPRE},
7697 {"BufWriteCmd", EVENT_BUFWRITECMD},
7698 {"CmdwinEnter", EVENT_CMDWINENTER},
7699 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007700 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007701 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007702 {"CursorHold", EVENT_CURSORHOLD},
7703 {"CursorHoldI", EVENT_CURSORHOLDI},
7704 {"CursorMoved", EVENT_CURSORMOVED},
7705 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7707 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007708 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7709 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7710 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7711 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007712 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713 {"FileChangedRO", EVENT_FILECHANGEDRO},
7714 {"FileReadPost", EVENT_FILEREADPOST},
7715 {"FileReadPre", EVENT_FILEREADPRE},
7716 {"FileReadCmd", EVENT_FILEREADCMD},
7717 {"FileType", EVENT_FILETYPE},
7718 {"FileWritePost", EVENT_FILEWRITEPOST},
7719 {"FileWritePre", EVENT_FILEWRITEPRE},
7720 {"FileWriteCmd", EVENT_FILEWRITECMD},
7721 {"FilterReadPost", EVENT_FILTERREADPOST},
7722 {"FilterReadPre", EVENT_FILTERREADPRE},
7723 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7724 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7725 {"FocusGained", EVENT_FOCUSGAINED},
7726 {"FocusLost", EVENT_FOCUSLOST},
7727 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7728 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007729 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007730 {"InsertChange", EVENT_INSERTCHANGE},
7731 {"InsertEnter", EVENT_INSERTENTER},
7732 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007733 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007734 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007735 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7736 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007737 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007739 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007740 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7741 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007742 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007743 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007744 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007745 {"StdinReadPost", EVENT_STDINREADPOST},
7746 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007747 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007748 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007749 {"TabEnter", EVENT_TABENTER},
7750 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751 {"TermChanged", EVENT_TERMCHANGED},
7752 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007753 {"TextChanged", EVENT_TEXTCHANGED},
7754 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755 {"User", EVENT_USER},
7756 {"VimEnter", EVENT_VIMENTER},
7757 {"VimLeave", EVENT_VIMLEAVE},
7758 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7759 {"WinEnter", EVENT_WINENTER},
7760 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007761 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007762 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763};
7764
7765static AutoPat *first_autopat[NUM_EVENTS] =
7766{
7767 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7768 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7769 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7770 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007771 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7772 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773};
7774
7775/*
7776 * struct used to keep status while executing autocommands for an event.
7777 */
7778typedef struct AutoPatCmd
7779{
7780 AutoPat *curpat; /* next AutoPat to examine */
7781 AutoCmd *nextcmd; /* next AutoCmd to execute */
7782 int group; /* group being used */
7783 char_u *fname; /* fname to match with */
7784 char_u *sfname; /* sfname to match with */
7785 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007786 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007787 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7788 buf is deleted */
7789 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790} AutoPatCmd;
7791
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007792static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007793
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794/*
7795 * augroups stores a list of autocmd group names.
7796 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007797static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7799
7800/*
7801 * The ID of the current group. Group 0 is the default one.
7802 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803static int current_augroup = AUGROUP_DEFAULT;
7804
7805static int au_need_clean = FALSE; /* need to delete marked patterns */
7806
Bram Moolenaar754b5602006-02-09 23:53:20 +00007807static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007808static void au_remove_pat __ARGS((AutoPat *ap));
7809static void au_remove_cmds __ARGS((AutoPat *ap));
7810static void au_cleanup __ARGS((void));
7811static int au_new_group __ARGS((char_u *name));
7812static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007813static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7814static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007816static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007818static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007819static 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 +00007820static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7821
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007822
Bram Moolenaar754b5602006-02-09 23:53:20 +00007823static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007825static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007826
7827/*
7828 * Show the autocommands for one AutoPat.
7829 */
7830 static void
7831show_autocmd(ap, event)
7832 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007833 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834{
7835 AutoCmd *ac;
7836
7837 /* Check for "got_int" (here and at various places below), which is set
7838 * when "q" has been hit for the "--more--" prompt */
7839 if (got_int)
7840 return;
7841 if (ap->pat == NULL) /* pattern has been removed */
7842 return;
7843
7844 msg_putchar('\n');
7845 if (got_int)
7846 return;
7847 if (event != last_event || ap->group != last_group)
7848 {
7849 if (ap->group != AUGROUP_DEFAULT)
7850 {
7851 if (AUGROUP_NAME(ap->group) == NULL)
7852 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7853 else
7854 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7855 msg_puts((char_u *)" ");
7856 }
7857 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7858 last_event = event;
7859 last_group = ap->group;
7860 msg_putchar('\n');
7861 if (got_int)
7862 return;
7863 }
7864 msg_col = 4;
7865 msg_outtrans(ap->pat);
7866
7867 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7868 {
7869 if (ac->cmd != NULL) /* skip removed commands */
7870 {
7871 if (msg_col >= 14)
7872 msg_putchar('\n');
7873 msg_col = 14;
7874 if (got_int)
7875 return;
7876 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007877#ifdef FEAT_EVAL
7878 if (p_verbose > 0)
7879 last_set_msg(ac->scriptID);
7880#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007881 if (got_int)
7882 return;
7883 if (ac->next != NULL)
7884 {
7885 msg_putchar('\n');
7886 if (got_int)
7887 return;
7888 }
7889 }
7890 }
7891}
7892
7893/*
7894 * Mark an autocommand pattern for deletion.
7895 */
7896 static void
7897au_remove_pat(ap)
7898 AutoPat *ap;
7899{
7900 vim_free(ap->pat);
7901 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007902 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903 au_need_clean = TRUE;
7904}
7905
7906/*
7907 * Mark all commands for a pattern for deletion.
7908 */
7909 static void
7910au_remove_cmds(ap)
7911 AutoPat *ap;
7912{
7913 AutoCmd *ac;
7914
7915 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7916 {
7917 vim_free(ac->cmd);
7918 ac->cmd = NULL;
7919 }
7920 au_need_clean = TRUE;
7921}
7922
7923/*
7924 * Cleanup autocommands and patterns that have been deleted.
7925 * This is only done when not executing autocommands.
7926 */
7927 static void
7928au_cleanup()
7929{
7930 AutoPat *ap, **prev_ap;
7931 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007932 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007933
7934 if (autocmd_busy || !au_need_clean)
7935 return;
7936
7937 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007938 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7939 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940 {
7941 /* loop over all autocommand patterns */
7942 prev_ap = &(first_autopat[(int)event]);
7943 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7944 {
7945 /* loop over all commands for this pattern */
7946 prev_ac = &(ap->cmds);
7947 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7948 {
7949 /* remove the command if the pattern is to be deleted or when
7950 * the command has been marked for deletion */
7951 if (ap->pat == NULL || ac->cmd == NULL)
7952 {
7953 *prev_ac = ac->next;
7954 vim_free(ac->cmd);
7955 vim_free(ac);
7956 }
7957 else
7958 prev_ac = &(ac->next);
7959 }
7960
7961 /* remove the pattern if it has been marked for deletion */
7962 if (ap->pat == NULL)
7963 {
7964 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007965 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007966 vim_free(ap);
7967 }
7968 else
7969 prev_ap = &(ap->next);
7970 }
7971 }
7972
7973 au_need_clean = FALSE;
7974}
7975
7976/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007977 * Called when buffer is freed, to remove/invalidate related buffer-local
7978 * autocmds.
7979 */
7980 void
7981aubuflocal_remove(buf)
7982 buf_T *buf;
7983{
7984 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007985 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007986 AutoPatCmd *apc;
7987
7988 /* invalidate currently executing autocommands */
7989 for (apc = active_apc_list; apc; apc = apc->next)
7990 if (buf->b_fnum == apc->arg_bufnr)
7991 apc->arg_bufnr = 0;
7992
7993 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007994 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7995 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007996 /* loop over all autocommand patterns */
7997 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7998 if (ap->buflocal_nr == buf->b_fnum)
7999 {
8000 au_remove_pat(ap);
8001 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008002 {
8003 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008004 smsg((char_u *)
8005 _("auto-removing autocommand: %s <buffer=%d>"),
8006 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008007 verbose_leave();
8008 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008009 }
8010 au_cleanup();
8011}
8012
8013/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008014 * Add an autocmd group name.
8015 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8016 */
8017 static int
8018au_new_group(name)
8019 char_u *name;
8020{
8021 int i;
8022
8023 i = au_find_group(name);
8024 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8025 {
8026 /* First try using a free entry. */
8027 for (i = 0; i < augroups.ga_len; ++i)
8028 if (AUGROUP_NAME(i) == NULL)
8029 break;
8030 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8031 return AUGROUP_ERROR;
8032
8033 AUGROUP_NAME(i) = vim_strsave(name);
8034 if (AUGROUP_NAME(i) == NULL)
8035 return AUGROUP_ERROR;
8036 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008037 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038 }
8039
8040 return i;
8041}
8042
8043 static void
8044au_del_group(name)
8045 char_u *name;
8046{
8047 int i;
8048
8049 i = au_find_group(name);
8050 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8051 EMSG2(_("E367: No such group: \"%s\""), name);
8052 else
8053 {
8054 vim_free(AUGROUP_NAME(i));
8055 AUGROUP_NAME(i) = NULL;
8056 }
8057}
8058
8059/*
8060 * Find the ID of an autocmd group name.
8061 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8062 */
8063 static int
8064au_find_group(name)
8065 char_u *name;
8066{
8067 int i;
8068
8069 for (i = 0; i < augroups.ga_len; ++i)
8070 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8071 return i;
8072 return AUGROUP_ERROR;
8073}
8074
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008075/*
8076 * Return TRUE if augroup "name" exists.
8077 */
8078 int
8079au_has_group(name)
8080 char_u *name;
8081{
8082 return au_find_group(name) != AUGROUP_ERROR;
8083}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008084
Bram Moolenaar071d4272004-06-13 20:20:40 +00008085/*
8086 * ":augroup {name}".
8087 */
8088 void
8089do_augroup(arg, del_group)
8090 char_u *arg;
8091 int del_group;
8092{
8093 int i;
8094
8095 if (del_group)
8096 {
8097 if (*arg == NUL)
8098 EMSG(_(e_argreq));
8099 else
8100 au_del_group(arg);
8101 }
8102 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8103 current_augroup = AUGROUP_DEFAULT;
8104 else if (*arg) /* ":aug xxx": switch to group xxx */
8105 {
8106 i = au_new_group(arg);
8107 if (i != AUGROUP_ERROR)
8108 current_augroup = i;
8109 }
8110 else /* ":aug": list the group names */
8111 {
8112 msg_start();
8113 for (i = 0; i < augroups.ga_len; ++i)
8114 {
8115 if (AUGROUP_NAME(i) != NULL)
8116 {
8117 msg_puts(AUGROUP_NAME(i));
8118 msg_puts((char_u *)" ");
8119 }
8120 }
8121 msg_clr_eos();
8122 msg_end();
8123 }
8124}
8125
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008126#if defined(EXITFREE) || defined(PROTO)
8127 void
8128free_all_autocmds()
8129{
8130 for (current_augroup = -1; current_augroup < augroups.ga_len;
8131 ++current_augroup)
8132 do_autocmd((char_u *)"", TRUE);
8133 ga_clear_strings(&augroups);
8134}
8135#endif
8136
Bram Moolenaar071d4272004-06-13 20:20:40 +00008137/*
8138 * Return the event number for event name "start".
8139 * Return NUM_EVENTS if the event name was not found.
8140 * Return a pointer to the next event name in "end".
8141 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008142 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143event_name2nr(start, end)
8144 char_u *start;
8145 char_u **end;
8146{
8147 char_u *p;
8148 int i;
8149 int len;
8150
8151 /* the event name ends with end of line, a blank or a comma */
8152 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8153 ;
8154 for (i = 0; event_names[i].name != NULL; ++i)
8155 {
8156 len = (int)STRLEN(event_names[i].name);
8157 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8158 break;
8159 }
8160 if (*p == ',')
8161 ++p;
8162 *end = p;
8163 if (event_names[i].name == NULL)
8164 return NUM_EVENTS;
8165 return event_names[i].event;
8166}
8167
8168/*
8169 * Return the name for event "event".
8170 */
8171 static char_u *
8172event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008173 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008174{
8175 int i;
8176
8177 for (i = 0; event_names[i].name != NULL; ++i)
8178 if (event_names[i].event == event)
8179 return (char_u *)event_names[i].name;
8180 return (char_u *)"Unknown";
8181}
8182
8183/*
8184 * Scan over the events. "*" stands for all events.
8185 */
8186 static char_u *
8187find_end_event(arg, have_group)
8188 char_u *arg;
8189 int have_group; /* TRUE when group name was found */
8190{
8191 char_u *pat;
8192 char_u *p;
8193
8194 if (*arg == '*')
8195 {
8196 if (arg[1] && !vim_iswhite(arg[1]))
8197 {
8198 EMSG2(_("E215: Illegal character after *: %s"), arg);
8199 return NULL;
8200 }
8201 pat = arg + 1;
8202 }
8203 else
8204 {
8205 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8206 {
8207 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8208 {
8209 if (have_group)
8210 EMSG2(_("E216: No such event: %s"), pat);
8211 else
8212 EMSG2(_("E216: No such group or event: %s"), pat);
8213 return NULL;
8214 }
8215 }
8216 }
8217 return pat;
8218}
8219
8220/*
8221 * Return TRUE if "event" is included in 'eventignore'.
8222 */
8223 static int
8224event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008225 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008226{
8227 char_u *p = p_ei;
8228
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008229 while (*p != NUL)
8230 {
8231 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8232 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008233 if (event_name2nr(p, &p) == event)
8234 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008236
8237 return FALSE;
8238}
8239
8240/*
8241 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8242 */
8243 int
8244check_ei()
8245{
8246 char_u *p = p_ei;
8247
Bram Moolenaar071d4272004-06-13 20:20:40 +00008248 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008249 {
8250 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8251 {
8252 p += 3;
8253 if (*p == ',')
8254 ++p;
8255 }
8256 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008257 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008259
8260 return OK;
8261}
8262
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008263# if defined(FEAT_SYN_HL) || defined(PROTO)
8264
8265/*
8266 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8267 * buffer loaded into the window. "what" must start with a comma.
8268 * Returns the old value of 'eventignore' in allocated memory.
8269 */
8270 char_u *
8271au_event_disable(what)
8272 char *what;
8273{
8274 char_u *new_ei;
8275 char_u *save_ei;
8276
8277 save_ei = vim_strsave(p_ei);
8278 if (save_ei != NULL)
8279 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008280 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008281 if (new_ei != NULL)
8282 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008283 if (*what == ',' && *p_ei == NUL)
8284 STRCPY(new_ei, what + 1);
8285 else
8286 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008287 set_string_option_direct((char_u *)"ei", -1, new_ei,
8288 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008289 vim_free(new_ei);
8290 }
8291 }
8292 return save_ei;
8293}
8294
8295 void
8296au_event_restore(old_ei)
8297 char_u *old_ei;
8298{
8299 if (old_ei != NULL)
8300 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008301 set_string_option_direct((char_u *)"ei", -1, old_ei,
8302 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008303 vim_free(old_ei);
8304 }
8305}
8306# endif /* FEAT_SYN_HL */
8307
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308/*
8309 * do_autocmd() -- implements the :autocmd command. Can be used in the
8310 * following ways:
8311 *
8312 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8313 * will be automatically executed for <event>
8314 * when editing a file matching <pat>, in
8315 * the current group.
8316 * :autocmd <event> <pat> Show the auto-commands associated with
8317 * <event> and <pat>.
8318 * :autocmd <event> Show the auto-commands associated with
8319 * <event>.
8320 * :autocmd Show all auto-commands.
8321 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8322 * <event> and <pat>, and add the command
8323 * <cmd>, for the current group.
8324 * :autocmd! <event> <pat> Remove all auto-commands associated with
8325 * <event> and <pat> for the current group.
8326 * :autocmd! <event> Remove all auto-commands associated with
8327 * <event> for the current group.
8328 * :autocmd! Remove ALL auto-commands for the current
8329 * group.
8330 *
8331 * Multiple events and patterns may be given separated by commas. Here are
8332 * some examples:
8333 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8334 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8335 *
8336 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008337 *
8338 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339 */
8340 void
8341do_autocmd(arg, forceit)
8342 char_u *arg;
8343 int forceit;
8344{
8345 char_u *pat;
8346 char_u *envpat = NULL;
8347 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008348 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008349 int need_free = FALSE;
8350 int nested = FALSE;
8351 int group;
8352
8353 /*
8354 * Check for a legal group name. If not, use AUGROUP_ALL.
8355 */
8356 group = au_get_grouparg(&arg);
8357 if (arg == NULL) /* out of memory */
8358 return;
8359
8360 /*
8361 * Scan over the events.
8362 * If we find an illegal name, return here, don't do anything.
8363 */
8364 pat = find_end_event(arg, group != AUGROUP_ALL);
8365 if (pat == NULL)
8366 return;
8367
8368 /*
8369 * Scan over the pattern. Put a NUL at the end.
8370 */
8371 pat = skipwhite(pat);
8372 cmd = pat;
8373 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8374 cmd++;
8375 if (*cmd)
8376 *cmd++ = NUL;
8377
8378 /* Expand environment variables in the pattern. Set 'shellslash', we want
8379 * forward slashes here. */
8380 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8381 {
8382#ifdef BACKSLASH_IN_FILENAME
8383 int p_ssl_save = p_ssl;
8384
8385 p_ssl = TRUE;
8386#endif
8387 envpat = expand_env_save(pat);
8388#ifdef BACKSLASH_IN_FILENAME
8389 p_ssl = p_ssl_save;
8390#endif
8391 if (envpat != NULL)
8392 pat = envpat;
8393 }
8394
8395 /*
8396 * Check for "nested" flag.
8397 */
8398 cmd = skipwhite(cmd);
8399 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8400 {
8401 nested = TRUE;
8402 cmd = skipwhite(cmd + 6);
8403 }
8404
8405 /*
8406 * Find the start of the commands.
8407 * Expand <sfile> in it.
8408 */
8409 if (*cmd != NUL)
8410 {
8411 cmd = expand_sfile(cmd);
8412 if (cmd == NULL) /* some error */
8413 return;
8414 need_free = TRUE;
8415 }
8416
8417 /*
8418 * Print header when showing autocommands.
8419 */
8420 if (!forceit && *cmd == NUL)
8421 {
8422 /* Highlight title */
8423 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8424 }
8425
8426 /*
8427 * Loop over the events.
8428 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008429 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008430 last_group = AUGROUP_ERROR; /* for listing the group name */
8431 if (*arg == '*' || *arg == NUL)
8432 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008433 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8434 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008435 if (do_autocmd_event(event, pat,
8436 nested, cmd, forceit, group) == FAIL)
8437 break;
8438 }
8439 else
8440 {
8441 while (*arg && !vim_iswhite(*arg))
8442 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8443 nested, cmd, forceit, group) == FAIL)
8444 break;
8445 }
8446
8447 if (need_free)
8448 vim_free(cmd);
8449 vim_free(envpat);
8450}
8451
8452/*
8453 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8454 * The "argp" argument is advanced to the following argument.
8455 *
8456 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8457 */
8458 static int
8459au_get_grouparg(argp)
8460 char_u **argp;
8461{
8462 char_u *group_name;
8463 char_u *p;
8464 char_u *arg = *argp;
8465 int group = AUGROUP_ALL;
8466
8467 p = skiptowhite(arg);
8468 if (p > arg)
8469 {
8470 group_name = vim_strnsave(arg, (int)(p - arg));
8471 if (group_name == NULL) /* out of memory */
8472 return AUGROUP_ERROR;
8473 group = au_find_group(group_name);
8474 if (group == AUGROUP_ERROR)
8475 group = AUGROUP_ALL; /* no match, use all groups */
8476 else
8477 *argp = skipwhite(p); /* match, skip over group name */
8478 vim_free(group_name);
8479 }
8480 return group;
8481}
8482
8483/*
8484 * do_autocmd() for one event.
8485 * If *pat == NUL do for all patterns.
8486 * If *cmd == NUL show entries.
8487 * If forceit == TRUE delete entries.
8488 * If group is not AUGROUP_ALL, only use this group.
8489 */
8490 static int
8491do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008492 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008493 char_u *pat;
8494 int nested;
8495 char_u *cmd;
8496 int forceit;
8497 int group;
8498{
8499 AutoPat *ap;
8500 AutoPat **prev_ap;
8501 AutoCmd *ac;
8502 AutoCmd **prev_ac;
8503 int brace_level;
8504 char_u *endpat;
8505 int findgroup;
8506 int allgroups;
8507 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008508 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008509 int buflocal_nr;
8510 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008511
8512 if (group == AUGROUP_ALL)
8513 findgroup = current_augroup;
8514 else
8515 findgroup = group;
8516 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8517
8518 /*
8519 * Show or delete all patterns for an event.
8520 */
8521 if (*pat == NUL)
8522 {
8523 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8524 {
8525 if (forceit) /* delete the AutoPat, if it's in the current group */
8526 {
8527 if (ap->group == findgroup)
8528 au_remove_pat(ap);
8529 }
8530 else if (group == AUGROUP_ALL || ap->group == group)
8531 show_autocmd(ap, event);
8532 }
8533 }
8534
8535 /*
8536 * Loop through all the specified patterns.
8537 */
8538 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8539 {
8540 /*
8541 * Find end of the pattern.
8542 * Watch out for a comma in braces, like "*.\{obj,o\}".
8543 */
8544 brace_level = 0;
8545 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8546 || endpat[-1] == '\\'); ++endpat)
8547 {
8548 if (*endpat == '{')
8549 brace_level++;
8550 else if (*endpat == '}')
8551 brace_level--;
8552 }
8553 if (pat == endpat) /* ignore single comma */
8554 continue;
8555 patlen = (int)(endpat - pat);
8556
8557 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008558 * detect special <buflocal[=X]> buffer-local patterns
8559 */
8560 is_buflocal = FALSE;
8561 buflocal_nr = 0;
8562
8563 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8564 && pat[patlen - 1] == '>')
8565 {
8566 /* Error will be printed only for addition. printing and removing
8567 * will proceed silently. */
8568 is_buflocal = TRUE;
8569 if (patlen == 8)
8570 buflocal_nr = curbuf->b_fnum;
8571 else if (patlen > 9 && pat[7] == '=')
8572 {
8573 /* <buffer=abuf> */
8574 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8575 buflocal_nr = autocmd_bufnr;
8576 /* <buffer=123> */
8577 else if (skipdigits(pat + 8) == pat + patlen - 1)
8578 buflocal_nr = atoi((char *)pat + 8);
8579 }
8580 }
8581
8582 if (is_buflocal)
8583 {
8584 /* normalize pat into standard "<buffer>#N" form */
8585 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8586 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008587 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008588 }
8589
8590 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008591 * Find AutoPat entries with this pattern.
8592 */
8593 prev_ap = &first_autopat[(int)event];
8594 while ((ap = *prev_ap) != NULL)
8595 {
8596 if (ap->pat != NULL)
8597 {
8598 /* Accept a pattern when:
8599 * - a group was specified and it's that group, or a group was
8600 * not specified and it's the current group, or a group was
8601 * not specified and we are listing
8602 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008603 * - the pattern matches.
8604 * For <buffer[=X]>, this condition works because we normalize
8605 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008606 */
8607 if ((allgroups || ap->group == findgroup)
8608 && ap->patlen == patlen
8609 && STRNCMP(pat, ap->pat, patlen) == 0)
8610 {
8611 /*
8612 * Remove existing autocommands.
8613 * If adding any new autocmd's for this AutoPat, don't
8614 * delete the pattern from the autopat list, append to
8615 * this list.
8616 */
8617 if (forceit)
8618 {
8619 if (*cmd != NUL && ap->next == NULL)
8620 {
8621 au_remove_cmds(ap);
8622 break;
8623 }
8624 au_remove_pat(ap);
8625 }
8626
8627 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008628 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008629 */
8630 else if (*cmd == NUL)
8631 show_autocmd(ap, event);
8632
8633 /*
8634 * Add autocmd to this autopat, if it's the last one.
8635 */
8636 else if (ap->next == NULL)
8637 break;
8638 }
8639 }
8640 prev_ap = &ap->next;
8641 }
8642
8643 /*
8644 * Add a new command.
8645 */
8646 if (*cmd != NUL)
8647 {
8648 /*
8649 * If the pattern we want to add a command to does appear at the
8650 * end of the list (or not is not in the list at all), add the
8651 * pattern at the end of the list.
8652 */
8653 if (ap == NULL)
8654 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008655 /* refuse to add buffer-local ap if buffer number is invalid */
8656 if (is_buflocal && (buflocal_nr == 0
8657 || buflist_findnr(buflocal_nr) == NULL))
8658 {
8659 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8660 buflocal_nr);
8661 return FAIL;
8662 }
8663
Bram Moolenaar071d4272004-06-13 20:20:40 +00008664 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8665 if (ap == NULL)
8666 return FAIL;
8667 ap->pat = vim_strnsave(pat, patlen);
8668 ap->patlen = patlen;
8669 if (ap->pat == NULL)
8670 {
8671 vim_free(ap);
8672 return FAIL;
8673 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008674
8675 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008676 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008677 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008678 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008679 }
8680 else
8681 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008682 char_u *reg_pat;
8683
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008684 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008685 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008686 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008687 if (reg_pat != NULL)
8688 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008689 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008690 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008691 {
8692 vim_free(ap->pat);
8693 vim_free(ap);
8694 return FAIL;
8695 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008696 }
8697 ap->cmds = NULL;
8698 *prev_ap = ap;
8699 ap->next = NULL;
8700 if (group == AUGROUP_ALL)
8701 ap->group = current_augroup;
8702 else
8703 ap->group = group;
8704 }
8705
8706 /*
8707 * Add the autocmd at the end of the AutoCmd list.
8708 */
8709 prev_ac = &(ap->cmds);
8710 while ((ac = *prev_ac) != NULL)
8711 prev_ac = &ac->next;
8712 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8713 if (ac == NULL)
8714 return FAIL;
8715 ac->cmd = vim_strsave(cmd);
8716#ifdef FEAT_EVAL
8717 ac->scriptID = current_SID;
8718#endif
8719 if (ac->cmd == NULL)
8720 {
8721 vim_free(ac);
8722 return FAIL;
8723 }
8724 ac->next = NULL;
8725 *prev_ac = ac;
8726 ac->nested = nested;
8727 }
8728 }
8729
8730 au_cleanup(); /* may really delete removed patterns/commands now */
8731 return OK;
8732}
8733
8734/*
8735 * Implementation of ":doautocmd [group] event [fname]".
8736 * Return OK for success, FAIL for failure;
8737 */
8738 int
8739do_doautocmd(arg, do_msg)
8740 char_u *arg;
8741 int do_msg; /* give message for no matching autocmds? */
8742{
8743 char_u *fname;
8744 int nothing_done = TRUE;
8745 int group;
8746
8747 /*
8748 * Check for a legal group name. If not, use AUGROUP_ALL.
8749 */
8750 group = au_get_grouparg(&arg);
8751 if (arg == NULL) /* out of memory */
8752 return FAIL;
8753
8754 if (*arg == '*')
8755 {
8756 EMSG(_("E217: Can't execute autocommands for ALL events"));
8757 return FAIL;
8758 }
8759
8760 /*
8761 * Scan over the events.
8762 * If we find an illegal name, return here, don't do anything.
8763 */
8764 fname = find_end_event(arg, group != AUGROUP_ALL);
8765 if (fname == NULL)
8766 return FAIL;
8767
8768 fname = skipwhite(fname);
8769
8770 /*
8771 * Loop over the events.
8772 */
8773 while (*arg && !vim_iswhite(*arg))
8774 if (apply_autocmds_group(event_name2nr(arg, &arg),
8775 fname, NULL, TRUE, group, curbuf, NULL))
8776 nothing_done = FALSE;
8777
8778 if (nothing_done && do_msg)
8779 MSG(_("No matching autocommands"));
8780
8781#ifdef FEAT_EVAL
8782 return aborting() ? FAIL : OK;
8783#else
8784 return OK;
8785#endif
8786}
8787
8788/*
8789 * ":doautoall": execute autocommands for each loaded buffer.
8790 */
8791 void
8792ex_doautoall(eap)
8793 exarg_T *eap;
8794{
8795 int retval;
8796 aco_save_T aco;
8797 buf_T *buf;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008798 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008799 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008800
8801 /*
8802 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8803 * equal to curbuf, but for some buffers there may not be a window.
8804 * So we change the buffer for the current window for a moment. This
8805 * gives problems when the autocommands make changes to the list of
8806 * buffers or windows...
8807 */
8808 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8809 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008810 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008811 {
8812 /* find a window for this buffer and save some values */
8813 aucmd_prepbuf(&aco, buf);
8814
8815 /* execute the autocommands for this buffer */
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008816 retval = do_doautocmd(arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008817
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008818 if (call_do_modelines)
8819 {
8820 /* Execute the modeline settings, but don't set window-local
8821 * options if we are using the current window for another
8822 * buffer. */
8823 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008825
8826 /* restore the current window */
8827 aucmd_restbuf(&aco);
8828
8829 /* stop if there is some error or buffer was deleted */
8830 if (retval == FAIL || !buf_valid(buf))
8831 break;
8832 }
8833 }
8834
8835 check_cursor(); /* just in case lines got deleted */
8836}
8837
8838/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008839 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8840 * return TRUE and advance *argp to after it.
8841 * Thus return TRUE when do_modelines() should be called.
8842 */
8843 int
8844check_nomodeline(argp)
8845 char_u **argp;
8846{
8847 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8848 {
8849 *argp = skipwhite(*argp + 12);
8850 return FALSE;
8851 }
8852 return TRUE;
8853}
8854
8855/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008856 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008857 * Search for a visible window containing the current buffer. If there isn't
8858 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008860 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008861 */
8862 void
8863aucmd_prepbuf(aco, buf)
8864 aco_save_T *aco; /* structure to save values in */
8865 buf_T *buf; /* new curbuf */
8866{
8867 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008868#ifdef FEAT_WINDOWS
8869 int save_ea;
8870#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008871#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008872 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008874
8875 /* Find a window that is for the new buffer */
8876 if (buf == curbuf) /* be quick when buf is curbuf */
8877 win = curwin;
8878 else
8879#ifdef FEAT_WINDOWS
8880 for (win = firstwin; win != NULL; win = win->w_next)
8881 if (win->w_buffer == buf)
8882 break;
8883#else
8884 win = NULL;
8885#endif
8886
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008887 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8888 * back to using the current window. */
8889 if (win == NULL && aucmd_win == NULL)
8890 {
8891 win_alloc_aucmd_win();
8892 if (aucmd_win == NULL)
8893 win = curwin;
8894 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008895 if (win == NULL && aucmd_win_used)
8896 /* Strange recursive autocommand, fall back to using the current
8897 * window. Expect a few side effects... */
8898 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008899
8900 aco->save_curwin = curwin;
8901 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902 if (win != NULL)
8903 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008904 /* There is a window for "buf" in the current tab page, make it the
8905 * curwin. This is preferred, it has the least side effects (esp. if
8906 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008907 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008909 }
8910 else
8911 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008912 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008913 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008914 * Anything related to a window (e.g., setting folds) may have
8915 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008916 aco->use_aucmd_win = TRUE;
8917 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008918 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008919 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008920 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008921 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008922
8923 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8924 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008925 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008926 aucmd_win->w_localdir = NULL;
8927 aco->globaldir = globaldir;
8928 globaldir = NULL;
8929
Bram Moolenaar071d4272004-06-13 20:20:40 +00008930
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008931#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008932 /* Split the current window, put the aucmd_win in the upper half.
8933 * We don't want the BufEnter or WinEnter autocommands. */
8934 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008935 make_snapshot(SNAP_AUCMD_IDX);
8936 save_ea = p_ea;
8937 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008938
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008939# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008940 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8941 save_acd = p_acd;
8942 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008943# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008944
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008945 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8946 (void)win_comp_pos(); /* recompute window positions */
8947 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008948# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008949 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008950# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008951 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008952#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008953 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008956 aco->new_curwin = curwin;
8957 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008958}
8959
8960/*
8961 * Cleanup after executing autocommands for a (hidden) buffer.
8962 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008963 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008964 */
8965 void
8966aucmd_restbuf(aco)
8967 aco_save_T *aco; /* structure holding saved values */
8968{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008969#ifdef FEAT_WINDOWS
8970 int dummy;
8971#endif
8972
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008973 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008974 {
8975 --curbuf->b_nwindows;
8976#ifdef FEAT_WINDOWS
8977 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008978 * page. Do not trigger autocommands here. */
8979 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008980 if (curwin != aucmd_win)
8981 {
8982 tabpage_T *tp;
8983 win_T *wp;
8984
8985 FOR_ALL_TAB_WINDOWS(tp, wp)
8986 {
8987 if (wp == aucmd_win)
8988 {
8989 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008990 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008991 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008992 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008993 }
8994 }
8995 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008996win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008997
8998 /* Remove the window and frame from the tree of frames. */
8999 (void)winframe_remove(curwin, &dummy, NULL);
9000 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009001 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009002 last_status(FALSE); /* may need to remove last status line */
9003 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9004 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009005 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009006
9007 if (win_valid(aco->save_curwin))
9008 curwin = aco->save_curwin;
9009 else
9010 /* Hmm, original window disappeared. Just use the first one. */
9011 curwin = firstwin;
9012# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009013 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9014 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009015# endif
9016#else
9017 curwin = aco->save_curwin;
9018#endif
9019 curbuf = curwin->w_buffer;
9020
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009021 vim_free(globaldir);
9022 globaldir = aco->globaldir;
9023
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009024 /* the buffer contents may have changed */
9025 check_cursor();
9026 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9027 {
9028 curwin->w_topline = curbuf->b_ml.ml_line_count;
9029#ifdef FEAT_DIFF
9030 curwin->w_topfill = 0;
9031#endif
9032 }
9033#if defined(FEAT_GUI)
9034 /* Hide the scrollbars from the aucmd_win and update. */
9035 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9036 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9037 gui_may_update_scrollbars();
9038#endif
9039 }
9040 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009041 {
9042 /* restore curwin */
9043#ifdef FEAT_WINDOWS
9044 if (win_valid(aco->save_curwin))
9045#endif
9046 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009047 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009048 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009049 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009050 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009051 && curbuf != aco->new_curbuf
9052 && buf_valid(aco->new_curbuf)
9053 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009054 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009055# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9056 if (curwin->w_s == &curbuf->b_s)
9057 curwin->w_s = &aco->new_curbuf->b_s;
9058# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009059 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009060 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009061 curwin->w_buffer = curbuf;
9062 ++curbuf->b_nwindows;
9063 }
9064
9065 curwin = aco->save_curwin;
9066 curbuf = curwin->w_buffer;
9067 }
9068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009069}
9070
9071static int autocmd_nested = FALSE;
9072
9073/*
9074 * Execute autocommands for "event" and file name "fname".
9075 * Return TRUE if some commands were executed.
9076 */
9077 int
9078apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009079 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080 char_u *fname; /* NULL or empty means use actual file name */
9081 char_u *fname_io; /* fname to use for <afile> on cmdline */
9082 int force; /* when TRUE, ignore autocmd_busy */
9083 buf_T *buf; /* buffer for <abuf> */
9084{
9085 return apply_autocmds_group(event, fname, fname_io, force,
9086 AUGROUP_ALL, buf, NULL);
9087}
9088
9089/*
9090 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9091 * setting v:filearg.
9092 */
9093 static int
9094apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009095 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009096 char_u *fname;
9097 char_u *fname_io;
9098 int force;
9099 buf_T *buf;
9100 exarg_T *eap;
9101{
9102 return apply_autocmds_group(event, fname, fname_io, force,
9103 AUGROUP_ALL, buf, eap);
9104}
9105
9106/*
9107 * Like apply_autocmds(), but handles the caller's retval. If the script
9108 * processing is being aborted or if retval is FAIL when inside a try
9109 * conditional, no autocommands are executed. If otherwise the autocommands
9110 * cause the script to be aborted, retval is set to FAIL.
9111 */
9112 int
9113apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009114 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009115 char_u *fname; /* NULL or empty means use actual file name */
9116 char_u *fname_io; /* fname to use for <afile> on cmdline */
9117 int force; /* when TRUE, ignore autocmd_busy */
9118 buf_T *buf; /* buffer for <abuf> */
9119 int *retval; /* pointer to caller's retval */
9120{
9121 int did_cmd;
9122
Bram Moolenaar1e015462005-09-25 22:16:38 +00009123#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009124 if (should_abort(*retval))
9125 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009126#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009127
9128 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9129 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009130 if (did_cmd
9131#ifdef FEAT_EVAL
9132 && aborting()
9133#endif
9134 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009135 *retval = FAIL;
9136 return did_cmd;
9137}
9138
Bram Moolenaard35f9712005-12-18 22:02:33 +00009139/*
9140 * Return TRUE when there is a CursorHold autocommand defined.
9141 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009142 int
9143has_cursorhold()
9144{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009145 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9146 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009147}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009148
9149/*
9150 * Return TRUE if the CursorHold event can be triggered.
9151 */
9152 int
9153trigger_cursorhold()
9154{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009155 int state;
9156
Bram Moolenaar05334432011-07-20 18:29:39 +02009157 if (!did_cursorhold
9158 && has_cursorhold()
9159 && !Recording
9160 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009161#ifdef FEAT_INS_EXPAND
9162 && !ins_compl_active()
9163#endif
9164 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009165 {
9166 state = get_real_state();
9167 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9168 return TRUE;
9169 }
9170 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009171}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009172
9173/*
9174 * Return TRUE when there is a CursorMoved autocommand defined.
9175 */
9176 int
9177has_cursormoved()
9178{
9179 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9180}
9181
9182/*
9183 * Return TRUE when there is a CursorMovedI autocommand defined.
9184 */
9185 int
9186has_cursormovedI()
9187{
9188 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9189}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009190
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009191/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009192 * Return TRUE when there is a TextChanged autocommand defined.
9193 */
9194 int
9195has_textchanged()
9196{
9197 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9198}
9199
9200/*
9201 * Return TRUE when there is a TextChangedI autocommand defined.
9202 */
9203 int
9204has_textchangedI()
9205{
9206 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9207}
9208
9209/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009210 * Return TRUE when there is an InsertCharPre autocommand defined.
9211 */
9212 int
9213has_insertcharpre()
9214{
9215 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9216}
9217
Bram Moolenaar071d4272004-06-13 20:20:40 +00009218 static int
9219apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009220 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009221 char_u *fname; /* NULL or empty means use actual file name */
9222 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9223 use fname */
9224 int force; /* when TRUE, ignore autocmd_busy */
9225 int group; /* group ID, or AUGROUP_ALL */
9226 buf_T *buf; /* buffer for <abuf> */
9227 exarg_T *eap; /* command arguments */
9228{
9229 char_u *sfname = NULL; /* short file name */
9230 char_u *tail;
9231 int save_changed;
9232 buf_T *old_curbuf;
9233 int retval = FALSE;
9234 char_u *save_sourcing_name;
9235 linenr_T save_sourcing_lnum;
9236 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009237 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009238 int save_autocmd_bufnr;
9239 char_u *save_autocmd_match;
9240 int save_autocmd_busy;
9241 int save_autocmd_nested;
9242 static int nesting = 0;
9243 AutoPatCmd patcmd;
9244 AutoPat *ap;
9245#ifdef FEAT_EVAL
9246 scid_T save_current_SID;
9247 void *save_funccalp;
9248 char_u *save_cmdarg;
9249 long save_cmdbang;
9250#endif
9251 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009252#ifdef FEAT_PROFILE
9253 proftime_T wait_time;
9254#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009255
9256 /*
9257 * Quickly return if there are no autocommands for this event or
9258 * autocommands are blocked.
9259 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009260 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009261 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009262
9263 /*
9264 * When autocommands are busy, new autocommands are only executed when
9265 * explicitly enabled with the "nested" flag.
9266 */
9267 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009268 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269
9270#ifdef FEAT_EVAL
9271 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009272 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009273 * occurred or an exception was thrown but not caught.
9274 */
9275 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009276 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009277#endif
9278
9279 /*
9280 * FileChangedShell never nests, because it can create an endless loop.
9281 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009282 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9283 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009284 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009285
9286 /*
9287 * Ignore events in 'eventignore'.
9288 */
9289 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009290 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009291
9292 /*
9293 * Allow nesting of autocommands, but restrict the depth, because it's
9294 * possible to create an endless loop.
9295 */
9296 if (nesting == 10)
9297 {
9298 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009299 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009300 }
9301
9302 /*
9303 * Check if these autocommands are disabled. Used when doing ":all" or
9304 * ":ball".
9305 */
9306 if ( (autocmd_no_enter
9307 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9308 || (autocmd_no_leave
9309 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009310 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009311
9312 /*
9313 * Save the autocmd_* variables and info about the current buffer.
9314 */
9315 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009316 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009317 save_autocmd_bufnr = autocmd_bufnr;
9318 save_autocmd_match = autocmd_match;
9319 save_autocmd_busy = autocmd_busy;
9320 save_autocmd_nested = autocmd_nested;
9321 save_changed = curbuf->b_changed;
9322 old_curbuf = curbuf;
9323
9324 /*
9325 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009326 * Make a copy to avoid that changing a buffer name or directory makes it
9327 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009328 */
9329 if (fname_io == NULL)
9330 {
9331 if (fname != NULL && *fname != NUL)
9332 autocmd_fname = fname;
9333 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009334 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009335 else
9336 autocmd_fname = NULL;
9337 }
9338 else
9339 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009340 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009341 autocmd_fname = vim_strsave(autocmd_fname);
9342 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009343
9344 /*
9345 * Set the buffer number to be used for <abuf>.
9346 */
9347 if (buf == NULL)
9348 autocmd_bufnr = 0;
9349 else
9350 autocmd_bufnr = buf->b_fnum;
9351
9352 /*
9353 * When the file name is NULL or empty, use the file name of buffer "buf".
9354 * Always use the full path of the file name to match with, in case
9355 * "allow_dirs" is set.
9356 */
9357 if (fname == NULL || *fname == NUL)
9358 {
9359 if (buf == NULL)
9360 fname = NULL;
9361 else
9362 {
9363#ifdef FEAT_SYN_HL
9364 if (event == EVENT_SYNTAX)
9365 fname = buf->b_p_syn;
9366 else
9367#endif
9368 if (event == EVENT_FILETYPE)
9369 fname = buf->b_p_ft;
9370 else
9371 {
9372 if (buf->b_sfname != NULL)
9373 sfname = vim_strsave(buf->b_sfname);
9374 fname = buf->b_ffname;
9375 }
9376 }
9377 if (fname == NULL)
9378 fname = (char_u *)"";
9379 fname = vim_strsave(fname); /* make a copy, so we can change it */
9380 }
9381 else
9382 {
9383 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009384 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9385 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009386 if (event == EVENT_FILETYPE
9387 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009388 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009389 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009390 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009391 || event == EVENT_QUICKFIXCMDPRE
9392 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009393 fname = vim_strsave(fname);
9394 else
9395 fname = FullName_save(fname, FALSE);
9396 }
9397 if (fname == NULL) /* out of memory */
9398 {
9399 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009400 retval = FALSE;
9401 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009402 }
9403
9404#ifdef BACKSLASH_IN_FILENAME
9405 /*
9406 * Replace all backslashes with forward slashes. This makes the
9407 * autocommand patterns portable between Unix and MS-DOS.
9408 */
9409 if (sfname != NULL)
9410 forward_slash(sfname);
9411 forward_slash(fname);
9412#endif
9413
9414#ifdef VMS
9415 /* remove version for correct match */
9416 if (sfname != NULL)
9417 vms_remove_version(sfname);
9418 vms_remove_version(fname);
9419#endif
9420
9421 /*
9422 * Set the name to be used for <amatch>.
9423 */
9424 autocmd_match = fname;
9425
9426
9427 /* Don't redraw while doing auto commands. */
9428 ++RedrawingDisabled;
9429 save_sourcing_name = sourcing_name;
9430 sourcing_name = NULL; /* don't free this one */
9431 save_sourcing_lnum = sourcing_lnum;
9432 sourcing_lnum = 0; /* no line number here */
9433
9434#ifdef FEAT_EVAL
9435 save_current_SID = current_SID;
9436
Bram Moolenaar05159a02005-02-26 23:04:13 +00009437# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009438 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009439 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9440# endif
9441
Bram Moolenaar071d4272004-06-13 20:20:40 +00009442 /* Don't use local function variables, if called from a function */
9443 save_funccalp = save_funccal();
9444#endif
9445
9446 /*
9447 * When starting to execute autocommands, save the search patterns.
9448 */
9449 if (!autocmd_busy)
9450 {
9451 save_search_patterns();
9452 saveRedobuff();
9453 did_filetype = keep_filetype;
9454 }
9455
9456 /*
9457 * Note that we are applying autocmds. Some commands need to know.
9458 */
9459 autocmd_busy = TRUE;
9460 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9461 ++nesting; /* see matching decrement below */
9462
9463 /* Remember that FileType was triggered. Used for did_filetype(). */
9464 if (event == EVENT_FILETYPE)
9465 did_filetype = TRUE;
9466
9467 tail = gettail(fname);
9468
9469 /* Find first autocommand that matches */
9470 patcmd.curpat = first_autopat[(int)event];
9471 patcmd.nextcmd = NULL;
9472 patcmd.group = group;
9473 patcmd.fname = fname;
9474 patcmd.sfname = sfname;
9475 patcmd.tail = tail;
9476 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009477 patcmd.arg_bufnr = autocmd_bufnr;
9478 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009479 auto_next_pat(&patcmd, FALSE);
9480
9481 /* found one, start executing the autocommands */
9482 if (patcmd.curpat != NULL)
9483 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009484 /* add to active_apc_list */
9485 patcmd.next = active_apc_list;
9486 active_apc_list = &patcmd;
9487
Bram Moolenaar071d4272004-06-13 20:20:40 +00009488#ifdef FEAT_EVAL
9489 /* set v:cmdarg (only when there is a matching pattern) */
9490 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9491 if (eap != NULL)
9492 {
9493 save_cmdarg = set_cmdarg(eap, NULL);
9494 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9495 }
9496 else
9497 save_cmdarg = NULL; /* avoid gcc warning */
9498#endif
9499 retval = TRUE;
9500 /* mark the last pattern, to avoid an endless loop when more patterns
9501 * are added when executing autocommands */
9502 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9503 ap->last = FALSE;
9504 ap->last = TRUE;
9505 check_lnums(TRUE); /* make sure cursor and topline are valid */
9506 do_cmdline(NULL, getnextac, (void *)&patcmd,
9507 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9508#ifdef FEAT_EVAL
9509 if (eap != NULL)
9510 {
9511 (void)set_cmdarg(NULL, save_cmdarg);
9512 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9513 }
9514#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009515 /* delete from active_apc_list */
9516 if (active_apc_list == &patcmd) /* just in case */
9517 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009518 }
9519
9520 --RedrawingDisabled;
9521 autocmd_busy = save_autocmd_busy;
9522 filechangeshell_busy = FALSE;
9523 autocmd_nested = save_autocmd_nested;
9524 vim_free(sourcing_name);
9525 sourcing_name = save_sourcing_name;
9526 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009527 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009528 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009529 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009530 autocmd_bufnr = save_autocmd_bufnr;
9531 autocmd_match = save_autocmd_match;
9532#ifdef FEAT_EVAL
9533 current_SID = save_current_SID;
9534 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009535# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009536 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009537 prof_child_exit(&wait_time);
9538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009539#endif
9540 vim_free(fname);
9541 vim_free(sfname);
9542 --nesting; /* see matching increment above */
9543
9544 /*
9545 * When stopping to execute autocommands, restore the search patterns and
9546 * the redo buffer.
9547 */
9548 if (!autocmd_busy)
9549 {
9550 restore_search_patterns();
9551 restoreRedobuff();
9552 did_filetype = FALSE;
9553 }
9554
9555 /*
9556 * Some events don't set or reset the Changed flag.
9557 * Check if still in the same buffer!
9558 */
9559 if (curbuf == old_curbuf
9560 && (event == EVENT_BUFREADPOST
9561 || event == EVENT_BUFWRITEPOST
9562 || event == EVENT_FILEAPPENDPOST
9563 || event == EVENT_VIMLEAVE
9564 || event == EVENT_VIMLEAVEPRE))
9565 {
9566#ifdef FEAT_TITLE
9567 if (curbuf->b_changed != save_changed)
9568 need_maketitle = TRUE;
9569#endif
9570 curbuf->b_changed = save_changed;
9571 }
9572
9573 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009574
9575BYPASS_AU:
9576 /* When wiping out a buffer make sure all its buffer-local autocommands
9577 * are deleted. */
9578 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9579 aubuflocal_remove(buf);
9580
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581 return retval;
9582}
9583
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009584# ifdef FEAT_EVAL
9585static char_u *old_termresponse = NULL;
9586# endif
9587
9588/*
9589 * Block triggering autocommands until unblock_autocmd() is called.
9590 * Can be used recursively, so long as it's symmetric.
9591 */
9592 void
9593block_autocmds()
9594{
9595# ifdef FEAT_EVAL
9596 /* Remember the value of v:termresponse. */
9597 if (autocmd_blocked == 0)
9598 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9599# endif
9600 ++autocmd_blocked;
9601}
9602
9603 void
9604unblock_autocmds()
9605{
9606 --autocmd_blocked;
9607
9608# ifdef FEAT_EVAL
9609 /* When v:termresponse was set while autocommands were blocked, trigger
9610 * the autocommands now. Esp. useful when executing a shell command
9611 * during startup (vimdiff). */
9612 if (autocmd_blocked == 0
9613 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9614 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9615# endif
9616}
9617
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009618 int
9619is_autocmd_blocked()
9620{
9621 return autocmd_blocked != 0;
9622}
9623
Bram Moolenaar071d4272004-06-13 20:20:40 +00009624/*
9625 * Find next autocommand pattern that matches.
9626 */
9627 static void
9628auto_next_pat(apc, stop_at_last)
9629 AutoPatCmd *apc;
9630 int stop_at_last; /* stop when 'last' flag is set */
9631{
9632 AutoPat *ap;
9633 AutoCmd *cp;
9634 char_u *name;
9635 char *s;
9636
9637 vim_free(sourcing_name);
9638 sourcing_name = NULL;
9639
9640 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9641 {
9642 apc->curpat = NULL;
9643
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009644 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009645 * the group matches. For buffer-local autocommands only check the
9646 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009647 if (ap->pat != NULL && ap->cmds != NULL
9648 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9649 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009650 /* execution-condition */
9651 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009652 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9653 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009654 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009655 {
9656 name = event_nr2name(apc->event);
9657 s = _("%s Auto commands for \"%s\"");
9658 sourcing_name = alloc((unsigned)(STRLEN(s)
9659 + STRLEN(name) + ap->patlen + 1));
9660 if (sourcing_name != NULL)
9661 {
9662 sprintf((char *)sourcing_name, s,
9663 (char *)name, (char *)ap->pat);
9664 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009665 {
9666 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009667 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009668 verbose_leave();
9669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009670 }
9671
9672 apc->curpat = ap;
9673 apc->nextcmd = ap->cmds;
9674 /* mark last command */
9675 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9676 cp->last = FALSE;
9677 cp->last = TRUE;
9678 }
9679 line_breakcheck();
9680 if (apc->curpat != NULL) /* found a match */
9681 break;
9682 }
9683 if (stop_at_last && ap->last)
9684 break;
9685 }
9686}
9687
9688/*
9689 * Get next autocommand command.
9690 * Called by do_cmdline() to get the next line for ":if".
9691 * Returns allocated string, or NULL for end of autocommands.
9692 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009693 char_u *
Bram Moolenaar071d4272004-06-13 20:20:40 +00009694getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009695 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009696 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009697 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009698{
9699 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9700 char_u *retval;
9701 AutoCmd *ac;
9702
9703 /* Can be called again after returning the last line. */
9704 if (acp->curpat == NULL)
9705 return NULL;
9706
9707 /* repeat until we find an autocommand to execute */
9708 for (;;)
9709 {
9710 /* skip removed commands */
9711 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9712 if (acp->nextcmd->last)
9713 acp->nextcmd = NULL;
9714 else
9715 acp->nextcmd = acp->nextcmd->next;
9716
9717 if (acp->nextcmd != NULL)
9718 break;
9719
9720 /* at end of commands, find next pattern that matches */
9721 if (acp->curpat->last)
9722 acp->curpat = NULL;
9723 else
9724 acp->curpat = acp->curpat->next;
9725 if (acp->curpat != NULL)
9726 auto_next_pat(acp, TRUE);
9727 if (acp->curpat == NULL)
9728 return NULL;
9729 }
9730
9731 ac = acp->nextcmd;
9732
9733 if (p_verbose >= 9)
9734 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009735 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009736 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009737 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009738 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009739 }
9740 retval = vim_strsave(ac->cmd);
9741 autocmd_nested = ac->nested;
9742#ifdef FEAT_EVAL
9743 current_SID = ac->scriptID;
9744#endif
9745 if (ac->last)
9746 acp->nextcmd = NULL;
9747 else
9748 acp->nextcmd = ac->next;
9749 return retval;
9750}
9751
9752/*
9753 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009754 * To account for buffer-local autocommands, function needs to know
9755 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009756 */
9757 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009758has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009759 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009760 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009761 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009762{
9763 AutoPat *ap;
9764 char_u *fname;
9765 char_u *tail = gettail(sfname);
9766 int retval = FALSE;
9767
9768 fname = FullName_save(sfname, FALSE);
9769 if (fname == NULL)
9770 return FALSE;
9771
9772#ifdef BACKSLASH_IN_FILENAME
9773 /*
9774 * Replace all backslashes with forward slashes. This makes the
9775 * autocommand patterns portable between Unix and MS-DOS.
9776 */
9777 sfname = vim_strsave(sfname);
9778 if (sfname != NULL)
9779 forward_slash(sfname);
9780 forward_slash(fname);
9781#endif
9782
9783 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9784 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009785 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009786 ? match_file_pat(NULL, ap->reg_prog,
9787 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009788 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009789 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009790 {
9791 retval = TRUE;
9792 break;
9793 }
9794
9795 vim_free(fname);
9796#ifdef BACKSLASH_IN_FILENAME
9797 vim_free(sfname);
9798#endif
9799
9800 return retval;
9801}
9802
9803#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9804/*
9805 * Function given to ExpandGeneric() to obtain the list of autocommand group
9806 * names.
9807 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009808 char_u *
9809get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009810 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009811 int idx;
9812{
9813 if (idx == augroups.ga_len) /* add "END" add the end */
9814 return (char_u *)"END";
9815 if (idx >= augroups.ga_len) /* end of list */
9816 return NULL;
9817 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9818 return (char_u *)"";
9819 return AUGROUP_NAME(idx); /* return a name */
9820}
9821
9822static int include_groups = FALSE;
9823
9824 char_u *
9825set_context_in_autocmd(xp, arg, doautocmd)
9826 expand_T *xp;
9827 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009828 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009829{
9830 char_u *p;
9831 int group;
9832
9833 /* check for a group name, skip it if present */
9834 include_groups = FALSE;
9835 p = arg;
9836 group = au_get_grouparg(&arg);
9837 if (group == AUGROUP_ERROR)
9838 return NULL;
9839 /* If there only is a group name that's what we expand. */
9840 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9841 {
9842 arg = p;
9843 group = AUGROUP_ALL;
9844 }
9845
9846 /* skip over event name */
9847 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9848 if (*p == ',')
9849 arg = p + 1;
9850 if (*p == NUL)
9851 {
9852 if (group == AUGROUP_ALL)
9853 include_groups = TRUE;
9854 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9855 xp->xp_pattern = arg;
9856 return NULL;
9857 }
9858
9859 /* skip over pattern */
9860 arg = skipwhite(p);
9861 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9862 arg++;
9863 if (*arg)
9864 return arg; /* expand (next) command */
9865
9866 if (doautocmd)
9867 xp->xp_context = EXPAND_FILES; /* expand file names */
9868 else
9869 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9870 return NULL;
9871}
9872
9873/*
9874 * Function given to ExpandGeneric() to obtain the list of event names.
9875 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009876 char_u *
9877get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009878 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009879 int idx;
9880{
9881 if (idx < augroups.ga_len) /* First list group names, if wanted */
9882 {
9883 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9884 return (char_u *)""; /* skip deleted entries */
9885 return AUGROUP_NAME(idx); /* return a name */
9886 }
9887 return (char_u *)event_names[idx - augroups.ga_len].name;
9888}
9889
9890#endif /* FEAT_CMDL_COMPL */
9891
9892/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009893 * Return TRUE if autocmd is supported.
9894 */
9895 int
9896autocmd_supported(name)
9897 char_u *name;
9898{
9899 char_u *p;
9900
9901 return (event_name2nr(name, &p) != NUM_EVENTS);
9902}
9903
9904/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009905 * Return TRUE if an autocommand is defined for a group, event and
9906 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9907 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9908 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9909 * Used for:
9910 * exists("#Group") or
9911 * exists("#Group#Event") or
9912 * exists("#Group#Event#pat") or
9913 * exists("#Event") or
9914 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009915 */
9916 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009917au_exists(arg)
9918 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009919{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009920 char_u *arg_save;
9921 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922 char_u *event_name;
9923 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009924 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009925 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009926 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009927 int group;
9928 int retval = FALSE;
9929
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009930 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009931 arg_save = vim_strsave(arg);
9932 if (arg_save == NULL)
9933 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009934 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009935 if (p != NULL)
9936 *p++ = NUL;
9937
9938 /* First, look for an autocmd group name */
9939 group = au_find_group(arg_save);
9940 if (group == AUGROUP_ERROR)
9941 {
9942 /* Didn't match a group name, assume the first argument is an event. */
9943 group = AUGROUP_ALL;
9944 event_name = arg_save;
9945 }
9946 else
9947 {
9948 if (p == NULL)
9949 {
9950 /* "Group": group name is present and it's recognized */
9951 retval = TRUE;
9952 goto theend;
9953 }
9954
9955 /* Must be "Group#Event" or "Group#Event#pat". */
9956 event_name = p;
9957 p = vim_strchr(event_name, '#');
9958 if (p != NULL)
9959 *p++ = NUL; /* "Group#Event#pat" */
9960 }
9961
9962 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009963
9964 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009965 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009966
9967 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009968 if (event == NUM_EVENTS)
9969 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009970
9971 /* Find the first autocommand for this event.
9972 * If there isn't any, return FALSE;
9973 * If there is one and no pattern given, return TRUE; */
9974 ap = first_autopat[(int)event];
9975 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009976 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009977
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009978 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9979 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009980 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009981 buflocal_buf = curbuf;
9982
Bram Moolenaar071d4272004-06-13 20:20:40 +00009983 /* Check if there is an autocommand with the given pattern. */
9984 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009985 /* only use a pattern when it has not been removed and has commands. */
9986 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009988 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009989 && (pattern == NULL
9990 || (buflocal_buf == NULL
9991 ? fnamecmp(ap->pat, pattern) == 0
9992 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009993 {
9994 retval = TRUE;
9995 break;
9996 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009997
Bram Moolenaar195d6352005-12-19 22:08:24 +00009998theend:
9999 vim_free(arg_save);
10000 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010001}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010002
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010003#else /* FEAT_AUTOCMD */
10004
10005/*
10006 * Prepare for executing commands for (hidden) buffer "buf".
10007 * This is the non-autocommand version, it simply saves "curbuf" and sets
10008 * "curbuf" and "curwin" to match "buf".
10009 */
10010 void
10011aucmd_prepbuf(aco, buf)
10012 aco_save_T *aco; /* structure to save values in */
10013 buf_T *buf; /* new curbuf */
10014{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010015 aco->save_curbuf = curbuf;
10016 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010017 curbuf = buf;
10018 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010019 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010020}
10021
10022/*
10023 * Restore after executing commands for a (hidden) buffer.
10024 * This is the non-autocommand version.
10025 */
10026 void
10027aucmd_restbuf(aco)
10028 aco_save_T *aco; /* structure holding saved values */
10029{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010030 --curbuf->b_nwindows;
10031 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010032 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010033 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010034}
10035
Bram Moolenaar071d4272004-06-13 20:20:40 +000010036#endif /* FEAT_AUTOCMD */
10037
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010038
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10040/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010041 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10042 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10043 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010044 * Used for autocommands and 'wildignore'.
10045 * Returns TRUE if there is a match, FALSE otherwise.
10046 */
10047 int
Bram Moolenaar748bf032005-02-02 23:04:36 +000010048match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010049 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +000010050 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010051 char_u *fname; /* full path of file name */
10052 char_u *sfname; /* short file name or NULL */
10053 char_u *tail; /* tail of path */
10054 int allow_dirs; /* allow matching with dir */
10055{
10056 regmatch_T regmatch;
10057 int result = FALSE;
10058#ifdef FEAT_OSFILETYPE
10059 int no_pattern = FALSE; /* TRUE if check is filetype only */
10060 char_u *type_start;
10061 char_u c;
10062 int match = FALSE;
10063#endif
10064
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010065 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010066#ifdef FEAT_OSFILETYPE
10067 if (*pattern == '<')
10068 {
10069 /* There is a filetype condition specified with this pattern.
10070 * Check the filetype matches first. If not, don't bother with the
10071 * pattern (set regprog to NULL).
10072 * Always use magic for the regexp.
10073 */
10074
10075 for (type_start = pattern + 1; (c = *pattern); pattern++)
10076 {
10077 if ((c == ';' || c == '>') && match == FALSE)
10078 {
10079 *pattern = NUL; /* Terminate the string */
Bram Moolenaar05334432011-07-20 18:29:39 +020010080 /* TODO: match with 'filetype' of buffer that "fname" comes
10081 * from. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010082 match = mch_check_filetype(fname, type_start);
10083 *pattern = c; /* Restore the terminator */
10084 type_start = pattern + 1;
10085 }
10086 if (c == '>')
10087 break;
10088 }
10089
10090 /* (c should never be NUL, but check anyway) */
10091 if (match == FALSE || c == NUL)
10092 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
10093 else if (*pattern == NUL)
10094 {
10095 regmatch.regprog = NULL; /* Vim will try to free regprog later */
10096 no_pattern = TRUE; /* Always matches - don't check pat. */
10097 }
10098 else
10099 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
10100 }
10101 else
10102#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +000010103 {
10104 if (prog != NULL)
10105 regmatch.regprog = prog;
10106 else
10107 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
10108 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010109
10110 /*
10111 * Try for a match with the pattern with:
10112 * 1. the full file name, when the pattern has a '/'.
10113 * 2. the short file name, when the pattern has a '/'.
10114 * 3. the tail of the file name, when the pattern has no '/'.
10115 */
10116 if (
10117#ifdef FEAT_OSFILETYPE
10118 /* If the check is for a filetype only and we don't care
10119 * about the path then skip all the regexp stuff.
10120 */
10121 no_pattern ||
10122#endif
10123 (regmatch.regprog != NULL
10124 && ((allow_dirs
10125 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10126 || (sfname != NULL
10127 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
10128 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
10129 result = TRUE;
10130
Bram Moolenaar748bf032005-02-02 23:04:36 +000010131 if (prog == NULL)
Bram Moolenaar473de612013-06-08 18:19:48 +020010132 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010133 return result;
10134}
10135#endif
10136
10137#if defined(FEAT_WILDIGN) || defined(PROTO)
10138/*
10139 * Return TRUE if a file matches with a pattern in "list".
10140 * "list" is a comma-separated list of patterns, like 'wildignore'.
10141 * "sfname" is the short file name or NULL, "ffname" the long file name.
10142 */
10143 int
10144match_file_list(list, sfname, ffname)
10145 char_u *list;
10146 char_u *sfname;
10147 char_u *ffname;
10148{
10149 char_u buf[100];
10150 char_u *tail;
10151 char_u *regpat;
10152 char allow_dirs;
10153 int match;
10154 char_u *p;
10155
10156 tail = gettail(sfname);
10157
10158 /* try all patterns in 'wildignore' */
10159 p = list;
10160 while (*p)
10161 {
10162 copy_option_part(&p, buf, 100, ",");
10163 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10164 if (regpat == NULL)
10165 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010166 match = match_file_pat(regpat, NULL, ffname, sfname,
10167 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010168 vim_free(regpat);
10169 if (match)
10170 return TRUE;
10171 }
10172 return FALSE;
10173}
10174#endif
10175
10176/*
10177 * Convert the given pattern "pat" which has shell style wildcards in it, into
10178 * a regular expression, and return the result in allocated memory. If there
10179 * is a directory path separator to be matched, then TRUE is put in
10180 * allow_dirs, otherwise FALSE is put there -- webb.
10181 * Handle backslashes before special characters, like "\*" and "\ ".
10182 *
10183 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10184 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10185 *
10186 * Returns NULL when out of memory.
10187 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010188 char_u *
10189file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10190 char_u *pat;
10191 char_u *pat_end; /* first char after pattern or NULL */
10192 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010193 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010194{
10195 int size;
10196 char_u *endp;
10197 char_u *reg_pat;
10198 char_u *p;
10199 int i;
10200 int nested = 0;
10201 int add_dollar = TRUE;
10202#ifdef FEAT_OSFILETYPE
10203 int check_length = 0;
10204#endif
10205
10206 if (allow_dirs != NULL)
10207 *allow_dirs = FALSE;
10208 if (pat_end == NULL)
10209 pat_end = pat + STRLEN(pat);
10210
10211#ifdef FEAT_OSFILETYPE
10212 /* Find out how much of the string is the filetype check */
10213 if (*pat == '<')
10214 {
10215 /* Count chars until the next '>' */
10216 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10217 ;
10218 if (p < pat_end)
10219 {
10220 /* Pattern is of the form <.*>.* */
10221 check_length = p - pat + 1;
10222 if (p + 1 >= pat_end)
10223 {
10224 /* The 'pattern' is a filetype check ONLY */
10225 reg_pat = (char_u *)alloc(check_length + 1);
10226 if (reg_pat != NULL)
10227 {
10228 mch_memmove(reg_pat, pat, (size_t)check_length);
10229 reg_pat[check_length] = NUL;
10230 }
10231 return reg_pat;
10232 }
10233 }
10234 /* else: there was no closing '>' - assume it was a normal pattern */
10235
10236 }
10237 pat += check_length;
10238 size = 2 + check_length;
10239#else
10240 size = 2; /* '^' at start, '$' at end */
10241#endif
10242
10243 for (p = pat; p < pat_end; p++)
10244 {
10245 switch (*p)
10246 {
10247 case '*':
10248 case '.':
10249 case ',':
10250 case '{':
10251 case '}':
10252 case '~':
10253 size += 2; /* extra backslash */
10254 break;
10255#ifdef BACKSLASH_IN_FILENAME
10256 case '\\':
10257 case '/':
10258 size += 4; /* could become "[\/]" */
10259 break;
10260#endif
10261 default:
10262 size++;
10263# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010264 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265 {
10266 ++p;
10267 ++size;
10268 }
10269# endif
10270 break;
10271 }
10272 }
10273 reg_pat = alloc(size + 1);
10274 if (reg_pat == NULL)
10275 return NULL;
10276
10277#ifdef FEAT_OSFILETYPE
10278 /* Copy the type check in to the start. */
10279 if (check_length)
10280 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10281 i = check_length;
10282#else
10283 i = 0;
10284#endif
10285
10286 if (pat[0] == '*')
10287 while (pat[0] == '*' && pat < pat_end - 1)
10288 pat++;
10289 else
10290 reg_pat[i++] = '^';
10291 endp = pat_end - 1;
10292 if (*endp == '*')
10293 {
10294 while (endp - pat > 0 && *endp == '*')
10295 endp--;
10296 add_dollar = FALSE;
10297 }
10298 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10299 {
10300 switch (*p)
10301 {
10302 case '*':
10303 reg_pat[i++] = '.';
10304 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010305 while (p[1] == '*') /* "**" matches like "*" */
10306 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010307 break;
10308 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010309 case '~':
10310 reg_pat[i++] = '\\';
10311 reg_pat[i++] = *p;
10312 break;
10313 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010314 reg_pat[i++] = '.';
10315 break;
10316 case '\\':
10317 if (p[1] == NUL)
10318 break;
10319#ifdef BACKSLASH_IN_FILENAME
10320 if (!no_bslash)
10321 {
10322 /* translate:
10323 * "\x" to "\\x" e.g., "dir\file"
10324 * "\*" to "\\.*" e.g., "dir\*.c"
10325 * "\?" to "\\." e.g., "dir\??.c"
10326 * "\+" to "\+" e.g., "fileX\+.c"
10327 */
10328 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10329 && p[1] != '+')
10330 {
10331 reg_pat[i++] = '[';
10332 reg_pat[i++] = '\\';
10333 reg_pat[i++] = '/';
10334 reg_pat[i++] = ']';
10335 if (allow_dirs != NULL)
10336 *allow_dirs = TRUE;
10337 break;
10338 }
10339 }
10340#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010341 /* Undo escaping from ExpandEscape():
10342 * foo\?bar -> foo?bar
10343 * foo\%bar -> foo%bar
10344 * foo\,bar -> foo,bar
10345 * foo\ bar -> foo bar
10346 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010347 * regexp.
10348 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010349 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010350 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010351 if (*++p == '?'
10352#ifdef BACKSLASH_IN_FILENAME
10353 && no_bslash
10354#endif
10355 )
10356 reg_pat[i++] = '?';
10357 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010358 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaara946afe2013-08-02 15:22:39 +020010359 || *p == ' ' || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010360 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010361 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10362 {
10363 reg_pat[i++] = '\\';
10364 reg_pat[i++] = '{';
10365 p += 2;
10366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010367 else
10368 {
10369 if (allow_dirs != NULL && vim_ispathsep(*p)
10370#ifdef BACKSLASH_IN_FILENAME
10371 && (!no_bslash || *p != '\\')
10372#endif
10373 )
10374 *allow_dirs = TRUE;
10375 reg_pat[i++] = '\\';
10376 reg_pat[i++] = *p;
10377 }
10378 break;
10379#ifdef BACKSLASH_IN_FILENAME
10380 case '/':
10381 reg_pat[i++] = '[';
10382 reg_pat[i++] = '\\';
10383 reg_pat[i++] = '/';
10384 reg_pat[i++] = ']';
10385 if (allow_dirs != NULL)
10386 *allow_dirs = TRUE;
10387 break;
10388#endif
10389 case '{':
10390 reg_pat[i++] = '\\';
10391 reg_pat[i++] = '(';
10392 nested++;
10393 break;
10394 case '}':
10395 reg_pat[i++] = '\\';
10396 reg_pat[i++] = ')';
10397 --nested;
10398 break;
10399 case ',':
10400 if (nested)
10401 {
10402 reg_pat[i++] = '\\';
10403 reg_pat[i++] = '|';
10404 }
10405 else
10406 reg_pat[i++] = ',';
10407 break;
10408 default:
10409# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010410 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010411 reg_pat[i++] = *p++;
10412 else
10413# endif
10414 if (allow_dirs != NULL && vim_ispathsep(*p))
10415 *allow_dirs = TRUE;
10416 reg_pat[i++] = *p;
10417 break;
10418 }
10419 }
10420 if (add_dollar)
10421 reg_pat[i++] = '$';
10422 reg_pat[i] = NUL;
10423 if (nested != 0)
10424 {
10425 if (nested < 0)
10426 EMSG(_("E219: Missing {."));
10427 else
10428 EMSG(_("E220: Missing }."));
10429 vim_free(reg_pat);
10430 reg_pat = NULL;
10431 }
10432 return reg_pat;
10433}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010434
10435#if defined(EINTR) || defined(PROTO)
10436/*
10437 * Version of read() that retries when interrupted by EINTR (possibly
10438 * by a SIGWINCH).
10439 */
10440 long
10441read_eintr(fd, buf, bufsize)
10442 int fd;
10443 void *buf;
10444 size_t bufsize;
10445{
10446 long ret;
10447
10448 for (;;)
10449 {
10450 ret = vim_read(fd, buf, bufsize);
10451 if (ret >= 0 || errno != EINTR)
10452 break;
10453 }
10454 return ret;
10455}
10456
10457/*
10458 * Version of write() that retries when interrupted by EINTR (possibly
10459 * by a SIGWINCH).
10460 */
10461 long
10462write_eintr(fd, buf, bufsize)
10463 int fd;
10464 void *buf;
10465 size_t bufsize;
10466{
10467 long ret = 0;
10468 long wlen;
10469
10470 /* Repeat the write() so long it didn't fail, other than being interrupted
10471 * by a signal. */
10472 while (ret < (long)bufsize)
10473 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010474 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010475 if (wlen < 0)
10476 {
10477 if (errno != EINTR)
10478 break;
10479 }
10480 else
10481 ret += wlen;
10482 }
10483 return ret;
10484}
10485#endif