blob: 0ddd079280991b5e3f51523b87c27b63d66a3080 [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
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
Bram Moolenaar941aea22015-12-11 17:14:27 +010030#if (defined(sun) || defined(__FreeBSD__)) && defined(S_ISCHR)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000031# define OPEN_CHR_FILES
32static int is_dev_fd_file(char_u *fname);
33#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000034#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010035static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000036# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038# endif
39#endif
40#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010041static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000042#endif
43#ifdef FEAT_CRYPT
Bram Moolenaard25c16e2016-01-29 22:13:30 +010044static char_u *check_for_cryptkey(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 +000045#endif
46#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010047static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000048#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int set_rw_fname(char_u *fname, char_u *sfname);
50static int msg_add_fileformat(int eol_type);
51static void msg_add_eol(void);
52static int check_mtime(buf_T *buf, struct stat *s);
53static int time_differs(long t1, long t2);
Bram Moolenaar071d4272004-06-13 20:20:40 +000054#ifdef FEAT_AUTOCMD
Bram Moolenaard25c16e2016-01-29 22:13:30 +010055static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
56static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000057
58# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000059# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000060# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000061#endif
62
63#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
64# define HAS_BW_FLAGS
65# define FIO_LATIN1 0x01 /* convert Latin1 */
66# define FIO_UTF8 0x02 /* convert UTF-8 */
67# define FIO_UCS2 0x04 /* convert UCS-2 */
68# define FIO_UCS4 0x08 /* convert UCS-4 */
69# define FIO_UTF16 0x10 /* convert UTF-16 */
70# ifdef WIN3264
71# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
72# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
73# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
74# endif
75# ifdef MACOS_X
76# define FIO_MACROMAN 0x20 /* convert MacRoman */
77# endif
78# define FIO_ENDIAN_L 0x80 /* little endian */
79# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
80# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
81# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
82# define FIO_ALL -1 /* allow all formats */
83#endif
84
85/* When converting, a read() or write() may leave some bytes to be converted
86 * for the next call. The value is guessed... */
87#define CONV_RESTLEN 30
88
89/* We have to guess how much a sequence of bytes may expand when converting
90 * with iconv() to be able to allocate a buffer. */
91#define ICONV_MULT 8
92
93/*
94 * Structure to pass arguments from buf_write() to buf_write_bytes().
95 */
96struct bw_info
97{
98 int bw_fd; /* file descriptor */
99 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000100 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101#ifdef HAS_BW_FLAGS
102 int bw_flags; /* FIO_ flags */
103#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200104#ifdef FEAT_CRYPT
105 buf_T *bw_buffer; /* buffer being written */
106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107#ifdef FEAT_MBYTE
108 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
109 int bw_restlen; /* nr of bytes in bw_rest[] */
110 int bw_first; /* first write call */
111 char_u *bw_conv_buf; /* buffer for writing converted chars */
112 int bw_conv_buflen; /* size of bw_conv_buf */
113 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000114 linenr_T bw_conv_error_lnum; /* first line with error or zero */
115 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116# ifdef USE_ICONV
117 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
118# endif
119#endif
120};
121
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100122static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000123
124#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100125static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
126static int ucs2bytes(unsigned c, char_u **pp, int flags);
127static int need_conversion(char_u *fenc);
128static int get_fio_flags(char_u *ptr);
129static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
130static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000131# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100132static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133# endif
134# ifdef MACOS_X
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100135static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136# endif
137#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100138static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000139#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100140static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000141#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000142#ifdef FEAT_AUTOCMD
143static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
144#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000145
Bram Moolenaarc3691332016-04-20 12:49:49 +0200146#ifdef FEAT_AUTOCMD
147/*
148 * Set by the apply_autocmds_group function if the given event is equal to
149 * EVENT_FILETYPE. Used by the readfile function in order to determine if
150 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
151 *
152 * Relying on this value requires one to reset it prior calling
153 * apply_autocmds_group.
154 */
155static int au_did_filetype INIT(= FALSE);
156#endif
157
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100159filemess(
160 buf_T *buf,
161 char_u *name,
162 char_u *s,
163 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164{
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
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100219readfile(
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)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000227{
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 Moolenaar071d4272004-06-13 20:20:40 +0000253#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200254#ifdef FEAT_PERSISTENT_UNDO
255 context_sha256_T sha_ctx;
256 int read_undo_file = FALSE;
257#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 int split = 0; /* number of split lines */
259#define UNKNOWN 0x0fffffff /* file size is unknown */
260 linenr_T linecnt;
261 int error = FALSE; /* errors encountered */
262 int ff_error = EOL_UNKNOWN; /* file format with errors */
263 long linerest = 0; /* remaining chars in line */
264#ifdef UNIX
265 int perm = 0;
266 int swap_mode = -1; /* protection bits for swap file */
267#else
268 int perm;
269#endif
270 int fileformat = 0; /* end-of-line format */
271 int keep_fileformat = FALSE;
272 struct stat st;
273 int file_readonly;
274 linenr_T skip_count = 0;
275 linenr_T read_count = 0;
276 int msg_save = msg_scroll;
277 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
278 * last read was missing the eol */
279 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
280 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
281 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
282 int file_rewind = FALSE;
283#ifdef FEAT_MBYTE
284 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000285 linenr_T conv_error = 0; /* line nr with conversion error */
286 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
288 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000289 int bad_char_behavior = BAD_REPLACE;
290 /* BAD_KEEP, BAD_DROP or character to
291 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292 char_u *tmpname = NULL; /* name of 'charconvert' output file */
293 int fio_flags = 0;
294 char_u *fenc; /* fileencoding to use */
295 int fenc_alloced; /* fenc_next is in allocated memory */
296 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
297 int advance_fenc = FALSE;
298 long real_size = 0;
299# ifdef USE_ICONV
300 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
301# ifdef FEAT_EVAL
302 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
303 'charconvert' next */
304# endif
305# endif
306 int converted = FALSE; /* TRUE if conversion done */
307 int notconverted = FALSE; /* TRUE if conversion wanted but it
308 wasn't possible */
309 char_u conv_rest[CONV_RESTLEN];
310 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
311#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000312#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200313 buf_T *old_curbuf;
314 char_u *old_b_ffname;
315 char_u *old_b_fname;
316 int using_b_ffname;
317 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000318#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200319
Bram Moolenaarc3691332016-04-20 12:49:49 +0200320#ifdef FEAT_AUTOCMD
321 au_did_filetype = FALSE; /* reset before triggering any autocommands */
322#endif
323
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100324 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325
326 /*
327 * If there is no file name yet, use the one for the read file.
328 * BF_NOTEDITED is set to reflect this.
329 * Don't do this for a read from a filter.
330 * Only do this when 'cpoptions' contains the 'f' flag.
331 */
332 if (curbuf->b_ffname == NULL
333 && !filtering
334 && fname != NULL
335 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
336 && !(flags & READ_DUMMY))
337 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000338 if (set_rw_fname(fname, sfname) == FAIL)
339 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 }
341
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200342#ifdef FEAT_AUTOCMD
343 /* Remember the initial values of curbuf, curbuf->b_ffname and
344 * curbuf->b_fname to detect whether they are altered as a result of
345 * executing nasty autocommands. Also check if "fname" and "sfname"
346 * point to one of these values. */
347 old_curbuf = curbuf;
348 old_b_ffname = curbuf->b_ffname;
349 old_b_fname = curbuf->b_fname;
350 using_b_ffname = (fname == curbuf->b_ffname)
351 || (sfname == curbuf->b_ffname);
352 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
353#endif
354
Bram Moolenaardf177f62005-02-22 08:39:57 +0000355 /* After reading a file the cursor line changes but we don't want to
356 * display the line. */
357 ex_no_reprint = TRUE;
358
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000359 /* don't display the file info for another buffer now */
360 need_fileinfo = FALSE;
361
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362 /*
363 * For Unix: Use the short file name whenever possible.
364 * Avoids problems with networks and when directory names are changed.
365 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
366 * another directory, which we don't detect.
367 */
368 if (sfname == NULL)
369 sfname = fname;
370#if defined(UNIX) || defined(__EMX__)
371 fname = sfname;
372#endif
373
374#ifdef FEAT_AUTOCMD
375 /*
376 * The BufReadCmd and FileReadCmd events intercept the reading process by
377 * executing the associated commands instead.
378 */
379 if (!filtering && !read_stdin && !read_buffer)
380 {
381 pos_T pos;
382
383 pos = curbuf->b_op_start;
384
385 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
386 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
387 curbuf->b_op_start.col = 0;
388
389 if (newfile)
390 {
391 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
392 FALSE, curbuf, eap))
393#ifdef FEAT_EVAL
394 return aborting() ? FAIL : OK;
395#else
396 return OK;
397#endif
398 }
399 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
400 FALSE, NULL, eap))
401#ifdef FEAT_EVAL
402 return aborting() ? FAIL : OK;
403#else
404 return OK;
405#endif
406
407 curbuf->b_op_start = pos;
408 }
409#endif
410
411 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
412 msg_scroll = FALSE; /* overwrite previous file message */
413 else
414 msg_scroll = TRUE; /* don't overwrite previous file message */
415
416 /*
417 * If the name ends in a path separator, we can't open it. Check here,
418 * because reading the file may actually work, but then creating the swap
419 * file may destroy it! Reported on MS-DOS and Win 95.
420 * If the name is too long we might crash further on, quit here.
421 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000422 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000423 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000424 p = fname + STRLEN(fname);
425 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000426 {
427 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
428 msg_end();
429 msg_scroll = msg_save;
430 return FAIL;
431 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 }
433
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434 if (!read_stdin && !read_buffer)
435 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200436#ifdef UNIX
437 /*
438 * On Unix it is possible to read a directory, so we have to
439 * check for it before the mch_open().
440 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 perm = mch_getperm(fname);
442 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
443# ifdef S_ISFIFO
444 && !S_ISFIFO(perm) /* ... or fifo */
445# endif
446# ifdef S_ISSOCK
447 && !S_ISSOCK(perm) /* ... or socket */
448# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000449# ifdef OPEN_CHR_FILES
450 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
451 /* ... or a character special file named /dev/fd/<n> */
452# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453 )
454 {
455 if (S_ISDIR(perm))
456 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
457 else
458 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
459 msg_end();
460 msg_scroll = msg_save;
461 return FAIL;
462 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200463#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100464#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000465 /*
466 * MS-Windows allows opening a device, but we will probably get stuck
467 * trying to read it.
468 */
469 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
470 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000471 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000472 msg_end();
473 msg_scroll = msg_save;
474 return FAIL;
475 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000476#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200477 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000478
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200479 /* Set default or forced 'fileformat' and 'binary'. */
480 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481
482 /*
483 * When opening a new file we take the readonly flag from the file.
484 * Default is r/w, can be set to r/o below.
485 * Don't reset it when in readonly mode
486 * Only set/reset b_p_ro when BF_CHECK_RO is set.
487 */
488 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000489 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490 curbuf->b_p_ro = FALSE;
491
492 if (newfile && !read_stdin && !read_buffer)
493 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200494 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 if (mch_stat((char *)fname, &st) >= 0)
496 {
497 buf_store_time(curbuf, &st, fname);
498 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499#ifdef UNIX
500 /*
501 * Use the protection bits of the original file for the swap file.
502 * This makes it possible for others to read the name of the
503 * edited file from the swapfile, but only if they can read the
504 * edited file.
505 * Remove the "write" and "execute" bits for group and others
506 * (they must not write the swapfile).
507 * Add the "read" and "write" bits for the user, otherwise we may
508 * not be able to write to the file ourselves.
509 * Setting the bits is done below, after creating the swap file.
510 */
511 swap_mode = (st.st_mode & 0644) | 0600;
512#endif
513#ifdef FEAT_CW_EDITOR
514 /* Get the FSSpec on MacOS
515 * TODO: Update it properly when the buffer name changes
516 */
517 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
518#endif
519#ifdef VMS
520 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000521 curbuf->b_fab_rat = st.st_fab_rat;
522 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523#endif
524 }
525 else
526 {
527 curbuf->b_mtime = 0;
528 curbuf->b_mtime_read = 0;
529 curbuf->b_orig_size = 0;
530 curbuf->b_orig_mode = 0;
531 }
532
533 /* Reset the "new file" flag. It will be set again below when the
534 * file doesn't exist. */
535 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
536 }
537
538/*
539 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100540 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541 */
542 file_readonly = FALSE;
543 if (read_stdin)
544 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100545#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
547 setmode(0, O_BINARY);
548#endif
549 }
550 else if (!read_buffer)
551 {
552#ifdef USE_MCH_ACCESS
553 if (
554# ifdef UNIX
555 !(perm & 0222) ||
556# endif
557 mch_access((char *)fname, W_OK))
558 file_readonly = TRUE;
559 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
560#else
561 if (!newfile
562 || readonlymode
563 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
564 {
565 file_readonly = TRUE;
566 /* try to open ro */
567 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
568 }
569#endif
570 }
571
572 if (fd < 0) /* cannot open at all */
573 {
574#ifndef UNIX
575 int isdir_f;
576#endif
577 msg_scroll = msg_save;
578#ifndef UNIX
579 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100580 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581 */
582 isdir_f = (mch_isdir(fname));
583 perm = mch_getperm(fname); /* check if the file exists */
584 if (isdir_f)
585 {
586 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
587 curbuf->b_p_ro = TRUE; /* must use "w!" now */
588 }
589 else
590#endif
591 if (newfile)
592 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200593 if (perm < 0
594#ifdef ENOENT
595 && errno == ENOENT
596#endif
597 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 {
599 /*
600 * Set the 'new-file' flag, so that when the file has
601 * been created by someone else, a ":w" will complain.
602 */
603 curbuf->b_flags |= BF_NEW;
604
605 /* Create a swap file now, so that other Vims are warned
606 * that we are editing this file. Don't do this for a
607 * "nofile" or "nowrite" buffer type. */
608#ifdef FEAT_QUICKFIX
609 if (!bt_dontwrite(curbuf))
610#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000611 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000613#ifdef FEAT_AUTOCMD
614 /* SwapExists autocommand may mess things up */
615 if (curbuf != old_curbuf
616 || (using_b_ffname
617 && (old_b_ffname != curbuf->b_ffname))
618 || (using_b_fname
619 && (old_b_fname != curbuf->b_fname)))
620 {
621 EMSG(_(e_auchangedbuf));
622 return FAIL;
623 }
624#endif
625 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000626 if (dir_of_file_exists(fname))
627 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
628 else
629 filemess(curbuf, sfname,
630 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000631#ifdef FEAT_VIMINFO
632 /* Even though this is a new file, it might have been
633 * edited before and deleted. Get the old marks. */
634 check_marks_read();
635#endif
636#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200637 /* Set forced 'fileencoding'. */
638 if (eap != NULL)
639 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640#endif
641#ifdef FEAT_AUTOCMD
642 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
643 FALSE, curbuf, eap);
644#endif
645 /* remember the current fileformat */
646 save_file_ff(curbuf);
647
648#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
649 if (aborting()) /* autocmds may abort script processing */
650 return FAIL;
651#endif
652 return OK; /* a new file is not an error */
653 }
654 else
655 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000656 filemess(curbuf, sfname, (char_u *)(
657# ifdef EFBIG
658 (errno == EFBIG) ? _("[File too big]") :
659# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200660# ifdef EOVERFLOW
661 (errno == EOVERFLOW) ? _("[File too big]") :
662# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000663 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 curbuf->b_p_ro = TRUE; /* must use "w!" now */
665 }
666 }
667
668 return FAIL;
669 }
670
671 /*
672 * Only set the 'ro' flag for readonly files the first time they are
673 * loaded. Help files always get readonly mode
674 */
675 if ((check_readonly && file_readonly) || curbuf->b_help)
676 curbuf->b_p_ro = TRUE;
677
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000678 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000680 /* Don't change 'eol' if reading from buffer as it will already be
681 * correctly set when reading stdin. */
682 if (!read_buffer)
683 {
684 curbuf->b_p_eol = TRUE;
685 curbuf->b_start_eol = TRUE;
686 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687#ifdef FEAT_MBYTE
688 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000689 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#endif
691 }
692
693 /* Create a swap file now, so that other Vims are warned that we are
694 * editing this file.
695 * Don't do this for a "nofile" or "nowrite" buffer type. */
696#ifdef FEAT_QUICKFIX
697 if (!bt_dontwrite(curbuf))
698#endif
699 {
700 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000701#ifdef FEAT_AUTOCMD
702 if (!read_stdin && (curbuf != old_curbuf
703 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
704 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
705 {
706 EMSG(_(e_auchangedbuf));
707 if (!read_buffer)
708 close(fd);
709 return FAIL;
710 }
711#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712#ifdef UNIX
713 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000714 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
715 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
717#endif
718 }
719
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000720#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 /* If "Quit" selected at ATTENTION dialog, don't load the file */
722 if (swap_exists_action == SEA_QUIT)
723 {
724 if (!read_buffer && !read_stdin)
725 close(fd);
726 return FAIL;
727 }
728#endif
729
730 ++no_wait_return; /* don't wait for return yet */
731
732 /*
733 * Set '[ mark to the line above where the lines go (line 1 if zero).
734 */
735 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
736 curbuf->b_op_start.col = 0;
737
738#ifdef FEAT_AUTOCMD
739 if (!read_buffer)
740 {
741 int m = msg_scroll;
742 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743
744 /*
745 * The file must be closed again, the autocommands may want to change
746 * the file before reading it.
747 */
748 if (!read_stdin)
749 close(fd); /* ignore errors */
750
751 /*
752 * The output from the autocommands should not overwrite anything and
753 * should not be overwritten: Set msg_scroll, restore its value if no
754 * output was done.
755 */
756 msg_scroll = TRUE;
757 if (filtering)
758 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
759 FALSE, curbuf, eap);
760 else if (read_stdin)
761 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
762 FALSE, curbuf, eap);
763 else if (newfile)
764 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
765 FALSE, curbuf, eap);
766 else
767 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
768 FALSE, NULL, eap);
769 if (msg_scrolled == n)
770 msg_scroll = m;
771
772#ifdef FEAT_EVAL
773 if (aborting()) /* autocmds may abort script processing */
774 {
775 --no_wait_return;
776 msg_scroll = msg_save;
777 curbuf->b_p_ro = TRUE; /* must use "w!" now */
778 return FAIL;
779 }
780#endif
781 /*
782 * Don't allow the autocommands to change the current buffer.
783 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000784 *
785 * Don't allow the autocommands to change the buffer name either
786 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787 */
788 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000789 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
790 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
792 {
793 --no_wait_return;
794 msg_scroll = msg_save;
795 if (fd < 0)
796 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
797 else
798 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
799 curbuf->b_p_ro = TRUE; /* must use "w!" now */
800 return FAIL;
801 }
802 }
803#endif /* FEAT_AUTOCMD */
804
805 /* Autocommands may add lines to the file, need to check if it is empty */
806 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
807
808 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
809 {
810 /*
811 * Show the user that we are busy reading the input. Sometimes this
812 * may take a while. When reading from stdin another program may
813 * still be running, don't move the cursor to the last line, unless
814 * always using the GUI.
815 */
816 if (read_stdin)
817 {
818#ifndef ALWAYS_USE_GUI
819 mch_msg(_("Vim: Reading from stdin...\n"));
820#endif
821#ifdef FEAT_GUI
822 /* Also write a message in the GUI window, if there is one. */
823 if (gui.in_use && !gui.dying && !gui.starting)
824 {
825 p = (char_u *)_("Reading from stdin...");
826 gui_write(p, (int)STRLEN(p));
827 }
828#endif
829 }
830 else if (!read_buffer)
831 filemess(curbuf, sfname, (char_u *)"", 0);
832 }
833
834 msg_scroll = FALSE; /* overwrite the file message */
835
836 /*
837 * Set linecnt now, before the "retry" caused by a wrong guess for
838 * fileformat, and after the autocommands, which may change them.
839 */
840 linecnt = curbuf->b_ml.ml_line_count;
841
842#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000843 /* "++bad=" argument. */
844 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000845 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000846 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000847 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000848 curbuf->b_bad_char = eap->bad_char;
849 }
850 else
851 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000852
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000854 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855 */
856 if (eap != NULL && eap->force_enc != 0)
857 {
858 fenc = enc_canonize(eap->cmd + eap->force_enc);
859 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000860 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000861 }
862 else if (curbuf->b_p_bin)
863 {
864 fenc = (char_u *)""; /* binary: don't convert */
865 fenc_alloced = FALSE;
866 }
867 else if (curbuf->b_help)
868 {
869 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000870 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871
872 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
873 * fails it must be latin1.
874 * Always do this when 'encoding' is "utf-8". Otherwise only do
875 * this when needed to avoid [converted] remarks all the time.
876 * It is needed when the first line contains non-ASCII characters.
877 * That is only in *.??x files. */
878 fenc = (char_u *)"latin1";
879 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000880 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000882 fc = fname[STRLEN(fname) - 1];
883 if (TOLOWER_ASC(fc) == 'x')
884 {
885 /* Read the first line (and a bit more). Immediately rewind to
886 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100887 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000888 lseek(fd, (off_t)0L, SEEK_SET);
889 for (p = firstline; p < firstline + len; ++p)
890 if (*p >= 0x80)
891 {
892 c = TRUE;
893 break;
894 }
895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 }
897
898 if (c)
899 {
900 fenc_next = fenc;
901 fenc = (char_u *)"utf-8";
902
903 /* When the file is utf-8 but a character doesn't fit in
904 * 'encoding' don't retry. In help text editing utf-8 bytes
905 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000906 if (!enc_utf8)
907 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 }
909 fenc_alloced = FALSE;
910 }
911 else if (*p_fencs == NUL)
912 {
913 fenc = curbuf->b_p_fenc; /* use format from buffer */
914 fenc_alloced = FALSE;
915 }
916 else
917 {
918 fenc_next = p_fencs; /* try items in 'fileencodings' */
919 fenc = next_fenc(&fenc_next);
920 fenc_alloced = TRUE;
921 }
922#endif
923
924 /*
925 * Jump back here to retry reading the file in different ways.
926 * Reasons to retry:
927 * - encoding conversion failed: try another one from "fenc_next"
928 * - BOM detected and fenc was set, need to setup conversion
929 * - "fileformat" check failed: try another
930 *
931 * Variables set for special retry actions:
932 * "file_rewind" Rewind the file to start reading it again.
933 * "advance_fenc" Advance "fenc" using "fenc_next".
934 * "skip_read" Re-use already read bytes (BOM detected).
935 * "did_iconv" iconv() conversion failed, try 'charconvert'.
936 * "keep_fileformat" Don't reset "fileformat".
937 *
938 * Other status indicators:
939 * "tmpname" When != NULL did conversion with 'charconvert'.
940 * Output file has to be deleted afterwards.
941 * "iconv_fd" When != -1 did conversion with iconv().
942 */
943retry:
944
945 if (file_rewind)
946 {
947 if (read_buffer)
948 {
949 read_buf_lnum = 1;
950 read_buf_col = 0;
951 }
952 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
953 {
954 /* Can't rewind the file, give up. */
955 error = TRUE;
956 goto failed;
957 }
958 /* Delete the previously read lines. */
959 while (lnum > from)
960 ml_delete(lnum--, FALSE);
961 file_rewind = FALSE;
962#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000963 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000964 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000966 curbuf->b_start_bomb = FALSE;
967 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000968 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969#endif
970 }
971
972 /*
973 * When retrying with another "fenc" and the first time "fileformat"
974 * will be reset.
975 */
976 if (keep_fileformat)
977 keep_fileformat = FALSE;
978 else
979 {
980 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000981 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000983 try_unix = try_dos = try_mac = FALSE;
984 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985 else if (curbuf->b_p_bin)
986 fileformat = EOL_UNIX; /* binary: use Unix format */
987 else if (*p_ffs == NUL)
988 fileformat = get_fileformat(curbuf);/* use format from buffer */
989 else
990 fileformat = EOL_UNKNOWN; /* detect from file */
991 }
992
993#ifdef FEAT_MBYTE
994# ifdef USE_ICONV
995 if (iconv_fd != (iconv_t)-1)
996 {
997 /* aborted conversion with iconv(), close the descriptor */
998 iconv_close(iconv_fd);
999 iconv_fd = (iconv_t)-1;
1000 }
1001# endif
1002
1003 if (advance_fenc)
1004 {
1005 /*
1006 * Try the next entry in 'fileencodings'.
1007 */
1008 advance_fenc = FALSE;
1009
1010 if (eap != NULL && eap->force_enc != 0)
1011 {
1012 /* Conversion given with "++cc=" wasn't possible, read
1013 * without conversion. */
1014 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001015 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 if (fenc_alloced)
1017 vim_free(fenc);
1018 fenc = (char_u *)"";
1019 fenc_alloced = FALSE;
1020 }
1021 else
1022 {
1023 if (fenc_alloced)
1024 vim_free(fenc);
1025 if (fenc_next != NULL)
1026 {
1027 fenc = next_fenc(&fenc_next);
1028 fenc_alloced = (fenc_next != NULL);
1029 }
1030 else
1031 {
1032 fenc = (char_u *)"";
1033 fenc_alloced = FALSE;
1034 }
1035 }
1036 if (tmpname != NULL)
1037 {
1038 mch_remove(tmpname); /* delete converted file */
1039 vim_free(tmpname);
1040 tmpname = NULL;
1041 }
1042 }
1043
1044 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001045 * Conversion may be required when the encoding of the file is different
1046 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 */
1048 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001049 converted = need_conversion(fenc);
1050 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 {
1052
1053 /* "ucs-bom" means we need to check the first bytes of the file
1054 * for a BOM. */
1055 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1056 fio_flags = FIO_UCSBOM;
1057
1058 /*
1059 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1060 * done. This is handled below after read(). Prepare the
1061 * fio_flags to avoid having to parse the string each time.
1062 * Also check for Unicode to Latin1 conversion, because iconv()
1063 * appears not to handle this correctly. This works just like
1064 * conversion to UTF-8 except how the resulting character is put in
1065 * the buffer.
1066 */
1067 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1068 fio_flags = get_fio_flags(fenc);
1069
1070# ifdef WIN3264
1071 /*
1072 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1073 * is handled with MultiByteToWideChar().
1074 */
1075 if (fio_flags == 0)
1076 fio_flags = get_win_fio_flags(fenc);
1077# endif
1078
1079# ifdef MACOS_X
1080 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1081 if (fio_flags == 0)
1082 fio_flags = get_mac_fio_flags(fenc);
1083# endif
1084
1085# ifdef USE_ICONV
1086 /*
1087 * Try using iconv() if we can't convert internally.
1088 */
1089 if (fio_flags == 0
1090# ifdef FEAT_EVAL
1091 && !did_iconv
1092# endif
1093 )
1094 iconv_fd = (iconv_t)my_iconv_open(
1095 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1096# endif
1097
1098# ifdef FEAT_EVAL
1099 /*
1100 * Use the 'charconvert' expression when conversion is required
1101 * and we can't do it internally or with iconv().
1102 */
1103 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1104# ifdef USE_ICONV
1105 && iconv_fd == (iconv_t)-1
1106# endif
1107 )
1108 {
1109# ifdef USE_ICONV
1110 did_iconv = FALSE;
1111# endif
1112 /* Skip conversion when it's already done (retry for wrong
1113 * "fileformat"). */
1114 if (tmpname == NULL)
1115 {
1116 tmpname = readfile_charconvert(fname, fenc, &fd);
1117 if (tmpname == NULL)
1118 {
1119 /* Conversion failed. Try another one. */
1120 advance_fenc = TRUE;
1121 if (fd < 0)
1122 {
1123 /* Re-opening the original file failed! */
1124 EMSG(_("E202: Conversion made file unreadable!"));
1125 error = TRUE;
1126 goto failed;
1127 }
1128 goto retry;
1129 }
1130 }
1131 }
1132 else
1133# endif
1134 {
1135 if (fio_flags == 0
1136# ifdef USE_ICONV
1137 && iconv_fd == (iconv_t)-1
1138# endif
1139 )
1140 {
1141 /* Conversion wanted but we can't.
1142 * Try the next conversion in 'fileencodings' */
1143 advance_fenc = TRUE;
1144 goto retry;
1145 }
1146 }
1147 }
1148
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001149 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001151 * stdin or fixed at a specific encoding. */
1152 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153#endif
1154
1155 if (!skip_read)
1156 {
1157 linerest = 0;
1158 filesize = 0;
1159 skip_count = lines_to_skip;
1160 read_count = lines_to_read;
1161#ifdef FEAT_MBYTE
1162 conv_restlen = 0;
1163#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001164#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001165 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1166 && curbuf->b_ffname != NULL
1167 && curbuf->b_p_udf
1168 && !filtering
1169 && !read_stdin
1170 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001171 if (read_undo_file)
1172 sha256_start(&sha_ctx);
1173#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001174#ifdef FEAT_CRYPT
1175 if (curbuf->b_cryptstate != NULL)
1176 {
1177 /* Need to free the state, but keep the key, don't want to ask for
1178 * it again. */
1179 crypt_free_state(curbuf->b_cryptstate);
1180 curbuf->b_cryptstate = NULL;
1181 }
1182#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 }
1184
1185 while (!error && !got_int)
1186 {
1187 /*
1188 * We allocate as much space for the file as we can get, plus
1189 * space for the old line plus room for one terminating NUL.
1190 * The amount is limited by the fact that read() only can read
1191 * upto max_unsigned characters (and other things).
1192 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001193#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 if (linerest >= 0x7ff0)
1195 {
1196 ++split;
1197 *ptr = NL; /* split line by inserting a NL */
1198 size = 1;
1199 }
1200 else
1201#endif
1202 {
1203 if (!skip_read)
1204 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001205#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001206# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 size = SSIZE_MAX; /* use max I/O size, 52K */
1208# else
1209 size = 0x10000L; /* use buffer >= 64K */
1210# endif
1211#else
1212 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1213#endif
1214
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001215 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 {
1217 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1218 FALSE)) != NULL)
1219 break;
1220 }
1221 if (new_buffer == NULL)
1222 {
1223 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1224 error = TRUE;
1225 break;
1226 }
1227 if (linerest) /* copy characters from the previous buffer */
1228 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1229 vim_free(buffer);
1230 buffer = new_buffer;
1231 ptr = buffer + linerest;
1232 line_start = buffer;
1233
1234#ifdef FEAT_MBYTE
1235 /* May need room to translate into.
1236 * For iconv() we don't really know the required space, use a
1237 * factor ICONV_MULT.
1238 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1239 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1240 * become up to 4 bytes, size must be multiple of 2
1241 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1242 * multiple of 2
1243 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1244 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001245 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246# ifdef USE_ICONV
1247 if (iconv_fd != (iconv_t)-1)
1248 size = size / ICONV_MULT;
1249 else
1250# endif
1251 if (fio_flags & FIO_LATIN1)
1252 size = size / 2;
1253 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1254 size = (size * 2 / 3) & ~1;
1255 else if (fio_flags & FIO_UCS4)
1256 size = (size * 2 / 3) & ~3;
1257 else if (fio_flags == FIO_UCSBOM)
1258 size = size / ICONV_MULT; /* worst case */
1259# ifdef WIN3264
1260 else if (fio_flags & FIO_CODEPAGE)
1261 size = size / ICONV_MULT; /* also worst case */
1262# endif
1263# ifdef MACOS_X
1264 else if (fio_flags & FIO_MACROMAN)
1265 size = size / ICONV_MULT; /* also worst case */
1266# endif
1267#endif
1268
1269#ifdef FEAT_MBYTE
1270 if (conv_restlen > 0)
1271 {
1272 /* Insert unconverted bytes from previous line. */
1273 mch_memmove(ptr, conv_rest, conv_restlen);
1274 ptr += conv_restlen;
1275 size -= conv_restlen;
1276 }
1277#endif
1278
1279 if (read_buffer)
1280 {
1281 /*
1282 * Read bytes from curbuf. Used for converting text read
1283 * from stdin.
1284 */
1285 if (read_buf_lnum > from)
1286 size = 0;
1287 else
1288 {
1289 int n, ni;
1290 long tlen;
1291
1292 tlen = 0;
1293 for (;;)
1294 {
1295 p = ml_get(read_buf_lnum) + read_buf_col;
1296 n = (int)STRLEN(p);
1297 if ((int)tlen + n + 1 > size)
1298 {
1299 /* Filled up to "size", append partial line.
1300 * Change NL to NUL to reverse the effect done
1301 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001302 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 for (ni = 0; ni < n; ++ni)
1304 {
1305 if (p[ni] == NL)
1306 ptr[tlen++] = NUL;
1307 else
1308 ptr[tlen++] = p[ni];
1309 }
1310 read_buf_col += n;
1311 break;
1312 }
1313 else
1314 {
1315 /* Append whole line and new-line. Change NL
1316 * to NUL to reverse the effect done below. */
1317 for (ni = 0; ni < n; ++ni)
1318 {
1319 if (p[ni] == NL)
1320 ptr[tlen++] = NUL;
1321 else
1322 ptr[tlen++] = p[ni];
1323 }
1324 ptr[tlen++] = NL;
1325 read_buf_col = 0;
1326 if (++read_buf_lnum > from)
1327 {
1328 /* When the last line didn't have an
1329 * end-of-line don't add it now either. */
1330 if (!curbuf->b_p_eol)
1331 --tlen;
1332 size = tlen;
1333 break;
1334 }
1335 }
1336 }
1337 }
1338 }
1339 else
1340 {
1341 /*
1342 * Read bytes from the file.
1343 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001344 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345 }
1346
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001347#ifdef FEAT_CRYPT
1348 /*
1349 * At start of file: Check for magic number of encryption.
1350 */
1351 if (filesize == 0 && size > 0)
1352 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1353 &filesize, newfile, sfname,
1354 &did_ask_for_key);
1355 /*
1356 * Decrypt the read bytes. This is done before checking for
1357 * EOF because the crypt layer may be buffering.
1358 */
1359 if (cryptkey != NULL && size > 0)
1360 {
1361 if (crypt_works_inplace(curbuf->b_cryptstate))
1362 {
1363 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1364 }
1365 else
1366 {
1367 char_u *newptr = NULL;
1368 int decrypted_size;
1369
1370 decrypted_size = crypt_decode_alloc(
1371 curbuf->b_cryptstate, ptr, size, &newptr);
1372
1373 /* If the crypt layer is buffering, not producing
1374 * anything yet, need to read more. */
1375 if (size > 0 && decrypted_size == 0)
1376 continue;
1377
1378 if (linerest == 0)
1379 {
1380 /* Simple case: reuse returned buffer (may be
1381 * NULL, checked later). */
1382 new_buffer = newptr;
1383 }
1384 else
1385 {
1386 long_u new_size;
1387
1388 /* Need new buffer to add bytes carried over. */
1389 new_size = (long_u)(decrypted_size + linerest + 1);
1390 new_buffer = lalloc(new_size, FALSE);
1391 if (new_buffer == NULL)
1392 {
1393 do_outofmem_msg(new_size);
1394 error = TRUE;
1395 break;
1396 }
1397
1398 mch_memmove(new_buffer, buffer, linerest);
1399 if (newptr != NULL)
1400 mch_memmove(new_buffer + linerest, newptr,
1401 decrypted_size);
1402 }
1403
1404 if (new_buffer != NULL)
1405 {
1406 vim_free(buffer);
1407 buffer = new_buffer;
1408 new_buffer = NULL;
1409 line_start = buffer;
1410 ptr = buffer + linerest;
1411 }
1412 size = decrypted_size;
1413 }
1414 }
1415#endif
1416
Bram Moolenaar071d4272004-06-13 20:20:40 +00001417 if (size <= 0)
1418 {
1419 if (size < 0) /* read error */
1420 error = TRUE;
1421#ifdef FEAT_MBYTE
1422 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001423 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001424 /*
1425 * Reached end-of-file but some trailing bytes could
1426 * not be converted. Truncated file?
1427 */
1428
1429 /* When we did a conversion report an error. */
1430 if (fio_flags != 0
1431# ifdef USE_ICONV
1432 || iconv_fd != (iconv_t)-1
1433# endif
1434 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001435 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001436 if (can_retry)
1437 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001438 if (conv_error == 0)
1439 conv_error = curbuf->b_ml.ml_line_count
1440 - linecnt + 1;
1441 }
1442 /* Remember the first linenr with an illegal byte */
1443 else if (illegal_byte == 0)
1444 illegal_byte = curbuf->b_ml.ml_line_count
1445 - linecnt + 1;
1446 if (bad_char_behavior == BAD_DROP)
1447 {
1448 *(ptr - conv_restlen) = NUL;
1449 conv_restlen = 0;
1450 }
1451 else
1452 {
1453 /* Replace the trailing bytes with the replacement
1454 * character if we were converting; if we weren't,
1455 * leave the UTF8 checking code to do it, as it
1456 * works slightly differently. */
1457 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1458# ifdef USE_ICONV
1459 || iconv_fd != (iconv_t)-1
1460# endif
1461 ))
1462 {
1463 while (conv_restlen > 0)
1464 {
1465 *(--ptr) = bad_char_behavior;
1466 --conv_restlen;
1467 }
1468 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001469 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001470# ifdef USE_ICONV
1471 if (iconv_fd != (iconv_t)-1)
1472 {
1473 iconv_close(iconv_fd);
1474 iconv_fd = (iconv_t)-1;
1475 }
1476# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001477 }
1478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479#endif
1480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 }
1482 skip_read = FALSE;
1483
1484#ifdef FEAT_MBYTE
1485 /*
1486 * At start of file (or after crypt magic number): Check for BOM.
1487 * Also check for a BOM for other Unicode encodings, but not after
1488 * converting with 'charconvert' or when a BOM has already been
1489 * found.
1490 */
1491 if ((filesize == 0
1492# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001493 || (cryptkey != NULL
1494 && filesize == crypt_get_header_len(
1495 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496# endif
1497 )
1498 && (fio_flags == FIO_UCSBOM
1499 || (!curbuf->b_p_bomb
1500 && tmpname == NULL
1501 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1502 {
1503 char_u *ccname;
1504 int blen;
1505
1506 /* no BOM detection in a short file or in binary mode */
1507 if (size < 2 || curbuf->b_p_bin)
1508 ccname = NULL;
1509 else
1510 ccname = check_for_bom(ptr, size, &blen,
1511 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1512 if (ccname != NULL)
1513 {
1514 /* Remove BOM from the text */
1515 filesize += blen;
1516 size -= blen;
1517 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001518 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001519 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001521 curbuf->b_start_bomb = TRUE;
1522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 }
1524
1525 if (fio_flags == FIO_UCSBOM)
1526 {
1527 if (ccname == NULL)
1528 {
1529 /* No BOM detected: retry with next encoding. */
1530 advance_fenc = TRUE;
1531 }
1532 else
1533 {
1534 /* BOM detected: set "fenc" and jump back */
1535 if (fenc_alloced)
1536 vim_free(fenc);
1537 fenc = ccname;
1538 fenc_alloced = FALSE;
1539 }
1540 /* retry reading without getting new bytes or rewinding */
1541 skip_read = TRUE;
1542 goto retry;
1543 }
1544 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001545
1546 /* Include not converted bytes. */
1547 ptr -= conv_restlen;
1548 size += conv_restlen;
1549 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550#endif
1551 /*
1552 * Break here for a read error or end-of-file.
1553 */
1554 if (size <= 0)
1555 break;
1556
1557#ifdef FEAT_MBYTE
1558
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559# ifdef USE_ICONV
1560 if (iconv_fd != (iconv_t)-1)
1561 {
1562 /*
1563 * Attempt conversion of the read bytes to 'encoding' using
1564 * iconv().
1565 */
1566 const char *fromp;
1567 char *top;
1568 size_t from_size;
1569 size_t to_size;
1570
1571 fromp = (char *)ptr;
1572 from_size = size;
1573 ptr += size;
1574 top = (char *)ptr;
1575 to_size = real_size - size;
1576
1577 /*
1578 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001579 * another conversion. Except for when there is no
1580 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001582 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1583 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1585 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001586 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001587 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001588 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001589 if (conv_error == 0)
1590 conv_error = readfile_linenr(linecnt,
1591 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001592
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001593 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001594 ++fromp;
1595 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001596 if (bad_char_behavior == BAD_KEEP)
1597 {
1598 *top++ = *(fromp - 1);
1599 --to_size;
1600 }
1601 else if (bad_char_behavior != BAD_DROP)
1602 {
1603 *top++ = bad_char_behavior;
1604 --to_size;
1605 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001606 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607
1608 if (from_size > 0)
1609 {
1610 /* Some remaining characters, keep them for the next
1611 * round. */
1612 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1613 conv_restlen = (int)from_size;
1614 }
1615
1616 /* move the linerest to before the converted characters */
1617 line_start = ptr - linerest;
1618 mch_memmove(line_start, buffer, (size_t)linerest);
1619 size = (long)((char_u *)top - ptr);
1620 }
1621# endif
1622
1623# ifdef WIN3264
1624 if (fio_flags & FIO_CODEPAGE)
1625 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001627 WCHAR ucs2buf[3];
1628 int ucs2len;
1629 int codepage = FIO_GET_CP(fio_flags);
1630 int bytelen;
1631 int found_bad;
1632 char replstr[2];
1633
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634 /*
1635 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 * a codepage, using standard MS-Windows functions. This
1637 * requires two steps:
1638 * 1. convert from 'fileencoding' to ucs-2
1639 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 * Because there may be illegal bytes AND an incomplete byte
1642 * sequence at the end, we may have to do the conversion one
1643 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001646 /* Replacement string for WideCharToMultiByte(). */
1647 if (bad_char_behavior > 0)
1648 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001650 replstr[0] = '?';
1651 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001654 * Move the bytes to the end of the buffer, so that we have
1655 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001657 src = ptr + real_size - size;
1658 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001660 /*
1661 * Do the conversion.
1662 */
1663 dst = ptr;
1664 size = size;
1665 while (size > 0)
1666 {
1667 found_bad = FALSE;
1668
1669# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1670 if (codepage == CP_UTF8)
1671 {
1672 /* Handle CP_UTF8 input ourselves to be able to handle
1673 * trailing bytes properly.
1674 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001675 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001676 if (bytelen > size)
1677 {
1678 /* Only got some bytes of a character. Normally
1679 * it's put in "conv_rest", but if it's too long
1680 * deal with it as if they were illegal bytes. */
1681 if (bytelen <= CONV_RESTLEN)
1682 break;
1683
1684 /* weird overlong byte sequence */
1685 bytelen = size;
1686 found_bad = TRUE;
1687 }
1688 else
1689 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001690 int u8c = utf_ptr2char(src);
1691
Bram Moolenaar86e01082005-12-29 22:45:34 +00001692 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001693 found_bad = TRUE;
1694 ucs2buf[0] = u8c;
1695 ucs2len = 1;
1696 }
1697 }
1698 else
1699# endif
1700 {
1701 /* We don't know how long the byte sequence is, try
1702 * from one to three bytes. */
1703 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1704 ++bytelen)
1705 {
1706 ucs2len = MultiByteToWideChar(codepage,
1707 MB_ERR_INVALID_CHARS,
1708 (LPCSTR)src, bytelen,
1709 ucs2buf, 3);
1710 if (ucs2len > 0)
1711 break;
1712 }
1713 if (ucs2len == 0)
1714 {
1715 /* If we have only one byte then it's probably an
1716 * incomplete byte sequence. Otherwise discard
1717 * one byte as a bad character. */
1718 if (size == 1)
1719 break;
1720 found_bad = TRUE;
1721 bytelen = 1;
1722 }
1723 }
1724
1725 if (!found_bad)
1726 {
1727 int i;
1728
1729 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1730 if (enc_utf8)
1731 {
1732 /* From UCS-2 to UTF-8. Cannot fail. */
1733 for (i = 0; i < ucs2len; ++i)
1734 dst += utf_char2bytes(ucs2buf[i], dst);
1735 }
1736 else
1737 {
1738 BOOL bad = FALSE;
1739 int dstlen;
1740
1741 /* From UCS-2 to "enc_codepage". If the
1742 * conversion uses the default character "?",
1743 * the data doesn't fit in this encoding. */
1744 dstlen = WideCharToMultiByte(enc_codepage, 0,
1745 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001746 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001747 replstr, &bad);
1748 if (bad)
1749 found_bad = TRUE;
1750 else
1751 dst += dstlen;
1752 }
1753 }
1754
1755 if (found_bad)
1756 {
1757 /* Deal with bytes we can't convert. */
1758 if (can_retry)
1759 goto rewind_retry;
1760 if (conv_error == 0)
1761 conv_error = readfile_linenr(linecnt, ptr, dst);
1762 if (bad_char_behavior != BAD_DROP)
1763 {
1764 if (bad_char_behavior == BAD_KEEP)
1765 {
1766 mch_memmove(dst, src, bytelen);
1767 dst += bytelen;
1768 }
1769 else
1770 *dst++ = bad_char_behavior;
1771 }
1772 }
1773
1774 src += bytelen;
1775 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001777
1778 if (size > 0)
1779 {
1780 /* An incomplete byte sequence remaining. */
1781 mch_memmove(conv_rest, src, size);
1782 conv_restlen = size;
1783 }
1784
1785 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001786 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787 }
1788 else
1789# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001790# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 if (fio_flags & FIO_MACROMAN)
1792 {
1793 /*
1794 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001795 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001797 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
1800 else
1801# endif
1802 if (fio_flags != 0)
1803 {
1804 int u8c;
1805 char_u *dest;
1806 char_u *tail = NULL;
1807
1808 /*
1809 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1810 * "enc_utf8" not set: Convert Unicode to Latin1.
1811 * Go from end to start through the buffer, because the number
1812 * of bytes may increase.
1813 * "dest" points to after where the UTF-8 bytes go, "p" points
1814 * to after the next character to convert.
1815 */
1816 dest = ptr + real_size;
1817 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1818 {
1819 p = ptr + size;
1820 if (fio_flags == FIO_UTF8)
1821 {
1822 /* Check for a trailing incomplete UTF-8 sequence */
1823 tail = ptr + size - 1;
1824 while (tail > ptr && (*tail & 0xc0) == 0x80)
1825 --tail;
1826 if (tail + utf_byte2len(*tail) <= ptr + size)
1827 tail = NULL;
1828 else
1829 p = tail;
1830 }
1831 }
1832 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1833 {
1834 /* Check for a trailing byte */
1835 p = ptr + (size & ~1);
1836 if (size & 1)
1837 tail = p;
1838 if ((fio_flags & FIO_UTF16) && p > ptr)
1839 {
1840 /* Check for a trailing leading word */
1841 if (fio_flags & FIO_ENDIAN_L)
1842 {
1843 u8c = (*--p << 8);
1844 u8c += *--p;
1845 }
1846 else
1847 {
1848 u8c = *--p;
1849 u8c += (*--p << 8);
1850 }
1851 if (u8c >= 0xd800 && u8c <= 0xdbff)
1852 tail = p;
1853 else
1854 p += 2;
1855 }
1856 }
1857 else /* FIO_UCS4 */
1858 {
1859 /* Check for trailing 1, 2 or 3 bytes */
1860 p = ptr + (size & ~3);
1861 if (size & 3)
1862 tail = p;
1863 }
1864
1865 /* If there is a trailing incomplete sequence move it to
1866 * conv_rest[]. */
1867 if (tail != NULL)
1868 {
1869 conv_restlen = (int)((ptr + size) - tail);
1870 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1871 size -= conv_restlen;
1872 }
1873
1874
1875 while (p > ptr)
1876 {
1877 if (fio_flags & FIO_LATIN1)
1878 u8c = *--p;
1879 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1880 {
1881 if (fio_flags & FIO_ENDIAN_L)
1882 {
1883 u8c = (*--p << 8);
1884 u8c += *--p;
1885 }
1886 else
1887 {
1888 u8c = *--p;
1889 u8c += (*--p << 8);
1890 }
1891 if ((fio_flags & FIO_UTF16)
1892 && u8c >= 0xdc00 && u8c <= 0xdfff)
1893 {
1894 int u16c;
1895
1896 if (p == ptr)
1897 {
1898 /* Missing leading word. */
1899 if (can_retry)
1900 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001901 if (conv_error == 0)
1902 conv_error = readfile_linenr(linecnt,
1903 ptr, p);
1904 if (bad_char_behavior == BAD_DROP)
1905 continue;
1906 if (bad_char_behavior != BAD_KEEP)
1907 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
1909
1910 /* found second word of double-word, get the first
1911 * word and compute the resulting character */
1912 if (fio_flags & FIO_ENDIAN_L)
1913 {
1914 u16c = (*--p << 8);
1915 u16c += *--p;
1916 }
1917 else
1918 {
1919 u16c = *--p;
1920 u16c += (*--p << 8);
1921 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001922 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1923 + (u8c & 0x3ff);
1924
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 /* Check if the word is indeed a leading word. */
1926 if (u16c < 0xd800 || u16c > 0xdbff)
1927 {
1928 if (can_retry)
1929 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001930 if (conv_error == 0)
1931 conv_error = readfile_linenr(linecnt,
1932 ptr, p);
1933 if (bad_char_behavior == BAD_DROP)
1934 continue;
1935 if (bad_char_behavior != BAD_KEEP)
1936 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939 }
1940 else if (fio_flags & FIO_UCS4)
1941 {
1942 if (fio_flags & FIO_ENDIAN_L)
1943 {
1944 u8c = (*--p << 24);
1945 u8c += (*--p << 16);
1946 u8c += (*--p << 8);
1947 u8c += *--p;
1948 }
1949 else /* big endian */
1950 {
1951 u8c = *--p;
1952 u8c += (*--p << 8);
1953 u8c += (*--p << 16);
1954 u8c += (*--p << 24);
1955 }
1956 }
1957 else /* UTF-8 */
1958 {
1959 if (*--p < 0x80)
1960 u8c = *p;
1961 else
1962 {
1963 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001964 p -= len;
1965 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 if (len == 0)
1967 {
1968 /* Not a valid UTF-8 character, retry with
1969 * another fenc when possible, otherwise just
1970 * report the error. */
1971 if (can_retry)
1972 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001973 if (conv_error == 0)
1974 conv_error = readfile_linenr(linecnt,
1975 ptr, p);
1976 if (bad_char_behavior == BAD_DROP)
1977 continue;
1978 if (bad_char_behavior != BAD_KEEP)
1979 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 }
1982 }
1983 if (enc_utf8) /* produce UTF-8 */
1984 {
1985 dest -= utf_char2len(u8c);
1986 (void)utf_char2bytes(u8c, dest);
1987 }
1988 else /* produce Latin1 */
1989 {
1990 --dest;
1991 if (u8c >= 0x100)
1992 {
1993 /* character doesn't fit in latin1, retry with
1994 * another fenc when possible, otherwise just
1995 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001996 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001998 if (conv_error == 0)
1999 conv_error = readfile_linenr(linecnt, ptr, p);
2000 if (bad_char_behavior == BAD_DROP)
2001 ++dest;
2002 else if (bad_char_behavior == BAD_KEEP)
2003 *dest = u8c;
2004 else if (eap != NULL && eap->bad_char != 0)
2005 *dest = bad_char_behavior;
2006 else
2007 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 }
2009 else
2010 *dest = u8c;
2011 }
2012 }
2013
2014 /* move the linerest to before the converted characters */
2015 line_start = dest - linerest;
2016 mch_memmove(line_start, buffer, (size_t)linerest);
2017 size = (long)((ptr + real_size) - dest);
2018 ptr = dest;
2019 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002020 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002022 int incomplete_tail = FALSE;
2023
2024 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2025 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002027 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028 int l;
2029
2030 if (todo <= 0)
2031 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 if (*p >= 0x80)
2033 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 /* A length of 1 means it's an illegal byte. Accept
2035 * an incomplete character at the end though, the next
2036 * read() will get the next bytes, we'll check it
2037 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002038 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002039 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002041 /* Avoid retrying with a different encoding when
2042 * a truncated file is more likely, or attempting
2043 * to read the rest of an incomplete sequence when
2044 * we have already done so. */
2045 if (p > ptr || filesize > 0)
2046 incomplete_tail = TRUE;
2047 /* Incomplete byte sequence, move it to conv_rest[]
2048 * and try to read the rest of it, unless we've
2049 * already done so. */
2050 if (p > ptr)
2051 {
2052 conv_restlen = todo;
2053 mch_memmove(conv_rest, p, conv_restlen);
2054 size -= conv_restlen;
2055 break;
2056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002058 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002059 {
2060 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002061 * do that, unless at EOF where a truncated
2062 * file is more likely than a conversion error. */
2063 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002064 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002065# ifdef USE_ICONV
2066 /* When we did a conversion report an error. */
2067 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2068 conv_error = readfile_linenr(linecnt, ptr, p);
2069# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002070 /* Remember the first linenr with an illegal byte */
2071 if (conv_error == 0 && illegal_byte == 0)
2072 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002073
2074 /* Drop, keep or replace the bad byte. */
2075 if (bad_char_behavior == BAD_DROP)
2076 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002077 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 --p;
2079 --size;
2080 }
2081 else if (bad_char_behavior != BAD_KEEP)
2082 *p = bad_char_behavior;
2083 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002084 else
2085 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 }
2087 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002088 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 {
2090 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002092 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002094 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2095 /* iconv() failed, try 'charconvert' */
2096 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 else
2098# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002099 /* use next item from 'fileencodings' */
2100 advance_fenc = TRUE;
2101 file_rewind = TRUE;
2102 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 }
2104 }
2105#endif
2106
2107 /* count the number of characters (after conversion!) */
2108 filesize += size;
2109
2110 /*
2111 * when reading the first part of a file: guess EOL type
2112 */
2113 if (fileformat == EOL_UNKNOWN)
2114 {
2115 /* First try finding a NL, for Dos and Unix */
2116 if (try_dos || try_unix)
2117 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002118 /* Reset the carriage return counter. */
2119 if (try_mac)
2120 try_mac = 1;
2121
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122 for (p = ptr; p < ptr + size; ++p)
2123 {
2124 if (*p == NL)
2125 {
2126 if (!try_unix
2127 || (try_dos && p > ptr && p[-1] == CAR))
2128 fileformat = EOL_DOS;
2129 else
2130 fileformat = EOL_UNIX;
2131 break;
2132 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002133 else if (*p == CAR && try_mac)
2134 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 }
2136
2137 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2138 if (fileformat == EOL_UNIX && try_mac)
2139 {
2140 /* Need to reset the counters when retrying fenc. */
2141 try_mac = 1;
2142 try_unix = 1;
2143 for (; p >= ptr && *p != CAR; p--)
2144 ;
2145 if (p >= ptr)
2146 {
2147 for (p = ptr; p < ptr + size; ++p)
2148 {
2149 if (*p == NL)
2150 try_unix++;
2151 else if (*p == CAR)
2152 try_mac++;
2153 }
2154 if (try_mac > try_unix)
2155 fileformat = EOL_MAC;
2156 }
2157 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002158 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2159 /* Looking for CR but found no end-of-line markers at
2160 * all: use the default format. */
2161 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 }
2163
2164 /* No NL found: may use Mac format */
2165 if (fileformat == EOL_UNKNOWN && try_mac)
2166 fileformat = EOL_MAC;
2167
2168 /* Still nothing found? Use first format in 'ffs' */
2169 if (fileformat == EOL_UNKNOWN)
2170 fileformat = default_fileformat();
2171
2172 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002173 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 set_fileformat(fileformat, OPT_LOCAL);
2175 }
2176 }
2177
2178 /*
2179 * This loop is executed once for every character read.
2180 * Keep it fast!
2181 */
2182 if (fileformat == EOL_MAC)
2183 {
2184 --ptr;
2185 while (++ptr, --size >= 0)
2186 {
2187 /* catch most common case first */
2188 if ((c = *ptr) != NUL && c != CAR && c != NL)
2189 continue;
2190 if (c == NUL)
2191 *ptr = NL; /* NULs are replaced by newlines! */
2192 else if (c == NL)
2193 *ptr = CAR; /* NLs are replaced by CRs! */
2194 else
2195 {
2196 if (skip_count == 0)
2197 {
2198 *ptr = NUL; /* end of line */
2199 len = (colnr_T) (ptr - line_start + 1);
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 else
2224 {
2225 --ptr;
2226 while (++ptr, --size >= 0)
2227 {
2228 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2229 continue;
2230 if (c == NUL)
2231 *ptr = NL; /* NULs are replaced by newlines! */
2232 else
2233 {
2234 if (skip_count == 0)
2235 {
2236 *ptr = NUL; /* end of line */
2237 len = (colnr_T)(ptr - line_start + 1);
2238 if (fileformat == EOL_DOS)
2239 {
2240 if (ptr[-1] == CAR) /* remove CR */
2241 {
2242 ptr[-1] = NUL;
2243 --len;
2244 }
2245 /*
2246 * Reading in Dos format, but no CR-LF found!
2247 * When 'fileformats' includes "unix", delete all
2248 * the lines read so far and start all over again.
2249 * Otherwise give an error message later.
2250 */
2251 else if (ff_error != EOL_DOS)
2252 {
2253 if ( try_unix
2254 && !read_stdin
2255 && (read_buffer
2256 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2257 {
2258 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002259 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 set_fileformat(EOL_UNIX, OPT_LOCAL);
2261 file_rewind = TRUE;
2262 keep_fileformat = TRUE;
2263 goto retry;
2264 }
2265 ff_error = EOL_DOS;
2266 }
2267 }
2268 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2269 {
2270 error = TRUE;
2271 break;
2272 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002273#ifdef FEAT_PERSISTENT_UNDO
2274 if (read_undo_file)
2275 sha256_update(&sha_ctx, line_start, len);
2276#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 ++lnum;
2278 if (--read_count == 0)
2279 {
2280 error = TRUE; /* break loop */
2281 line_start = ptr; /* nothing left to write */
2282 break;
2283 }
2284 }
2285 else
2286 --skip_count;
2287 line_start = ptr + 1;
2288 }
2289 }
2290 }
2291 linerest = (long)(ptr - line_start);
2292 ui_breakcheck();
2293 }
2294
2295failed:
2296 /* not an error, max. number of lines reached */
2297 if (error && read_count == 0)
2298 error = FALSE;
2299
2300 /*
2301 * If we get EOF in the middle of a line, note the fact and
2302 * complete the line ourselves.
2303 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2304 */
2305 if (!error
2306 && !got_int
2307 && linerest != 0
2308 && !(!curbuf->b_p_bin
2309 && fileformat == EOL_DOS
2310 && *line_start == Ctrl_Z
2311 && ptr == line_start + 1))
2312 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002313 /* remember for when writing */
2314 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 curbuf->b_p_eol = FALSE;
2316 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002317 len = (colnr_T)(ptr - line_start + 1);
2318 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 error = TRUE;
2320 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002321 {
2322#ifdef FEAT_PERSISTENT_UNDO
2323 if (read_undo_file)
2324 sha256_update(&sha_ctx, line_start, len);
2325#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002327 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 }
2329
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002330 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 save_file_ff(curbuf); /* remember the current file format */
2332
2333#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002334 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002335 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002336 crypt_free_state(curbuf->b_cryptstate);
2337 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002338 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002339 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2340 crypt_free_key(cryptkey);
2341 /* Don't set cryptkey to NULL, it's used below as a flag that
2342 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343#endif
2344
2345#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002346 /* If editing a new file: set 'fenc' for the current buffer.
2347 * Also for ":read ++edit file". */
2348 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002350 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 if (fenc_alloced)
2352 vim_free(fenc);
2353# ifdef USE_ICONV
2354 if (iconv_fd != (iconv_t)-1)
2355 {
2356 iconv_close(iconv_fd);
2357 iconv_fd = (iconv_t)-1;
2358 }
2359# endif
2360#endif
2361
2362 if (!read_buffer && !read_stdin)
2363 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002364#ifdef HAVE_FD_CLOEXEC
2365 else
2366 {
2367 int fdflags = fcntl(fd, F_GETFD);
2368 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002369 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002370 }
2371#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 vim_free(buffer);
2373
2374#ifdef HAVE_DUP
2375 if (read_stdin)
2376 {
2377 /* Use stderr for stdin, makes shell commands work. */
2378 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002379 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 }
2381#endif
2382
2383#ifdef FEAT_MBYTE
2384 if (tmpname != NULL)
2385 {
2386 mch_remove(tmpname); /* delete converted file */
2387 vim_free(tmpname);
2388 }
2389#endif
2390 --no_wait_return; /* may wait for return now */
2391
2392 /*
2393 * In recovery mode everything but autocommands is skipped.
2394 */
2395 if (!recoverymode)
2396 {
2397 /* need to delete the last line, which comes from the empty buffer */
2398 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2399 {
2400#ifdef FEAT_NETBEANS_INTG
2401 netbeansFireChanges = 0;
2402#endif
2403 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2404#ifdef FEAT_NETBEANS_INTG
2405 netbeansFireChanges = 1;
2406#endif
2407 --linecnt;
2408 }
2409 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2410 if (filesize == 0)
2411 linecnt = 0;
2412 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002413 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002415#ifdef FEAT_DIFF
2416 /* After reading the text into the buffer the diff info needs to
2417 * be updated. */
2418 diff_invalidate(curbuf);
2419#endif
2420#ifdef FEAT_FOLDING
2421 /* All folds in the window are invalid now. Mark them for update
2422 * before triggering autocommands. */
2423 foldUpdateAll(curwin);
2424#endif
2425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 else if (linecnt) /* appended at least one line */
2427 appended_lines_mark(from, linecnt);
2428
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429#ifndef ALWAYS_USE_GUI
2430 /*
2431 * If we were reading from the same terminal as where messages go,
2432 * the screen will have been messed up.
2433 * Switch on raw mode now and clear the screen.
2434 */
2435 if (read_stdin)
2436 {
2437 settmode(TMODE_RAW); /* set to raw mode */
2438 starttermcap();
2439 screenclear();
2440 }
2441#endif
2442
2443 if (got_int)
2444 {
2445 if (!(flags & READ_DUMMY))
2446 {
2447 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2448 if (newfile)
2449 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2450 }
2451 msg_scroll = msg_save;
2452#ifdef FEAT_VIMINFO
2453 check_marks_read();
2454#endif
2455 return OK; /* an interrupt isn't really an error */
2456 }
2457
2458 if (!filtering && !(flags & READ_DUMMY))
2459 {
2460 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2461 c = FALSE;
2462
2463#ifdef UNIX
2464# ifdef S_ISFIFO
2465 if (S_ISFIFO(perm)) /* fifo or socket */
2466 {
2467 STRCAT(IObuff, _("[fifo/socket]"));
2468 c = TRUE;
2469 }
2470# else
2471# ifdef S_IFIFO
2472 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2473 {
2474 STRCAT(IObuff, _("[fifo]"));
2475 c = TRUE;
2476 }
2477# endif
2478# ifdef S_IFSOCK
2479 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2480 {
2481 STRCAT(IObuff, _("[socket]"));
2482 c = TRUE;
2483 }
2484# endif
2485# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002486# ifdef OPEN_CHR_FILES
2487 if (S_ISCHR(perm)) /* or character special */
2488 {
2489 STRCAT(IObuff, _("[character special]"));
2490 c = TRUE;
2491 }
2492# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493#endif
2494 if (curbuf->b_p_ro)
2495 {
2496 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2497 c = TRUE;
2498 }
2499 if (read_no_eol_lnum)
2500 {
2501 msg_add_eol();
2502 c = TRUE;
2503 }
2504 if (ff_error == EOL_DOS)
2505 {
2506 STRCAT(IObuff, _("[CR missing]"));
2507 c = TRUE;
2508 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 if (split)
2510 {
2511 STRCAT(IObuff, _("[long lines split]"));
2512 c = TRUE;
2513 }
2514#ifdef FEAT_MBYTE
2515 if (notconverted)
2516 {
2517 STRCAT(IObuff, _("[NOT converted]"));
2518 c = TRUE;
2519 }
2520 else if (converted)
2521 {
2522 STRCAT(IObuff, _("[converted]"));
2523 c = TRUE;
2524 }
2525#endif
2526#ifdef FEAT_CRYPT
2527 if (cryptkey != NULL)
2528 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002529 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 c = TRUE;
2531 }
2532#endif
2533#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002534 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002536 sprintf((char *)IObuff + STRLEN(IObuff),
2537 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538 c = TRUE;
2539 }
2540 else if (illegal_byte > 0)
2541 {
2542 sprintf((char *)IObuff + STRLEN(IObuff),
2543 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2544 c = TRUE;
2545 }
2546 else
2547#endif
2548 if (error)
2549 {
2550 STRCAT(IObuff, _("[READ ERRORS]"));
2551 c = TRUE;
2552 }
2553 if (msg_add_fileformat(fileformat))
2554 c = TRUE;
2555#ifdef FEAT_CRYPT
2556 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002557 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002558 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 else
2560#endif
2561 msg_add_lines(c, (long)linecnt, filesize);
2562
2563 vim_free(keep_msg);
2564 keep_msg = NULL;
2565 msg_scrolled_ign = TRUE;
2566#ifdef ALWAYS_USE_GUI
2567 /* Don't show the message when reading stdin, it would end up in a
2568 * message box (which might be shown when exiting!) */
2569 if (read_stdin || read_buffer)
2570 p = msg_may_trunc(FALSE, IObuff);
2571 else
2572#endif
2573 p = msg_trunc_attr(IObuff, FALSE, 0);
2574 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002575 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 /* Need to repeat the message after redrawing when:
2577 * - When reading from stdin (the screen will be cleared next).
2578 * - When restart_edit is set (otherwise there will be a delay
2579 * before redrawing).
2580 * - When the screen was scrolled but there is no wait-return
2581 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002582 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 msg_scrolled_ign = FALSE;
2584 }
2585
2586 /* with errors writing the file requires ":w!" */
2587 if (newfile && (error
2588#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002589 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002590 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591#endif
2592 ))
2593 curbuf->b_p_ro = TRUE;
2594
2595 u_clearline(); /* cannot use "U" command after adding lines */
2596
2597 /*
2598 * In Ex mode: cursor at last new line.
2599 * Otherwise: cursor at first new line.
2600 */
2601 if (exmode_active)
2602 curwin->w_cursor.lnum = from + linecnt;
2603 else
2604 curwin->w_cursor.lnum = from + 1;
2605 check_cursor_lnum();
2606 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2607
2608 /*
2609 * Set '[ and '] marks to the newly read lines.
2610 */
2611 curbuf->b_op_start.lnum = from + 1;
2612 curbuf->b_op_start.col = 0;
2613 curbuf->b_op_end.lnum = from + linecnt;
2614 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002615
2616#ifdef WIN32
2617 /*
2618 * Work around a weird problem: When a file has two links (only
2619 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002620 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002621 * It's correct again after reading the file, thus reset the timestamp
2622 * here.
2623 */
2624 if (newfile && !read_stdin && !read_buffer
2625 && mch_stat((char *)fname, &st) >= 0)
2626 {
2627 buf_store_time(curbuf, &st, fname);
2628 curbuf->b_mtime_read = curbuf->b_mtime;
2629 }
2630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 }
2632 msg_scroll = msg_save;
2633
2634#ifdef FEAT_VIMINFO
2635 /*
2636 * Get the marks before executing autocommands, so they can be used there.
2637 */
2638 check_marks_read();
2639#endif
2640
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002642 * We remember if the last line of the read didn't have
2643 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2644 * or writing the read again with 'binary' on. The latter is required
2645 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002647 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002649 /* When reloading a buffer put the cursor at the first line that is
2650 * different. */
2651 if (flags & READ_KEEP_UNDO)
2652 u_find_first_changed();
2653
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002654#ifdef FEAT_PERSISTENT_UNDO
2655 /*
2656 * When opening a new file locate undo info and read it.
2657 */
2658 if (read_undo_file)
2659 {
2660 char_u hash[UNDO_HASH_SIZE];
2661
2662 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002663 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002664 }
2665#endif
2666
Bram Moolenaardf177f62005-02-22 08:39:57 +00002667#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 if (!read_stdin && !read_buffer)
2669 {
2670 int m = msg_scroll;
2671 int n = msg_scrolled;
2672
2673 /* Save the fileformat now, otherwise the buffer will be considered
2674 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002675 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676 save_file_ff(curbuf);
2677
2678 /*
2679 * The output from the autocommands should not overwrite anything and
2680 * should not be overwritten: Set msg_scroll, restore its value if no
2681 * output was done.
2682 */
2683 msg_scroll = TRUE;
2684 if (filtering)
2685 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2686 FALSE, curbuf, eap);
2687 else if (newfile)
Bram Moolenaarc3691332016-04-20 12:49:49 +02002688 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2690 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002691 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2692 /*
2693 * EVENT_FILETYPE was not triggered but the buffer already has a
2694 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2695 */
2696 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2697 TRUE, curbuf);
2698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 else
2700 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2701 FALSE, NULL, eap);
2702 if (msg_scrolled == n)
2703 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002704# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705 if (aborting()) /* autocmds may abort script processing */
2706 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002707# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 }
2709#endif
2710
2711 if (recoverymode && error)
2712 return FAIL;
2713 return OK;
2714}
2715
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002716#ifdef OPEN_CHR_FILES
2717/*
2718 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2719 * which is the name of files used for process substitution output by
2720 * some shells on some operating systems, e.g., bash on SunOS.
2721 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2722 */
2723 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002724is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002725{
2726 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2727 && VIM_ISDIGIT(fname[8])
2728 && *skipdigits(fname + 9) == NUL
2729 && (fname[9] != NUL
2730 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2731}
2732#endif
2733
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002734#ifdef FEAT_MBYTE
2735
2736/*
2737 * From the current line count and characters read after that, estimate the
2738 * line number where we are now.
2739 * Used for error messages that include a line number.
2740 */
2741 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002742readfile_linenr(
2743 linenr_T linecnt, /* line count before reading more bytes */
2744 char_u *p, /* start of more bytes read */
2745 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002746{
2747 char_u *s;
2748 linenr_T lnum;
2749
2750 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2751 for (s = p; s < endp; ++s)
2752 if (*s == '\n')
2753 ++lnum;
2754 return lnum;
2755}
2756#endif
2757
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002759 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2760 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 * Returns OK or FAIL.
2762 */
2763 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002764prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765{
2766 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2767#ifdef FEAT_MBYTE
2768 + STRLEN(buf->b_p_fenc)
2769#endif
2770 + 15));
2771 if (eap->cmd == NULL)
2772 return FAIL;
2773
2774#ifdef FEAT_MBYTE
2775 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2776 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002777 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778#else
2779 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2780#endif
2781 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002782
2783 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002784 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002785 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 return OK;
2787}
2788
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002789/*
2790 * Set default or forced 'fileformat' and 'binary'.
2791 */
2792 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002793set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002794{
2795 /* set default 'fileformat' */
2796 if (set_options)
2797 {
2798 if (eap != NULL && eap->force_ff != 0)
2799 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2800 else if (*p_ffs != NUL)
2801 set_fileformat(default_fileformat(), OPT_LOCAL);
2802 }
2803
2804 /* set or reset 'binary' */
2805 if (eap != NULL && eap->force_bin != 0)
2806 {
2807 int oldval = curbuf->b_p_bin;
2808
2809 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2810 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2811 }
2812}
2813
2814#if defined(FEAT_MBYTE) || defined(PROTO)
2815/*
2816 * Set forced 'fileencoding'.
2817 */
2818 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002819set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002820{
2821 if (eap->force_enc != 0)
2822 {
2823 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2824
2825 if (fenc != NULL)
2826 set_string_option_direct((char_u *)"fenc", -1,
2827 fenc, OPT_FREE|OPT_LOCAL, 0);
2828 vim_free(fenc);
2829 }
2830}
2831
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832/*
2833 * Find next fileencoding to use from 'fileencodings'.
2834 * "pp" points to fenc_next. It's advanced to the next item.
2835 * When there are no more items, an empty string is returned and *pp is set to
2836 * NULL.
2837 * When *pp is not set to NULL, the result is in allocated memory.
2838 */
2839 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002840next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841{
2842 char_u *p;
2843 char_u *r;
2844
2845 if (**pp == NUL)
2846 {
2847 *pp = NULL;
2848 return (char_u *)"";
2849 }
2850 p = vim_strchr(*pp, ',');
2851 if (p == NULL)
2852 {
2853 r = enc_canonize(*pp);
2854 *pp += STRLEN(*pp);
2855 }
2856 else
2857 {
2858 r = vim_strnsave(*pp, (int)(p - *pp));
2859 *pp = p + 1;
2860 if (r != NULL)
2861 {
2862 p = enc_canonize(r);
2863 vim_free(r);
2864 r = p;
2865 }
2866 }
2867 if (r == NULL) /* out of memory */
2868 {
2869 r = (char_u *)"";
2870 *pp = NULL;
2871 }
2872 return r;
2873}
2874
2875# ifdef FEAT_EVAL
2876/*
2877 * Convert a file with the 'charconvert' expression.
2878 * This closes the file which is to be read, converts it and opens the
2879 * resulting file for reading.
2880 * Returns name of the resulting converted file (the caller should delete it
2881 * after reading it).
2882 * Returns NULL if the conversion failed ("*fdp" is not set) .
2883 */
2884 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002885readfile_charconvert(
2886 char_u *fname, /* name of input file */
2887 char_u *fenc, /* converted from */
2888 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889{
2890 char_u *tmpname;
2891 char_u *errmsg = NULL;
2892
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002893 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894 if (tmpname == NULL)
2895 errmsg = (char_u *)_("Can't find temp file for conversion");
2896 else
2897 {
2898 close(*fdp); /* close the input file, ignore errors */
2899 *fdp = -1;
2900 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2901 fname, tmpname) == FAIL)
2902 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2903 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2904 O_RDONLY | O_EXTRA, 0)) < 0)
2905 errmsg = (char_u *)_("can't read output of 'charconvert'");
2906 }
2907
2908 if (errmsg != NULL)
2909 {
2910 /* Don't use emsg(), it breaks mappings, the retry with
2911 * another type of conversion might still work. */
2912 MSG(errmsg);
2913 if (tmpname != NULL)
2914 {
2915 mch_remove(tmpname); /* delete converted file */
2916 vim_free(tmpname);
2917 tmpname = NULL;
2918 }
2919 }
2920
2921 /* If the input file is closed, open it (caller should check for error). */
2922 if (*fdp < 0)
2923 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2924
2925 return tmpname;
2926}
2927# endif
2928
2929#endif
2930
2931#ifdef FEAT_VIMINFO
2932/*
2933 * Read marks for the current buffer from the viminfo file, when we support
2934 * buffer marks and the buffer has a name.
2935 */
2936 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002937check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938{
2939 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2940 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002941 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942
2943 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2944 * the ' parameter after opening a buffer. */
2945 curbuf->b_marks_read = TRUE;
2946}
2947#endif
2948
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002949#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002951 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2953 * *filesizep are updated.
2954 * Return the (new) encryption key, NULL for no encryption.
2955 */
2956 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002957check_for_cryptkey(
2958 char_u *cryptkey, /* previous encryption key or NULL */
2959 char_u *ptr, /* pointer to read bytes */
2960 long *sizep, /* length of read bytes */
2961 off_t *filesizep, /* nr of bytes used from file */
2962 int newfile, /* editing a new buffer */
2963 char_u *fname, /* file name to display */
2964 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002966 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002967 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002968
2969 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002971 /* Mark the buffer as read-only until the decryption has taken place.
2972 * Avoids accidentally overwriting the file with garbage. */
2973 curbuf->b_p_ro = TRUE;
2974
Bram Moolenaar2be79502014-08-13 21:58:28 +02002975 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002976 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002977 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 {
2979 if (*curbuf->b_p_key)
2980 cryptkey = curbuf->b_p_key;
2981 else
2982 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002983 /* When newfile is TRUE, store the typed key in the 'key'
2984 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002985 * Don't ask for the key again when first time Enter was hit.
2986 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002987 smsg((char_u *)_(need_key_msg), fname);
2988 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002989 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002990 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002991 *did_ask = TRUE;
2992
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 /* check if empty key entered */
2994 if (cryptkey != NULL && *cryptkey == NUL)
2995 {
2996 if (cryptkey != curbuf->b_p_key)
2997 vim_free(cryptkey);
2998 cryptkey = NULL;
2999 }
3000 }
3001 }
3002
3003 if (cryptkey != NULL)
3004 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003005 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003006
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003007 curbuf->b_cryptstate = crypt_create_from_header(
3008 method, cryptkey, ptr);
3009 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003011 /* Remove cryptmethod specific header from the text. */
3012 header_len = crypt_get_header_len(method);
3013 *filesizep += header_len;
3014 *sizep -= header_len;
3015 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3016
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003017 /* Restore the read-only flag. */
3018 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019 }
3020 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003021 /* When starting to edit a new file which does not have encryption, clear
3022 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003023 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3025
3026 return cryptkey;
3027}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003028#endif /* FEAT_CRYPT */
3029
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030#ifdef UNIX
3031 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003032set_file_time(
3033 char_u *fname,
3034 time_t atime, /* access time */
3035 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036{
3037# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3038 struct utimbuf buf;
3039
3040 buf.actime = atime;
3041 buf.modtime = mtime;
3042 (void)utime((char *)fname, &buf);
3043# else
3044# if defined(HAVE_UTIMES)
3045 struct timeval tvp[2];
3046
3047 tvp[0].tv_sec = atime;
3048 tvp[0].tv_usec = 0;
3049 tvp[1].tv_sec = mtime;
3050 tvp[1].tv_usec = 0;
3051# ifdef NeXT
3052 (void)utimes((char *)fname, tvp);
3053# else
3054 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3055# endif
3056# endif
3057# endif
3058}
3059#endif /* UNIX */
3060
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003061#if defined(VMS) && !defined(MIN)
3062/* Older DECC compiler for VAX doesn't define MIN() */
3063# define MIN(a, b) ((a) < (b) ? (a) : (b))
3064#endif
3065
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003067 * Return TRUE if a file appears to be read-only from the file permissions.
3068 */
3069 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003070check_file_readonly(
3071 char_u *fname, /* full path to file */
3072 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003073{
3074#ifndef USE_MCH_ACCESS
3075 int fd = 0;
3076#endif
3077
3078 return (
3079#ifdef USE_MCH_ACCESS
3080# ifdef UNIX
3081 (perm & 0222) == 0 ||
3082# endif
3083 mch_access((char *)fname, W_OK)
3084#else
3085 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3086 ? TRUE : (close(fd), FALSE)
3087#endif
3088 );
3089}
3090
3091
3092/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003093 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094 *
3095 * We do our own buffering here because fwrite() is so slow.
3096 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003097 * If "forceit" is true, we don't care for errors when attempting backups.
3098 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003099 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003100 *
3101 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3102 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003103 *
3104 * This function must NOT use NameBuff (because it's called by autowrite()).
3105 *
3106 * return FAIL for failure, OK otherwise
3107 */
3108 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003109buf_write(
3110 buf_T *buf,
3111 char_u *fname,
3112 char_u *sfname,
3113 linenr_T start,
3114 linenr_T end,
3115 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003117 int append, /* append to the file */
3118 int forceit,
3119 int reset_changed,
3120 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121{
3122 int fd;
3123 char_u *backup = NULL;
3124 int backup_copy = FALSE; /* copy the original file? */
3125 int dobackup;
3126 char_u *ffname;
3127 char_u *wfname = NULL; /* name of file to write to */
3128 char_u *s;
3129 char_u *ptr;
3130 char_u c;
3131 int len;
3132 linenr_T lnum;
3133 long nchars;
3134 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003135 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136 char_u *errnum = NULL;
3137 char_u *buffer;
3138 char_u smallbuf[SMBUFSIZE];
3139 char_u *backup_ext;
3140 int bufsize;
3141 long perm; /* file permissions */
3142 int retval = OK;
3143 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3144 int msg_save = msg_scroll;
3145 int overwriting; /* TRUE if writing over original */
3146 int no_eol = FALSE; /* no end-of-line written */
3147 int device = FALSE; /* writing to a device */
3148 struct stat st_old;
3149 int prev_got_int = got_int;
3150 int file_readonly = FALSE; /* overwritten file is read-only */
3151 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3152#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3153 int made_writable = FALSE; /* 'w' bit has been set */
3154#endif
3155 /* writing everything */
3156 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3157#ifdef FEAT_AUTOCMD
3158 linenr_T old_line_count = buf->b_ml.ml_line_count;
3159#endif
3160 int attr;
3161 int fileformat;
3162 int write_bin;
3163 struct bw_info write_info; /* info for buf_write_bytes() */
3164#ifdef FEAT_MBYTE
3165 int converted = FALSE;
3166 int notconverted = FALSE;
3167 char_u *fenc; /* effective 'fileencoding' */
3168 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3169#endif
3170#ifdef HAS_BW_FLAGS
3171 int wb_flags = 0;
3172#endif
3173#ifdef HAVE_ACL
3174 vim_acl_T acl = NULL; /* ACL copied from original file to
3175 backup or new file */
3176#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003177#ifdef FEAT_PERSISTENT_UNDO
3178 int write_undo_file = FALSE;
3179 context_sha256_T sha_ctx;
3180#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003181 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182
3183 if (fname == NULL || *fname == NUL) /* safety check */
3184 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003185 if (buf->b_ml.ml_mfp == NULL)
3186 {
3187 /* This can happen during startup when there is a stray "w" in the
3188 * vimrc file. */
3189 EMSG(_(e_emptybuf));
3190 return FAIL;
3191 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192
3193 /*
3194 * Disallow writing from .exrc and .vimrc in current directory for
3195 * security reasons.
3196 */
3197 if (check_secure())
3198 return FAIL;
3199
3200 /* Avoid a crash for a long name. */
3201 if (STRLEN(fname) >= MAXPATHL)
3202 {
3203 EMSG(_(e_longname));
3204 return FAIL;
3205 }
3206
3207#ifdef FEAT_MBYTE
3208 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3209 write_info.bw_conv_buf = NULL;
3210 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003211 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212 write_info.bw_restlen = 0;
3213# ifdef USE_ICONV
3214 write_info.bw_iconv_fd = (iconv_t)-1;
3215# endif
3216#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003217#ifdef FEAT_CRYPT
3218 write_info.bw_buffer = buf;
3219#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220
Bram Moolenaardf177f62005-02-22 08:39:57 +00003221 /* After writing a file changedtick changes but we don't want to display
3222 * the line. */
3223 ex_no_reprint = TRUE;
3224
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225 /*
3226 * If there is no file name yet, use the one for the written file.
3227 * BF_NOTEDITED is set to reflect this (in case the write fails).
3228 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003229 * Don't do this when appending.
3230 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003232 if (buf->b_ffname == NULL
3233 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234 && whole
3235 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003236#ifdef FEAT_QUICKFIX
3237 && !bt_nofile(buf)
3238#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003240 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3242 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003243 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003245 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 }
3247
3248 if (sfname == NULL)
3249 sfname = fname;
3250 /*
3251 * For Unix: Use the short file name whenever possible.
3252 * Avoids problems with networks and when directory names are changed.
3253 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3254 * another directory, which we don't detect
3255 */
3256 ffname = fname; /* remember full fname */
3257#ifdef UNIX
3258 fname = sfname;
3259#endif
3260
3261 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3262 overwriting = TRUE;
3263 else
3264 overwriting = FALSE;
3265
3266 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003267 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268
3269 ++no_wait_return; /* don't wait for return yet */
3270
3271 /*
3272 * Set '[ and '] marks to the lines to be written.
3273 */
3274 buf->b_op_start.lnum = start;
3275 buf->b_op_start.col = 0;
3276 buf->b_op_end.lnum = end;
3277 buf->b_op_end.col = 0;
3278
3279#ifdef FEAT_AUTOCMD
3280 {
3281 aco_save_T aco;
3282 int buf_ffname = FALSE;
3283 int buf_sfname = FALSE;
3284 int buf_fname_f = FALSE;
3285 int buf_fname_s = FALSE;
3286 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003287 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003288 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289
3290 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003291 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 * Set curbuf to the buffer to be written.
3293 * Careful: The autocommands may call buf_write() recursively!
3294 */
3295 if (ffname == buf->b_ffname)
3296 buf_ffname = TRUE;
3297 if (sfname == buf->b_sfname)
3298 buf_sfname = TRUE;
3299 if (fname == buf->b_ffname)
3300 buf_fname_f = TRUE;
3301 if (fname == buf->b_sfname)
3302 buf_fname_s = TRUE;
3303
3304 /* set curwin/curbuf to buf and save a few things */
3305 aucmd_prepbuf(&aco, buf);
3306
3307 if (append)
3308 {
3309 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3310 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003311 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003312#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003313 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003314 nofile_err = TRUE;
3315 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003316#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003317 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003319 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320 }
3321 else if (filtering)
3322 {
3323 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3324 NULL, sfname, FALSE, curbuf, eap);
3325 }
3326 else if (reset_changed && whole)
3327 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003328 int was_changed = curbufIsChanged();
3329
3330 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3331 sfname, sfname, FALSE, curbuf, eap);
3332 if (did_cmd)
3333 {
3334 if (was_changed && !curbufIsChanged())
3335 {
3336 /* Written everything correctly and BufWriteCmd has reset
3337 * 'modified': Correct the undo information so that an
3338 * undo now sets 'modified'. */
3339 u_unchanged(curbuf);
3340 u_update_save_nr(curbuf);
3341 }
3342 }
3343 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003344 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003345#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003346 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003347 nofile_err = TRUE;
3348 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003349#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 }
3354 else
3355 {
3356 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3357 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003358 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003359#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003360 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003361 nofile_err = TRUE;
3362 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003363#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367 }
3368
3369 /* restore curwin/curbuf and a few other things */
3370 aucmd_restbuf(&aco);
3371
3372 /*
3373 * In three situations we return here and don't write the file:
3374 * 1. the autocommands deleted or unloaded the buffer.
3375 * 2. The autocommands abort script processing.
3376 * 3. If one of the "Cmd" autocommands was executed.
3377 */
3378 if (!buf_valid(buf))
3379 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003380 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003381 || did_cmd || nofile_err
3382#ifdef FEAT_EVAL
3383 || aborting()
3384#endif
3385 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 {
3387 --no_wait_return;
3388 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003389 if (nofile_err)
3390 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3391
Bram Moolenaar1e015462005-09-25 22:16:38 +00003392 if (nofile_err
3393#ifdef FEAT_EVAL
3394 || aborting()
3395#endif
3396 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 /* An aborting error, interrupt or exception in the
3398 * autocommands. */
3399 return FAIL;
3400 if (did_cmd)
3401 {
3402 if (buf == NULL)
3403 /* The buffer was deleted. We assume it was written
3404 * (can't retry anyway). */
3405 return OK;
3406 if (overwriting)
3407 {
3408 /* Assume the buffer was written, update the timestamp. */
3409 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003410 if (append)
3411 buf->b_flags &= ~BF_NEW;
3412 else
3413 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003414 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003415 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003416 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003417 /* Buffer still changed, the autocommands didn't work
3418 * properly. */
3419 return FAIL;
3420 return OK;
3421 }
3422#ifdef FEAT_EVAL
3423 if (!aborting())
3424#endif
3425 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3426 return FAIL;
3427 }
3428
3429 /*
3430 * The autocommands may have changed the number of lines in the file.
3431 * When writing the whole file, adjust the end.
3432 * When writing part of the file, assume that the autocommands only
3433 * changed the number of lines that are to be written (tricky!).
3434 */
3435 if (buf->b_ml.ml_line_count != old_line_count)
3436 {
3437 if (whole) /* write all */
3438 end = buf->b_ml.ml_line_count;
3439 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3440 end += buf->b_ml.ml_line_count - old_line_count;
3441 else /* less lines */
3442 {
3443 end -= old_line_count - buf->b_ml.ml_line_count;
3444 if (end < start)
3445 {
3446 --no_wait_return;
3447 msg_scroll = msg_save;
3448 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3449 return FAIL;
3450 }
3451 }
3452 }
3453
3454 /*
3455 * The autocommands may have changed the name of the buffer, which may
3456 * be kept in fname, ffname and sfname.
3457 */
3458 if (buf_ffname)
3459 ffname = buf->b_ffname;
3460 if (buf_sfname)
3461 sfname = buf->b_sfname;
3462 if (buf_fname_f)
3463 fname = buf->b_ffname;
3464 if (buf_fname_s)
3465 fname = buf->b_sfname;
3466 }
3467#endif
3468
3469#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003470 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471 {
3472 if (whole)
3473 {
3474 /*
3475 * b_changed can be 0 after an undo, but we still need to write
3476 * the buffer to NetBeans.
3477 */
3478 if (buf->b_changed || isNetbeansModified(buf))
3479 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003480 --no_wait_return; /* may wait for return now */
3481 msg_scroll = msg_save;
3482 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 return retval;
3484 }
3485 else
3486 {
3487 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003488 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 buffer = NULL;
3490 goto fail;
3491 }
3492 }
3493 else
3494 {
3495 errnum = (char_u *)"E657: ";
3496 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3497 buffer = NULL;
3498 goto fail;
3499 }
3500 }
3501#endif
3502
3503 if (shortmess(SHM_OVER) && !exiting)
3504 msg_scroll = FALSE; /* overwrite previous file message */
3505 else
3506 msg_scroll = TRUE; /* don't overwrite previous file message */
3507 if (!filtering)
3508 filemess(buf,
3509#ifndef UNIX
3510 sfname,
3511#else
3512 fname,
3513#endif
3514 (char_u *)"", 0); /* show that we are busy */
3515 msg_scroll = FALSE; /* always overwrite the file message now */
3516
3517 buffer = alloc(BUFSIZE);
3518 if (buffer == NULL) /* can't allocate big buffer, use small
3519 * one (to be able to write when out of
3520 * memory) */
3521 {
3522 buffer = smallbuf;
3523 bufsize = SMBUFSIZE;
3524 }
3525 else
3526 bufsize = BUFSIZE;
3527
3528 /*
3529 * Get information about original file (if there is one).
3530 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003531#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003532 st_old.st_dev = 0;
3533 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 perm = -1;
3535 if (mch_stat((char *)fname, &st_old) < 0)
3536 newfile = TRUE;
3537 else
3538 {
3539 perm = st_old.st_mode;
3540 if (!S_ISREG(st_old.st_mode)) /* not a file */
3541 {
3542 if (S_ISDIR(st_old.st_mode))
3543 {
3544 errnum = (char_u *)"E502: ";
3545 errmsg = (char_u *)_("is a directory");
3546 goto fail;
3547 }
3548 if (mch_nodetype(fname) != NODE_WRITABLE)
3549 {
3550 errnum = (char_u *)"E503: ";
3551 errmsg = (char_u *)_("is not a file or writable device");
3552 goto fail;
3553 }
3554 /* It's a device of some kind (or a fifo) which we can write to
3555 * but for which we can't make a backup. */
3556 device = TRUE;
3557 newfile = TRUE;
3558 perm = -1;
3559 }
3560 }
3561#else /* !UNIX */
3562 /*
3563 * Check for a writable device name.
3564 */
3565 c = mch_nodetype(fname);
3566 if (c == NODE_OTHER)
3567 {
3568 errnum = (char_u *)"E503: ";
3569 errmsg = (char_u *)_("is not a file or writable device");
3570 goto fail;
3571 }
3572 if (c == NODE_WRITABLE)
3573 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003574# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003575 /* MS-Windows allows opening a device, but we will probably get stuck
3576 * trying to write to it. */
3577 if (!p_odev)
3578 {
3579 errnum = (char_u *)"E796: ";
3580 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3581 goto fail;
3582 }
3583# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 device = TRUE;
3585 newfile = TRUE;
3586 perm = -1;
3587 }
3588 else
3589 {
3590 perm = mch_getperm(fname);
3591 if (perm < 0)
3592 newfile = TRUE;
3593 else if (mch_isdir(fname))
3594 {
3595 errnum = (char_u *)"E502: ";
3596 errmsg = (char_u *)_("is a directory");
3597 goto fail;
3598 }
3599 if (overwriting)
3600 (void)mch_stat((char *)fname, &st_old);
3601 }
3602#endif /* !UNIX */
3603
3604 if (!device && !newfile)
3605 {
3606 /*
3607 * Check if the file is really writable (when renaming the file to
3608 * make a backup we won't discover it later).
3609 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003610 file_readonly = check_file_readonly(fname, (int)perm);
3611
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612 if (!forceit && file_readonly)
3613 {
3614 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3615 {
3616 errnum = (char_u *)"E504: ";
3617 errmsg = (char_u *)_(err_readonly);
3618 }
3619 else
3620 {
3621 errnum = (char_u *)"E505: ";
3622 errmsg = (char_u *)_("is read-only (add ! to override)");
3623 }
3624 goto fail;
3625 }
3626
3627 /*
3628 * Check if the timestamp hasn't changed since reading the file.
3629 */
3630 if (overwriting)
3631 {
3632 retval = check_mtime(buf, &st_old);
3633 if (retval == FAIL)
3634 goto fail;
3635 }
3636 }
3637
3638#ifdef HAVE_ACL
3639 /*
3640 * For systems that support ACL: get the ACL from the original file.
3641 */
3642 if (!newfile)
3643 acl = mch_get_acl(fname);
3644#endif
3645
3646 /*
3647 * If 'backupskip' is not empty, don't make a backup for some files.
3648 */
3649 dobackup = (p_wb || p_bk || *p_pm != NUL);
3650#ifdef FEAT_WILDIGN
3651 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3652 dobackup = FALSE;
3653#endif
3654
3655 /*
3656 * Save the value of got_int and reset it. We don't want a previous
3657 * interruption cancel writing, only hitting CTRL-C while writing should
3658 * abort it.
3659 */
3660 prev_got_int = got_int;
3661 got_int = FALSE;
3662
3663 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3664 buf->b_saving = TRUE;
3665
3666 /*
3667 * If we are not appending or filtering, the file exists, and the
3668 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3669 * When 'patchmode' is set also make a backup when appending.
3670 *
3671 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3672 * off. This helps when editing large files on almost-full disks.
3673 */
3674 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3675 {
3676#if defined(UNIX) || defined(WIN32)
3677 struct stat st;
3678#endif
3679
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003680 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681 backup_copy = TRUE;
3682#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003683 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 {
3685 int i;
3686
3687# ifdef UNIX
3688 /*
3689 * Don't rename the file when:
3690 * - it's a hard link
3691 * - it's a symbolic link
3692 * - we don't have write permission in the directory
3693 * - we can't set the owner/group of the new file
3694 */
3695 if (st_old.st_nlink > 1
3696 || mch_lstat((char *)fname, &st) < 0
3697 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003698 || st.st_ino != st_old.st_ino
3699# ifndef HAVE_FCHOWN
3700 || st.st_uid != st_old.st_uid
3701 || st.st_gid != st_old.st_gid
3702# endif
3703 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 backup_copy = TRUE;
3705 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003706# else
3707# ifdef WIN32
3708 /* On NTFS file systems hard links are possible. */
3709 if (mch_is_linked(fname))
3710 backup_copy = TRUE;
3711 else
3712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713# endif
3714 {
3715 /*
3716 * Check if we can create a file and set the owner/group to
3717 * the ones from the original file.
3718 * First find a file name that doesn't exist yet (use some
3719 * arbitrary numbers).
3720 */
3721 STRCPY(IObuff, fname);
3722 for (i = 4913; ; i += 123)
3723 {
3724 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003725 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 break;
3727 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003728 fd = mch_open((char *)IObuff,
3729 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 if (fd < 0) /* can't write in directory */
3731 backup_copy = TRUE;
3732 else
3733 {
3734# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003735# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003736 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003737# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 if (mch_stat((char *)IObuff, &st) < 0
3739 || st.st_uid != st_old.st_uid
3740 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003741 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 backup_copy = TRUE;
3743# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003744 /* Close the file before removing it, on MS-Windows we
3745 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003747 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003748# ifdef MSWIN
3749 /* MS-Windows may trigger a virus scanner to open the
3750 * file, we can't delete it then. Keep trying for half a
3751 * second. */
3752 {
3753 int try;
3754
3755 for (try = 0; try < 10; ++try)
3756 {
3757 if (mch_lstat((char *)IObuff, &st) < 0)
3758 break;
3759 ui_delay(50L, TRUE); /* wait 50 msec */
3760 mch_remove(IObuff);
3761 }
3762 }
3763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764 }
3765 }
3766 }
3767
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768 /*
3769 * Break symlinks and/or hardlinks if we've been asked to.
3770 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003771 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003773# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 int lstat_res;
3775
3776 lstat_res = mch_lstat((char *)fname, &st);
3777
3778 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003779 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780 && lstat_res == 0
3781 && st.st_ino != st_old.st_ino)
3782 backup_copy = FALSE;
3783
3784 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003785 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 && st_old.st_nlink > 1
3787 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3788 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003789# else
3790# if defined(WIN32)
3791 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003792 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003793 backup_copy = FALSE;
3794
3795 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003796 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003797 backup_copy = FALSE;
3798# endif
3799# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801
3802#endif
3803
3804 /* make sure we have a valid backup extension to use */
3805 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 else
3808 backup_ext = p_bex;
3809
3810 if (backup_copy
3811 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3812 {
3813 int bfd;
3814 char_u *copybuf, *wp;
3815 int some_error = FALSE;
3816 struct stat st_new;
3817 char_u *dirp;
3818 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003819#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 int did_set_shortname;
3821#endif
3822
3823 copybuf = alloc(BUFSIZE + 1);
3824 if (copybuf == NULL)
3825 {
3826 some_error = TRUE; /* out of memory */
3827 goto nobackup;
3828 }
3829
3830 /*
3831 * Try to make the backup in each directory in the 'bdir' option.
3832 *
3833 * Unix semantics has it, that we may have a writable file,
3834 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3835 * - the directory is not writable,
3836 * - the file may be a symbolic link,
3837 * - the file may belong to another user/group, etc.
3838 *
3839 * For these reasons, the existing writable file must be truncated
3840 * and reused. Creation of a backup COPY will be attempted.
3841 */
3842 dirp = p_bdir;
3843 while (*dirp)
3844 {
3845#ifdef UNIX
3846 st_new.st_ino = 0;
3847 st_new.st_dev = 0;
3848 st_new.st_gid = 0;
3849#endif
3850
3851 /*
3852 * Isolate one directory name, using an entry in 'bdir'.
3853 */
3854 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3855 rootname = get_file_in_dir(fname, copybuf);
3856 if (rootname == NULL)
3857 {
3858 some_error = TRUE; /* out of memory */
3859 goto nobackup;
3860 }
3861
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003862#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 did_set_shortname = FALSE;
3864#endif
3865
3866 /*
3867 * May try twice if 'shortname' not set.
3868 */
3869 for (;;)
3870 {
3871 /*
3872 * Make backup file name.
3873 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003874 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875 rootname, backup_ext, FALSE);
3876 if (backup == NULL)
3877 {
3878 vim_free(rootname);
3879 some_error = TRUE; /* out of memory */
3880 goto nobackup;
3881 }
3882
3883 /*
3884 * Check if backup file already exists.
3885 */
3886 if (mch_stat((char *)backup, &st_new) >= 0)
3887 {
3888#ifdef UNIX
3889 /*
3890 * Check if backup file is same as original file.
3891 * May happen when modname() gave the same file back.
3892 * E.g. silly link, or file name-length reached.
3893 * If we don't check here, we either ruin the file
3894 * when copying or erase it after writing. jw.
3895 */
3896 if (st_new.st_dev == st_old.st_dev
3897 && st_new.st_ino == st_old.st_ino)
3898 {
3899 vim_free(backup);
3900 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 /*
3902 * may try again with 'shortname' set
3903 */
3904 if (!(buf->b_shortname || buf->b_p_sn))
3905 {
3906 buf->b_shortname = TRUE;
3907 did_set_shortname = TRUE;
3908 continue;
3909 }
3910 /* setting shortname didn't help */
3911 if (did_set_shortname)
3912 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 break;
3914 }
3915#endif
3916
3917 /*
3918 * If we are not going to keep the backup file, don't
3919 * delete an existing one, try to use another name.
3920 * Change one character, just before the extension.
3921 */
3922 if (!p_bk)
3923 {
3924 wp = backup + STRLEN(backup) - 1
3925 - STRLEN(backup_ext);
3926 if (wp < backup) /* empty file name ??? */
3927 wp = backup;
3928 *wp = 'z';
3929 while (*wp > 'a'
3930 && mch_stat((char *)backup, &st_new) >= 0)
3931 --*wp;
3932 /* They all exist??? Must be something wrong. */
3933 if (*wp == 'a')
3934 {
3935 vim_free(backup);
3936 backup = NULL;
3937 }
3938 }
3939 }
3940 break;
3941 }
3942 vim_free(rootname);
3943
3944 /*
3945 * Try to create the backup file
3946 */
3947 if (backup != NULL)
3948 {
3949 /* remove old backup, if present */
3950 mch_remove(backup);
3951 /* Open with O_EXCL to avoid the file being created while
3952 * we were sleeping (symlink hacker attack?) */
3953 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003954 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3955 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 if (bfd < 0)
3957 {
3958 vim_free(backup);
3959 backup = NULL;
3960 }
3961 else
3962 {
3963 /* set file protection same as original file, but
3964 * strip s-bit */
3965 (void)mch_setperm(backup, perm & 0777);
3966
3967#ifdef UNIX
3968 /*
3969 * Try to set the group of the backup same as the
3970 * original file. If this fails, set the protection
3971 * bits for the group same as the protection bits for
3972 * others.
3973 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003974 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003976 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003977# endif
3978 )
3979 mch_setperm(backup,
3980 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003981# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003982 mch_copy_sec(fname, backup);
3983# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984#endif
3985
3986 /*
3987 * copy the file.
3988 */
3989 write_info.bw_fd = bfd;
3990 write_info.bw_buf = copybuf;
3991#ifdef HAS_BW_FLAGS
3992 write_info.bw_flags = FIO_NOCONVERT;
3993#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003994 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995 BUFSIZE)) > 0)
3996 {
3997 if (buf_write_bytes(&write_info) == FAIL)
3998 {
3999 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4000 break;
4001 }
4002 ui_breakcheck();
4003 if (got_int)
4004 {
4005 errmsg = (char_u *)_(e_interr);
4006 break;
4007 }
4008 }
4009
4010 if (close(bfd) < 0 && errmsg == NULL)
4011 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4012 if (write_info.bw_len < 0)
4013 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4014#ifdef UNIX
4015 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4016#endif
4017#ifdef HAVE_ACL
4018 mch_set_acl(backup, acl);
4019#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004020#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004021 mch_copy_sec(fname, backup);
4022#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023 break;
4024 }
4025 }
4026 }
4027 nobackup:
4028 close(fd); /* ignore errors for closing read file */
4029 vim_free(copybuf);
4030
4031 if (backup == NULL && errmsg == NULL)
4032 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4033 /* ignore errors when forceit is TRUE */
4034 if ((some_error || errmsg != NULL) && !forceit)
4035 {
4036 retval = FAIL;
4037 goto fail;
4038 }
4039 errmsg = NULL;
4040 }
4041 else
4042 {
4043 char_u *dirp;
4044 char_u *p;
4045 char_u *rootname;
4046
4047 /*
4048 * Make a backup by renaming the original file.
4049 */
4050 /*
4051 * If 'cpoptions' includes the "W" flag, we don't want to
4052 * overwrite a read-only file. But rename may be possible
4053 * anyway, thus we need an extra check here.
4054 */
4055 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4056 {
4057 errnum = (char_u *)"E504: ";
4058 errmsg = (char_u *)_(err_readonly);
4059 goto fail;
4060 }
4061
4062 /*
4063 *
4064 * Form the backup file name - change path/fo.o.h to
4065 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4066 * that works is used.
4067 */
4068 dirp = p_bdir;
4069 while (*dirp)
4070 {
4071 /*
4072 * Isolate one directory name and make the backup file name.
4073 */
4074 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4075 rootname = get_file_in_dir(fname, IObuff);
4076 if (rootname == NULL)
4077 backup = NULL;
4078 else
4079 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004080 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 rootname, backup_ext, FALSE);
4082 vim_free(rootname);
4083 }
4084
4085 if (backup != NULL)
4086 {
4087 /*
4088 * If we are not going to keep the backup file, don't
4089 * delete an existing one, try to use another name.
4090 * Change one character, just before the extension.
4091 */
4092 if (!p_bk && mch_getperm(backup) >= 0)
4093 {
4094 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4095 if (p < backup) /* empty file name ??? */
4096 p = backup;
4097 *p = 'z';
4098 while (*p > 'a' && mch_getperm(backup) >= 0)
4099 --*p;
4100 /* They all exist??? Must be something wrong! */
4101 if (*p == 'a')
4102 {
4103 vim_free(backup);
4104 backup = NULL;
4105 }
4106 }
4107 }
4108 if (backup != NULL)
4109 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004111 * Delete any existing backup and move the current version
4112 * to the backup. For safety, we don't remove the backup
4113 * until the write has finished successfully. And if the
4114 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 */
4116 /*
4117 * If the renaming of the original file to the backup file
4118 * works, quit here.
4119 */
4120 if (vim_rename(fname, backup) == 0)
4121 break;
4122
4123 vim_free(backup); /* don't do the rename below */
4124 backup = NULL;
4125 }
4126 }
4127 if (backup == NULL && !forceit)
4128 {
4129 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4130 goto fail;
4131 }
4132 }
4133 }
4134
Bram Moolenaar53076832015-12-31 19:53:21 +01004135#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 /* When using ":w!" and the file was read-only: make it writable */
4137 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4138 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4139 {
4140 perm |= 0200;
4141 (void)mch_setperm(fname, perm);
4142 made_writable = TRUE;
4143 }
4144#endif
4145
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004146 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004147 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4148 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 {
4150 buf->b_p_ro = FALSE;
4151#ifdef FEAT_TITLE
4152 need_maketitle = TRUE; /* set window title later */
4153#endif
4154#ifdef FEAT_WINDOWS
4155 status_redraw_all(); /* redraw status lines later */
4156#endif
4157 }
4158
4159 if (end > buf->b_ml.ml_line_count)
4160 end = buf->b_ml.ml_line_count;
4161 if (buf->b_ml.ml_flags & ML_EMPTY)
4162 start = end + 1;
4163
4164 /*
4165 * If the original file is being overwritten, there is a small chance that
4166 * we crash in the middle of writing. Therefore the file is preserved now.
4167 * This makes all block numbers positive so that recovery does not need
4168 * the original file.
4169 * Don't do this if there is a backup file and we are exiting.
4170 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004171 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 && !(exiting && backup != NULL))
4173 {
4174 ml_preserve(buf, FALSE);
4175 if (got_int)
4176 {
4177 errmsg = (char_u *)_(e_interr);
4178 goto restore_backup;
4179 }
4180 }
4181
4182#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4183 /*
4184 * Before risking to lose the original file verify if there's
4185 * a resource fork to preserve, and if cannot be done warn
4186 * the users. This happens when overwriting without backups.
4187 */
4188 if (backup == NULL && overwriting && !append)
4189 if (mch_has_resource_fork(fname))
4190 {
4191 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4192 goto restore_backup;
4193 }
4194#endif
4195
4196#ifdef VMS
4197 vms_remove_version(fname); /* remove version */
4198#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004199 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200 * multi-byte conversion. */
4201 wfname = fname;
4202
4203#ifdef FEAT_MBYTE
4204 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4205 if (eap != NULL && eap->force_enc != 0)
4206 {
4207 fenc = eap->cmd + eap->force_enc;
4208 fenc = enc_canonize(fenc);
4209 fenc_tofree = fenc;
4210 }
4211 else
4212 fenc = buf->b_p_fenc;
4213
4214 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004215 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004216 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004217 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218
4219 /*
4220 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4221 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4222 * Prepare the flags for it and allocate bw_conv_buf when needed.
4223 */
4224 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4225 {
4226 wb_flags = get_fio_flags(fenc);
4227 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4228 {
4229 /* Need to allocate a buffer to translate into. */
4230 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4231 write_info.bw_conv_buflen = bufsize * 2;
4232 else /* FIO_UCS4 */
4233 write_info.bw_conv_buflen = bufsize * 4;
4234 write_info.bw_conv_buf
4235 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4236 if (write_info.bw_conv_buf == NULL)
4237 end = 0;
4238 }
4239 }
4240
4241# ifdef WIN3264
4242 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4243 {
4244 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4245 write_info.bw_conv_buflen = bufsize * 4;
4246 write_info.bw_conv_buf
4247 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4248 if (write_info.bw_conv_buf == NULL)
4249 end = 0;
4250 }
4251# endif
4252
4253# ifdef MACOS_X
4254 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4255 {
4256 write_info.bw_conv_buflen = bufsize * 3;
4257 write_info.bw_conv_buf
4258 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4259 if (write_info.bw_conv_buf == NULL)
4260 end = 0;
4261 }
4262# endif
4263
4264# if defined(FEAT_EVAL) || defined(USE_ICONV)
4265 if (converted && wb_flags == 0)
4266 {
4267# ifdef USE_ICONV
4268 /*
4269 * Use iconv() conversion when conversion is needed and it's not done
4270 * internally.
4271 */
4272 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4273 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4274 if (write_info.bw_iconv_fd != (iconv_t)-1)
4275 {
4276 /* We're going to use iconv(), allocate a buffer to convert in. */
4277 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4278 write_info.bw_conv_buf
4279 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4280 if (write_info.bw_conv_buf == NULL)
4281 end = 0;
4282 write_info.bw_first = TRUE;
4283 }
4284# ifdef FEAT_EVAL
4285 else
4286# endif
4287# endif
4288
4289# ifdef FEAT_EVAL
4290 /*
4291 * When the file needs to be converted with 'charconvert' after
4292 * writing, write to a temp file instead and let the conversion
4293 * overwrite the original file.
4294 */
4295 if (*p_ccv != NUL)
4296 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004297 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 if (wfname == NULL) /* Can't write without a tempfile! */
4299 {
4300 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4301 goto restore_backup;
4302 }
4303 }
4304# endif
4305 }
4306# endif
4307 if (converted && wb_flags == 0
4308# ifdef USE_ICONV
4309 && write_info.bw_iconv_fd == (iconv_t)-1
4310# endif
4311# ifdef FEAT_EVAL
4312 && wfname == fname
4313# endif
4314 )
4315 {
4316 if (!forceit)
4317 {
4318 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4319 goto restore_backup;
4320 }
4321 notconverted = TRUE;
4322 }
4323#endif
4324
4325 /*
4326 * Open the file "wfname" for writing.
4327 * We may try to open the file twice: If we can't write to the
4328 * file and forceit is TRUE we delete the existing file and try to create
4329 * a new one. If this still fails we may have lost the original file!
4330 * (this may happen when the user reached his quotum for number of files).
4331 * Appending will fail if the file does not exist and forceit is FALSE.
4332 */
4333 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4334 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4335 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004336 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 {
4338 /*
4339 * A forced write will try to create a new file if the old one is
4340 * still readonly. This may also happen when the directory is
4341 * read-only. In that case the mch_remove() will fail.
4342 */
4343 if (errmsg == NULL)
4344 {
4345#ifdef UNIX
4346 struct stat st;
4347
4348 /* Don't delete the file when it's a hard or symbolic link. */
4349 if ((!newfile && st_old.st_nlink > 1)
4350 || (mch_lstat((char *)fname, &st) == 0
4351 && (st.st_dev != st_old.st_dev
4352 || st.st_ino != st_old.st_ino)))
4353 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4354 else
4355#endif
4356 {
4357 errmsg = (char_u *)_("E212: Can't open file for writing");
4358 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4359 && perm >= 0)
4360 {
4361#ifdef UNIX
4362 /* we write to the file, thus it should be marked
4363 writable after all */
4364 if (!(perm & 0200))
4365 made_writable = TRUE;
4366 perm |= 0200;
4367 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4368 perm &= 0777;
4369#endif
4370 if (!append) /* don't remove when appending */
4371 mch_remove(wfname);
4372 continue;
4373 }
4374 }
4375 }
4376
4377restore_backup:
4378 {
4379 struct stat st;
4380
4381 /*
4382 * If we failed to open the file, we don't need a backup. Throw it
4383 * away. If we moved or removed the original file try to put the
4384 * backup in its place.
4385 */
4386 if (backup != NULL && wfname == fname)
4387 {
4388 if (backup_copy)
4389 {
4390 /*
4391 * There is a small chance that we removed the original,
4392 * try to move the copy in its place.
4393 * This may not work if the vim_rename() fails.
4394 * In that case we leave the copy around.
4395 */
4396 /* If file does not exist, put the copy in its place */
4397 if (mch_stat((char *)fname, &st) < 0)
4398 vim_rename(backup, fname);
4399 /* if original file does exist throw away the copy */
4400 if (mch_stat((char *)fname, &st) >= 0)
4401 mch_remove(backup);
4402 }
4403 else
4404 {
4405 /* try to put the original file back */
4406 vim_rename(backup, fname);
4407 }
4408 }
4409
4410 /* if original file no longer exists give an extra warning */
4411 if (!newfile && mch_stat((char *)fname, &st) < 0)
4412 end = 0;
4413 }
4414
4415#ifdef FEAT_MBYTE
4416 if (wfname != fname)
4417 vim_free(wfname);
4418#endif
4419 goto fail;
4420 }
4421 errmsg = NULL;
4422
4423#if defined(MACOS_CLASSIC) || defined(WIN3264)
4424 /* TODO: Is it need for MACOS_X? (Dany) */
4425 /*
4426 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004427 * This is done in order to preserve the resource fork and the
4428 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004429 */
4430 if (backup != NULL && overwriting && !append)
4431 {
4432 if (backup_copy)
4433 (void)mch_copy_file_attribute(wfname, backup);
4434 else
4435 (void)mch_copy_file_attribute(backup, wfname);
4436 }
4437
4438 if (!overwriting && !append)
4439 {
4440 if (buf->b_ffname != NULL)
4441 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004442 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 }
4444#endif
4445
4446 write_info.bw_fd = fd;
4447
4448#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004449 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004451 char_u *header;
4452 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004453
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004454 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4455 buf->b_p_key, &header, &header_len);
4456 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004457 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004458 else
4459 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004460 /* Write magic number, so that Vim knows how this file is
4461 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004462 write_info.bw_buf = header;
4463 write_info.bw_len = header_len;
4464 write_info.bw_flags = FIO_NOCONVERT;
4465 if (buf_write_bytes(&write_info) == FAIL)
4466 end = 0;
4467 wb_flags |= FIO_ENCRYPTED;
4468 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 }
4471#endif
4472
4473 write_info.bw_buf = buffer;
4474 nchars = 0;
4475
4476 /* use "++bin", "++nobin" or 'binary' */
4477 if (eap != NULL && eap->force_bin != 0)
4478 write_bin = (eap->force_bin == FORCE_BIN);
4479 else
4480 write_bin = buf->b_p_bin;
4481
4482#ifdef FEAT_MBYTE
4483 /*
4484 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004485 * Skip it when appending and the file already existed, the BOM only makes
4486 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004488 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 {
4490 write_info.bw_len = make_bom(buffer, fenc);
4491 if (write_info.bw_len > 0)
4492 {
4493 /* don't convert, do encryption */
4494 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4495 if (buf_write_bytes(&write_info) == FAIL)
4496 end = 0;
4497 else
4498 nchars += write_info.bw_len;
4499 }
4500 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004501 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502#endif
4503
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004504#ifdef FEAT_PERSISTENT_UNDO
4505 write_undo_file = (buf->b_p_udf && overwriting && !append
4506 && !filtering && reset_changed);
4507 if (write_undo_file)
4508 /* Prepare for computing the hash value of the text. */
4509 sha256_start(&sha_ctx);
4510#endif
4511
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512 write_info.bw_len = bufsize;
4513#ifdef HAS_BW_FLAGS
4514 write_info.bw_flags = wb_flags;
4515#endif
4516 fileformat = get_fileformat_force(buf, eap);
4517 s = buffer;
4518 len = 0;
4519 for (lnum = start; lnum <= end; ++lnum)
4520 {
4521 /*
4522 * The next while loop is done once for each character written.
4523 * Keep it fast!
4524 */
4525 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004526#ifdef FEAT_PERSISTENT_UNDO
4527 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004528 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004529#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530 while ((c = *++ptr) != NUL)
4531 {
4532 if (c == NL)
4533 *s = NUL; /* replace newlines with NULs */
4534 else if (c == CAR && fileformat == EOL_MAC)
4535 *s = NL; /* Mac: replace CRs with NLs */
4536 else
4537 *s = c;
4538 ++s;
4539 if (++len != bufsize)
4540 continue;
4541 if (buf_write_bytes(&write_info) == FAIL)
4542 {
4543 end = 0; /* write error: break loop */
4544 break;
4545 }
4546 nchars += bufsize;
4547 s = buffer;
4548 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004549#ifdef FEAT_MBYTE
4550 write_info.bw_start_lnum = lnum;
4551#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552 }
4553 /* write failed or last line has no EOL: stop here */
4554 if (end == 0
4555 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004556 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004557 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4559 {
4560 ++lnum; /* written the line, count it */
4561 no_eol = TRUE;
4562 break;
4563 }
4564 if (fileformat == EOL_UNIX)
4565 *s++ = NL;
4566 else
4567 {
4568 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4569 if (fileformat == EOL_DOS) /* write CR-NL */
4570 {
4571 if (++len == bufsize)
4572 {
4573 if (buf_write_bytes(&write_info) == FAIL)
4574 {
4575 end = 0; /* write error: break loop */
4576 break;
4577 }
4578 nchars += bufsize;
4579 s = buffer;
4580 len = 0;
4581 }
4582 *s++ = NL;
4583 }
4584 }
4585 if (++len == bufsize && end)
4586 {
4587 if (buf_write_bytes(&write_info) == FAIL)
4588 {
4589 end = 0; /* write error: break loop */
4590 break;
4591 }
4592 nchars += bufsize;
4593 s = buffer;
4594 len = 0;
4595
4596 ui_breakcheck();
4597 if (got_int)
4598 {
4599 end = 0; /* Interrupted, break loop */
4600 break;
4601 }
4602 }
4603#ifdef VMS
4604 /*
4605 * On VMS there is a problem: newlines get added when writing blocks
4606 * at a time. Fix it by writing a line at a time.
4607 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004608 * Explanation: VAX/DECC RTL insists that records in some RMS
4609 * structures end with a newline (carriage return) character, and if
4610 * they don't it adds one.
4611 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004613 if (buf->b_fab_rfm == FAB$C_VFC
4614 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004616 int b2write;
4617
4618 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4619 ? MIN(4096, bufsize)
4620 : MIN(buf->b_fab_mrs, bufsize));
4621
4622 b2write = len;
4623 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004625 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4626 if (buf_write_bytes(&write_info) == FAIL)
4627 {
4628 end = 0;
4629 break;
4630 }
4631 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 }
4633 write_info.bw_len = bufsize;
4634 nchars += len;
4635 s = buffer;
4636 len = 0;
4637 }
4638#endif
4639 }
4640 if (len > 0 && end > 0)
4641 {
4642 write_info.bw_len = len;
4643 if (buf_write_bytes(&write_info) == FAIL)
4644 end = 0; /* write error */
4645 nchars += len;
4646 }
4647
4648#if defined(UNIX) && defined(HAVE_FSYNC)
4649 /* On many journalling file systems there is a bug that causes both the
4650 * original and the backup file to be lost when halting the system right
4651 * after writing the file. That's because only the meta-data is
4652 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004653 * been written to disk and we don't lose it.
4654 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004655 * (could be a pipe).
4656 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4657 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004658 {
4659 errmsg = (char_u *)_("E667: Fsync failed");
4660 end = 0;
4661 }
4662#endif
4663
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004664#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004665 /* Probably need to set the security context. */
4666 if (!backup_copy)
4667 mch_copy_sec(backup, wfname);
4668#endif
4669
Bram Moolenaara5792f52005-11-23 21:25:05 +00004670#ifdef UNIX
4671 /* When creating a new file, set its owner/group to that of the original
4672 * file. Get the new device and inode number. */
4673 if (backup != NULL && !backup_copy)
4674 {
4675# ifdef HAVE_FCHOWN
4676 struct stat st;
4677
4678 /* don't change the owner when it's already OK, some systems remove
4679 * permission or ACL stuff */
4680 if (mch_stat((char *)wfname, &st) < 0
4681 || st.st_uid != st_old.st_uid
4682 || st.st_gid != st_old.st_gid)
4683 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004684 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004685 if (perm >= 0) /* set permission again, may have changed */
4686 (void)mch_setperm(wfname, perm);
4687 }
4688# endif
4689 buf_setino(buf);
4690 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004691 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004692 /* Set the inode when creating a new file. */
4693 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004694#endif
4695
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696 if (close(fd) != 0)
4697 {
4698 errmsg = (char_u *)_("E512: Close failed");
4699 end = 0;
4700 }
4701
4702#ifdef UNIX
4703 if (made_writable)
4704 perm &= ~0200; /* reset 'w' bit for security reasons */
4705#endif
4706 if (perm >= 0) /* set perm. of new file same as old file */
4707 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708#ifdef HAVE_ACL
4709 /* Probably need to set the ACL before changing the user (can't set the
4710 * ACL on a file the user doesn't own). */
4711 if (!backup_copy)
4712 mch_set_acl(wfname, acl);
4713#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004714#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004715 if (buf->b_cryptstate != NULL)
4716 {
4717 crypt_free_state(buf->b_cryptstate);
4718 buf->b_cryptstate = NULL;
4719 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004720#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4723 if (wfname != fname)
4724 {
4725 /*
4726 * The file was written to a temp file, now it needs to be converted
4727 * with 'charconvert' to (overwrite) the output file.
4728 */
4729 if (end != 0)
4730 {
4731 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4732 wfname, fname) == FAIL)
4733 {
4734 write_info.bw_conv_error = TRUE;
4735 end = 0;
4736 }
4737 }
4738 mch_remove(wfname);
4739 vim_free(wfname);
4740 }
4741#endif
4742
4743 if (end == 0)
4744 {
4745 if (errmsg == NULL)
4746 {
4747#ifdef FEAT_MBYTE
4748 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004749 {
4750 if (write_info.bw_conv_error_lnum == 0)
4751 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4752 else
4753 {
4754 errmsg_allocated = TRUE;
4755 errmsg = alloc(300);
4756 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4757 (long)write_info.bw_conv_error_lnum);
4758 }
4759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760 else
4761#endif
4762 if (got_int)
4763 errmsg = (char_u *)_(e_interr);
4764 else
4765 errmsg = (char_u *)_("E514: write error (file system full?)");
4766 }
4767
4768 /*
4769 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004770 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 * original file when trying to make a backup when writing the file a
4772 * second time.
4773 * When "backup_copy" is set we need to copy the backup over the new
4774 * file. Otherwise rename the backup file.
4775 * If this is OK, don't give the extra warning message.
4776 */
4777 if (backup != NULL)
4778 {
4779 if (backup_copy)
4780 {
4781 /* This may take a while, if we were interrupted let the user
4782 * know we got the message. */
4783 if (got_int)
4784 {
4785 MSG(_(e_interr));
4786 out_flush();
4787 }
4788 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4789 {
4790 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004791 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4792 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793 {
4794 /* copy the file. */
4795 write_info.bw_buf = smallbuf;
4796#ifdef HAS_BW_FLAGS
4797 write_info.bw_flags = FIO_NOCONVERT;
4798#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004799 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 SMBUFSIZE)) > 0)
4801 if (buf_write_bytes(&write_info) == FAIL)
4802 break;
4803
4804 if (close(write_info.bw_fd) >= 0
4805 && write_info.bw_len == 0)
4806 end = 1; /* success */
4807 }
4808 close(fd); /* ignore errors for closing read file */
4809 }
4810 }
4811 else
4812 {
4813 if (vim_rename(backup, fname) == 0)
4814 end = 1;
4815 }
4816 }
4817 goto fail;
4818 }
4819
4820 lnum -= start; /* compute number of written lines */
4821 --no_wait_return; /* may wait for return now */
4822
4823#if !(defined(UNIX) || defined(VMS))
4824 fname = sfname; /* use shortname now, for the messages */
4825#endif
4826 if (!filtering)
4827 {
4828 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4829 c = FALSE;
4830#ifdef FEAT_MBYTE
4831 if (write_info.bw_conv_error)
4832 {
4833 STRCAT(IObuff, _(" CONVERSION ERROR"));
4834 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004835 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004836 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004837 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838 }
4839 else if (notconverted)
4840 {
4841 STRCAT(IObuff, _("[NOT converted]"));
4842 c = TRUE;
4843 }
4844 else if (converted)
4845 {
4846 STRCAT(IObuff, _("[converted]"));
4847 c = TRUE;
4848 }
4849#endif
4850 if (device)
4851 {
4852 STRCAT(IObuff, _("[Device]"));
4853 c = TRUE;
4854 }
4855 else if (newfile)
4856 {
4857 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4858 c = TRUE;
4859 }
4860 if (no_eol)
4861 {
4862 msg_add_eol();
4863 c = TRUE;
4864 }
4865 /* may add [unix/dos/mac] */
4866 if (msg_add_fileformat(fileformat))
4867 c = TRUE;
4868#ifdef FEAT_CRYPT
4869 if (wb_flags & FIO_ENCRYPTED)
4870 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004871 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 c = TRUE;
4873 }
4874#endif
4875 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4876 if (!shortmess(SHM_WRITE))
4877 {
4878 if (append)
4879 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4880 else
4881 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4882 }
4883
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004884 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004885 }
4886
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004887 /* When written everything correctly: reset 'modified'. Unless not
4888 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004889 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890#ifdef FEAT_MBYTE
4891 && !write_info.bw_conv_error
4892#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004893 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4894 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 {
4896 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004897#ifdef FEAT_AUTOCMD
4898 /* buf->b_changedtick is always incremented in unchanged() but that
4899 * should not trigger a TextChanged event. */
4900 if (last_changedtick + 1 == buf->b_changedtick
4901 && last_changedtick_buf == buf)
4902 last_changedtick = buf->b_changedtick;
4903#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004905 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 }
4907
4908 /*
4909 * If written to the current file, update the timestamp of the swap file
4910 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4911 */
4912 if (overwriting)
4913 {
4914 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004915 if (append)
4916 buf->b_flags &= ~BF_NEW;
4917 else
4918 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 }
4920
4921 /*
4922 * If we kept a backup until now, and we are in patch mode, then we make
4923 * the backup file our 'original' file.
4924 */
4925 if (*p_pm && dobackup)
4926 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004927 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 fname, p_pm, FALSE);
4929
4930 if (backup != NULL)
4931 {
4932 struct stat st;
4933
4934 /*
4935 * If the original file does not exist yet
4936 * the current backup file becomes the original file
4937 */
4938 if (org == NULL)
4939 EMSG(_("E205: Patchmode: can't save original file"));
4940 else if (mch_stat(org, &st) < 0)
4941 {
4942 vim_rename(backup, (char_u *)org);
4943 vim_free(backup); /* don't delete the file */
4944 backup = NULL;
4945#ifdef UNIX
4946 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4947#endif
4948 }
4949 }
4950 /*
4951 * If there is no backup file, remember that a (new) file was
4952 * created.
4953 */
4954 else
4955 {
4956 int empty_fd;
4957
4958 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004959 || (empty_fd = mch_open(org,
4960 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004961 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 EMSG(_("E206: patchmode: can't touch empty original file"));
4963 else
4964 close(empty_fd);
4965 }
4966 if (org != NULL)
4967 {
4968 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4969 vim_free(org);
4970 }
4971 }
4972
4973 /*
4974 * Remove the backup unless 'backup' option is set
4975 */
4976 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4977 EMSG(_("E207: Can't delete backup file"));
4978
4979#ifdef FEAT_SUN_WORKSHOP
4980 if (usingSunWorkShop)
4981 workshop_file_saved((char *) ffname);
4982#endif
4983
4984 goto nofail;
4985
4986 /*
4987 * Finish up. We get here either after failure or success.
4988 */
4989fail:
4990 --no_wait_return; /* may wait for return now */
4991nofail:
4992
4993 /* Done saving, we accept changed buffer warnings again */
4994 buf->b_saving = FALSE;
4995
4996 vim_free(backup);
4997 if (buffer != smallbuf)
4998 vim_free(buffer);
4999#ifdef FEAT_MBYTE
5000 vim_free(fenc_tofree);
5001 vim_free(write_info.bw_conv_buf);
5002# ifdef USE_ICONV
5003 if (write_info.bw_iconv_fd != (iconv_t)-1)
5004 {
5005 iconv_close(write_info.bw_iconv_fd);
5006 write_info.bw_iconv_fd = (iconv_t)-1;
5007 }
5008# endif
5009#endif
5010#ifdef HAVE_ACL
5011 mch_free_acl(acl);
5012#endif
5013
5014 if (errmsg != NULL)
5015 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005016 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017
5018 attr = hl_attr(HLF_E); /* set highlight for error messages */
5019 msg_add_fname(buf,
5020#ifndef UNIX
5021 sfname
5022#else
5023 fname
5024#endif
5025 ); /* put file name in IObuff with quotes */
5026 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5027 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5028 /* If the error message has the form "is ...", put the error number in
5029 * front of the file name. */
5030 if (errnum != NULL)
5031 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005032 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033 mch_memmove(IObuff, errnum, (size_t)numlen);
5034 }
5035 STRCAT(IObuff, errmsg);
5036 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005037 if (errmsg_allocated)
5038 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005039
5040 retval = FAIL;
5041 if (end == 0)
5042 {
5043 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5044 attr | MSG_HIST);
5045 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5046 attr | MSG_HIST);
5047
5048 /* Update the timestamp to avoid an "overwrite changed file"
5049 * prompt when writing again. */
5050 if (mch_stat((char *)fname, &st_old) >= 0)
5051 {
5052 buf_store_time(buf, &st_old, fname);
5053 buf->b_mtime_read = buf->b_mtime;
5054 }
5055 }
5056 }
5057 msg_scroll = msg_save;
5058
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005059#ifdef FEAT_PERSISTENT_UNDO
5060 /*
5061 * When writing the whole file and 'undofile' is set, also write the undo
5062 * file.
5063 */
5064 if (retval == OK && write_undo_file)
5065 {
5066 char_u hash[UNDO_HASH_SIZE];
5067
5068 sha256_finish(&sha_ctx, hash);
5069 u_write_undo(NULL, FALSE, buf, hash);
5070 }
5071#endif
5072
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073#ifdef FEAT_AUTOCMD
5074#ifdef FEAT_EVAL
5075 if (!should_abort(retval))
5076#else
5077 if (!got_int)
5078#endif
5079 {
5080 aco_save_T aco;
5081
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005082 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5083
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084 /*
5085 * Apply POST autocommands.
5086 * Careful: The autocommands may call buf_write() recursively!
5087 */
5088 aucmd_prepbuf(&aco, buf);
5089
5090 if (append)
5091 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5092 FALSE, curbuf, eap);
5093 else if (filtering)
5094 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5095 FALSE, curbuf, eap);
5096 else if (reset_changed && whole)
5097 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5098 FALSE, curbuf, eap);
5099 else
5100 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5101 FALSE, curbuf, eap);
5102
5103 /* restore curwin/curbuf and a few other things */
5104 aucmd_restbuf(&aco);
5105
5106#ifdef FEAT_EVAL
5107 if (aborting()) /* autocmds may abort script processing */
5108 retval = FALSE;
5109#endif
5110 }
5111#endif
5112
5113 got_int |= prev_got_int;
5114
5115#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5116 /* Update machine specific information. */
5117 mch_post_buffer_write(buf);
5118#endif
5119 return retval;
5120}
5121
5122/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005123 * Set the name of the current buffer. Use when the buffer doesn't have a
5124 * name and a ":r" or ":w" command with a file name is used.
5125 */
5126 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005127set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005128{
5129#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005130 buf_T *buf = curbuf;
5131
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005132 /* It's like the unnamed buffer is deleted.... */
5133 if (curbuf->b_p_bl)
5134 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5135 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5136# ifdef FEAT_EVAL
5137 if (aborting()) /* autocmds may abort script processing */
5138 return FAIL;
5139# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005140 if (curbuf != buf)
5141 {
5142 /* We are in another buffer now, don't do the renaming. */
5143 EMSG(_(e_auchangedbuf));
5144 return FAIL;
5145 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005146#endif
5147
5148 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5149 curbuf->b_flags |= BF_NOTEDITED;
5150
5151#ifdef FEAT_AUTOCMD
5152 /* ....and a new named one is created */
5153 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5154 if (curbuf->b_p_bl)
5155 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5156# ifdef FEAT_EVAL
5157 if (aborting()) /* autocmds may abort script processing */
5158 return FAIL;
5159# endif
5160
5161 /* Do filetype detection now if 'filetype' is empty. */
5162 if (*curbuf->b_p_ft == NUL)
5163 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005164 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005165 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005166 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005167 }
5168#endif
5169
5170 return OK;
5171}
5172
5173/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174 * Put file name into IObuff with quotes.
5175 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005176 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005177msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005178{
5179 if (fname == NULL)
5180 fname = (char_u *)"-stdin-";
5181 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5182 IObuff[0] = '"';
5183 STRCAT(IObuff, "\" ");
5184}
5185
5186/*
5187 * Append message for text mode to IObuff.
5188 * Return TRUE if something appended.
5189 */
5190 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005191msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192{
5193#ifndef USE_CRNL
5194 if (eol_type == EOL_DOS)
5195 {
5196 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5197 return TRUE;
5198 }
5199#endif
5200#ifndef USE_CR
5201 if (eol_type == EOL_MAC)
5202 {
5203 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5204 return TRUE;
5205 }
5206#endif
5207#if defined(USE_CRNL) || defined(USE_CR)
5208 if (eol_type == EOL_UNIX)
5209 {
5210 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5211 return TRUE;
5212 }
5213#endif
5214 return FALSE;
5215}
5216
5217/*
5218 * Append line and character count to IObuff.
5219 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005220 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005221msg_add_lines(
5222 int insert_space,
5223 long lnum,
5224 off_t nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225{
5226 char_u *p;
5227
5228 p = IObuff + STRLEN(IObuff);
5229
5230 if (insert_space)
5231 *p++ = ' ';
5232 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005233 sprintf((char *)p,
5234#ifdef LONG_LONG_OFF_T
Bram Moolenaar581966e2014-02-23 22:58:17 +01005235 "%ldL, %lldC", lnum, (long long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005236#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005237 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5238 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005239#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005240 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 else
5242 {
5243 if (lnum == 1)
5244 STRCPY(p, _("1 line, "));
5245 else
5246 sprintf((char *)p, _("%ld lines, "), lnum);
5247 p += STRLEN(p);
5248 if (nchars == 1)
5249 STRCPY(p, _("1 character"));
5250 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005251 sprintf((char *)p,
5252#ifdef LONG_LONG_OFF_T
Bram Moolenaar581966e2014-02-23 22:58:17 +01005253 _("%lld characters"), (long long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005254#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005255 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5256 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005257#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005258 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259 }
5260}
5261
5262/*
5263 * Append message for missing line separator to IObuff.
5264 */
5265 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005266msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267{
5268 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5269}
5270
5271/*
5272 * Check modification time of file, before writing to it.
5273 * The size isn't checked, because using a tool like "gzip" takes care of
5274 * using the same timestamp but can't set the size.
5275 */
5276 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005277check_mtime(buf_T *buf, struct stat *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278{
5279 if (buf->b_mtime_read != 0
5280 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5281 {
5282 msg_scroll = TRUE; /* don't overwrite messages here */
5283 msg_silent = 0; /* must give this prompt */
5284 /* don't use emsg() here, don't want to flush the buffers */
5285 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5286 hl_attr(HLF_E));
5287 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5288 TRUE) == 'n')
5289 return FAIL;
5290 msg_scroll = FALSE; /* always overwrite the file message now */
5291 }
5292 return OK;
5293}
5294
5295 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005296time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005297{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005298#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5300 * the seconds. Since the roundoff is done when flushing the inode, the
5301 * time may change unexpectedly by one second!!! */
5302 return (t1 - t2 > 1 || t2 - t1 > 1);
5303#else
5304 return (t1 != t2);
5305#endif
5306}
5307
5308/*
5309 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005310 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311 *
5312 * Return FAIL for failure, OK otherwise.
5313 */
5314 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005315buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005316{
5317 int wlen;
5318 char_u *buf = ip->bw_buf; /* data to write */
5319 int len = ip->bw_len; /* length of data */
5320#ifdef HAS_BW_FLAGS
5321 int flags = ip->bw_flags; /* extra flags */
5322#endif
5323
5324#ifdef FEAT_MBYTE
5325 /*
5326 * Skip conversion when writing the crypt magic number or the BOM.
5327 */
5328 if (!(flags & FIO_NOCONVERT))
5329 {
5330 char_u *p;
5331 unsigned c;
5332 int n;
5333
5334 if (flags & FIO_UTF8)
5335 {
5336 /*
5337 * Convert latin1 in the buffer to UTF-8 in the file.
5338 */
5339 p = ip->bw_conv_buf; /* translate to buffer */
5340 for (wlen = 0; wlen < len; ++wlen)
5341 p += utf_char2bytes(buf[wlen], p);
5342 buf = ip->bw_conv_buf;
5343 len = (int)(p - ip->bw_conv_buf);
5344 }
5345 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5346 {
5347 /*
5348 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5349 * Latin1 chars in the file.
5350 */
5351 if (flags & FIO_LATIN1)
5352 p = buf; /* translate in-place (can only get shorter) */
5353 else
5354 p = ip->bw_conv_buf; /* translate to buffer */
5355 for (wlen = 0; wlen < len; wlen += n)
5356 {
5357 if (wlen == 0 && ip->bw_restlen != 0)
5358 {
5359 int l;
5360
5361 /* Use remainder of previous call. Append the start of
5362 * buf[] to get a full sequence. Might still be too
5363 * short! */
5364 l = CONV_RESTLEN - ip->bw_restlen;
5365 if (l > len)
5366 l = len;
5367 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005368 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005369 if (n > ip->bw_restlen + len)
5370 {
5371 /* We have an incomplete byte sequence at the end to
5372 * be written. We can't convert it without the
5373 * remaining bytes. Keep them for the next call. */
5374 if (ip->bw_restlen + len > CONV_RESTLEN)
5375 return FAIL;
5376 ip->bw_restlen += len;
5377 break;
5378 }
5379 if (n > 1)
5380 c = utf_ptr2char(ip->bw_rest);
5381 else
5382 c = ip->bw_rest[0];
5383 if (n >= ip->bw_restlen)
5384 {
5385 n -= ip->bw_restlen;
5386 ip->bw_restlen = 0;
5387 }
5388 else
5389 {
5390 ip->bw_restlen -= n;
5391 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5392 (size_t)ip->bw_restlen);
5393 n = 0;
5394 }
5395 }
5396 else
5397 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005398 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399 if (n > len - wlen)
5400 {
5401 /* We have an incomplete byte sequence at the end to
5402 * be written. We can't convert it without the
5403 * remaining bytes. Keep them for the next call. */
5404 if (len - wlen > CONV_RESTLEN)
5405 return FAIL;
5406 ip->bw_restlen = len - wlen;
5407 mch_memmove(ip->bw_rest, buf + wlen,
5408 (size_t)ip->bw_restlen);
5409 break;
5410 }
5411 if (n > 1)
5412 c = utf_ptr2char(buf + wlen);
5413 else
5414 c = buf[wlen];
5415 }
5416
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005417 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5418 {
5419 ip->bw_conv_error = TRUE;
5420 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5421 }
5422 if (c == NL)
5423 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005424 }
5425 if (flags & FIO_LATIN1)
5426 len = (int)(p - buf);
5427 else
5428 {
5429 buf = ip->bw_conv_buf;
5430 len = (int)(p - ip->bw_conv_buf);
5431 }
5432 }
5433
5434# ifdef WIN3264
5435 else if (flags & FIO_CODEPAGE)
5436 {
5437 /*
5438 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5439 * codepage.
5440 */
5441 char_u *from;
5442 size_t fromlen;
5443 char_u *to;
5444 int u8c;
5445 BOOL bad = FALSE;
5446 int needed;
5447
5448 if (ip->bw_restlen > 0)
5449 {
5450 /* Need to concatenate the remainder of the previous call and
5451 * the bytes of the current call. Use the end of the
5452 * conversion buffer for this. */
5453 fromlen = len + ip->bw_restlen;
5454 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5455 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5456 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5457 }
5458 else
5459 {
5460 from = buf;
5461 fromlen = len;
5462 }
5463
5464 to = ip->bw_conv_buf;
5465 if (enc_utf8)
5466 {
5467 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5468 * The buffer has been allocated to be big enough. */
5469 while (fromlen > 0)
5470 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005471 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 if (n > (int)fromlen) /* incomplete byte sequence */
5473 break;
5474 u8c = utf_ptr2char(from);
5475 *to++ = (u8c & 0xff);
5476 *to++ = (u8c >> 8);
5477 fromlen -= n;
5478 from += n;
5479 }
5480
5481 /* Copy remainder to ip->bw_rest[] to be used for the next
5482 * call. */
5483 if (fromlen > CONV_RESTLEN)
5484 {
5485 /* weird overlong sequence */
5486 ip->bw_conv_error = TRUE;
5487 return FAIL;
5488 }
5489 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005490 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491 }
5492 else
5493 {
5494 /* Convert from enc_codepage to UCS-2, to the start of the
5495 * buffer. The buffer has been allocated to be big enough. */
5496 ip->bw_restlen = 0;
5497 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005498 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499 NULL, 0);
5500 if (needed == 0)
5501 {
5502 /* When conversion fails there may be a trailing byte. */
5503 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005504 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505 NULL, 0);
5506 if (needed == 0)
5507 {
5508 /* Conversion doesn't work. */
5509 ip->bw_conv_error = TRUE;
5510 return FAIL;
5511 }
5512 /* Save the trailing byte for the next call. */
5513 ip->bw_rest[0] = from[fromlen - 1];
5514 ip->bw_restlen = 1;
5515 }
5516 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005517 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 (LPWSTR)to, needed);
5519 if (needed == 0)
5520 {
5521 /* Safety check: Conversion doesn't work. */
5522 ip->bw_conv_error = TRUE;
5523 return FAIL;
5524 }
5525 to += needed * 2;
5526 }
5527
5528 fromlen = to - ip->bw_conv_buf;
5529 buf = to;
5530# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5531 if (FIO_GET_CP(flags) == CP_UTF8)
5532 {
5533 /* Convert from UCS-2 to UTF-8, using the remainder of the
5534 * conversion buffer. Fails when out of space. */
5535 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5536 {
5537 u8c = *from++;
5538 u8c += (*from++ << 8);
5539 to += utf_char2bytes(u8c, to);
5540 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5541 {
5542 ip->bw_conv_error = TRUE;
5543 return FAIL;
5544 }
5545 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005546 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 }
5548 else
5549#endif
5550 {
5551 /* Convert from UCS-2 to the codepage, using the remainder of
5552 * the conversion buffer. If the conversion uses the default
5553 * character "0", the data doesn't fit in this encoding, so
5554 * fail. */
5555 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5556 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005557 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5558 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559 if (bad)
5560 {
5561 ip->bw_conv_error = TRUE;
5562 return FAIL;
5563 }
5564 }
5565 }
5566# endif
5567
Bram Moolenaar56718732006-03-15 22:53:57 +00005568# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005569 else if (flags & FIO_MACROMAN)
5570 {
5571 /*
5572 * Convert UTF-8 or latin1 to Apple MacRoman.
5573 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 char_u *from;
5575 size_t fromlen;
5576
5577 if (ip->bw_restlen > 0)
5578 {
5579 /* Need to concatenate the remainder of the previous call and
5580 * the bytes of the current call. Use the end of the
5581 * conversion buffer for this. */
5582 fromlen = len + ip->bw_restlen;
5583 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5584 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5585 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5586 }
5587 else
5588 {
5589 from = buf;
5590 fromlen = len;
5591 }
5592
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005593 if (enc2macroman(from, fromlen,
5594 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5595 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 {
5597 ip->bw_conv_error = TRUE;
5598 return FAIL;
5599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 }
5602# endif
5603
5604# ifdef USE_ICONV
5605 if (ip->bw_iconv_fd != (iconv_t)-1)
5606 {
5607 const char *from;
5608 size_t fromlen;
5609 char *to;
5610 size_t tolen;
5611
5612 /* Convert with iconv(). */
5613 if (ip->bw_restlen > 0)
5614 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005615 char *fp;
5616
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617 /* Need to concatenate the remainder of the previous call and
5618 * the bytes of the current call. Use the end of the
5619 * conversion buffer for this. */
5620 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005621 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5622 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5623 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5624 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 tolen = ip->bw_conv_buflen - fromlen;
5626 }
5627 else
5628 {
5629 from = (const char *)buf;
5630 fromlen = len;
5631 tolen = ip->bw_conv_buflen;
5632 }
5633 to = (char *)ip->bw_conv_buf;
5634
5635 if (ip->bw_first)
5636 {
5637 size_t save_len = tolen;
5638
5639 /* output the initial shift state sequence */
5640 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5641
5642 /* There is a bug in iconv() on Linux (which appears to be
5643 * wide-spread) which sets "to" to NULL and messes up "tolen".
5644 */
5645 if (to == NULL)
5646 {
5647 to = (char *)ip->bw_conv_buf;
5648 tolen = save_len;
5649 }
5650 ip->bw_first = FALSE;
5651 }
5652
5653 /*
5654 * If iconv() has an error or there is not enough room, fail.
5655 */
5656 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5657 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5658 || fromlen > CONV_RESTLEN)
5659 {
5660 ip->bw_conv_error = TRUE;
5661 return FAIL;
5662 }
5663
5664 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5665 if (fromlen > 0)
5666 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5667 ip->bw_restlen = (int)fromlen;
5668
5669 buf = ip->bw_conv_buf;
5670 len = (int)((char_u *)to - ip->bw_conv_buf);
5671 }
5672# endif
5673 }
5674#endif /* FEAT_MBYTE */
5675
5676#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005677 if (flags & FIO_ENCRYPTED)
5678 {
5679 /* Encrypt the data. Do it in-place if possible, otherwise use an
5680 * allocated buffer. */
5681 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5682 {
5683 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5684 }
5685 else
5686 {
5687 char_u *outbuf;
5688
5689 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5690 if (len == 0)
5691 return OK; /* Crypt layer is buffering, will flush later. */
5692 wlen = write_eintr(ip->bw_fd, outbuf, len);
5693 vim_free(outbuf);
5694 return (wlen < len) ? FAIL : OK;
5695 }
5696 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005697#endif
5698
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005699 wlen = write_eintr(ip->bw_fd, buf, len);
5700 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701}
5702
5703#ifdef FEAT_MBYTE
5704/*
5705 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005706 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 */
5708 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005709ucs2bytes(
5710 unsigned c, /* in: character */
5711 char_u **pp, /* in/out: pointer to result */
5712 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713{
5714 char_u *p = *pp;
5715 int error = FALSE;
5716 int cc;
5717
5718
5719 if (flags & FIO_UCS4)
5720 {
5721 if (flags & FIO_ENDIAN_L)
5722 {
5723 *p++ = c;
5724 *p++ = (c >> 8);
5725 *p++ = (c >> 16);
5726 *p++ = (c >> 24);
5727 }
5728 else
5729 {
5730 *p++ = (c >> 24);
5731 *p++ = (c >> 16);
5732 *p++ = (c >> 8);
5733 *p++ = c;
5734 }
5735 }
5736 else if (flags & (FIO_UCS2 | FIO_UTF16))
5737 {
5738 if (c >= 0x10000)
5739 {
5740 if (flags & FIO_UTF16)
5741 {
5742 /* Make two words, ten bits of the character in each. First
5743 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5744 c -= 0x10000;
5745 if (c >= 0x100000)
5746 error = TRUE;
5747 cc = ((c >> 10) & 0x3ff) + 0xd800;
5748 if (flags & FIO_ENDIAN_L)
5749 {
5750 *p++ = cc;
5751 *p++ = ((unsigned)cc >> 8);
5752 }
5753 else
5754 {
5755 *p++ = ((unsigned)cc >> 8);
5756 *p++ = cc;
5757 }
5758 c = (c & 0x3ff) + 0xdc00;
5759 }
5760 else
5761 error = TRUE;
5762 }
5763 if (flags & FIO_ENDIAN_L)
5764 {
5765 *p++ = c;
5766 *p++ = (c >> 8);
5767 }
5768 else
5769 {
5770 *p++ = (c >> 8);
5771 *p++ = c;
5772 }
5773 }
5774 else /* Latin1 */
5775 {
5776 if (c >= 0x100)
5777 {
5778 error = TRUE;
5779 *p++ = 0xBF;
5780 }
5781 else
5782 *p++ = c;
5783 }
5784
5785 *pp = p;
5786 return error;
5787}
5788
5789/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005790 * Return TRUE if file encoding "fenc" requires conversion from or to
5791 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 */
5793 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005794need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005796 int same_encoding;
5797 int enc_flags;
5798 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005800 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005801 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005802 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005803 fenc_flags = 0;
5804 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005805 else
5806 {
5807 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5808 * "ucs-4be", etc. */
5809 enc_flags = get_fio_flags(p_enc);
5810 fenc_flags = get_fio_flags(fenc);
5811 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5812 }
5813 if (same_encoding)
5814 {
5815 /* Specified encoding matches with 'encoding'. This requires
5816 * conversion when 'encoding' is Unicode but not UTF-8. */
5817 return enc_unicode != 0;
5818 }
5819
5820 /* Encodings differ. However, conversion is not needed when 'enc' is any
5821 * Unicode encoding and the file is UTF-8. */
5822 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823}
5824
5825/*
5826 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5827 * internal conversion.
5828 * if "ptr" is an empty string, use 'encoding'.
5829 */
5830 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005831get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832{
5833 int prop;
5834
5835 if (*ptr == NUL)
5836 ptr = p_enc;
5837
5838 prop = enc_canon_props(ptr);
5839 if (prop & ENC_UNICODE)
5840 {
5841 if (prop & ENC_2BYTE)
5842 {
5843 if (prop & ENC_ENDIAN_L)
5844 return FIO_UCS2 | FIO_ENDIAN_L;
5845 return FIO_UCS2;
5846 }
5847 if (prop & ENC_4BYTE)
5848 {
5849 if (prop & ENC_ENDIAN_L)
5850 return FIO_UCS4 | FIO_ENDIAN_L;
5851 return FIO_UCS4;
5852 }
5853 if (prop & ENC_2WORD)
5854 {
5855 if (prop & ENC_ENDIAN_L)
5856 return FIO_UTF16 | FIO_ENDIAN_L;
5857 return FIO_UTF16;
5858 }
5859 return FIO_UTF8;
5860 }
5861 if (prop & ENC_LATIN1)
5862 return FIO_LATIN1;
5863 /* must be ENC_DBCS, requires iconv() */
5864 return 0;
5865}
5866
5867#ifdef WIN3264
5868/*
5869 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5870 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5871 * Used for conversion between 'encoding' and 'fileencoding'.
5872 */
5873 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005874get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875{
5876 int cp;
5877
5878 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5879 if (!enc_utf8 && enc_codepage <= 0)
5880 return 0;
5881
5882 cp = encname2codepage(ptr);
5883 if (cp == 0)
5884 {
5885# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5886 if (STRCMP(ptr, "utf-8") == 0)
5887 cp = CP_UTF8;
5888 else
5889# endif
5890 return 0;
5891 }
5892 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5893}
5894#endif
5895
5896#ifdef MACOS_X
5897/*
5898 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5899 * needed for the internal conversion to/from utf-8 or latin1.
5900 */
5901 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005902get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903{
5904 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5905 && (enc_canon_props(ptr) & ENC_MACROMAN))
5906 return FIO_MACROMAN;
5907 return 0;
5908}
5909#endif
5910
5911/*
5912 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5913 * "size" must be at least 2.
5914 * Return the name of the encoding and set "*lenp" to the length.
5915 * Returns NULL when no BOM found.
5916 */
5917 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005918check_for_bom(
5919 char_u *p,
5920 long size,
5921 int *lenp,
5922 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923{
5924 char *name = NULL;
5925 int len = 2;
5926
5927 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005928 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929 {
5930 name = "utf-8"; /* EF BB BF */
5931 len = 3;
5932 }
5933 else if (p[0] == 0xff && p[1] == 0xfe)
5934 {
5935 if (size >= 4 && p[2] == 0 && p[3] == 0
5936 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5937 {
5938 name = "ucs-4le"; /* FF FE 00 00 */
5939 len = 4;
5940 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005941 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005943 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5944 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 name = "utf-16le"; /* FF FE */
5946 }
5947 else if (p[0] == 0xfe && p[1] == 0xff
5948 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5949 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005950 /* Default to utf-16, it works also for ucs-2 text. */
5951 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005953 else
5954 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 }
5956 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5957 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5958 {
5959 name = "ucs-4"; /* 00 00 FE FF */
5960 len = 4;
5961 }
5962
5963 *lenp = len;
5964 return (char_u *)name;
5965}
5966
5967/*
5968 * Generate a BOM in "buf[4]" for encoding "name".
5969 * Return the length of the BOM (zero when no BOM).
5970 */
5971 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005972make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973{
5974 int flags;
5975 char_u *p;
5976
5977 flags = get_fio_flags(name);
5978
5979 /* Can't put a BOM in a non-Unicode file. */
5980 if (flags == FIO_LATIN1 || flags == 0)
5981 return 0;
5982
5983 if (flags == FIO_UTF8) /* UTF-8 */
5984 {
5985 buf[0] = 0xef;
5986 buf[1] = 0xbb;
5987 buf[2] = 0xbf;
5988 return 3;
5989 }
5990 p = buf;
5991 (void)ucs2bytes(0xfeff, &p, flags);
5992 return (int)(p - buf);
5993}
5994#endif
5995
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005996#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005997 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998/*
5999 * Try to find a shortname by comparing the fullname with the current
6000 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006001 * Returns "full_path" or pointer into "full_path" if shortened.
6002 */
6003 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006004shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006005{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006006 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006007 char_u *p = full_path;
6008
Bram Moolenaard9462e32011-04-11 21:35:11 +02006009 dirname = alloc(MAXPATHL);
6010 if (dirname == NULL)
6011 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006012 if (mch_dirname(dirname, MAXPATHL) == OK)
6013 {
6014 p = shorten_fname(full_path, dirname);
6015 if (p == NULL || *p == NUL)
6016 p = full_path;
6017 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006018 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006019 return p;
6020}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006021#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006022
6023/*
6024 * Try to find a shortname by comparing the fullname with the current
6025 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 * Returns NULL if not shorter name possible, pointer into "full_path"
6027 * otherwise.
6028 */
6029 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006030shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031{
6032 int len;
6033 char_u *p;
6034
6035 if (full_path == NULL)
6036 return NULL;
6037 len = (int)STRLEN(dir_name);
6038 if (fnamencmp(dir_name, full_path, len) == 0)
6039 {
6040 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006041#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006043 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 * slash, since C: by itself does not define a specific dir. In this
6045 * case p may already be correct. <negri>
6046 */
6047 if (!((len > 2) && (*(p - 2) == ':')))
6048#endif
6049 {
6050 if (vim_ispathsep(*p))
6051 ++p;
6052#ifndef VMS /* the path separator is always part of the path */
6053 else
6054 p = NULL;
6055#endif
6056 }
6057 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006058#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059 /*
6060 * When using a file in the current drive, remove the drive name:
6061 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6062 * a floppy from "A:\dir" to "B:\dir".
6063 */
6064 else if (len > 3
6065 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6066 && full_path[1] == ':'
6067 && vim_ispathsep(full_path[2]))
6068 p = full_path + 2;
6069#endif
6070 else
6071 p = NULL;
6072 return p;
6073}
6074
6075/*
6076 * Shorten filenames for all buffers.
6077 * When "force" is TRUE: Use full path from now on for files currently being
6078 * edited, both for file name and swap file name. Try to shorten the file
6079 * names a bit, if safe to do so.
6080 * When "force" is FALSE: Only try to shorten absolute file names.
6081 * For buffers that have buftype "nofile" or "scratch": never change the file
6082 * name.
6083 */
6084 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006085shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086{
6087 char_u dirname[MAXPATHL];
6088 buf_T *buf;
6089 char_u *p;
6090
6091 mch_dirname(dirname, MAXPATHL);
6092 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6093 {
6094 if (buf->b_fname != NULL
6095#ifdef FEAT_QUICKFIX
6096 && !bt_nofile(buf)
6097#endif
6098 && !path_with_url(buf->b_fname)
6099 && (force
6100 || buf->b_sfname == NULL
6101 || mch_isFullName(buf->b_sfname)))
6102 {
6103 vim_free(buf->b_sfname);
6104 buf->b_sfname = NULL;
6105 p = shorten_fname(buf->b_ffname, dirname);
6106 if (p != NULL)
6107 {
6108 buf->b_sfname = vim_strsave(p);
6109 buf->b_fname = buf->b_sfname;
6110 }
6111 if (p == NULL || buf->b_fname == NULL)
6112 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006114
6115 /* Always make the swap file name a full path, a "nofile" buffer may
6116 * also have a swap file. */
6117 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 }
6119#ifdef FEAT_WINDOWS
6120 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006121 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122#endif
6123}
6124
6125#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6126 || defined(FEAT_GUI_MSWIN) \
6127 || defined(FEAT_GUI_MAC) \
6128 || defined(PROTO)
6129/*
6130 * Shorten all filenames in "fnames[count]" by current directory.
6131 */
6132 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006133shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134{
6135 int i;
6136 char_u dirname[MAXPATHL];
6137 char_u *p;
6138
6139 if (fnames == NULL || count < 1)
6140 return;
6141 mch_dirname(dirname, sizeof(dirname));
6142 for (i = 0; i < count; ++i)
6143 {
6144 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6145 {
6146 /* shorten_fname() returns pointer in given "fnames[i]". If free
6147 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6148 * "p" first then free fnames[i]. */
6149 p = vim_strsave(p);
6150 vim_free(fnames[i]);
6151 fnames[i] = p;
6152 }
6153 }
6154}
6155#endif
6156
6157/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006158 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159 * fo_o_h.ext for MSDOS or when shortname option set.
6160 *
6161 * Assumed that fname is a valid name found in the filesystem we assure that
6162 * the return value is a different name and ends in 'ext'.
6163 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6164 * characters otherwise.
6165 * Space for the returned name is allocated, must be freed later.
6166 * Returns NULL when out of memory.
6167 */
6168 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006169modname(
6170 char_u *fname,
6171 char_u *ext,
6172 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006174 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 fname, ext, prepend_dot);
6176}
6177
6178 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006179buf_modname(
6180 int shortname, /* use 8.3 file name */
6181 char_u *fname,
6182 char_u *ext,
6183 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184{
6185 char_u *retval;
6186 char_u *s;
6187 char_u *e;
6188 char_u *ptr;
6189 int fnamelen, extlen;
6190
6191 extlen = (int)STRLEN(ext);
6192
6193 /*
6194 * If there is no file name we must get the name of the current directory
6195 * (we need the full path in case :cd is used).
6196 */
6197 if (fname == NULL || *fname == NUL)
6198 {
6199 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6200 if (retval == NULL)
6201 return NULL;
6202 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6203 (fnamelen = (int)STRLEN(retval)) == 0)
6204 {
6205 vim_free(retval);
6206 return NULL;
6207 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006208 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 {
6210 retval[fnamelen++] = PATHSEP;
6211 retval[fnamelen] = NUL;
6212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 }
6215 else
6216 {
6217 fnamelen = (int)STRLEN(fname);
6218 retval = alloc((unsigned)(fnamelen + extlen + 3));
6219 if (retval == NULL)
6220 return NULL;
6221 STRCPY(retval, fname);
6222#ifdef VMS
6223 vms_remove_version(retval); /* we do not need versions here */
6224#endif
6225 }
6226
6227 /*
6228 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6229 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6230 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6231 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6232 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006233 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006236#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006238#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006240#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 )
6242 if (*ptr == '.') /* replace '.' by '_' */
6243 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006245 {
6246 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250
6251 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6253 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254
6255 s = ptr + STRLEN(ptr);
6256
6257 /*
6258 * For 8.3 file names we may have to reduce the length.
6259 */
6260#ifdef USE_LONG_FNAME
6261 if (!USE_LONG_FNAME || shortname)
6262#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264#endif
6265 {
6266 /*
6267 * If there is no file name, or the file name ends in '/', and the
6268 * extension starts with '.', put a '_' before the dot, because just
6269 * ".ext" is invalid.
6270 */
6271 if (fname == NULL || *fname == NUL
6272 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6273 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 *s++ = '_';
6276 }
6277 /*
6278 * If the extension starts with '.', truncate the base name at 8
6279 * characters
6280 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006283 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 {
6285 s = ptr + 8;
6286 *s = '\0';
6287 }
6288 }
6289 /*
6290 * If the extension doesn't start with '.', and the file name
6291 * doesn't have an extension yet, append a '.'
6292 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 else if ((e = vim_strchr(ptr, '.')) == NULL)
6294 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 /*
6296 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006297 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 */
6299 else if ((int)STRLEN(e) + extlen > 4)
6300 s = e + 4 - extlen;
6301 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006302#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 /*
6304 * If there is no file name, and the extension starts with '.', put a
6305 * '_' before the dot, because just ".ext" may be invalid if it's on a
6306 * FAT partition, and on HPFS it doesn't matter.
6307 */
6308 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6309 *s++ = '_';
6310#endif
6311
6312 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006313 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 * ext can start with '.' and cannot exceed 3 more characters.
6315 */
6316 STRCPY(s, ext);
6317
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 /*
6319 * Prepend the dot.
6320 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006321 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322#ifdef USE_LONG_FNAME
6323 && USE_LONG_FNAME
6324#endif
6325 )
6326 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006327 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330
6331 /*
6332 * Check that, after appending the extension, the file name is really
6333 * different.
6334 */
6335 if (fname != NULL && STRCMP(fname, retval) == 0)
6336 {
6337 /* we search for a character that can be replaced by '_' */
6338 while (--s >= ptr)
6339 {
6340 if (*s != '_')
6341 {
6342 *s = '_';
6343 break;
6344 }
6345 }
6346 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6347 *ptr = 'v';
6348 }
6349 return retval;
6350}
6351
6352/*
6353 * Like fgets(), but if the file line is too long, it is truncated and the
6354 * rest of the line is thrown away. Returns TRUE for end-of-file.
6355 */
6356 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006357vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358{
6359 char *eof;
6360#define FGETS_SIZE 200
6361 char tbuf[FGETS_SIZE];
6362
6363 buf[size - 2] = NUL;
6364#ifdef USE_CR
6365 eof = fgets_cr((char *)buf, size, fp);
6366#else
6367 eof = fgets((char *)buf, size, fp);
6368#endif
6369 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6370 {
6371 buf[size - 1] = NUL; /* Truncate the line */
6372
6373 /* Now throw away the rest of the line: */
6374 do
6375 {
6376 tbuf[FGETS_SIZE - 2] = NUL;
6377#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006378 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006380 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381#endif
6382 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6383 }
6384 return (eof == NULL);
6385}
6386
6387#if defined(USE_CR) || defined(PROTO)
6388/*
6389 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6390 * Returns TRUE for end-of-file.
6391 * Only used for the Mac, because it's much slower than vim_fgets().
6392 */
6393 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006394tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395{
6396 int i = 0;
6397 int c;
6398 int eof = FALSE;
6399
6400 for (;;)
6401 {
6402 c = fgetc(fp);
6403 if (c == EOF)
6404 {
6405 eof = TRUE;
6406 break;
6407 }
6408 if (c == '\r')
6409 {
6410 /* Always store a NL for end-of-line. */
6411 if (i < size - 1)
6412 buf[i++] = '\n';
6413 c = fgetc(fp);
6414 if (c != '\n') /* Macintosh format: single CR. */
6415 ungetc(c, fp);
6416 break;
6417 }
6418 if (i < size - 1)
6419 buf[i++] = c;
6420 if (c == '\n')
6421 break;
6422 }
6423 buf[i] = NUL;
6424 return eof;
6425}
6426#endif
6427
6428/*
6429 * rename() only works if both files are on the same file system, this
6430 * function will (attempts to?) copy the file across if rename fails -- webb
6431 * Return -1 for failure, 0 for success.
6432 */
6433 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006434vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435{
6436 int fd_in;
6437 int fd_out;
6438 int n;
6439 char *errmsg = NULL;
6440 char *buffer;
6441#ifdef AMIGA
6442 BPTR flock;
6443#endif
6444 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006445 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006446#ifdef HAVE_ACL
6447 vim_acl_T acl; /* ACL from original file */
6448#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006449 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450
6451 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006452 * When the names are identical, there is nothing to do. When they refer
6453 * to the same file (ignoring case and slash/backslash differences) but
6454 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 */
6456 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006457 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006458 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006459 use_tmp_file = TRUE;
6460 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006461 return 0;
6462 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463
6464 /*
6465 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6466 */
6467 if (mch_stat((char *)from, &st) < 0)
6468 return -1;
6469
Bram Moolenaar3576da72008-12-30 15:15:57 +00006470#ifdef UNIX
6471 {
6472 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006473
6474 /* It's possible for the source and destination to be the same file.
6475 * This happens when "from" and "to" differ in case and are on a FAT32
6476 * filesystem. In that case go through a temp file name. */
6477 if (mch_stat((char *)to, &st_to) >= 0
6478 && st.st_dev == st_to.st_dev
6479 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006480 use_tmp_file = TRUE;
6481 }
6482#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006483#ifdef WIN3264
6484 {
6485 BY_HANDLE_FILE_INFORMATION info1, info2;
6486
6487 /* It's possible for the source and destination to be the same file.
6488 * In that case go through a temp file name. This makes rename("foo",
6489 * "./foo") a no-op (in a complicated way). */
6490 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6491 && win32_fileinfo(to, &info2) == FILEINFO_OK
6492 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6493 && info1.nFileIndexHigh == info2.nFileIndexHigh
6494 && info1.nFileIndexLow == info2.nFileIndexLow)
6495 use_tmp_file = TRUE;
6496 }
6497#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006498
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006499 if (use_tmp_file)
6500 {
6501 char tempname[MAXPATHL + 1];
6502
6503 /*
6504 * Find a name that doesn't exist and is in the same directory.
6505 * Rename "from" to "tempname" and then rename "tempname" to "to".
6506 */
6507 if (STRLEN(from) >= MAXPATHL - 5)
6508 return -1;
6509 STRCPY(tempname, from);
6510 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006511 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006512 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6513 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006514 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006515 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006516 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006517 if (mch_rename(tempname, (char *)to) == 0)
6518 return 0;
6519 /* Strange, the second step failed. Try moving the
6520 * file back and return failure. */
6521 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006522 return -1;
6523 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006524 /* If it fails for one temp name it will most likely fail
6525 * for any temp name, give up. */
6526 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006527 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006528 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006529 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006530 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006531
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 /*
6533 * Delete the "to" file, this is required on some systems to make the
6534 * mch_rename() work, on other systems it makes sure that we don't have
6535 * two files when the mch_rename() fails.
6536 */
6537
6538#ifdef AMIGA
6539 /*
6540 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6541 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006542 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 * deleting the "from" file (horror!) we lock it during the remove.
6544 *
6545 * When used for making a backup before writing the file: This should not
6546 * happen with ":w", because startscript() should detect this problem and
6547 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6548 * name. This problem does exist with ":w filename", but then the
6549 * original file will be somewhere else so the backup isn't really
6550 * important. If autoscripting is off the rename may fail.
6551 */
6552 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6553#endif
6554 mch_remove(to);
6555#ifdef AMIGA
6556 if (flock)
6557 UnLock(flock);
6558#endif
6559
6560 /*
6561 * First try a normal rename, return if it works.
6562 */
6563 if (mch_rename((char *)from, (char *)to) == 0)
6564 return 0;
6565
6566 /*
6567 * Rename() failed, try copying the file.
6568 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006569 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006570#ifdef HAVE_ACL
6571 /* For systems that support ACL: get the ACL from the original file. */
6572 acl = mch_get_acl(from);
6573#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6575 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006576 {
6577#ifdef HAVE_ACL
6578 mch_free_acl(acl);
6579#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006581 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006582
6583 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006584 fd_out = mch_open((char *)to,
6585 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 if (fd_out == -1)
6587 {
6588 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006589#ifdef HAVE_ACL
6590 mch_free_acl(acl);
6591#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 return -1;
6593 }
6594
6595 buffer = (char *)alloc(BUFSIZE);
6596 if (buffer == NULL)
6597 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006599 close(fd_in);
6600#ifdef HAVE_ACL
6601 mch_free_acl(acl);
6602#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 return -1;
6604 }
6605
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006606 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6607 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 {
6609 errmsg = _("E208: Error writing to \"%s\"");
6610 break;
6611 }
6612
6613 vim_free(buffer);
6614 close(fd_in);
6615 if (close(fd_out) < 0)
6616 errmsg = _("E209: Error closing \"%s\"");
6617 if (n < 0)
6618 {
6619 errmsg = _("E210: Error reading \"%s\"");
6620 to = from;
6621 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006622#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006623 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006624#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006625#ifdef HAVE_ACL
6626 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006627 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006628#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006629#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006630 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006631#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 if (errmsg != NULL)
6633 {
6634 EMSG2(errmsg, to);
6635 return -1;
6636 }
6637 mch_remove(from);
6638 return 0;
6639}
6640
6641static int already_warned = FALSE;
6642
6643/*
6644 * Check if any not hidden buffer has been changed.
6645 * Postpone the check if there are characters in the stuff buffer, a global
6646 * command is being executed, a mapping is being executed or an autocommand is
6647 * busy.
6648 * Returns TRUE if some message was written (screen should be redrawn and
6649 * cursor positioned).
6650 */
6651 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006652check_timestamps(
6653 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654{
6655 buf_T *buf;
6656 int didit = 0;
6657 int n;
6658
6659 /* Don't check timestamps while system() or another low-level function may
6660 * cause us to lose and gain focus. */
6661 if (no_check_timestamps > 0)
6662 return FALSE;
6663
6664 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6665 * event and we would keep on checking if the file is steadily growing.
6666 * Do check again after typing something. */
6667 if (focus && did_check_timestamps)
6668 {
6669 need_check_timestamps = TRUE;
6670 return FALSE;
6671 }
6672
6673 if (!stuff_empty() || global_busy || !typebuf_typed()
6674#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006675 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676#endif
6677 )
6678 need_check_timestamps = TRUE; /* check later */
6679 else
6680 {
6681 ++no_wait_return;
6682 did_check_timestamps = TRUE;
6683 already_warned = FALSE;
6684 for (buf = firstbuf; buf != NULL; )
6685 {
6686 /* Only check buffers in a window. */
6687 if (buf->b_nwindows > 0)
6688 {
6689 n = buf_check_timestamp(buf, focus);
6690 if (didit < n)
6691 didit = n;
6692 if (n > 0 && !buf_valid(buf))
6693 {
6694 /* Autocommands have removed the buffer, start at the
6695 * first one again. */
6696 buf = firstbuf;
6697 continue;
6698 }
6699 }
6700 buf = buf->b_next;
6701 }
6702 --no_wait_return;
6703 need_check_timestamps = FALSE;
6704 if (need_wait_return && didit == 2)
6705 {
6706 /* make sure msg isn't overwritten */
6707 msg_puts((char_u *)"\n");
6708 out_flush();
6709 }
6710 }
6711 return didit;
6712}
6713
6714/*
6715 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6716 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6717 * empty.
6718 */
6719 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006720move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721{
6722 buf_T *tbuf = curbuf;
6723 int retval = OK;
6724 linenr_T lnum;
6725 char_u *p;
6726
6727 /* Copy the lines in "frombuf" to "tobuf". */
6728 curbuf = tobuf;
6729 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6730 {
6731 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6732 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6733 {
6734 vim_free(p);
6735 retval = FAIL;
6736 break;
6737 }
6738 vim_free(p);
6739 }
6740
6741 /* Delete all the lines in "frombuf". */
6742 if (retval != FAIL)
6743 {
6744 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006745 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6746 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 {
6748 /* Oops! We could try putting back the saved lines, but that
6749 * might fail again... */
6750 retval = FAIL;
6751 break;
6752 }
6753 }
6754
6755 curbuf = tbuf;
6756 return retval;
6757}
6758
6759/*
6760 * Check if buffer "buf" has been changed.
6761 * Also check if the file for a new buffer unexpectedly appeared.
6762 * return 1 if a changed buffer was found.
6763 * return 2 if a message has been displayed.
6764 * return 0 otherwise.
6765 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006767buf_check_timestamp(
6768 buf_T *buf,
6769 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770{
6771 struct stat st;
6772 int stat_res;
6773 int retval = 0;
6774 char_u *path;
6775 char_u *tbuf;
6776 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006777 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 int helpmesg = FALSE;
6779 int reload = FALSE;
6780#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6781 int can_reload = FALSE;
6782#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006783 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 int orig_mode = buf->b_orig_mode;
6785#ifdef FEAT_GUI
6786 int save_mouse_correct = need_mouse_correct;
6787#endif
6788#ifdef FEAT_AUTOCMD
6789 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006790 int n;
6791 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006793 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794
6795 /* If there is no file name, the buffer is not loaded, 'buftype' is
6796 * set, we are in the middle of a save or being called recursively: ignore
6797 * this buffer. */
6798 if (buf->b_ffname == NULL
6799 || buf->b_ml.ml_mfp == NULL
6800#if defined(FEAT_QUICKFIX)
6801 || *buf->b_p_bt != NUL
6802#endif
6803 || buf->b_saving
6804#ifdef FEAT_AUTOCMD
6805 || busy
6806#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006807#ifdef FEAT_NETBEANS_INTG
6808 || isNetbeansBuffer(buf)
6809#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 )
6811 return 0;
6812
6813 if ( !(buf->b_flags & BF_NOTEDITED)
6814 && buf->b_mtime != 0
6815 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6816 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006817 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818#ifdef HAVE_ST_MODE
6819 || (int)st.st_mode != buf->b_orig_mode
6820#else
6821 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6822#endif
6823 ))
6824 {
6825 retval = 1;
6826
Bram Moolenaar316059c2006-01-14 21:18:42 +00006827 /* set b_mtime to stop further warnings (e.g., when executing
6828 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 if (stat_res < 0)
6830 {
6831 buf->b_mtime = 0;
6832 buf->b_orig_size = 0;
6833 buf->b_orig_mode = 0;
6834 }
6835 else
6836 buf_store_time(buf, &st, buf->b_ffname);
6837
6838 /* Don't do anything for a directory. Might contain the file
6839 * explorer. */
6840 if (mch_isdir(buf->b_fname))
6841 ;
6842
6843 /*
6844 * If 'autoread' is set, the buffer has no changes and the file still
6845 * exists, reload the buffer. Use the buffer-local option value if it
6846 * was set, the global option value otherwise.
6847 */
6848 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6849 && !bufIsChanged(buf) && stat_res >= 0)
6850 reload = TRUE;
6851 else
6852 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006853 if (stat_res < 0)
6854 reason = "deleted";
6855 else if (bufIsChanged(buf))
6856 reason = "conflict";
6857 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6858 reason = "changed";
6859 else if (orig_mode != buf->b_orig_mode)
6860 reason = "mode";
6861 else
6862 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006864#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865 /*
6866 * Only give the warning if there are no FileChangedShell
6867 * autocommands.
6868 * Avoid being called recursively by setting "busy".
6869 */
6870 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006871# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006872 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6873 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006874# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006875 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6877 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006878 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 busy = FALSE;
6880 if (n)
6881 {
6882 if (!buf_valid(buf))
6883 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006884# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006885 s = get_vim_var_str(VV_FCS_CHOICE);
6886 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6887 reload = TRUE;
6888 else if (STRCMP(s, "ask") == 0)
6889 n = FALSE;
6890 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006891# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006892 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006894 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895#endif
6896 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006897 if (*reason == 'd')
6898 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 else
6900 {
6901 helpmesg = TRUE;
6902#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6903 can_reload = TRUE;
6904#endif
6905 /*
6906 * Check if the file contents really changed to avoid
6907 * giving a warning when only the timestamp was set (e.g.,
6908 * checked out of CVS). Always warn when the buffer was
6909 * changed.
6910 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006911 if (reason[2] == 'n')
6912 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006914 mesg2 = _("See \":help W12\" for more info.");
6915 }
6916 else if (reason[1] == 'h')
6917 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006919 mesg2 = _("See \":help W11\" for more info.");
6920 }
6921 else if (*reason == 'm')
6922 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006924 mesg2 = _("See \":help W16\" for more info.");
6925 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006926 else
6927 /* Only timestamp changed, store it to avoid a warning
6928 * in check_mtime() later. */
6929 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930 }
6931 }
6932 }
6933
6934 }
6935 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6936 && vim_fexists(buf->b_ffname))
6937 {
6938 retval = 1;
6939 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6940 buf->b_flags |= BF_NEW_W;
6941#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6942 can_reload = TRUE;
6943#endif
6944 }
6945
6946 if (mesg != NULL)
6947 {
6948 path = home_replace_save(buf, buf->b_fname);
6949 if (path != NULL)
6950 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006951 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952 mesg2 = "";
6953 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6954 + STRLEN(mesg2) + 2));
6955 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006956#ifdef FEAT_EVAL
6957 /* Set warningmsg here, before the unimportant and output-specific
6958 * mesg2 has been appended. */
6959 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6960#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6962 if (can_reload)
6963 {
6964 if (*mesg2 != NUL)
6965 {
6966 STRCAT(tbuf, "\n");
6967 STRCAT(tbuf, mesg2);
6968 }
6969 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006970 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971 reload = TRUE;
6972 }
6973 else
6974#endif
6975 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6976 {
6977 if (*mesg2 != NUL)
6978 {
6979 STRCAT(tbuf, "; ");
6980 STRCAT(tbuf, mesg2);
6981 }
6982 EMSG(tbuf);
6983 retval = 2;
6984 }
6985 else
6986 {
Bram Moolenaared203462004-06-16 11:19:22 +00006987# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006989# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 {
6991 msg_start();
6992 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6993 if (*mesg2 != NUL)
6994 msg_puts_attr((char_u *)mesg2,
6995 hl_attr(HLF_W) + MSG_HIST);
6996 msg_clr_eos();
6997 (void)msg_end();
6998 if (emsg_silent == 0)
6999 {
7000 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007001# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007003# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 /* give the user some time to think about it */
7005 ui_delay(1000L, TRUE);
7006
7007 /* don't redraw and erase the message */
7008 redraw_cmdline = FALSE;
7009 }
7010 }
7011 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 }
7013
7014 vim_free(path);
7015 vim_free(tbuf);
7016 }
7017 }
7018
7019 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007020 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007021 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007022 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007023#ifdef FEAT_PERSISTENT_UNDO
7024 if (buf->b_p_udf && buf->b_ffname != NULL)
7025 {
7026 char_u hash[UNDO_HASH_SIZE];
7027 buf_T *save_curbuf = curbuf;
7028
7029 /* Any existing undo file is unusable, write it now. */
7030 curbuf = buf;
7031 u_compute_hash(hash);
7032 u_write_undo(NULL, FALSE, buf, hash);
7033 curbuf = save_curbuf;
7034 }
7035#endif
7036 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037
Bram Moolenaar56718732006-03-15 22:53:57 +00007038#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007039 /* Trigger FileChangedShell when the file was changed in any way. */
7040 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007041 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7042 buf->b_fname, buf->b_fname, FALSE, buf);
7043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044#ifdef FEAT_GUI
7045 /* restore this in case an autocommand has set it; it would break
7046 * 'mousefocus' */
7047 need_mouse_correct = save_mouse_correct;
7048#endif
7049
7050 return retval;
7051}
7052
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007053/*
7054 * Reload a buffer that is already loaded.
7055 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007056 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7057 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007058 */
7059 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007060buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007061{
7062 exarg_T ea;
7063 pos_T old_cursor;
7064 linenr_T old_topline;
7065 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007066 buf_T *savebuf;
7067 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007068 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007069 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007070
7071 /* set curwin/curbuf for "buf" and save some things */
7072 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073
7074 /* We only want to read the text from the file, not reset the syntax
7075 * highlighting, clear marks, diff status, etc. Force the fileformat
7076 * and encoding to be the same. */
7077 if (prep_exarg(&ea, buf) == OK)
7078 {
7079 old_cursor = curwin->w_cursor;
7080 old_topline = curwin->w_topline;
7081
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007082 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007083 {
7084 /* Save all the text, so that the reload can be undone.
7085 * Sync first so that this is a separate undo-able action. */
7086 u_sync(FALSE);
7087 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7088 flags |= READ_KEEP_UNDO;
7089 }
7090
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007091 /*
7092 * To behave like when a new file is edited (matters for
7093 * BufReadPost autocommands) we first need to delete the current
7094 * buffer contents. But if reading the file fails we should keep
7095 * the old contents. Can't use memory only, the file might be
7096 * too big. Use a hidden buffer to move the buffer contents to.
7097 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007098 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007099 savebuf = NULL;
7100 else
7101 {
7102 /* Allocate a buffer without putting it in the buffer list. */
7103 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007104 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007105 {
7106 /* Open the memline. */
7107 curbuf = savebuf;
7108 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007109 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007110 curbuf = buf;
7111 curwin->w_buffer = buf;
7112 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007113 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007114 || move_lines(buf, savebuf) == FAIL)
7115 {
7116 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7117 buf->b_fname);
7118 saved = FAIL;
7119 }
7120 }
7121
7122 if (saved == OK)
7123 {
7124 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7125#ifdef FEAT_AUTOCMD
7126 keep_filetype = TRUE; /* don't detect 'filetype' */
7127#endif
7128 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7129 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007130 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007131 {
7132#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7133 if (!aborting())
7134#endif
7135 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007136 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137 {
7138 /* Put the text back from the save buffer. First
7139 * delete any lines that readfile() added. */
7140 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007141 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007142 break;
7143 (void)move_lines(savebuf, buf);
7144 }
7145 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007146 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007147 {
7148 /* Mark the buffer as unmodified and free undo info. */
7149 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007150 if ((flags & READ_KEEP_UNDO) == 0)
7151 {
7152 u_blockfree(buf);
7153 u_clearall(buf);
7154 }
7155 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007156 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007157 /* Mark all undo states as changed. */
7158 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007159 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007160 }
7161 }
7162 vim_free(ea.cmd);
7163
Bram Moolenaar8424a622006-04-19 21:23:36 +00007164 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165 wipe_buffer(savebuf, FALSE);
7166
7167#ifdef FEAT_DIFF
7168 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007169 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007170#endif
7171
7172 /* Restore the topline and cursor position and check it (lines may
7173 * have been removed). */
7174 if (old_topline > curbuf->b_ml.ml_line_count)
7175 curwin->w_topline = curbuf->b_ml.ml_line_count;
7176 else
7177 curwin->w_topline = old_topline;
7178 curwin->w_cursor = old_cursor;
7179 check_cursor();
7180 update_topline();
7181#ifdef FEAT_AUTOCMD
7182 keep_filetype = FALSE;
7183#endif
7184#ifdef FEAT_FOLDING
7185 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007186 win_T *wp;
7187 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007188
7189 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007190 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007191 if (wp->w_buffer == curwin->w_buffer
7192 && !foldmethodIsManual(wp))
7193 foldUpdateAll(wp);
7194 }
7195#endif
7196 /* If the mode didn't change and 'readonly' was set, keep the old
7197 * value; the user probably used the ":view" command. But don't
7198 * reset it, might have had a read error. */
7199 if (orig_mode == curbuf->b_orig_mode)
7200 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007201
7202 /* Modelines must override settings done by autocommands. */
7203 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007204 }
7205
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007206 /* restore curwin/curbuf and a few other things */
7207 aucmd_restbuf(&aco);
7208 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007209}
7210
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007212buf_store_time(buf_T *buf, struct stat *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213{
7214 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007215 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007216#ifdef HAVE_ST_MODE
7217 buf->b_orig_mode = (int)st->st_mode;
7218#else
7219 buf->b_orig_mode = mch_getperm(fname);
7220#endif
7221}
7222
7223/*
7224 * Adjust the line with missing eol, used for the next write.
7225 * Used for do_filter(), when the input lines for the filter are deleted.
7226 */
7227 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007228write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007230 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7231 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232}
7233
Bram Moolenaarda440d22016-01-16 21:27:23 +01007234#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7235/*
7236 * Delete "name" and everything in it, recursively.
7237 * return 0 for succes, -1 if some file was not deleted.
7238 */
7239 int
7240delete_recursive(char_u *name)
7241{
7242 int result = 0;
7243 char_u **files;
7244 int file_count;
7245 int i;
7246 char_u *exp;
7247
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007248 /* A symbolic link to a directory itself is deleted, not the directory it
7249 * points to. */
7250 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007251# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007252 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007253# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007254 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007255# endif
7256 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007257 {
7258 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7259 exp = vim_strsave(NameBuff);
7260 if (exp == NULL)
7261 return -1;
7262 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007263 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007264 {
7265 for (i = 0; i < file_count; ++i)
7266 if (delete_recursive(files[i]) != 0)
7267 result = -1;
7268 FreeWild(file_count, files);
7269 }
7270 else
7271 result = -1;
7272 vim_free(exp);
7273 (void)mch_rmdir(name);
7274 }
7275 else
7276 result = mch_remove(name) == 0 ? 0 : -1;
7277
7278 return result;
7279}
7280#endif
7281
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282#if defined(TEMPDIRNAMES) || defined(PROTO)
7283static long temp_count = 0; /* Temp filename counter. */
7284
7285/*
7286 * Delete the temp directory and all files it contains.
7287 */
7288 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007289vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007290{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291 if (vim_tempdir != NULL)
7292 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007293 /* remove the trailing path separator */
7294 gettail(vim_tempdir)[-1] = NUL;
7295 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 vim_free(vim_tempdir);
7297 vim_tempdir = NULL;
7298 }
7299}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300
7301/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007302 * Directory "tempdir" was created. Expand this name to a full path and put
7303 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7304 * "tempdir" must be no longer than MAXPATHL.
7305 */
7306 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007307vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007308{
7309 char_u *buf;
7310
7311 buf = alloc((unsigned)MAXPATHL + 2);
7312 if (buf != NULL)
7313 {
7314 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7315 STRCPY(buf, tempdir);
7316# ifdef __EMX__
7317 if (vim_strchr(buf, '/') != NULL)
7318 STRCAT(buf, "/");
7319 else
7320# endif
7321 add_pathsep(buf);
7322 vim_tempdir = vim_strsave(buf);
7323 vim_free(buf);
7324 }
7325}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007326#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007327
7328/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 * vim_tempname(): Return a unique name that can be used for a temp file.
7330 *
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007331 * The temp file is NOT garanteed to be created. If "keep" is FALSE it is
7332 * garanteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 *
7334 * The returned pointer is to allocated memory.
7335 * The returned pointer is NULL if no valid name was found.
7336 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007338vim_tempname(
7339 int extra_char UNUSED, /* char to use in the name instead of '?' */
7340 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341{
7342#ifdef USE_TMPNAM
7343 char_u itmp[L_tmpnam]; /* use tmpnam() */
7344#else
7345 char_u itmp[TEMPNAMELEN];
7346#endif
7347
7348#ifdef TEMPDIRNAMES
7349 static char *(tempdirs[]) = {TEMPDIRNAMES};
7350 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351# ifndef EEXIST
7352 struct stat st;
7353# endif
7354
7355 /*
7356 * This will create a directory for private use by this instance of Vim.
7357 * This is done once, and the same directory is used for all temp files.
7358 * This method avoids security problems because of symlink attacks et al.
7359 * It's also a bit faster, because we only need to check for an existing
7360 * file when creating the directory and not for each temp file.
7361 */
7362 if (vim_tempdir == NULL)
7363 {
7364 /*
7365 * Try the entries in TEMPDIRNAMES to create the temp directory.
7366 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007367 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007368 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007369# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007370 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007371 long nr;
7372 long off;
7373# endif
7374
Bram Moolenaare1a61992015-12-03 21:02:27 +01007375 /* Expand $TMP, leave room for "/v1100000/999999999".
7376 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007378 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007380 /* directory exists */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381# ifdef __EMX__
7382 /* If $TMP contains a forward slash (perhaps using bash or
7383 * tcsh), don't add a backslash, use a forward slash!
7384 * Adding 2 backslashes didn't work. */
7385 if (vim_strchr(itmp, '/') != NULL)
7386 STRCAT(itmp, "/");
7387 else
7388# endif
7389 add_pathsep(itmp);
7390
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391# ifdef HAVE_MKDTEMP
7392 /* Leave room for filename */
7393 STRCAT(itmp, "vXXXXXX");
7394 if (mkdtemp((char *)itmp) != NULL)
7395 vim_settempdir(itmp);
7396# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 /* Get an arbitrary number of up to 6 digits. When it's
7398 * unlikely that it already exists it will be faster,
7399 * otherwise it doesn't matter. The use of mkdir() avoids any
7400 * security problems because of the predictable number. */
7401 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007402 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403
7404 /* Try up to 10000 different values until we find a name that
7405 * doesn't exist. */
7406 for (off = 0; off < 10000L; ++off)
7407 {
7408 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007409# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412
Bram Moolenaareaf03392009-11-17 11:08:52 +00007413 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7414# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 /* If mkdir() does not set errno to EEXIST, check for
7416 * existing file here. There is a race condition then,
7417 * although it's fail-safe. */
7418 if (mch_stat((char *)itmp, &st) >= 0)
7419 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# endif
7421# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 /* Make sure the umask doesn't remove the executable bit.
7423 * "repl" has been reported to use "177". */
7424 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007425# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 if (r == 0)
7431 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 break;
7434 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 /* If the mkdir() didn't fail because the file/dir exists,
7437 * we probably can't create any dir here, try another
7438 * place. */
7439 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 break;
7442 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 if (vim_tempdir != NULL)
7445 break;
7446 }
7447 }
7448 }
7449
7450 if (vim_tempdir != NULL)
7451 {
7452 /* There is no need to check if the file exists, because we own the
7453 * directory and nobody else creates a file in it. */
7454 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7455 return vim_strsave(itmp);
7456 }
7457
7458 return NULL;
7459
7460#else /* TEMPDIRNAMES */
7461
7462# ifdef WIN3264
7463 char szTempFile[_MAX_PATH + 1];
7464 char buf4[4];
7465 char_u *retval;
7466 char_u *p;
7467
7468 STRCPY(itmp, "");
7469 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007470 {
7471 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7472 szTempFile[1] = NUL;
7473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007474 strcpy(buf4, "VIM");
7475 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007476 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007478 if (!keep)
7479 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007480 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481
7482 /* Backslashes in a temp file name cause problems when filtering with
7483 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7484 * didn't set 'shellslash'. */
7485 retval = vim_strsave(itmp);
7486 if (*p_shcf == '-' || p_ssl)
7487 for (p = retval; *p; ++p)
7488 if (*p == '\\')
7489 *p = '/';
7490 return retval;
7491
7492# else /* WIN3264 */
7493
7494# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007495 char_u *p;
7496
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007498 p = tmpnam((char *)itmp);
7499 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 return NULL;
7501# else
7502 char_u *p;
7503
7504# ifdef VMS_TEMPNAM
7505 /* mktemp() is not working on VMS. It seems to be
7506 * a do-nothing function. Therefore we use tempnam().
7507 */
7508 sprintf((char *)itmp, "VIM%c", extra_char);
7509 p = (char_u *)tempnam("tmp:", (char *)itmp);
7510 if (p != NULL)
7511 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007512 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 * and VIM will then be unable to find the file later */
7514 STRCPY(itmp, p);
7515 STRCAT(itmp, ".txt");
7516 free(p);
7517 }
7518 else
7519 return NULL;
7520# else
7521 STRCPY(itmp, TEMPNAME);
7522 if ((p = vim_strchr(itmp, '?')) != NULL)
7523 *p = extra_char;
7524 if (mktemp((char *)itmp) == NULL)
7525 return NULL;
7526# endif
7527# endif
7528
7529 return vim_strsave(itmp);
7530# endif /* WIN3264 */
7531#endif /* TEMPDIRNAMES */
7532}
7533
7534#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7535/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007536 * Convert all backslashes in fname to forward slashes in-place, unless when
7537 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007538 */
7539 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007540forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541{
7542 char_u *p;
7543
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007544 if (path_with_url(fname))
7545 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007546 for (p = fname; *p != NUL; ++p)
7547# ifdef FEAT_MBYTE
7548 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007549 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550 ++p;
7551 else
7552# endif
7553 if (*p == '\\')
7554 *p = '/';
7555}
7556#endif
7557
7558
7559/*
7560 * Code for automatic commands.
7561 *
7562 * Only included when "FEAT_AUTOCMD" has been defined.
7563 */
7564
7565#if defined(FEAT_AUTOCMD) || defined(PROTO)
7566
7567/*
7568 * The autocommands are stored in a list for each event.
7569 * Autocommands for the same pattern, that are consecutive, are joined
7570 * together, to avoid having to match the pattern too often.
7571 * The result is an array of Autopat lists, which point to AutoCmd lists:
7572 *
7573 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7574 * Autopat.cmds Autopat.cmds
7575 * | |
7576 * V V
7577 * AutoCmd.next AutoCmd.next
7578 * | |
7579 * V V
7580 * AutoCmd.next NULL
7581 * |
7582 * V
7583 * NULL
7584 *
7585 * first_autopat[1] --> Autopat.next --> NULL
7586 * Autopat.cmds
7587 * |
7588 * V
7589 * AutoCmd.next
7590 * |
7591 * V
7592 * NULL
7593 * etc.
7594 *
7595 * The order of AutoCmds is important, this is the order in which they were
7596 * defined and will have to be executed.
7597 */
7598typedef struct AutoCmd
7599{
7600 char_u *cmd; /* The command to be executed (NULL
7601 when command has been removed) */
7602 char nested; /* If autocommands nest here */
7603 char last; /* last command in list */
7604#ifdef FEAT_EVAL
7605 scid_T scriptID; /* script ID where defined */
7606#endif
7607 struct AutoCmd *next; /* Next AutoCmd in list */
7608} AutoCmd;
7609
7610typedef struct AutoPat
7611{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612 char_u *pat; /* pattern as typed (NULL when pattern
7613 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007614 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007615 AutoCmd *cmds; /* list of commands to do */
7616 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007617 int group; /* group ID */
7618 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007619 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007620 char allow_dirs; /* Pattern may match whole path */
7621 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007622} AutoPat;
7623
7624static struct event_name
7625{
7626 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007627 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628} event_names[] =
7629{
7630 {"BufAdd", EVENT_BUFADD},
7631 {"BufCreate", EVENT_BUFADD},
7632 {"BufDelete", EVENT_BUFDELETE},
7633 {"BufEnter", EVENT_BUFENTER},
7634 {"BufFilePost", EVENT_BUFFILEPOST},
7635 {"BufFilePre", EVENT_BUFFILEPRE},
7636 {"BufHidden", EVENT_BUFHIDDEN},
7637 {"BufLeave", EVENT_BUFLEAVE},
7638 {"BufNew", EVENT_BUFNEW},
7639 {"BufNewFile", EVENT_BUFNEWFILE},
7640 {"BufRead", EVENT_BUFREADPOST},
7641 {"BufReadCmd", EVENT_BUFREADCMD},
7642 {"BufReadPost", EVENT_BUFREADPOST},
7643 {"BufReadPre", EVENT_BUFREADPRE},
7644 {"BufUnload", EVENT_BUFUNLOAD},
7645 {"BufWinEnter", EVENT_BUFWINENTER},
7646 {"BufWinLeave", EVENT_BUFWINLEAVE},
7647 {"BufWipeout", EVENT_BUFWIPEOUT},
7648 {"BufWrite", EVENT_BUFWRITEPRE},
7649 {"BufWritePost", EVENT_BUFWRITEPOST},
7650 {"BufWritePre", EVENT_BUFWRITEPRE},
7651 {"BufWriteCmd", EVENT_BUFWRITECMD},
7652 {"CmdwinEnter", EVENT_CMDWINENTER},
7653 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007654 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007655 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007656 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007657 {"CursorHold", EVENT_CURSORHOLD},
7658 {"CursorHoldI", EVENT_CURSORHOLDI},
7659 {"CursorMoved", EVENT_CURSORMOVED},
7660 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007661 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7662 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7664 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7665 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7666 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007667 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 {"FileChangedRO", EVENT_FILECHANGEDRO},
7669 {"FileReadPost", EVENT_FILEREADPOST},
7670 {"FileReadPre", EVENT_FILEREADPRE},
7671 {"FileReadCmd", EVENT_FILEREADCMD},
7672 {"FileType", EVENT_FILETYPE},
7673 {"FileWritePost", EVENT_FILEWRITEPOST},
7674 {"FileWritePre", EVENT_FILEWRITEPRE},
7675 {"FileWriteCmd", EVENT_FILEWRITECMD},
7676 {"FilterReadPost", EVENT_FILTERREADPOST},
7677 {"FilterReadPre", EVENT_FILTERREADPRE},
7678 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7679 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7680 {"FocusGained", EVENT_FOCUSGAINED},
7681 {"FocusLost", EVENT_FOCUSLOST},
7682 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7683 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007684 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007685 {"InsertChange", EVENT_INSERTCHANGE},
7686 {"InsertEnter", EVENT_INSERTENTER},
7687 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007688 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007689 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007690 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007691 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7692 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007693 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007695 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007696 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7697 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007698 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007699 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007700 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 {"StdinReadPost", EVENT_STDINREADPOST},
7702 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007703 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007704 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007705 {"TabEnter", EVENT_TABENTER},
7706 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 {"TermChanged", EVENT_TERMCHANGED},
7708 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007709 {"TextChanged", EVENT_TEXTCHANGED},
7710 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007711 {"User", EVENT_USER},
7712 {"VimEnter", EVENT_VIMENTER},
7713 {"VimLeave", EVENT_VIMLEAVE},
7714 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7715 {"WinEnter", EVENT_WINENTER},
7716 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007717 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007718 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719};
7720
7721static AutoPat *first_autopat[NUM_EVENTS] =
7722{
7723 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7724 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7725 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7726 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007727 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007728 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729};
7730
7731/*
7732 * struct used to keep status while executing autocommands for an event.
7733 */
7734typedef struct AutoPatCmd
7735{
7736 AutoPat *curpat; /* next AutoPat to examine */
7737 AutoCmd *nextcmd; /* next AutoCmd to execute */
7738 int group; /* group being used */
7739 char_u *fname; /* fname to match with */
7740 char_u *sfname; /* sfname to match with */
7741 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007742 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007743 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7744 buf is deleted */
7745 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746} AutoPatCmd;
7747
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007748static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007749
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750/*
7751 * augroups stores a list of autocmd group names.
7752 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007753static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7755
7756/*
7757 * The ID of the current group. Group 0 is the default one.
7758 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759static int current_augroup = AUGROUP_DEFAULT;
7760
7761static int au_need_clean = FALSE; /* need to delete marked patterns */
7762
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007763static void show_autocmd(AutoPat *ap, event_T event);
7764static void au_remove_pat(AutoPat *ap);
7765static void au_remove_cmds(AutoPat *ap);
7766static void au_cleanup(void);
7767static int au_new_group(char_u *name);
7768static void au_del_group(char_u *name);
7769static event_T event_name2nr(char_u *start, char_u **end);
7770static char_u *event_nr2name(event_T event);
7771static char_u *find_end_event(char_u *arg, int have_group);
7772static int event_ignored(event_T event);
7773static int au_get_grouparg(char_u **argp);
7774static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7775static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7776static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007777#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007778static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007779#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007780
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007781
Bram Moolenaar754b5602006-02-09 23:53:20 +00007782static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007784static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785
7786/*
7787 * Show the autocommands for one AutoPat.
7788 */
7789 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007790show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007791{
7792 AutoCmd *ac;
7793
7794 /* Check for "got_int" (here and at various places below), which is set
7795 * when "q" has been hit for the "--more--" prompt */
7796 if (got_int)
7797 return;
7798 if (ap->pat == NULL) /* pattern has been removed */
7799 return;
7800
7801 msg_putchar('\n');
7802 if (got_int)
7803 return;
7804 if (event != last_event || ap->group != last_group)
7805 {
7806 if (ap->group != AUGROUP_DEFAULT)
7807 {
7808 if (AUGROUP_NAME(ap->group) == NULL)
7809 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7810 else
7811 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7812 msg_puts((char_u *)" ");
7813 }
7814 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7815 last_event = event;
7816 last_group = ap->group;
7817 msg_putchar('\n');
7818 if (got_int)
7819 return;
7820 }
7821 msg_col = 4;
7822 msg_outtrans(ap->pat);
7823
7824 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7825 {
7826 if (ac->cmd != NULL) /* skip removed commands */
7827 {
7828 if (msg_col >= 14)
7829 msg_putchar('\n');
7830 msg_col = 14;
7831 if (got_int)
7832 return;
7833 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007834#ifdef FEAT_EVAL
7835 if (p_verbose > 0)
7836 last_set_msg(ac->scriptID);
7837#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838 if (got_int)
7839 return;
7840 if (ac->next != NULL)
7841 {
7842 msg_putchar('\n');
7843 if (got_int)
7844 return;
7845 }
7846 }
7847 }
7848}
7849
7850/*
7851 * Mark an autocommand pattern for deletion.
7852 */
7853 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007854au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007855{
7856 vim_free(ap->pat);
7857 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007858 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 au_need_clean = TRUE;
7860}
7861
7862/*
7863 * Mark all commands for a pattern for deletion.
7864 */
7865 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007866au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867{
7868 AutoCmd *ac;
7869
7870 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7871 {
7872 vim_free(ac->cmd);
7873 ac->cmd = NULL;
7874 }
7875 au_need_clean = TRUE;
7876}
7877
7878/*
7879 * Cleanup autocommands and patterns that have been deleted.
7880 * This is only done when not executing autocommands.
7881 */
7882 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007883au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007884{
7885 AutoPat *ap, **prev_ap;
7886 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007887 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007888
7889 if (autocmd_busy || !au_need_clean)
7890 return;
7891
7892 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007893 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7894 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895 {
7896 /* loop over all autocommand patterns */
7897 prev_ap = &(first_autopat[(int)event]);
7898 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7899 {
7900 /* loop over all commands for this pattern */
7901 prev_ac = &(ap->cmds);
7902 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7903 {
7904 /* remove the command if the pattern is to be deleted or when
7905 * the command has been marked for deletion */
7906 if (ap->pat == NULL || ac->cmd == NULL)
7907 {
7908 *prev_ac = ac->next;
7909 vim_free(ac->cmd);
7910 vim_free(ac);
7911 }
7912 else
7913 prev_ac = &(ac->next);
7914 }
7915
7916 /* remove the pattern if it has been marked for deletion */
7917 if (ap->pat == NULL)
7918 {
7919 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007920 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007921 vim_free(ap);
7922 }
7923 else
7924 prev_ap = &(ap->next);
7925 }
7926 }
7927
7928 au_need_clean = FALSE;
7929}
7930
7931/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007932 * Called when buffer is freed, to remove/invalidate related buffer-local
7933 * autocmds.
7934 */
7935 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007936aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007937{
7938 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007939 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007940 AutoPatCmd *apc;
7941
7942 /* invalidate currently executing autocommands */
7943 for (apc = active_apc_list; apc; apc = apc->next)
7944 if (buf->b_fnum == apc->arg_bufnr)
7945 apc->arg_bufnr = 0;
7946
7947 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007948 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7949 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007950 /* loop over all autocommand patterns */
7951 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7952 if (ap->buflocal_nr == buf->b_fnum)
7953 {
7954 au_remove_pat(ap);
7955 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007956 {
7957 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007958 smsg((char_u *)
7959 _("auto-removing autocommand: %s <buffer=%d>"),
7960 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007961 verbose_leave();
7962 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007963 }
7964 au_cleanup();
7965}
7966
7967/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 * Add an autocmd group name.
7969 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7970 */
7971 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007972au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973{
7974 int i;
7975
7976 i = au_find_group(name);
7977 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7978 {
7979 /* First try using a free entry. */
7980 for (i = 0; i < augroups.ga_len; ++i)
7981 if (AUGROUP_NAME(i) == NULL)
7982 break;
7983 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7984 return AUGROUP_ERROR;
7985
7986 AUGROUP_NAME(i) = vim_strsave(name);
7987 if (AUGROUP_NAME(i) == NULL)
7988 return AUGROUP_ERROR;
7989 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007990 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007991 }
7992
7993 return i;
7994}
7995
7996 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007997au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998{
7999 int i;
8000
8001 i = au_find_group(name);
8002 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8003 EMSG2(_("E367: No such group: \"%s\""), name);
8004 else
8005 {
8006 vim_free(AUGROUP_NAME(i));
8007 AUGROUP_NAME(i) = NULL;
8008 }
8009}
8010
8011/*
8012 * Find the ID of an autocmd group name.
8013 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8014 */
8015 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008016au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017{
8018 int i;
8019
8020 for (i = 0; i < augroups.ga_len; ++i)
8021 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8022 return i;
8023 return AUGROUP_ERROR;
8024}
8025
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008026/*
8027 * Return TRUE if augroup "name" exists.
8028 */
8029 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008030au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008031{
8032 return au_find_group(name) != AUGROUP_ERROR;
8033}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008034
Bram Moolenaar071d4272004-06-13 20:20:40 +00008035/*
8036 * ":augroup {name}".
8037 */
8038 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008039do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008040{
8041 int i;
8042
8043 if (del_group)
8044 {
8045 if (*arg == NUL)
8046 EMSG(_(e_argreq));
8047 else
8048 au_del_group(arg);
8049 }
8050 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8051 current_augroup = AUGROUP_DEFAULT;
8052 else if (*arg) /* ":aug xxx": switch to group xxx */
8053 {
8054 i = au_new_group(arg);
8055 if (i != AUGROUP_ERROR)
8056 current_augroup = i;
8057 }
8058 else /* ":aug": list the group names */
8059 {
8060 msg_start();
8061 for (i = 0; i < augroups.ga_len; ++i)
8062 {
8063 if (AUGROUP_NAME(i) != NULL)
8064 {
8065 msg_puts(AUGROUP_NAME(i));
8066 msg_puts((char_u *)" ");
8067 }
8068 }
8069 msg_clr_eos();
8070 msg_end();
8071 }
8072}
8073
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008074#if defined(EXITFREE) || defined(PROTO)
8075 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008076free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008077{
8078 for (current_augroup = -1; current_augroup < augroups.ga_len;
8079 ++current_augroup)
8080 do_autocmd((char_u *)"", TRUE);
8081 ga_clear_strings(&augroups);
8082}
8083#endif
8084
Bram Moolenaar071d4272004-06-13 20:20:40 +00008085/*
8086 * Return the event number for event name "start".
8087 * Return NUM_EVENTS if the event name was not found.
8088 * Return a pointer to the next event name in "end".
8089 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008090 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008091event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092{
8093 char_u *p;
8094 int i;
8095 int len;
8096
8097 /* the event name ends with end of line, a blank or a comma */
8098 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8099 ;
8100 for (i = 0; event_names[i].name != NULL; ++i)
8101 {
8102 len = (int)STRLEN(event_names[i].name);
8103 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8104 break;
8105 }
8106 if (*p == ',')
8107 ++p;
8108 *end = p;
8109 if (event_names[i].name == NULL)
8110 return NUM_EVENTS;
8111 return event_names[i].event;
8112}
8113
8114/*
8115 * Return the name for event "event".
8116 */
8117 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008118event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008119{
8120 int i;
8121
8122 for (i = 0; event_names[i].name != NULL; ++i)
8123 if (event_names[i].event == event)
8124 return (char_u *)event_names[i].name;
8125 return (char_u *)"Unknown";
8126}
8127
8128/*
8129 * Scan over the events. "*" stands for all events.
8130 */
8131 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008132find_end_event(
8133 char_u *arg,
8134 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008135{
8136 char_u *pat;
8137 char_u *p;
8138
8139 if (*arg == '*')
8140 {
8141 if (arg[1] && !vim_iswhite(arg[1]))
8142 {
8143 EMSG2(_("E215: Illegal character after *: %s"), arg);
8144 return NULL;
8145 }
8146 pat = arg + 1;
8147 }
8148 else
8149 {
8150 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8151 {
8152 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8153 {
8154 if (have_group)
8155 EMSG2(_("E216: No such event: %s"), pat);
8156 else
8157 EMSG2(_("E216: No such group or event: %s"), pat);
8158 return NULL;
8159 }
8160 }
8161 }
8162 return pat;
8163}
8164
8165/*
8166 * Return TRUE if "event" is included in 'eventignore'.
8167 */
8168 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008169event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008170{
8171 char_u *p = p_ei;
8172
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008173 while (*p != NUL)
8174 {
8175 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8176 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008177 if (event_name2nr(p, &p) == event)
8178 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008179 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008180
8181 return FALSE;
8182}
8183
8184/*
8185 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8186 */
8187 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008188check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189{
8190 char_u *p = p_ei;
8191
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008193 {
8194 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8195 {
8196 p += 3;
8197 if (*p == ',')
8198 ++p;
8199 }
8200 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008203
8204 return OK;
8205}
8206
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008207# if defined(FEAT_SYN_HL) || defined(PROTO)
8208
8209/*
8210 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8211 * buffer loaded into the window. "what" must start with a comma.
8212 * Returns the old value of 'eventignore' in allocated memory.
8213 */
8214 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008215au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008216{
8217 char_u *new_ei;
8218 char_u *save_ei;
8219
8220 save_ei = vim_strsave(p_ei);
8221 if (save_ei != NULL)
8222 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008223 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008224 if (new_ei != NULL)
8225 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008226 if (*what == ',' && *p_ei == NUL)
8227 STRCPY(new_ei, what + 1);
8228 else
8229 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008230 set_string_option_direct((char_u *)"ei", -1, new_ei,
8231 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008232 vim_free(new_ei);
8233 }
8234 }
8235 return save_ei;
8236}
8237
8238 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008239au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008240{
8241 if (old_ei != NULL)
8242 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008243 set_string_option_direct((char_u *)"ei", -1, old_ei,
8244 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008245 vim_free(old_ei);
8246 }
8247}
8248# endif /* FEAT_SYN_HL */
8249
Bram Moolenaar071d4272004-06-13 20:20:40 +00008250/*
8251 * do_autocmd() -- implements the :autocmd command. Can be used in the
8252 * following ways:
8253 *
8254 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8255 * will be automatically executed for <event>
8256 * when editing a file matching <pat>, in
8257 * the current group.
8258 * :autocmd <event> <pat> Show the auto-commands associated with
8259 * <event> and <pat>.
8260 * :autocmd <event> Show the auto-commands associated with
8261 * <event>.
8262 * :autocmd Show all auto-commands.
8263 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8264 * <event> and <pat>, and add the command
8265 * <cmd>, for the current group.
8266 * :autocmd! <event> <pat> Remove all auto-commands associated with
8267 * <event> and <pat> for the current group.
8268 * :autocmd! <event> Remove all auto-commands associated with
8269 * <event> for the current group.
8270 * :autocmd! Remove ALL auto-commands for the current
8271 * group.
8272 *
8273 * Multiple events and patterns may be given separated by commas. Here are
8274 * some examples:
8275 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8276 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8277 *
8278 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008279 *
8280 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008281 */
8282 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008283do_autocmd(char_u *arg, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008284{
8285 char_u *pat;
8286 char_u *envpat = NULL;
8287 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008288 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008289 int need_free = FALSE;
8290 int nested = FALSE;
8291 int group;
8292
8293 /*
8294 * Check for a legal group name. If not, use AUGROUP_ALL.
8295 */
8296 group = au_get_grouparg(&arg);
8297 if (arg == NULL) /* out of memory */
8298 return;
8299
8300 /*
8301 * Scan over the events.
8302 * If we find an illegal name, return here, don't do anything.
8303 */
8304 pat = find_end_event(arg, group != AUGROUP_ALL);
8305 if (pat == NULL)
8306 return;
8307
8308 /*
8309 * Scan over the pattern. Put a NUL at the end.
8310 */
8311 pat = skipwhite(pat);
8312 cmd = pat;
8313 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8314 cmd++;
8315 if (*cmd)
8316 *cmd++ = NUL;
8317
8318 /* Expand environment variables in the pattern. Set 'shellslash', we want
8319 * forward slashes here. */
8320 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8321 {
8322#ifdef BACKSLASH_IN_FILENAME
8323 int p_ssl_save = p_ssl;
8324
8325 p_ssl = TRUE;
8326#endif
8327 envpat = expand_env_save(pat);
8328#ifdef BACKSLASH_IN_FILENAME
8329 p_ssl = p_ssl_save;
8330#endif
8331 if (envpat != NULL)
8332 pat = envpat;
8333 }
8334
8335 /*
8336 * Check for "nested" flag.
8337 */
8338 cmd = skipwhite(cmd);
8339 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8340 {
8341 nested = TRUE;
8342 cmd = skipwhite(cmd + 6);
8343 }
8344
8345 /*
8346 * Find the start of the commands.
8347 * Expand <sfile> in it.
8348 */
8349 if (*cmd != NUL)
8350 {
8351 cmd = expand_sfile(cmd);
8352 if (cmd == NULL) /* some error */
8353 return;
8354 need_free = TRUE;
8355 }
8356
8357 /*
8358 * Print header when showing autocommands.
8359 */
8360 if (!forceit && *cmd == NUL)
8361 {
8362 /* Highlight title */
8363 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8364 }
8365
8366 /*
8367 * Loop over the events.
8368 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008369 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008370 last_group = AUGROUP_ERROR; /* for listing the group name */
8371 if (*arg == '*' || *arg == NUL)
8372 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008373 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8374 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008375 if (do_autocmd_event(event, pat,
8376 nested, cmd, forceit, group) == FAIL)
8377 break;
8378 }
8379 else
8380 {
8381 while (*arg && !vim_iswhite(*arg))
8382 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8383 nested, cmd, forceit, group) == FAIL)
8384 break;
8385 }
8386
8387 if (need_free)
8388 vim_free(cmd);
8389 vim_free(envpat);
8390}
8391
8392/*
8393 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8394 * The "argp" argument is advanced to the following argument.
8395 *
8396 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8397 */
8398 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008399au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008400{
8401 char_u *group_name;
8402 char_u *p;
8403 char_u *arg = *argp;
8404 int group = AUGROUP_ALL;
8405
8406 p = skiptowhite(arg);
8407 if (p > arg)
8408 {
8409 group_name = vim_strnsave(arg, (int)(p - arg));
8410 if (group_name == NULL) /* out of memory */
8411 return AUGROUP_ERROR;
8412 group = au_find_group(group_name);
8413 if (group == AUGROUP_ERROR)
8414 group = AUGROUP_ALL; /* no match, use all groups */
8415 else
8416 *argp = skipwhite(p); /* match, skip over group name */
8417 vim_free(group_name);
8418 }
8419 return group;
8420}
8421
8422/*
8423 * do_autocmd() for one event.
8424 * If *pat == NUL do for all patterns.
8425 * If *cmd == NUL show entries.
8426 * If forceit == TRUE delete entries.
8427 * If group is not AUGROUP_ALL, only use this group.
8428 */
8429 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008430do_autocmd_event(
8431 event_T event,
8432 char_u *pat,
8433 int nested,
8434 char_u *cmd,
8435 int forceit,
8436 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437{
8438 AutoPat *ap;
8439 AutoPat **prev_ap;
8440 AutoCmd *ac;
8441 AutoCmd **prev_ac;
8442 int brace_level;
8443 char_u *endpat;
8444 int findgroup;
8445 int allgroups;
8446 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008447 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008448 int buflocal_nr;
8449 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008450
8451 if (group == AUGROUP_ALL)
8452 findgroup = current_augroup;
8453 else
8454 findgroup = group;
8455 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8456
8457 /*
8458 * Show or delete all patterns for an event.
8459 */
8460 if (*pat == NUL)
8461 {
8462 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8463 {
8464 if (forceit) /* delete the AutoPat, if it's in the current group */
8465 {
8466 if (ap->group == findgroup)
8467 au_remove_pat(ap);
8468 }
8469 else if (group == AUGROUP_ALL || ap->group == group)
8470 show_autocmd(ap, event);
8471 }
8472 }
8473
8474 /*
8475 * Loop through all the specified patterns.
8476 */
8477 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8478 {
8479 /*
8480 * Find end of the pattern.
8481 * Watch out for a comma in braces, like "*.\{obj,o\}".
8482 */
8483 brace_level = 0;
8484 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008485 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008486 {
8487 if (*endpat == '{')
8488 brace_level++;
8489 else if (*endpat == '}')
8490 brace_level--;
8491 }
8492 if (pat == endpat) /* ignore single comma */
8493 continue;
8494 patlen = (int)(endpat - pat);
8495
8496 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008497 * detect special <buflocal[=X]> buffer-local patterns
8498 */
8499 is_buflocal = FALSE;
8500 buflocal_nr = 0;
8501
Bram Moolenaar1e997822015-02-17 16:04:57 +01008502 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008503 && pat[patlen - 1] == '>')
8504 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008505 /* "<buffer...>": Error will be printed only for addition.
8506 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008507 is_buflocal = TRUE;
8508 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008509 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008510 buflocal_nr = curbuf->b_fnum;
8511 else if (patlen > 9 && pat[7] == '=')
8512 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008513 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8514 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008515 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008516 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008517 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008518 buflocal_nr = atoi((char *)pat + 8);
8519 }
8520 }
8521
8522 if (is_buflocal)
8523 {
8524 /* normalize pat into standard "<buffer>#N" form */
8525 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8526 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008527 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008528 }
8529
8530 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531 * Find AutoPat entries with this pattern.
8532 */
8533 prev_ap = &first_autopat[(int)event];
8534 while ((ap = *prev_ap) != NULL)
8535 {
8536 if (ap->pat != NULL)
8537 {
8538 /* Accept a pattern when:
8539 * - a group was specified and it's that group, or a group was
8540 * not specified and it's the current group, or a group was
8541 * not specified and we are listing
8542 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008543 * - the pattern matches.
8544 * For <buffer[=X]>, this condition works because we normalize
8545 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008546 */
8547 if ((allgroups || ap->group == findgroup)
8548 && ap->patlen == patlen
8549 && STRNCMP(pat, ap->pat, patlen) == 0)
8550 {
8551 /*
8552 * Remove existing autocommands.
8553 * If adding any new autocmd's for this AutoPat, don't
8554 * delete the pattern from the autopat list, append to
8555 * this list.
8556 */
8557 if (forceit)
8558 {
8559 if (*cmd != NUL && ap->next == NULL)
8560 {
8561 au_remove_cmds(ap);
8562 break;
8563 }
8564 au_remove_pat(ap);
8565 }
8566
8567 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008568 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008569 */
8570 else if (*cmd == NUL)
8571 show_autocmd(ap, event);
8572
8573 /*
8574 * Add autocmd to this autopat, if it's the last one.
8575 */
8576 else if (ap->next == NULL)
8577 break;
8578 }
8579 }
8580 prev_ap = &ap->next;
8581 }
8582
8583 /*
8584 * Add a new command.
8585 */
8586 if (*cmd != NUL)
8587 {
8588 /*
8589 * If the pattern we want to add a command to does appear at the
8590 * end of the list (or not is not in the list at all), add the
8591 * pattern at the end of the list.
8592 */
8593 if (ap == NULL)
8594 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008595 /* refuse to add buffer-local ap if buffer number is invalid */
8596 if (is_buflocal && (buflocal_nr == 0
8597 || buflist_findnr(buflocal_nr) == NULL))
8598 {
8599 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8600 buflocal_nr);
8601 return FAIL;
8602 }
8603
Bram Moolenaar071d4272004-06-13 20:20:40 +00008604 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8605 if (ap == NULL)
8606 return FAIL;
8607 ap->pat = vim_strnsave(pat, patlen);
8608 ap->patlen = patlen;
8609 if (ap->pat == NULL)
8610 {
8611 vim_free(ap);
8612 return FAIL;
8613 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008614
8615 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008616 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008617 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008618 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008619 }
8620 else
8621 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008622 char_u *reg_pat;
8623
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008624 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008625 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008626 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008627 if (reg_pat != NULL)
8628 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008629 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008630 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008631 {
8632 vim_free(ap->pat);
8633 vim_free(ap);
8634 return FAIL;
8635 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008636 }
8637 ap->cmds = NULL;
8638 *prev_ap = ap;
8639 ap->next = NULL;
8640 if (group == AUGROUP_ALL)
8641 ap->group = current_augroup;
8642 else
8643 ap->group = group;
8644 }
8645
8646 /*
8647 * Add the autocmd at the end of the AutoCmd list.
8648 */
8649 prev_ac = &(ap->cmds);
8650 while ((ac = *prev_ac) != NULL)
8651 prev_ac = &ac->next;
8652 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8653 if (ac == NULL)
8654 return FAIL;
8655 ac->cmd = vim_strsave(cmd);
8656#ifdef FEAT_EVAL
8657 ac->scriptID = current_SID;
8658#endif
8659 if (ac->cmd == NULL)
8660 {
8661 vim_free(ac);
8662 return FAIL;
8663 }
8664 ac->next = NULL;
8665 *prev_ac = ac;
8666 ac->nested = nested;
8667 }
8668 }
8669
8670 au_cleanup(); /* may really delete removed patterns/commands now */
8671 return OK;
8672}
8673
8674/*
8675 * Implementation of ":doautocmd [group] event [fname]".
8676 * Return OK for success, FAIL for failure;
8677 */
8678 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008679do_doautocmd(
8680 char_u *arg,
8681 int do_msg) /* give message for no matching autocmds? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008682{
8683 char_u *fname;
8684 int nothing_done = TRUE;
8685 int group;
8686
8687 /*
8688 * Check for a legal group name. If not, use AUGROUP_ALL.
8689 */
8690 group = au_get_grouparg(&arg);
8691 if (arg == NULL) /* out of memory */
8692 return FAIL;
8693
8694 if (*arg == '*')
8695 {
8696 EMSG(_("E217: Can't execute autocommands for ALL events"));
8697 return FAIL;
8698 }
8699
8700 /*
8701 * Scan over the events.
8702 * If we find an illegal name, return here, don't do anything.
8703 */
8704 fname = find_end_event(arg, group != AUGROUP_ALL);
8705 if (fname == NULL)
8706 return FAIL;
8707
8708 fname = skipwhite(fname);
8709
8710 /*
8711 * Loop over the events.
8712 */
8713 while (*arg && !vim_iswhite(*arg))
8714 if (apply_autocmds_group(event_name2nr(arg, &arg),
8715 fname, NULL, TRUE, group, curbuf, NULL))
8716 nothing_done = FALSE;
8717
8718 if (nothing_done && do_msg)
8719 MSG(_("No matching autocommands"));
8720
8721#ifdef FEAT_EVAL
8722 return aborting() ? FAIL : OK;
8723#else
8724 return OK;
8725#endif
8726}
8727
8728/*
8729 * ":doautoall": execute autocommands for each loaded buffer.
8730 */
8731 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008732ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008733{
8734 int retval;
8735 aco_save_T aco;
8736 buf_T *buf;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008737 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008738 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008739
8740 /*
8741 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8742 * equal to curbuf, but for some buffers there may not be a window.
8743 * So we change the buffer for the current window for a moment. This
8744 * gives problems when the autocommands make changes to the list of
8745 * buffers or windows...
8746 */
8747 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8748 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008749 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008750 {
8751 /* find a window for this buffer and save some values */
8752 aucmd_prepbuf(&aco, buf);
8753
8754 /* execute the autocommands for this buffer */
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008755 retval = do_doautocmd(arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008756
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008757 if (call_do_modelines)
8758 {
8759 /* Execute the modeline settings, but don't set window-local
8760 * options if we are using the current window for another
8761 * buffer. */
8762 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8763 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764
8765 /* restore the current window */
8766 aucmd_restbuf(&aco);
8767
8768 /* stop if there is some error or buffer was deleted */
8769 if (retval == FAIL || !buf_valid(buf))
8770 break;
8771 }
8772 }
8773
8774 check_cursor(); /* just in case lines got deleted */
8775}
8776
8777/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008778 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8779 * return TRUE and advance *argp to after it.
8780 * Thus return TRUE when do_modelines() should be called.
8781 */
8782 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008783check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008784{
8785 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8786 {
8787 *argp = skipwhite(*argp + 12);
8788 return FALSE;
8789 }
8790 return TRUE;
8791}
8792
8793/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008794 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008795 * Search for a visible window containing the current buffer. If there isn't
8796 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008797 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008798 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008799 */
8800 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008801aucmd_prepbuf(
8802 aco_save_T *aco, /* structure to save values in */
8803 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008804{
8805 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008806#ifdef FEAT_WINDOWS
8807 int save_ea;
8808#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008809#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008810 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008811#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812
8813 /* Find a window that is for the new buffer */
8814 if (buf == curbuf) /* be quick when buf is curbuf */
8815 win = curwin;
8816 else
8817#ifdef FEAT_WINDOWS
8818 for (win = firstwin; win != NULL; win = win->w_next)
8819 if (win->w_buffer == buf)
8820 break;
8821#else
8822 win = NULL;
8823#endif
8824
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008825 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8826 * back to using the current window. */
8827 if (win == NULL && aucmd_win == NULL)
8828 {
8829 win_alloc_aucmd_win();
8830 if (aucmd_win == NULL)
8831 win = curwin;
8832 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008833 if (win == NULL && aucmd_win_used)
8834 /* Strange recursive autocommand, fall back to using the current
8835 * window. Expect a few side effects... */
8836 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008837
8838 aco->save_curwin = curwin;
8839 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008840 if (win != NULL)
8841 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008842 /* There is a window for "buf" in the current tab page, make it the
8843 * curwin. This is preferred, it has the least side effects (esp. if
8844 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008845 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008846 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008847 }
8848 else
8849 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008850 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008851 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008852 * Anything related to a window (e.g., setting folds) may have
8853 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008854 aco->use_aucmd_win = TRUE;
8855 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008856 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008857 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008858 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008859 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008860
8861 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8862 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008863 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008864 aucmd_win->w_localdir = NULL;
8865 aco->globaldir = globaldir;
8866 globaldir = NULL;
8867
Bram Moolenaar071d4272004-06-13 20:20:40 +00008868
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008869#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008870 /* Split the current window, put the aucmd_win in the upper half.
8871 * We don't want the BufEnter or WinEnter autocommands. */
8872 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008873 make_snapshot(SNAP_AUCMD_IDX);
8874 save_ea = p_ea;
8875 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008876
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008877# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008878 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8879 save_acd = p_acd;
8880 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008881# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008882
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008883 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8884 (void)win_comp_pos(); /* recompute window positions */
8885 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008886# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008887 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008888# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008889 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008890#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008891 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008892 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008893 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008894 aco->new_curwin = curwin;
8895 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008896}
8897
8898/*
8899 * Cleanup after executing autocommands for a (hidden) buffer.
8900 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008901 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902 */
8903 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008904aucmd_restbuf(
8905 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008906{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008907#ifdef FEAT_WINDOWS
8908 int dummy;
8909#endif
8910
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008911 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008912 {
8913 --curbuf->b_nwindows;
8914#ifdef FEAT_WINDOWS
8915 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008916 * page. Do not trigger autocommands here. */
8917 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008918 if (curwin != aucmd_win)
8919 {
8920 tabpage_T *tp;
8921 win_T *wp;
8922
8923 FOR_ALL_TAB_WINDOWS(tp, wp)
8924 {
8925 if (wp == aucmd_win)
8926 {
8927 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008928 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008929 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008930 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008931 }
8932 }
8933 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008934win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008935
8936 /* Remove the window and frame from the tree of frames. */
8937 (void)winframe_remove(curwin, &dummy, NULL);
8938 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008939 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008940 last_status(FALSE); /* may need to remove last status line */
8941 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8942 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008943 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008944
8945 if (win_valid(aco->save_curwin))
8946 curwin = aco->save_curwin;
8947 else
8948 /* Hmm, original window disappeared. Just use the first one. */
8949 curwin = firstwin;
8950# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008951 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8952 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008953# endif
8954#else
8955 curwin = aco->save_curwin;
8956#endif
8957 curbuf = curwin->w_buffer;
8958
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008959 vim_free(globaldir);
8960 globaldir = aco->globaldir;
8961
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008962 /* the buffer contents may have changed */
8963 check_cursor();
8964 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8965 {
8966 curwin->w_topline = curbuf->b_ml.ml_line_count;
8967#ifdef FEAT_DIFF
8968 curwin->w_topfill = 0;
8969#endif
8970 }
8971#if defined(FEAT_GUI)
8972 /* Hide the scrollbars from the aucmd_win and update. */
8973 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8974 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8975 gui_may_update_scrollbars();
8976#endif
8977 }
8978 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008979 {
8980 /* restore curwin */
8981#ifdef FEAT_WINDOWS
8982 if (win_valid(aco->save_curwin))
8983#endif
8984 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008985 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008986 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008987 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008988 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008989 && curbuf != aco->new_curbuf
8990 && buf_valid(aco->new_curbuf)
8991 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02008993# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
8994 if (curwin->w_s == &curbuf->b_s)
8995 curwin->w_s = &aco->new_curbuf->b_s;
8996# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008997 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008998 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008999 curwin->w_buffer = curbuf;
9000 ++curbuf->b_nwindows;
9001 }
9002
9003 curwin = aco->save_curwin;
9004 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009005 /* In case the autocommand move the cursor to a position that that
9006 * not exist in curbuf. */
9007 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008 }
9009 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010}
9011
9012static int autocmd_nested = FALSE;
9013
9014/*
9015 * Execute autocommands for "event" and file name "fname".
9016 * Return TRUE if some commands were executed.
9017 */
9018 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009019apply_autocmds(
9020 event_T event,
9021 char_u *fname, /* NULL or empty means use actual file name */
9022 char_u *fname_io, /* fname to use for <afile> on cmdline */
9023 int force, /* when TRUE, ignore autocmd_busy */
9024 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025{
9026 return apply_autocmds_group(event, fname, fname_io, force,
9027 AUGROUP_ALL, buf, NULL);
9028}
9029
9030/*
9031 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9032 * setting v:filearg.
9033 */
9034 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009035apply_autocmds_exarg(
9036 event_T event,
9037 char_u *fname,
9038 char_u *fname_io,
9039 int force,
9040 buf_T *buf,
9041 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009042{
9043 return apply_autocmds_group(event, fname, fname_io, force,
9044 AUGROUP_ALL, buf, eap);
9045}
9046
9047/*
9048 * Like apply_autocmds(), but handles the caller's retval. If the script
9049 * processing is being aborted or if retval is FAIL when inside a try
9050 * conditional, no autocommands are executed. If otherwise the autocommands
9051 * cause the script to be aborted, retval is set to FAIL.
9052 */
9053 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009054apply_autocmds_retval(
9055 event_T event,
9056 char_u *fname, /* NULL or empty means use actual file name */
9057 char_u *fname_io, /* fname to use for <afile> on cmdline */
9058 int force, /* when TRUE, ignore autocmd_busy */
9059 buf_T *buf, /* buffer for <abuf> */
9060 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009061{
9062 int did_cmd;
9063
Bram Moolenaar1e015462005-09-25 22:16:38 +00009064#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009065 if (should_abort(*retval))
9066 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009067#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068
9069 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9070 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009071 if (did_cmd
9072#ifdef FEAT_EVAL
9073 && aborting()
9074#endif
9075 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076 *retval = FAIL;
9077 return did_cmd;
9078}
9079
Bram Moolenaard35f9712005-12-18 22:02:33 +00009080/*
9081 * Return TRUE when there is a CursorHold autocommand defined.
9082 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009083 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009084has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009085{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009086 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9087 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009089
9090/*
9091 * Return TRUE if the CursorHold event can be triggered.
9092 */
9093 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009094trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009095{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009096 int state;
9097
Bram Moolenaar05334432011-07-20 18:29:39 +02009098 if (!did_cursorhold
9099 && has_cursorhold()
9100 && !Recording
9101 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009102#ifdef FEAT_INS_EXPAND
9103 && !ins_compl_active()
9104#endif
9105 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009106 {
9107 state = get_real_state();
9108 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9109 return TRUE;
9110 }
9111 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009112}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009113
9114/*
9115 * Return TRUE when there is a CursorMoved autocommand defined.
9116 */
9117 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009118has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009119{
9120 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9121}
9122
9123/*
9124 * Return TRUE when there is a CursorMovedI autocommand defined.
9125 */
9126 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009127has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009128{
9129 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9130}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009131
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009132/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009133 * Return TRUE when there is a TextChanged autocommand defined.
9134 */
9135 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009136has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009137{
9138 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9139}
9140
9141/*
9142 * Return TRUE when there is a TextChangedI autocommand defined.
9143 */
9144 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009145has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009146{
9147 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9148}
9149
9150/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009151 * Return TRUE when there is an InsertCharPre autocommand defined.
9152 */
9153 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009154has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009155{
9156 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9157}
9158
Bram Moolenaard5005162014-08-22 23:05:54 +02009159/*
9160 * Return TRUE when there is an CmdUndefined autocommand defined.
9161 */
9162 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009163has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009164{
9165 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9166}
9167
9168/*
9169 * Return TRUE when there is an FuncUndefined autocommand defined.
9170 */
9171 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009172has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009173{
9174 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9175}
9176
Bram Moolenaar071d4272004-06-13 20:20:40 +00009177 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009178apply_autocmds_group(
9179 event_T event,
9180 char_u *fname, /* NULL or empty means use actual file name */
9181 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009182 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009183 int force, /* when TRUE, ignore autocmd_busy */
9184 int group, /* group ID, or AUGROUP_ALL */
9185 buf_T *buf, /* buffer for <abuf> */
9186 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009187{
9188 char_u *sfname = NULL; /* short file name */
9189 char_u *tail;
9190 int save_changed;
9191 buf_T *old_curbuf;
9192 int retval = FALSE;
9193 char_u *save_sourcing_name;
9194 linenr_T save_sourcing_lnum;
9195 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009196 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009197 int save_autocmd_bufnr;
9198 char_u *save_autocmd_match;
9199 int save_autocmd_busy;
9200 int save_autocmd_nested;
9201 static int nesting = 0;
9202 AutoPatCmd patcmd;
9203 AutoPat *ap;
9204#ifdef FEAT_EVAL
9205 scid_T save_current_SID;
9206 void *save_funccalp;
9207 char_u *save_cmdarg;
9208 long save_cmdbang;
9209#endif
9210 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009211#ifdef FEAT_PROFILE
9212 proftime_T wait_time;
9213#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009214 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009215
9216 /*
9217 * Quickly return if there are no autocommands for this event or
9218 * autocommands are blocked.
9219 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009220 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009221 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009222
9223 /*
9224 * When autocommands are busy, new autocommands are only executed when
9225 * explicitly enabled with the "nested" flag.
9226 */
9227 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009228 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009229
9230#ifdef FEAT_EVAL
9231 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009232 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009233 * occurred or an exception was thrown but not caught.
9234 */
9235 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009236 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237#endif
9238
9239 /*
9240 * FileChangedShell never nests, because it can create an endless loop.
9241 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009242 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9243 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009244 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009245
9246 /*
9247 * Ignore events in 'eventignore'.
9248 */
9249 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009250 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009251
9252 /*
9253 * Allow nesting of autocommands, but restrict the depth, because it's
9254 * possible to create an endless loop.
9255 */
9256 if (nesting == 10)
9257 {
9258 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009259 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009260 }
9261
9262 /*
9263 * Check if these autocommands are disabled. Used when doing ":all" or
9264 * ":ball".
9265 */
9266 if ( (autocmd_no_enter
9267 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9268 || (autocmd_no_leave
9269 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009270 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009271
9272 /*
9273 * Save the autocmd_* variables and info about the current buffer.
9274 */
9275 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009276 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009277 save_autocmd_bufnr = autocmd_bufnr;
9278 save_autocmd_match = autocmd_match;
9279 save_autocmd_busy = autocmd_busy;
9280 save_autocmd_nested = autocmd_nested;
9281 save_changed = curbuf->b_changed;
9282 old_curbuf = curbuf;
9283
9284 /*
9285 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009286 * Make a copy to avoid that changing a buffer name or directory makes it
9287 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009288 */
9289 if (fname_io == NULL)
9290 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009291 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009292 autocmd_fname = NULL;
9293 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009294 autocmd_fname = fname;
9295 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009296 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009297 else
9298 autocmd_fname = NULL;
9299 }
9300 else
9301 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009302 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009303 autocmd_fname = vim_strsave(autocmd_fname);
9304 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305
9306 /*
9307 * Set the buffer number to be used for <abuf>.
9308 */
9309 if (buf == NULL)
9310 autocmd_bufnr = 0;
9311 else
9312 autocmd_bufnr = buf->b_fnum;
9313
9314 /*
9315 * When the file name is NULL or empty, use the file name of buffer "buf".
9316 * Always use the full path of the file name to match with, in case
9317 * "allow_dirs" is set.
9318 */
9319 if (fname == NULL || *fname == NUL)
9320 {
9321 if (buf == NULL)
9322 fname = NULL;
9323 else
9324 {
9325#ifdef FEAT_SYN_HL
9326 if (event == EVENT_SYNTAX)
9327 fname = buf->b_p_syn;
9328 else
9329#endif
9330 if (event == EVENT_FILETYPE)
9331 fname = buf->b_p_ft;
9332 else
9333 {
9334 if (buf->b_sfname != NULL)
9335 sfname = vim_strsave(buf->b_sfname);
9336 fname = buf->b_ffname;
9337 }
9338 }
9339 if (fname == NULL)
9340 fname = (char_u *)"";
9341 fname = vim_strsave(fname); /* make a copy, so we can change it */
9342 }
9343 else
9344 {
9345 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009346 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9347 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009348 if (event == EVENT_FILETYPE
9349 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009350 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009351 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009352 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009353 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009354 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009355 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009356 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009357 fname = vim_strsave(fname);
9358 else
9359 fname = FullName_save(fname, FALSE);
9360 }
9361 if (fname == NULL) /* out of memory */
9362 {
9363 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009364 retval = FALSE;
9365 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009366 }
9367
9368#ifdef BACKSLASH_IN_FILENAME
9369 /*
9370 * Replace all backslashes with forward slashes. This makes the
9371 * autocommand patterns portable between Unix and MS-DOS.
9372 */
9373 if (sfname != NULL)
9374 forward_slash(sfname);
9375 forward_slash(fname);
9376#endif
9377
9378#ifdef VMS
9379 /* remove version for correct match */
9380 if (sfname != NULL)
9381 vms_remove_version(sfname);
9382 vms_remove_version(fname);
9383#endif
9384
9385 /*
9386 * Set the name to be used for <amatch>.
9387 */
9388 autocmd_match = fname;
9389
9390
9391 /* Don't redraw while doing auto commands. */
9392 ++RedrawingDisabled;
9393 save_sourcing_name = sourcing_name;
9394 sourcing_name = NULL; /* don't free this one */
9395 save_sourcing_lnum = sourcing_lnum;
9396 sourcing_lnum = 0; /* no line number here */
9397
9398#ifdef FEAT_EVAL
9399 save_current_SID = current_SID;
9400
Bram Moolenaar05159a02005-02-26 23:04:13 +00009401# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009402 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009403 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9404# endif
9405
Bram Moolenaar071d4272004-06-13 20:20:40 +00009406 /* Don't use local function variables, if called from a function */
9407 save_funccalp = save_funccal();
9408#endif
9409
9410 /*
9411 * When starting to execute autocommands, save the search patterns.
9412 */
9413 if (!autocmd_busy)
9414 {
9415 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009416#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009417 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009418#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009419 {
9420 saveRedobuff();
9421 did_save_redobuff = TRUE;
9422 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009423 did_filetype = keep_filetype;
9424 }
9425
9426 /*
9427 * Note that we are applying autocmds. Some commands need to know.
9428 */
9429 autocmd_busy = TRUE;
9430 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9431 ++nesting; /* see matching decrement below */
9432
9433 /* Remember that FileType was triggered. Used for did_filetype(). */
9434 if (event == EVENT_FILETYPE)
9435 did_filetype = TRUE;
9436
9437 tail = gettail(fname);
9438
9439 /* Find first autocommand that matches */
9440 patcmd.curpat = first_autopat[(int)event];
9441 patcmd.nextcmd = NULL;
9442 patcmd.group = group;
9443 patcmd.fname = fname;
9444 patcmd.sfname = sfname;
9445 patcmd.tail = tail;
9446 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009447 patcmd.arg_bufnr = autocmd_bufnr;
9448 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009449 auto_next_pat(&patcmd, FALSE);
9450
9451 /* found one, start executing the autocommands */
9452 if (patcmd.curpat != NULL)
9453 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009454 /* add to active_apc_list */
9455 patcmd.next = active_apc_list;
9456 active_apc_list = &patcmd;
9457
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458#ifdef FEAT_EVAL
9459 /* set v:cmdarg (only when there is a matching pattern) */
9460 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9461 if (eap != NULL)
9462 {
9463 save_cmdarg = set_cmdarg(eap, NULL);
9464 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9465 }
9466 else
9467 save_cmdarg = NULL; /* avoid gcc warning */
9468#endif
9469 retval = TRUE;
9470 /* mark the last pattern, to avoid an endless loop when more patterns
9471 * are added when executing autocommands */
9472 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9473 ap->last = FALSE;
9474 ap->last = TRUE;
9475 check_lnums(TRUE); /* make sure cursor and topline are valid */
9476 do_cmdline(NULL, getnextac, (void *)&patcmd,
9477 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9478#ifdef FEAT_EVAL
9479 if (eap != NULL)
9480 {
9481 (void)set_cmdarg(NULL, save_cmdarg);
9482 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9483 }
9484#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009485 /* delete from active_apc_list */
9486 if (active_apc_list == &patcmd) /* just in case */
9487 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009488 }
9489
9490 --RedrawingDisabled;
9491 autocmd_busy = save_autocmd_busy;
9492 filechangeshell_busy = FALSE;
9493 autocmd_nested = save_autocmd_nested;
9494 vim_free(sourcing_name);
9495 sourcing_name = save_sourcing_name;
9496 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009497 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009498 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009499 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009500 autocmd_bufnr = save_autocmd_bufnr;
9501 autocmd_match = save_autocmd_match;
9502#ifdef FEAT_EVAL
9503 current_SID = save_current_SID;
9504 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009505# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009506 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009507 prof_child_exit(&wait_time);
9508# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009509#endif
9510 vim_free(fname);
9511 vim_free(sfname);
9512 --nesting; /* see matching increment above */
9513
9514 /*
9515 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009516 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9517 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009518 */
9519 if (!autocmd_busy)
9520 {
9521 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009522 if (did_save_redobuff)
9523 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009524 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009525 while (au_pending_free_buf != NULL)
9526 {
9527 buf_T *b = au_pending_free_buf->b_next;
9528 vim_free(au_pending_free_buf);
9529 au_pending_free_buf = b;
9530 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009531 while (au_pending_free_win != NULL)
9532 {
9533 win_T *w = au_pending_free_win->w_next;
9534 vim_free(au_pending_free_win);
9535 au_pending_free_win = w;
9536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009537 }
9538
9539 /*
9540 * Some events don't set or reset the Changed flag.
9541 * Check if still in the same buffer!
9542 */
9543 if (curbuf == old_curbuf
9544 && (event == EVENT_BUFREADPOST
9545 || event == EVENT_BUFWRITEPOST
9546 || event == EVENT_FILEAPPENDPOST
9547 || event == EVENT_VIMLEAVE
9548 || event == EVENT_VIMLEAVEPRE))
9549 {
9550#ifdef FEAT_TITLE
9551 if (curbuf->b_changed != save_changed)
9552 need_maketitle = TRUE;
9553#endif
9554 curbuf->b_changed = save_changed;
9555 }
9556
9557 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009558
9559BYPASS_AU:
9560 /* When wiping out a buffer make sure all its buffer-local autocommands
9561 * are deleted. */
9562 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9563 aubuflocal_remove(buf);
9564
Bram Moolenaarc3691332016-04-20 12:49:49 +02009565 if (retval == OK && event == EVENT_FILETYPE)
9566 au_did_filetype = TRUE;
9567
Bram Moolenaar071d4272004-06-13 20:20:40 +00009568 return retval;
9569}
9570
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009571# ifdef FEAT_EVAL
9572static char_u *old_termresponse = NULL;
9573# endif
9574
9575/*
9576 * Block triggering autocommands until unblock_autocmd() is called.
9577 * Can be used recursively, so long as it's symmetric.
9578 */
9579 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009580block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009581{
9582# ifdef FEAT_EVAL
9583 /* Remember the value of v:termresponse. */
9584 if (autocmd_blocked == 0)
9585 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9586# endif
9587 ++autocmd_blocked;
9588}
9589
9590 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009591unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009592{
9593 --autocmd_blocked;
9594
9595# ifdef FEAT_EVAL
9596 /* When v:termresponse was set while autocommands were blocked, trigger
9597 * the autocommands now. Esp. useful when executing a shell command
9598 * during startup (vimdiff). */
9599 if (autocmd_blocked == 0
9600 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9601 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9602# endif
9603}
9604
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009605 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009606is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009607{
9608 return autocmd_blocked != 0;
9609}
9610
Bram Moolenaar071d4272004-06-13 20:20:40 +00009611/*
9612 * Find next autocommand pattern that matches.
9613 */
9614 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009615auto_next_pat(
9616 AutoPatCmd *apc,
9617 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009618{
9619 AutoPat *ap;
9620 AutoCmd *cp;
9621 char_u *name;
9622 char *s;
9623
9624 vim_free(sourcing_name);
9625 sourcing_name = NULL;
9626
9627 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9628 {
9629 apc->curpat = NULL;
9630
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009631 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009632 * the group matches. For buffer-local autocommands only check the
9633 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009634 if (ap->pat != NULL && ap->cmds != NULL
9635 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9636 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009637 /* execution-condition */
9638 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009639 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009640 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009641 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009642 {
9643 name = event_nr2name(apc->event);
9644 s = _("%s Auto commands for \"%s\"");
9645 sourcing_name = alloc((unsigned)(STRLEN(s)
9646 + STRLEN(name) + ap->patlen + 1));
9647 if (sourcing_name != NULL)
9648 {
9649 sprintf((char *)sourcing_name, s,
9650 (char *)name, (char *)ap->pat);
9651 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009652 {
9653 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009654 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009655 verbose_leave();
9656 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009657 }
9658
9659 apc->curpat = ap;
9660 apc->nextcmd = ap->cmds;
9661 /* mark last command */
9662 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9663 cp->last = FALSE;
9664 cp->last = TRUE;
9665 }
9666 line_breakcheck();
9667 if (apc->curpat != NULL) /* found a match */
9668 break;
9669 }
9670 if (stop_at_last && ap->last)
9671 break;
9672 }
9673}
9674
9675/*
9676 * Get next autocommand command.
9677 * Called by do_cmdline() to get the next line for ":if".
9678 * Returns allocated string, or NULL for end of autocommands.
9679 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009680 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009681getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009682{
9683 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9684 char_u *retval;
9685 AutoCmd *ac;
9686
9687 /* Can be called again after returning the last line. */
9688 if (acp->curpat == NULL)
9689 return NULL;
9690
9691 /* repeat until we find an autocommand to execute */
9692 for (;;)
9693 {
9694 /* skip removed commands */
9695 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9696 if (acp->nextcmd->last)
9697 acp->nextcmd = NULL;
9698 else
9699 acp->nextcmd = acp->nextcmd->next;
9700
9701 if (acp->nextcmd != NULL)
9702 break;
9703
9704 /* at end of commands, find next pattern that matches */
9705 if (acp->curpat->last)
9706 acp->curpat = NULL;
9707 else
9708 acp->curpat = acp->curpat->next;
9709 if (acp->curpat != NULL)
9710 auto_next_pat(acp, TRUE);
9711 if (acp->curpat == NULL)
9712 return NULL;
9713 }
9714
9715 ac = acp->nextcmd;
9716
9717 if (p_verbose >= 9)
9718 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009719 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009720 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009721 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009722 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009723 }
9724 retval = vim_strsave(ac->cmd);
9725 autocmd_nested = ac->nested;
9726#ifdef FEAT_EVAL
9727 current_SID = ac->scriptID;
9728#endif
9729 if (ac->last)
9730 acp->nextcmd = NULL;
9731 else
9732 acp->nextcmd = ac->next;
9733 return retval;
9734}
9735
9736/*
9737 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009738 * To account for buffer-local autocommands, function needs to know
9739 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009740 */
9741 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009742has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009743{
9744 AutoPat *ap;
9745 char_u *fname;
9746 char_u *tail = gettail(sfname);
9747 int retval = FALSE;
9748
9749 fname = FullName_save(sfname, FALSE);
9750 if (fname == NULL)
9751 return FALSE;
9752
9753#ifdef BACKSLASH_IN_FILENAME
9754 /*
9755 * Replace all backslashes with forward slashes. This makes the
9756 * autocommand patterns portable between Unix and MS-DOS.
9757 */
9758 sfname = vim_strsave(sfname);
9759 if (sfname != NULL)
9760 forward_slash(sfname);
9761 forward_slash(fname);
9762#endif
9763
9764 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9765 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009766 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009767 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009768 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009769 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009770 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009771 {
9772 retval = TRUE;
9773 break;
9774 }
9775
9776 vim_free(fname);
9777#ifdef BACKSLASH_IN_FILENAME
9778 vim_free(sfname);
9779#endif
9780
9781 return retval;
9782}
9783
9784#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9785/*
9786 * Function given to ExpandGeneric() to obtain the list of autocommand group
9787 * names.
9788 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009789 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009790get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009791{
9792 if (idx == augroups.ga_len) /* add "END" add the end */
9793 return (char_u *)"END";
9794 if (idx >= augroups.ga_len) /* end of list */
9795 return NULL;
9796 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9797 return (char_u *)"";
9798 return AUGROUP_NAME(idx); /* return a name */
9799}
9800
9801static int include_groups = FALSE;
9802
9803 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009804set_context_in_autocmd(
9805 expand_T *xp,
9806 char_u *arg,
9807 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009808{
9809 char_u *p;
9810 int group;
9811
9812 /* check for a group name, skip it if present */
9813 include_groups = FALSE;
9814 p = arg;
9815 group = au_get_grouparg(&arg);
9816 if (group == AUGROUP_ERROR)
9817 return NULL;
9818 /* If there only is a group name that's what we expand. */
9819 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9820 {
9821 arg = p;
9822 group = AUGROUP_ALL;
9823 }
9824
9825 /* skip over event name */
9826 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9827 if (*p == ',')
9828 arg = p + 1;
9829 if (*p == NUL)
9830 {
9831 if (group == AUGROUP_ALL)
9832 include_groups = TRUE;
9833 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9834 xp->xp_pattern = arg;
9835 return NULL;
9836 }
9837
9838 /* skip over pattern */
9839 arg = skipwhite(p);
9840 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9841 arg++;
9842 if (*arg)
9843 return arg; /* expand (next) command */
9844
9845 if (doautocmd)
9846 xp->xp_context = EXPAND_FILES; /* expand file names */
9847 else
9848 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9849 return NULL;
9850}
9851
9852/*
9853 * Function given to ExpandGeneric() to obtain the list of event names.
9854 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009855 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009856get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009857{
9858 if (idx < augroups.ga_len) /* First list group names, if wanted */
9859 {
9860 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9861 return (char_u *)""; /* skip deleted entries */
9862 return AUGROUP_NAME(idx); /* return a name */
9863 }
9864 return (char_u *)event_names[idx - augroups.ga_len].name;
9865}
9866
9867#endif /* FEAT_CMDL_COMPL */
9868
9869/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009870 * Return TRUE if autocmd is supported.
9871 */
9872 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009873autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009874{
9875 char_u *p;
9876
9877 return (event_name2nr(name, &p) != NUM_EVENTS);
9878}
9879
9880/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009881 * Return TRUE if an autocommand is defined for a group, event and
9882 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9883 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9884 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9885 * Used for:
9886 * exists("#Group") or
9887 * exists("#Group#Event") or
9888 * exists("#Group#Event#pat") or
9889 * exists("#Event") or
9890 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009891 */
9892 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009893au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009894{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009895 char_u *arg_save;
9896 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009897 char_u *event_name;
9898 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009899 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009900 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009901 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009902 int group;
9903 int retval = FALSE;
9904
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009905 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009906 arg_save = vim_strsave(arg);
9907 if (arg_save == NULL)
9908 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009909 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009910 if (p != NULL)
9911 *p++ = NUL;
9912
9913 /* First, look for an autocmd group name */
9914 group = au_find_group(arg_save);
9915 if (group == AUGROUP_ERROR)
9916 {
9917 /* Didn't match a group name, assume the first argument is an event. */
9918 group = AUGROUP_ALL;
9919 event_name = arg_save;
9920 }
9921 else
9922 {
9923 if (p == NULL)
9924 {
9925 /* "Group": group name is present and it's recognized */
9926 retval = TRUE;
9927 goto theend;
9928 }
9929
9930 /* Must be "Group#Event" or "Group#Event#pat". */
9931 event_name = p;
9932 p = vim_strchr(event_name, '#');
9933 if (p != NULL)
9934 *p++ = NUL; /* "Group#Event#pat" */
9935 }
9936
9937 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009938
9939 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009940 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009941
9942 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009943 if (event == NUM_EVENTS)
9944 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009945
9946 /* Find the first autocommand for this event.
9947 * If there isn't any, return FALSE;
9948 * If there is one and no pattern given, return TRUE; */
9949 ap = first_autopat[(int)event];
9950 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009951 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009952
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009953 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9954 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009955 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009956 buflocal_buf = curbuf;
9957
Bram Moolenaar071d4272004-06-13 20:20:40 +00009958 /* Check if there is an autocommand with the given pattern. */
9959 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009960 /* only use a pattern when it has not been removed and has commands. */
9961 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009962 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009963 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009964 && (pattern == NULL
9965 || (buflocal_buf == NULL
9966 ? fnamecmp(ap->pat, pattern) == 0
9967 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009968 {
9969 retval = TRUE;
9970 break;
9971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009972
Bram Moolenaar195d6352005-12-19 22:08:24 +00009973theend:
9974 vim_free(arg_save);
9975 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009976}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009977
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009978#else /* FEAT_AUTOCMD */
9979
9980/*
9981 * Prepare for executing commands for (hidden) buffer "buf".
9982 * This is the non-autocommand version, it simply saves "curbuf" and sets
9983 * "curbuf" and "curwin" to match "buf".
9984 */
9985 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01009986aucmd_prepbuf(
9987 aco_save_T *aco, /* structure to save values in */
9988 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009989{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009990 aco->save_curbuf = curbuf;
9991 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009992 curbuf = buf;
9993 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009994 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009995}
9996
9997/*
9998 * Restore after executing commands for a (hidden) buffer.
9999 * This is the non-autocommand version.
10000 */
10001 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010002aucmd_restbuf(
10003 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010004{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010005 --curbuf->b_nwindows;
10006 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010007 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010008 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010009}
10010
Bram Moolenaar071d4272004-06-13 20:20:40 +000010011#endif /* FEAT_AUTOCMD */
10012
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010013
Bram Moolenaar071d4272004-06-13 20:20:40 +000010014#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10015/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010016 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10017 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10018 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010019 * Used for autocommands and 'wildignore'.
10020 * Returns TRUE if there is a match, FALSE otherwise.
10021 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010022 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010023match_file_pat(
10024 char_u *pattern, /* pattern to match with */
10025 regprog_T **prog, /* pre-compiled regprog or NULL */
10026 char_u *fname, /* full path of file name */
10027 char_u *sfname, /* short file name or NULL */
10028 char_u *tail, /* tail of path */
10029 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010030{
10031 regmatch_T regmatch;
10032 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010033
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010034 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010035 if (prog != NULL)
10036 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010037 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010038 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039
10040 /*
10041 * Try for a match with the pattern with:
10042 * 1. the full file name, when the pattern has a '/'.
10043 * 2. the short file name, when the pattern has a '/'.
10044 * 3. the tail of the file name, when the pattern has no '/'.
10045 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010046 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010047 && ((allow_dirs
10048 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10049 || (sfname != NULL
10050 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010051 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010052 result = TRUE;
10053
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010054 if (prog != NULL)
10055 *prog = regmatch.regprog;
10056 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010057 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058 return result;
10059}
10060#endif
10061
10062#if defined(FEAT_WILDIGN) || defined(PROTO)
10063/*
10064 * Return TRUE if a file matches with a pattern in "list".
10065 * "list" is a comma-separated list of patterns, like 'wildignore'.
10066 * "sfname" is the short file name or NULL, "ffname" the long file name.
10067 */
10068 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010069match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010070{
10071 char_u buf[100];
10072 char_u *tail;
10073 char_u *regpat;
10074 char allow_dirs;
10075 int match;
10076 char_u *p;
10077
10078 tail = gettail(sfname);
10079
10080 /* try all patterns in 'wildignore' */
10081 p = list;
10082 while (*p)
10083 {
10084 copy_option_part(&p, buf, 100, ",");
10085 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10086 if (regpat == NULL)
10087 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010088 match = match_file_pat(regpat, NULL, ffname, sfname,
10089 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010090 vim_free(regpat);
10091 if (match)
10092 return TRUE;
10093 }
10094 return FALSE;
10095}
10096#endif
10097
10098/*
10099 * Convert the given pattern "pat" which has shell style wildcards in it, into
10100 * a regular expression, and return the result in allocated memory. If there
10101 * is a directory path separator to be matched, then TRUE is put in
10102 * allow_dirs, otherwise FALSE is put there -- webb.
10103 * Handle backslashes before special characters, like "\*" and "\ ".
10104 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010105 * Returns NULL when out of memory.
10106 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010107 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010108file_pat_to_reg_pat(
10109 char_u *pat,
10110 char_u *pat_end, /* first char after pattern or NULL */
10111 char *allow_dirs, /* Result passed back out in here */
10112 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010114 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010115 char_u *endp;
10116 char_u *reg_pat;
10117 char_u *p;
10118 int i;
10119 int nested = 0;
10120 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010121
10122 if (allow_dirs != NULL)
10123 *allow_dirs = FALSE;
10124 if (pat_end == NULL)
10125 pat_end = pat + STRLEN(pat);
10126
Bram Moolenaar071d4272004-06-13 20:20:40 +000010127 for (p = pat; p < pat_end; p++)
10128 {
10129 switch (*p)
10130 {
10131 case '*':
10132 case '.':
10133 case ',':
10134 case '{':
10135 case '}':
10136 case '~':
10137 size += 2; /* extra backslash */
10138 break;
10139#ifdef BACKSLASH_IN_FILENAME
10140 case '\\':
10141 case '/':
10142 size += 4; /* could become "[\/]" */
10143 break;
10144#endif
10145 default:
10146 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010147# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010148 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010149 {
10150 ++p;
10151 ++size;
10152 }
10153# endif
10154 break;
10155 }
10156 }
10157 reg_pat = alloc(size + 1);
10158 if (reg_pat == NULL)
10159 return NULL;
10160
Bram Moolenaar071d4272004-06-13 20:20:40 +000010161 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010162
10163 if (pat[0] == '*')
10164 while (pat[0] == '*' && pat < pat_end - 1)
10165 pat++;
10166 else
10167 reg_pat[i++] = '^';
10168 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010169 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010170 {
10171 while (endp - pat > 0 && *endp == '*')
10172 endp--;
10173 add_dollar = FALSE;
10174 }
10175 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10176 {
10177 switch (*p)
10178 {
10179 case '*':
10180 reg_pat[i++] = '.';
10181 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010182 while (p[1] == '*') /* "**" matches like "*" */
10183 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010184 break;
10185 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010186 case '~':
10187 reg_pat[i++] = '\\';
10188 reg_pat[i++] = *p;
10189 break;
10190 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191 reg_pat[i++] = '.';
10192 break;
10193 case '\\':
10194 if (p[1] == NUL)
10195 break;
10196#ifdef BACKSLASH_IN_FILENAME
10197 if (!no_bslash)
10198 {
10199 /* translate:
10200 * "\x" to "\\x" e.g., "dir\file"
10201 * "\*" to "\\.*" e.g., "dir\*.c"
10202 * "\?" to "\\." e.g., "dir\??.c"
10203 * "\+" to "\+" e.g., "fileX\+.c"
10204 */
10205 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10206 && p[1] != '+')
10207 {
10208 reg_pat[i++] = '[';
10209 reg_pat[i++] = '\\';
10210 reg_pat[i++] = '/';
10211 reg_pat[i++] = ']';
10212 if (allow_dirs != NULL)
10213 *allow_dirs = TRUE;
10214 break;
10215 }
10216 }
10217#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010218 /* Undo escaping from ExpandEscape():
10219 * foo\?bar -> foo?bar
10220 * foo\%bar -> foo%bar
10221 * foo\,bar -> foo,bar
10222 * foo\ bar -> foo bar
10223 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010224 * regexp.
10225 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010226 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010227 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010228 if (*++p == '?'
10229#ifdef BACKSLASH_IN_FILENAME
10230 && no_bslash
10231#endif
10232 )
10233 reg_pat[i++] = '?';
10234 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010235 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010236 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010237 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010238 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10239 {
10240 reg_pat[i++] = '\\';
10241 reg_pat[i++] = '{';
10242 p += 2;
10243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010244 else
10245 {
10246 if (allow_dirs != NULL && vim_ispathsep(*p)
10247#ifdef BACKSLASH_IN_FILENAME
10248 && (!no_bslash || *p != '\\')
10249#endif
10250 )
10251 *allow_dirs = TRUE;
10252 reg_pat[i++] = '\\';
10253 reg_pat[i++] = *p;
10254 }
10255 break;
10256#ifdef BACKSLASH_IN_FILENAME
10257 case '/':
10258 reg_pat[i++] = '[';
10259 reg_pat[i++] = '\\';
10260 reg_pat[i++] = '/';
10261 reg_pat[i++] = ']';
10262 if (allow_dirs != NULL)
10263 *allow_dirs = TRUE;
10264 break;
10265#endif
10266 case '{':
10267 reg_pat[i++] = '\\';
10268 reg_pat[i++] = '(';
10269 nested++;
10270 break;
10271 case '}':
10272 reg_pat[i++] = '\\';
10273 reg_pat[i++] = ')';
10274 --nested;
10275 break;
10276 case ',':
10277 if (nested)
10278 {
10279 reg_pat[i++] = '\\';
10280 reg_pat[i++] = '|';
10281 }
10282 else
10283 reg_pat[i++] = ',';
10284 break;
10285 default:
10286# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010287 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010288 reg_pat[i++] = *p++;
10289 else
10290# endif
10291 if (allow_dirs != NULL && vim_ispathsep(*p))
10292 *allow_dirs = TRUE;
10293 reg_pat[i++] = *p;
10294 break;
10295 }
10296 }
10297 if (add_dollar)
10298 reg_pat[i++] = '$';
10299 reg_pat[i] = NUL;
10300 if (nested != 0)
10301 {
10302 if (nested < 0)
10303 EMSG(_("E219: Missing {."));
10304 else
10305 EMSG(_("E220: Missing }."));
10306 vim_free(reg_pat);
10307 reg_pat = NULL;
10308 }
10309 return reg_pat;
10310}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010311
10312#if defined(EINTR) || defined(PROTO)
10313/*
10314 * Version of read() that retries when interrupted by EINTR (possibly
10315 * by a SIGWINCH).
10316 */
10317 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010318read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010319{
10320 long ret;
10321
10322 for (;;)
10323 {
10324 ret = vim_read(fd, buf, bufsize);
10325 if (ret >= 0 || errno != EINTR)
10326 break;
10327 }
10328 return ret;
10329}
10330
10331/*
10332 * Version of write() that retries when interrupted by EINTR (possibly
10333 * by a SIGWINCH).
10334 */
10335 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010336write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010337{
10338 long ret = 0;
10339 long wlen;
10340
10341 /* Repeat the write() so long it didn't fail, other than being interrupted
10342 * by a signal. */
10343 while (ret < (long)bufsize)
10344 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010345 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010346 if (wlen < 0)
10347 {
10348 if (errno != EINTR)
10349 break;
10350 }
10351 else
10352 ret += wlen;
10353 }
10354 return ret;
10355}
10356#endif