blob: fa927ff3499c19e0a24c7b0c16117e343a942979 [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 Moolenaar8767f522016-07-01 17:17:39 +020044static 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);
Bram Moolenaar8767f522016-07-01 17:17:39 +020052static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010053static 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 Moolenaar8767f522016-07-01 17:17:39 +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;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200272 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000273 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 Moolenaar8767f522016-07-01 17:17:39 +0200888 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000889 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 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200952 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 {
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
Bram Moolenaar8767f522016-07-01 17:17:39 +02002256 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2257 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 {
2259 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002260 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 set_fileformat(EOL_UNIX, OPT_LOCAL);
2262 file_rewind = TRUE;
2263 keep_fileformat = TRUE;
2264 goto retry;
2265 }
2266 ff_error = EOL_DOS;
2267 }
2268 }
2269 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2270 {
2271 error = TRUE;
2272 break;
2273 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002274#ifdef FEAT_PERSISTENT_UNDO
2275 if (read_undo_file)
2276 sha256_update(&sha_ctx, line_start, len);
2277#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 ++lnum;
2279 if (--read_count == 0)
2280 {
2281 error = TRUE; /* break loop */
2282 line_start = ptr; /* nothing left to write */
2283 break;
2284 }
2285 }
2286 else
2287 --skip_count;
2288 line_start = ptr + 1;
2289 }
2290 }
2291 }
2292 linerest = (long)(ptr - line_start);
2293 ui_breakcheck();
2294 }
2295
2296failed:
2297 /* not an error, max. number of lines reached */
2298 if (error && read_count == 0)
2299 error = FALSE;
2300
2301 /*
2302 * If we get EOF in the middle of a line, note the fact and
2303 * complete the line ourselves.
2304 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2305 */
2306 if (!error
2307 && !got_int
2308 && linerest != 0
2309 && !(!curbuf->b_p_bin
2310 && fileformat == EOL_DOS
2311 && *line_start == Ctrl_Z
2312 && ptr == line_start + 1))
2313 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002314 /* remember for when writing */
2315 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 curbuf->b_p_eol = FALSE;
2317 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002318 len = (colnr_T)(ptr - line_start + 1);
2319 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 error = TRUE;
2321 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002322 {
2323#ifdef FEAT_PERSISTENT_UNDO
2324 if (read_undo_file)
2325 sha256_update(&sha_ctx, line_start, len);
2326#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002328 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329 }
2330
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002331 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 save_file_ff(curbuf); /* remember the current file format */
2333
2334#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002335 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002336 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002337 crypt_free_state(curbuf->b_cryptstate);
2338 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002339 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002340 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2341 crypt_free_key(cryptkey);
2342 /* Don't set cryptkey to NULL, it's used below as a flag that
2343 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344#endif
2345
2346#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002347 /* If editing a new file: set 'fenc' for the current buffer.
2348 * Also for ":read ++edit file". */
2349 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002351 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 if (fenc_alloced)
2353 vim_free(fenc);
2354# ifdef USE_ICONV
2355 if (iconv_fd != (iconv_t)-1)
2356 {
2357 iconv_close(iconv_fd);
2358 iconv_fd = (iconv_t)-1;
2359 }
2360# endif
2361#endif
2362
2363 if (!read_buffer && !read_stdin)
2364 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002365#ifdef HAVE_FD_CLOEXEC
2366 else
2367 {
2368 int fdflags = fcntl(fd, F_GETFD);
2369 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002370 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002371 }
2372#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 vim_free(buffer);
2374
2375#ifdef HAVE_DUP
2376 if (read_stdin)
2377 {
2378 /* Use stderr for stdin, makes shell commands work. */
2379 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002380 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 }
2382#endif
2383
2384#ifdef FEAT_MBYTE
2385 if (tmpname != NULL)
2386 {
2387 mch_remove(tmpname); /* delete converted file */
2388 vim_free(tmpname);
2389 }
2390#endif
2391 --no_wait_return; /* may wait for return now */
2392
2393 /*
2394 * In recovery mode everything but autocommands is skipped.
2395 */
2396 if (!recoverymode)
2397 {
2398 /* need to delete the last line, which comes from the empty buffer */
2399 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2400 {
2401#ifdef FEAT_NETBEANS_INTG
2402 netbeansFireChanges = 0;
2403#endif
2404 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2405#ifdef FEAT_NETBEANS_INTG
2406 netbeansFireChanges = 1;
2407#endif
2408 --linecnt;
2409 }
2410 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2411 if (filesize == 0)
2412 linecnt = 0;
2413 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002414 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002416#ifdef FEAT_DIFF
2417 /* After reading the text into the buffer the diff info needs to
2418 * be updated. */
2419 diff_invalidate(curbuf);
2420#endif
2421#ifdef FEAT_FOLDING
2422 /* All folds in the window are invalid now. Mark them for update
2423 * before triggering autocommands. */
2424 foldUpdateAll(curwin);
2425#endif
2426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 else if (linecnt) /* appended at least one line */
2428 appended_lines_mark(from, linecnt);
2429
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430#ifndef ALWAYS_USE_GUI
2431 /*
2432 * If we were reading from the same terminal as where messages go,
2433 * the screen will have been messed up.
2434 * Switch on raw mode now and clear the screen.
2435 */
2436 if (read_stdin)
2437 {
2438 settmode(TMODE_RAW); /* set to raw mode */
2439 starttermcap();
2440 screenclear();
2441 }
2442#endif
2443
2444 if (got_int)
2445 {
2446 if (!(flags & READ_DUMMY))
2447 {
2448 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2449 if (newfile)
2450 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2451 }
2452 msg_scroll = msg_save;
2453#ifdef FEAT_VIMINFO
2454 check_marks_read();
2455#endif
2456 return OK; /* an interrupt isn't really an error */
2457 }
2458
2459 if (!filtering && !(flags & READ_DUMMY))
2460 {
2461 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2462 c = FALSE;
2463
2464#ifdef UNIX
2465# ifdef S_ISFIFO
2466 if (S_ISFIFO(perm)) /* fifo or socket */
2467 {
2468 STRCAT(IObuff, _("[fifo/socket]"));
2469 c = TRUE;
2470 }
2471# else
2472# ifdef S_IFIFO
2473 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2474 {
2475 STRCAT(IObuff, _("[fifo]"));
2476 c = TRUE;
2477 }
2478# endif
2479# ifdef S_IFSOCK
2480 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2481 {
2482 STRCAT(IObuff, _("[socket]"));
2483 c = TRUE;
2484 }
2485# endif
2486# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002487# ifdef OPEN_CHR_FILES
2488 if (S_ISCHR(perm)) /* or character special */
2489 {
2490 STRCAT(IObuff, _("[character special]"));
2491 c = TRUE;
2492 }
2493# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494#endif
2495 if (curbuf->b_p_ro)
2496 {
2497 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2498 c = TRUE;
2499 }
2500 if (read_no_eol_lnum)
2501 {
2502 msg_add_eol();
2503 c = TRUE;
2504 }
2505 if (ff_error == EOL_DOS)
2506 {
2507 STRCAT(IObuff, _("[CR missing]"));
2508 c = TRUE;
2509 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 if (split)
2511 {
2512 STRCAT(IObuff, _("[long lines split]"));
2513 c = TRUE;
2514 }
2515#ifdef FEAT_MBYTE
2516 if (notconverted)
2517 {
2518 STRCAT(IObuff, _("[NOT converted]"));
2519 c = TRUE;
2520 }
2521 else if (converted)
2522 {
2523 STRCAT(IObuff, _("[converted]"));
2524 c = TRUE;
2525 }
2526#endif
2527#ifdef FEAT_CRYPT
2528 if (cryptkey != NULL)
2529 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002530 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 c = TRUE;
2532 }
2533#endif
2534#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002535 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002537 sprintf((char *)IObuff + STRLEN(IObuff),
2538 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 c = TRUE;
2540 }
2541 else if (illegal_byte > 0)
2542 {
2543 sprintf((char *)IObuff + STRLEN(IObuff),
2544 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2545 c = TRUE;
2546 }
2547 else
2548#endif
2549 if (error)
2550 {
2551 STRCAT(IObuff, _("[READ ERRORS]"));
2552 c = TRUE;
2553 }
2554 if (msg_add_fileformat(fileformat))
2555 c = TRUE;
2556#ifdef FEAT_CRYPT
2557 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002558 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002559 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 else
2561#endif
2562 msg_add_lines(c, (long)linecnt, filesize);
2563
2564 vim_free(keep_msg);
2565 keep_msg = NULL;
2566 msg_scrolled_ign = TRUE;
2567#ifdef ALWAYS_USE_GUI
2568 /* Don't show the message when reading stdin, it would end up in a
2569 * message box (which might be shown when exiting!) */
2570 if (read_stdin || read_buffer)
2571 p = msg_may_trunc(FALSE, IObuff);
2572 else
2573#endif
2574 p = msg_trunc_attr(IObuff, FALSE, 0);
2575 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002576 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 /* Need to repeat the message after redrawing when:
2578 * - When reading from stdin (the screen will be cleared next).
2579 * - When restart_edit is set (otherwise there will be a delay
2580 * before redrawing).
2581 * - When the screen was scrolled but there is no wait-return
2582 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002583 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 msg_scrolled_ign = FALSE;
2585 }
2586
2587 /* with errors writing the file requires ":w!" */
2588 if (newfile && (error
2589#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002590 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002591 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592#endif
2593 ))
2594 curbuf->b_p_ro = TRUE;
2595
2596 u_clearline(); /* cannot use "U" command after adding lines */
2597
2598 /*
2599 * In Ex mode: cursor at last new line.
2600 * Otherwise: cursor at first new line.
2601 */
2602 if (exmode_active)
2603 curwin->w_cursor.lnum = from + linecnt;
2604 else
2605 curwin->w_cursor.lnum = from + 1;
2606 check_cursor_lnum();
2607 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2608
2609 /*
2610 * Set '[ and '] marks to the newly read lines.
2611 */
2612 curbuf->b_op_start.lnum = from + 1;
2613 curbuf->b_op_start.col = 0;
2614 curbuf->b_op_end.lnum = from + linecnt;
2615 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002616
2617#ifdef WIN32
2618 /*
2619 * Work around a weird problem: When a file has two links (only
2620 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002621 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002622 * It's correct again after reading the file, thus reset the timestamp
2623 * here.
2624 */
2625 if (newfile && !read_stdin && !read_buffer
2626 && mch_stat((char *)fname, &st) >= 0)
2627 {
2628 buf_store_time(curbuf, &st, fname);
2629 curbuf->b_mtime_read = curbuf->b_mtime;
2630 }
2631#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 }
2633 msg_scroll = msg_save;
2634
2635#ifdef FEAT_VIMINFO
2636 /*
2637 * Get the marks before executing autocommands, so they can be used there.
2638 */
2639 check_marks_read();
2640#endif
2641
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002643 * We remember if the last line of the read didn't have
2644 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2645 * or writing the read again with 'binary' on. The latter is required
2646 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002648 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002650 /* When reloading a buffer put the cursor at the first line that is
2651 * different. */
2652 if (flags & READ_KEEP_UNDO)
2653 u_find_first_changed();
2654
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002655#ifdef FEAT_PERSISTENT_UNDO
2656 /*
2657 * When opening a new file locate undo info and read it.
2658 */
2659 if (read_undo_file)
2660 {
2661 char_u hash[UNDO_HASH_SIZE];
2662
2663 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002664 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002665 }
2666#endif
2667
Bram Moolenaardf177f62005-02-22 08:39:57 +00002668#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669 if (!read_stdin && !read_buffer)
2670 {
2671 int m = msg_scroll;
2672 int n = msg_scrolled;
2673
2674 /* Save the fileformat now, otherwise the buffer will be considered
2675 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002676 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677 save_file_ff(curbuf);
2678
2679 /*
2680 * The output from the autocommands should not overwrite anything and
2681 * should not be overwritten: Set msg_scroll, restore its value if no
2682 * output was done.
2683 */
2684 msg_scroll = TRUE;
2685 if (filtering)
2686 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2687 FALSE, curbuf, eap);
2688 else if (newfile)
Bram Moolenaarc3691332016-04-20 12:49:49 +02002689 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2691 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002692 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2693 /*
2694 * EVENT_FILETYPE was not triggered but the buffer already has a
2695 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2696 */
2697 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2698 TRUE, curbuf);
2699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 else
2701 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2702 FALSE, NULL, eap);
2703 if (msg_scrolled == n)
2704 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002705# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 if (aborting()) /* autocmds may abort script processing */
2707 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 }
2710#endif
2711
2712 if (recoverymode && error)
2713 return FAIL;
2714 return OK;
2715}
2716
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002717#ifdef OPEN_CHR_FILES
2718/*
2719 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2720 * which is the name of files used for process substitution output by
2721 * some shells on some operating systems, e.g., bash on SunOS.
2722 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2723 */
2724 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002725is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002726{
2727 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2728 && VIM_ISDIGIT(fname[8])
2729 && *skipdigits(fname + 9) == NUL
2730 && (fname[9] != NUL
2731 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2732}
2733#endif
2734
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002735#ifdef FEAT_MBYTE
2736
2737/*
2738 * From the current line count and characters read after that, estimate the
2739 * line number where we are now.
2740 * Used for error messages that include a line number.
2741 */
2742 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002743readfile_linenr(
2744 linenr_T linecnt, /* line count before reading more bytes */
2745 char_u *p, /* start of more bytes read */
2746 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002747{
2748 char_u *s;
2749 linenr_T lnum;
2750
2751 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2752 for (s = p; s < endp; ++s)
2753 if (*s == '\n')
2754 ++lnum;
2755 return lnum;
2756}
2757#endif
2758
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002760 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2761 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 * Returns OK or FAIL.
2763 */
2764 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002765prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766{
2767 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2768#ifdef FEAT_MBYTE
2769 + STRLEN(buf->b_p_fenc)
2770#endif
2771 + 15));
2772 if (eap->cmd == NULL)
2773 return FAIL;
2774
2775#ifdef FEAT_MBYTE
2776 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2777 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002778 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779#else
2780 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2781#endif
2782 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002783
2784 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002785 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002786 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 return OK;
2788}
2789
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002790/*
2791 * Set default or forced 'fileformat' and 'binary'.
2792 */
2793 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002794set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002795{
2796 /* set default 'fileformat' */
2797 if (set_options)
2798 {
2799 if (eap != NULL && eap->force_ff != 0)
2800 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2801 else if (*p_ffs != NUL)
2802 set_fileformat(default_fileformat(), OPT_LOCAL);
2803 }
2804
2805 /* set or reset 'binary' */
2806 if (eap != NULL && eap->force_bin != 0)
2807 {
2808 int oldval = curbuf->b_p_bin;
2809
2810 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2811 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2812 }
2813}
2814
2815#if defined(FEAT_MBYTE) || defined(PROTO)
2816/*
2817 * Set forced 'fileencoding'.
2818 */
2819 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002820set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002821{
2822 if (eap->force_enc != 0)
2823 {
2824 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2825
2826 if (fenc != NULL)
2827 set_string_option_direct((char_u *)"fenc", -1,
2828 fenc, OPT_FREE|OPT_LOCAL, 0);
2829 vim_free(fenc);
2830 }
2831}
2832
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833/*
2834 * Find next fileencoding to use from 'fileencodings'.
2835 * "pp" points to fenc_next. It's advanced to the next item.
2836 * When there are no more items, an empty string is returned and *pp is set to
2837 * NULL.
2838 * When *pp is not set to NULL, the result is in allocated memory.
2839 */
2840 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002841next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842{
2843 char_u *p;
2844 char_u *r;
2845
2846 if (**pp == NUL)
2847 {
2848 *pp = NULL;
2849 return (char_u *)"";
2850 }
2851 p = vim_strchr(*pp, ',');
2852 if (p == NULL)
2853 {
2854 r = enc_canonize(*pp);
2855 *pp += STRLEN(*pp);
2856 }
2857 else
2858 {
2859 r = vim_strnsave(*pp, (int)(p - *pp));
2860 *pp = p + 1;
2861 if (r != NULL)
2862 {
2863 p = enc_canonize(r);
2864 vim_free(r);
2865 r = p;
2866 }
2867 }
2868 if (r == NULL) /* out of memory */
2869 {
2870 r = (char_u *)"";
2871 *pp = NULL;
2872 }
2873 return r;
2874}
2875
2876# ifdef FEAT_EVAL
2877/*
2878 * Convert a file with the 'charconvert' expression.
2879 * This closes the file which is to be read, converts it and opens the
2880 * resulting file for reading.
2881 * Returns name of the resulting converted file (the caller should delete it
2882 * after reading it).
2883 * Returns NULL if the conversion failed ("*fdp" is not set) .
2884 */
2885 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002886readfile_charconvert(
2887 char_u *fname, /* name of input file */
2888 char_u *fenc, /* converted from */
2889 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890{
2891 char_u *tmpname;
2892 char_u *errmsg = NULL;
2893
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002894 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 if (tmpname == NULL)
2896 errmsg = (char_u *)_("Can't find temp file for conversion");
2897 else
2898 {
2899 close(*fdp); /* close the input file, ignore errors */
2900 *fdp = -1;
2901 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2902 fname, tmpname) == FAIL)
2903 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2904 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2905 O_RDONLY | O_EXTRA, 0)) < 0)
2906 errmsg = (char_u *)_("can't read output of 'charconvert'");
2907 }
2908
2909 if (errmsg != NULL)
2910 {
2911 /* Don't use emsg(), it breaks mappings, the retry with
2912 * another type of conversion might still work. */
2913 MSG(errmsg);
2914 if (tmpname != NULL)
2915 {
2916 mch_remove(tmpname); /* delete converted file */
2917 vim_free(tmpname);
2918 tmpname = NULL;
2919 }
2920 }
2921
2922 /* If the input file is closed, open it (caller should check for error). */
2923 if (*fdp < 0)
2924 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2925
2926 return tmpname;
2927}
2928# endif
2929
2930#endif
2931
2932#ifdef FEAT_VIMINFO
2933/*
2934 * Read marks for the current buffer from the viminfo file, when we support
2935 * buffer marks and the buffer has a name.
2936 */
2937 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002938check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939{
2940 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2941 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002942 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943
2944 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2945 * the ' parameter after opening a buffer. */
2946 curbuf->b_marks_read = TRUE;
2947}
2948#endif
2949
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002950#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002952 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2954 * *filesizep are updated.
2955 * Return the (new) encryption key, NULL for no encryption.
2956 */
2957 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002958check_for_cryptkey(
2959 char_u *cryptkey, /* previous encryption key or NULL */
2960 char_u *ptr, /* pointer to read bytes */
2961 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002962 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002963 int newfile, /* editing a new buffer */
2964 char_u *fname, /* file name to display */
2965 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002967 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002968 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002969
2970 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002972 /* Mark the buffer as read-only until the decryption has taken place.
2973 * Avoids accidentally overwriting the file with garbage. */
2974 curbuf->b_p_ro = TRUE;
2975
Bram Moolenaar2be79502014-08-13 21:58:28 +02002976 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002977 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002978 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 {
2980 if (*curbuf->b_p_key)
2981 cryptkey = curbuf->b_p_key;
2982 else
2983 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002984 /* When newfile is TRUE, store the typed key in the 'key'
2985 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002986 * Don't ask for the key again when first time Enter was hit.
2987 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002988 smsg((char_u *)_(need_key_msg), fname);
2989 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002990 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002991 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002992 *did_ask = TRUE;
2993
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 /* check if empty key entered */
2995 if (cryptkey != NULL && *cryptkey == NUL)
2996 {
2997 if (cryptkey != curbuf->b_p_key)
2998 vim_free(cryptkey);
2999 cryptkey = NULL;
3000 }
3001 }
3002 }
3003
3004 if (cryptkey != NULL)
3005 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003006 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003007
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003008 curbuf->b_cryptstate = crypt_create_from_header(
3009 method, cryptkey, ptr);
3010 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003012 /* Remove cryptmethod specific header from the text. */
3013 header_len = crypt_get_header_len(method);
3014 *filesizep += header_len;
3015 *sizep -= header_len;
3016 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3017
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003018 /* Restore the read-only flag. */
3019 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 }
3021 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003022 /* When starting to edit a new file which does not have encryption, clear
3023 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003024 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3026
3027 return cryptkey;
3028}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003029#endif /* FEAT_CRYPT */
3030
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031#ifdef UNIX
3032 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003033set_file_time(
3034 char_u *fname,
3035 time_t atime, /* access time */
3036 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037{
3038# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3039 struct utimbuf buf;
3040
3041 buf.actime = atime;
3042 buf.modtime = mtime;
3043 (void)utime((char *)fname, &buf);
3044# else
3045# if defined(HAVE_UTIMES)
3046 struct timeval tvp[2];
3047
3048 tvp[0].tv_sec = atime;
3049 tvp[0].tv_usec = 0;
3050 tvp[1].tv_sec = mtime;
3051 tvp[1].tv_usec = 0;
3052# ifdef NeXT
3053 (void)utimes((char *)fname, tvp);
3054# else
3055 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3056# endif
3057# endif
3058# endif
3059}
3060#endif /* UNIX */
3061
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003062#if defined(VMS) && !defined(MIN)
3063/* Older DECC compiler for VAX doesn't define MIN() */
3064# define MIN(a, b) ((a) < (b) ? (a) : (b))
3065#endif
3066
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003068 * Return TRUE if a file appears to be read-only from the file permissions.
3069 */
3070 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003071check_file_readonly(
3072 char_u *fname, /* full path to file */
3073 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003074{
3075#ifndef USE_MCH_ACCESS
3076 int fd = 0;
3077#endif
3078
3079 return (
3080#ifdef USE_MCH_ACCESS
3081# ifdef UNIX
3082 (perm & 0222) == 0 ||
3083# endif
3084 mch_access((char *)fname, W_OK)
3085#else
3086 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3087 ? TRUE : (close(fd), FALSE)
3088#endif
3089 );
3090}
3091
3092
3093/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003094 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 *
3096 * We do our own buffering here because fwrite() is so slow.
3097 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003098 * If "forceit" is true, we don't care for errors when attempting backups.
3099 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003100 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003101 *
3102 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3103 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104 *
3105 * This function must NOT use NameBuff (because it's called by autowrite()).
3106 *
3107 * return FAIL for failure, OK otherwise
3108 */
3109 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003110buf_write(
3111 buf_T *buf,
3112 char_u *fname,
3113 char_u *sfname,
3114 linenr_T start,
3115 linenr_T end,
3116 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003118 int append, /* append to the file */
3119 int forceit,
3120 int reset_changed,
3121 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122{
3123 int fd;
3124 char_u *backup = NULL;
3125 int backup_copy = FALSE; /* copy the original file? */
3126 int dobackup;
3127 char_u *ffname;
3128 char_u *wfname = NULL; /* name of file to write to */
3129 char_u *s;
3130 char_u *ptr;
3131 char_u c;
3132 int len;
3133 linenr_T lnum;
3134 long nchars;
3135 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003136 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137 char_u *errnum = NULL;
3138 char_u *buffer;
3139 char_u smallbuf[SMBUFSIZE];
3140 char_u *backup_ext;
3141 int bufsize;
3142 long perm; /* file permissions */
3143 int retval = OK;
3144 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3145 int msg_save = msg_scroll;
3146 int overwriting; /* TRUE if writing over original */
3147 int no_eol = FALSE; /* no end-of-line written */
3148 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003149 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150 int prev_got_int = got_int;
3151 int file_readonly = FALSE; /* overwritten file is read-only */
3152 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3153#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3154 int made_writable = FALSE; /* 'w' bit has been set */
3155#endif
3156 /* writing everything */
3157 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3158#ifdef FEAT_AUTOCMD
3159 linenr_T old_line_count = buf->b_ml.ml_line_count;
3160#endif
3161 int attr;
3162 int fileformat;
3163 int write_bin;
3164 struct bw_info write_info; /* info for buf_write_bytes() */
3165#ifdef FEAT_MBYTE
3166 int converted = FALSE;
3167 int notconverted = FALSE;
3168 char_u *fenc; /* effective 'fileencoding' */
3169 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3170#endif
3171#ifdef HAS_BW_FLAGS
3172 int wb_flags = 0;
3173#endif
3174#ifdef HAVE_ACL
3175 vim_acl_T acl = NULL; /* ACL copied from original file to
3176 backup or new file */
3177#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003178#ifdef FEAT_PERSISTENT_UNDO
3179 int write_undo_file = FALSE;
3180 context_sha256_T sha_ctx;
3181#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003182 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183
3184 if (fname == NULL || *fname == NUL) /* safety check */
3185 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003186 if (buf->b_ml.ml_mfp == NULL)
3187 {
3188 /* This can happen during startup when there is a stray "w" in the
3189 * vimrc file. */
3190 EMSG(_(e_emptybuf));
3191 return FAIL;
3192 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193
3194 /*
3195 * Disallow writing from .exrc and .vimrc in current directory for
3196 * security reasons.
3197 */
3198 if (check_secure())
3199 return FAIL;
3200
3201 /* Avoid a crash for a long name. */
3202 if (STRLEN(fname) >= MAXPATHL)
3203 {
3204 EMSG(_(e_longname));
3205 return FAIL;
3206 }
3207
3208#ifdef FEAT_MBYTE
3209 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3210 write_info.bw_conv_buf = NULL;
3211 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003212 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 write_info.bw_restlen = 0;
3214# ifdef USE_ICONV
3215 write_info.bw_iconv_fd = (iconv_t)-1;
3216# endif
3217#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003218#ifdef FEAT_CRYPT
3219 write_info.bw_buffer = buf;
3220#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221
Bram Moolenaardf177f62005-02-22 08:39:57 +00003222 /* After writing a file changedtick changes but we don't want to display
3223 * the line. */
3224 ex_no_reprint = TRUE;
3225
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 /*
3227 * If there is no file name yet, use the one for the written file.
3228 * BF_NOTEDITED is set to reflect this (in case the write fails).
3229 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003230 * Don't do this when appending.
3231 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003233 if (buf->b_ffname == NULL
3234 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 && whole
3236 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003237#ifdef FEAT_QUICKFIX
3238 && !bt_nofile(buf)
3239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003241 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3243 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003244 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003246 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 }
3248
3249 if (sfname == NULL)
3250 sfname = fname;
3251 /*
3252 * For Unix: Use the short file name whenever possible.
3253 * Avoids problems with networks and when directory names are changed.
3254 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3255 * another directory, which we don't detect
3256 */
3257 ffname = fname; /* remember full fname */
3258#ifdef UNIX
3259 fname = sfname;
3260#endif
3261
3262 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3263 overwriting = TRUE;
3264 else
3265 overwriting = FALSE;
3266
3267 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003268 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270 ++no_wait_return; /* don't wait for return yet */
3271
3272 /*
3273 * Set '[ and '] marks to the lines to be written.
3274 */
3275 buf->b_op_start.lnum = start;
3276 buf->b_op_start.col = 0;
3277 buf->b_op_end.lnum = end;
3278 buf->b_op_end.col = 0;
3279
3280#ifdef FEAT_AUTOCMD
3281 {
3282 aco_save_T aco;
3283 int buf_ffname = FALSE;
3284 int buf_sfname = FALSE;
3285 int buf_fname_f = FALSE;
3286 int buf_fname_s = FALSE;
3287 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003288 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003289 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290
3291 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003292 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 * Set curbuf to the buffer to be written.
3294 * Careful: The autocommands may call buf_write() recursively!
3295 */
3296 if (ffname == buf->b_ffname)
3297 buf_ffname = TRUE;
3298 if (sfname == buf->b_sfname)
3299 buf_sfname = TRUE;
3300 if (fname == buf->b_ffname)
3301 buf_fname_f = TRUE;
3302 if (fname == buf->b_sfname)
3303 buf_fname_s = TRUE;
3304
3305 /* set curwin/curbuf to buf and save a few things */
3306 aucmd_prepbuf(&aco, buf);
3307
3308 if (append)
3309 {
3310 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3311 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003312 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003313#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003314 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003315 nofile_err = TRUE;
3316 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003317#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003318 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003319 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003320 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 }
3322 else if (filtering)
3323 {
3324 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3325 NULL, sfname, FALSE, curbuf, eap);
3326 }
3327 else if (reset_changed && whole)
3328 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003329 int was_changed = curbufIsChanged();
3330
3331 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3332 sfname, sfname, FALSE, curbuf, eap);
3333 if (did_cmd)
3334 {
3335 if (was_changed && !curbufIsChanged())
3336 {
3337 /* Written everything correctly and BufWriteCmd has reset
3338 * 'modified': Correct the undo information so that an
3339 * undo now sets 'modified'. */
3340 u_unchanged(curbuf);
3341 u_update_save_nr(curbuf);
3342 }
3343 }
3344 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003345 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003346#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003347 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003348 nofile_err = TRUE;
3349 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003350#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003351 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003353 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354 }
3355 else
3356 {
3357 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3358 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003360#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003361 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 nofile_err = TRUE;
3363 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003364#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 }
3369
3370 /* restore curwin/curbuf and a few other things */
3371 aucmd_restbuf(&aco);
3372
3373 /*
3374 * In three situations we return here and don't write the file:
3375 * 1. the autocommands deleted or unloaded the buffer.
3376 * 2. The autocommands abort script processing.
3377 * 3. If one of the "Cmd" autocommands was executed.
3378 */
3379 if (!buf_valid(buf))
3380 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003381 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003382 || did_cmd || nofile_err
3383#ifdef FEAT_EVAL
3384 || aborting()
3385#endif
3386 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387 {
3388 --no_wait_return;
3389 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003390 if (nofile_err)
3391 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3392
Bram Moolenaar1e015462005-09-25 22:16:38 +00003393 if (nofile_err
3394#ifdef FEAT_EVAL
3395 || aborting()
3396#endif
3397 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 /* An aborting error, interrupt or exception in the
3399 * autocommands. */
3400 return FAIL;
3401 if (did_cmd)
3402 {
3403 if (buf == NULL)
3404 /* The buffer was deleted. We assume it was written
3405 * (can't retry anyway). */
3406 return OK;
3407 if (overwriting)
3408 {
3409 /* Assume the buffer was written, update the timestamp. */
3410 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003411 if (append)
3412 buf->b_flags &= ~BF_NEW;
3413 else
3414 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003416 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003417 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 /* Buffer still changed, the autocommands didn't work
3419 * properly. */
3420 return FAIL;
3421 return OK;
3422 }
3423#ifdef FEAT_EVAL
3424 if (!aborting())
3425#endif
3426 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3427 return FAIL;
3428 }
3429
3430 /*
3431 * The autocommands may have changed the number of lines in the file.
3432 * When writing the whole file, adjust the end.
3433 * When writing part of the file, assume that the autocommands only
3434 * changed the number of lines that are to be written (tricky!).
3435 */
3436 if (buf->b_ml.ml_line_count != old_line_count)
3437 {
3438 if (whole) /* write all */
3439 end = buf->b_ml.ml_line_count;
3440 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3441 end += buf->b_ml.ml_line_count - old_line_count;
3442 else /* less lines */
3443 {
3444 end -= old_line_count - buf->b_ml.ml_line_count;
3445 if (end < start)
3446 {
3447 --no_wait_return;
3448 msg_scroll = msg_save;
3449 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3450 return FAIL;
3451 }
3452 }
3453 }
3454
3455 /*
3456 * The autocommands may have changed the name of the buffer, which may
3457 * be kept in fname, ffname and sfname.
3458 */
3459 if (buf_ffname)
3460 ffname = buf->b_ffname;
3461 if (buf_sfname)
3462 sfname = buf->b_sfname;
3463 if (buf_fname_f)
3464 fname = buf->b_ffname;
3465 if (buf_fname_s)
3466 fname = buf->b_sfname;
3467 }
3468#endif
3469
3470#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003471 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 {
3473 if (whole)
3474 {
3475 /*
3476 * b_changed can be 0 after an undo, but we still need to write
3477 * the buffer to NetBeans.
3478 */
3479 if (buf->b_changed || isNetbeansModified(buf))
3480 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003481 --no_wait_return; /* may wait for return now */
3482 msg_scroll = msg_save;
3483 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003484 return retval;
3485 }
3486 else
3487 {
3488 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003489 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 buffer = NULL;
3491 goto fail;
3492 }
3493 }
3494 else
3495 {
3496 errnum = (char_u *)"E657: ";
3497 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3498 buffer = NULL;
3499 goto fail;
3500 }
3501 }
3502#endif
3503
3504 if (shortmess(SHM_OVER) && !exiting)
3505 msg_scroll = FALSE; /* overwrite previous file message */
3506 else
3507 msg_scroll = TRUE; /* don't overwrite previous file message */
3508 if (!filtering)
3509 filemess(buf,
3510#ifndef UNIX
3511 sfname,
3512#else
3513 fname,
3514#endif
3515 (char_u *)"", 0); /* show that we are busy */
3516 msg_scroll = FALSE; /* always overwrite the file message now */
3517
3518 buffer = alloc(BUFSIZE);
3519 if (buffer == NULL) /* can't allocate big buffer, use small
3520 * one (to be able to write when out of
3521 * memory) */
3522 {
3523 buffer = smallbuf;
3524 bufsize = SMBUFSIZE;
3525 }
3526 else
3527 bufsize = BUFSIZE;
3528
3529 /*
3530 * Get information about original file (if there is one).
3531 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003532#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003533 st_old.st_dev = 0;
3534 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 perm = -1;
3536 if (mch_stat((char *)fname, &st_old) < 0)
3537 newfile = TRUE;
3538 else
3539 {
3540 perm = st_old.st_mode;
3541 if (!S_ISREG(st_old.st_mode)) /* not a file */
3542 {
3543 if (S_ISDIR(st_old.st_mode))
3544 {
3545 errnum = (char_u *)"E502: ";
3546 errmsg = (char_u *)_("is a directory");
3547 goto fail;
3548 }
3549 if (mch_nodetype(fname) != NODE_WRITABLE)
3550 {
3551 errnum = (char_u *)"E503: ";
3552 errmsg = (char_u *)_("is not a file or writable device");
3553 goto fail;
3554 }
3555 /* It's a device of some kind (or a fifo) which we can write to
3556 * but for which we can't make a backup. */
3557 device = TRUE;
3558 newfile = TRUE;
3559 perm = -1;
3560 }
3561 }
3562#else /* !UNIX */
3563 /*
3564 * Check for a writable device name.
3565 */
3566 c = mch_nodetype(fname);
3567 if (c == NODE_OTHER)
3568 {
3569 errnum = (char_u *)"E503: ";
3570 errmsg = (char_u *)_("is not a file or writable device");
3571 goto fail;
3572 }
3573 if (c == NODE_WRITABLE)
3574 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003575# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003576 /* MS-Windows allows opening a device, but we will probably get stuck
3577 * trying to write to it. */
3578 if (!p_odev)
3579 {
3580 errnum = (char_u *)"E796: ";
3581 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3582 goto fail;
3583 }
3584# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 device = TRUE;
3586 newfile = TRUE;
3587 perm = -1;
3588 }
3589 else
3590 {
3591 perm = mch_getperm(fname);
3592 if (perm < 0)
3593 newfile = TRUE;
3594 else if (mch_isdir(fname))
3595 {
3596 errnum = (char_u *)"E502: ";
3597 errmsg = (char_u *)_("is a directory");
3598 goto fail;
3599 }
3600 if (overwriting)
3601 (void)mch_stat((char *)fname, &st_old);
3602 }
3603#endif /* !UNIX */
3604
3605 if (!device && !newfile)
3606 {
3607 /*
3608 * Check if the file is really writable (when renaming the file to
3609 * make a backup we won't discover it later).
3610 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003611 file_readonly = check_file_readonly(fname, (int)perm);
3612
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613 if (!forceit && file_readonly)
3614 {
3615 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3616 {
3617 errnum = (char_u *)"E504: ";
3618 errmsg = (char_u *)_(err_readonly);
3619 }
3620 else
3621 {
3622 errnum = (char_u *)"E505: ";
3623 errmsg = (char_u *)_("is read-only (add ! to override)");
3624 }
3625 goto fail;
3626 }
3627
3628 /*
3629 * Check if the timestamp hasn't changed since reading the file.
3630 */
3631 if (overwriting)
3632 {
3633 retval = check_mtime(buf, &st_old);
3634 if (retval == FAIL)
3635 goto fail;
3636 }
3637 }
3638
3639#ifdef HAVE_ACL
3640 /*
3641 * For systems that support ACL: get the ACL from the original file.
3642 */
3643 if (!newfile)
3644 acl = mch_get_acl(fname);
3645#endif
3646
3647 /*
3648 * If 'backupskip' is not empty, don't make a backup for some files.
3649 */
3650 dobackup = (p_wb || p_bk || *p_pm != NUL);
3651#ifdef FEAT_WILDIGN
3652 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3653 dobackup = FALSE;
3654#endif
3655
3656 /*
3657 * Save the value of got_int and reset it. We don't want a previous
3658 * interruption cancel writing, only hitting CTRL-C while writing should
3659 * abort it.
3660 */
3661 prev_got_int = got_int;
3662 got_int = FALSE;
3663
3664 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3665 buf->b_saving = TRUE;
3666
3667 /*
3668 * If we are not appending or filtering, the file exists, and the
3669 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3670 * When 'patchmode' is set also make a backup when appending.
3671 *
3672 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3673 * off. This helps when editing large files on almost-full disks.
3674 */
3675 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3676 {
3677#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003678 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679#endif
3680
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003681 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 backup_copy = TRUE;
3683#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003684 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685 {
3686 int i;
3687
3688# ifdef UNIX
3689 /*
3690 * Don't rename the file when:
3691 * - it's a hard link
3692 * - it's a symbolic link
3693 * - we don't have write permission in the directory
3694 * - we can't set the owner/group of the new file
3695 */
3696 if (st_old.st_nlink > 1
3697 || mch_lstat((char *)fname, &st) < 0
3698 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003699 || st.st_ino != st_old.st_ino
3700# ifndef HAVE_FCHOWN
3701 || st.st_uid != st_old.st_uid
3702 || st.st_gid != st_old.st_gid
3703# endif
3704 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705 backup_copy = TRUE;
3706 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003707# else
3708# ifdef WIN32
3709 /* On NTFS file systems hard links are possible. */
3710 if (mch_is_linked(fname))
3711 backup_copy = TRUE;
3712 else
3713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714# endif
3715 {
3716 /*
3717 * Check if we can create a file and set the owner/group to
3718 * the ones from the original file.
3719 * First find a file name that doesn't exist yet (use some
3720 * arbitrary numbers).
3721 */
3722 STRCPY(IObuff, fname);
3723 for (i = 4913; ; i += 123)
3724 {
3725 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003726 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 break;
3728 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003729 fd = mch_open((char *)IObuff,
3730 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 if (fd < 0) /* can't write in directory */
3732 backup_copy = TRUE;
3733 else
3734 {
3735# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003736# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003737 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 if (mch_stat((char *)IObuff, &st) < 0
3740 || st.st_uid != st_old.st_uid
3741 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003742 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 backup_copy = TRUE;
3744# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003745 /* Close the file before removing it, on MS-Windows we
3746 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003747 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003748 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003749# ifdef MSWIN
3750 /* MS-Windows may trigger a virus scanner to open the
3751 * file, we can't delete it then. Keep trying for half a
3752 * second. */
3753 {
3754 int try;
3755
3756 for (try = 0; try < 10; ++try)
3757 {
3758 if (mch_lstat((char *)IObuff, &st) < 0)
3759 break;
3760 ui_delay(50L, TRUE); /* wait 50 msec */
3761 mch_remove(IObuff);
3762 }
3763 }
3764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 }
3766 }
3767 }
3768
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769 /*
3770 * Break symlinks and/or hardlinks if we've been asked to.
3771 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003772 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003774# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 int lstat_res;
3776
3777 lstat_res = mch_lstat((char *)fname, &st);
3778
3779 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003780 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 && lstat_res == 0
3782 && st.st_ino != st_old.st_ino)
3783 backup_copy = FALSE;
3784
3785 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003786 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 && st_old.st_nlink > 1
3788 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3789 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003790# else
3791# if defined(WIN32)
3792 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003793 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003794 backup_copy = FALSE;
3795
3796 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003797 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003798 backup_copy = FALSE;
3799# endif
3800# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003802
3803#endif
3804
3805 /* make sure we have a valid backup extension to use */
3806 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 else
3809 backup_ext = p_bex;
3810
3811 if (backup_copy
3812 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3813 {
3814 int bfd;
3815 char_u *copybuf, *wp;
3816 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003817 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 char_u *dirp;
3819 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003820#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821 int did_set_shortname;
3822#endif
3823
3824 copybuf = alloc(BUFSIZE + 1);
3825 if (copybuf == NULL)
3826 {
3827 some_error = TRUE; /* out of memory */
3828 goto nobackup;
3829 }
3830
3831 /*
3832 * Try to make the backup in each directory in the 'bdir' option.
3833 *
3834 * Unix semantics has it, that we may have a writable file,
3835 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3836 * - the directory is not writable,
3837 * - the file may be a symbolic link,
3838 * - the file may belong to another user/group, etc.
3839 *
3840 * For these reasons, the existing writable file must be truncated
3841 * and reused. Creation of a backup COPY will be attempted.
3842 */
3843 dirp = p_bdir;
3844 while (*dirp)
3845 {
3846#ifdef UNIX
3847 st_new.st_ino = 0;
3848 st_new.st_dev = 0;
3849 st_new.st_gid = 0;
3850#endif
3851
3852 /*
3853 * Isolate one directory name, using an entry in 'bdir'.
3854 */
3855 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3856 rootname = get_file_in_dir(fname, copybuf);
3857 if (rootname == NULL)
3858 {
3859 some_error = TRUE; /* out of memory */
3860 goto nobackup;
3861 }
3862
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003863#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864 did_set_shortname = FALSE;
3865#endif
3866
3867 /*
3868 * May try twice if 'shortname' not set.
3869 */
3870 for (;;)
3871 {
3872 /*
3873 * Make backup file name.
3874 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003875 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 rootname, backup_ext, FALSE);
3877 if (backup == NULL)
3878 {
3879 vim_free(rootname);
3880 some_error = TRUE; /* out of memory */
3881 goto nobackup;
3882 }
3883
3884 /*
3885 * Check if backup file already exists.
3886 */
3887 if (mch_stat((char *)backup, &st_new) >= 0)
3888 {
3889#ifdef UNIX
3890 /*
3891 * Check if backup file is same as original file.
3892 * May happen when modname() gave the same file back.
3893 * E.g. silly link, or file name-length reached.
3894 * If we don't check here, we either ruin the file
3895 * when copying or erase it after writing. jw.
3896 */
3897 if (st_new.st_dev == st_old.st_dev
3898 && st_new.st_ino == st_old.st_ino)
3899 {
3900 vim_free(backup);
3901 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 /*
3903 * may try again with 'shortname' set
3904 */
3905 if (!(buf->b_shortname || buf->b_p_sn))
3906 {
3907 buf->b_shortname = TRUE;
3908 did_set_shortname = TRUE;
3909 continue;
3910 }
3911 /* setting shortname didn't help */
3912 if (did_set_shortname)
3913 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 break;
3915 }
3916#endif
3917
3918 /*
3919 * If we are not going to keep the backup file, don't
3920 * delete an existing one, try to use another name.
3921 * Change one character, just before the extension.
3922 */
3923 if (!p_bk)
3924 {
3925 wp = backup + STRLEN(backup) - 1
3926 - STRLEN(backup_ext);
3927 if (wp < backup) /* empty file name ??? */
3928 wp = backup;
3929 *wp = 'z';
3930 while (*wp > 'a'
3931 && mch_stat((char *)backup, &st_new) >= 0)
3932 --*wp;
3933 /* They all exist??? Must be something wrong. */
3934 if (*wp == 'a')
3935 {
3936 vim_free(backup);
3937 backup = NULL;
3938 }
3939 }
3940 }
3941 break;
3942 }
3943 vim_free(rootname);
3944
3945 /*
3946 * Try to create the backup file
3947 */
3948 if (backup != NULL)
3949 {
3950 /* remove old backup, if present */
3951 mch_remove(backup);
3952 /* Open with O_EXCL to avoid the file being created while
3953 * we were sleeping (symlink hacker attack?) */
3954 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003955 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3956 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 if (bfd < 0)
3958 {
3959 vim_free(backup);
3960 backup = NULL;
3961 }
3962 else
3963 {
3964 /* set file protection same as original file, but
3965 * strip s-bit */
3966 (void)mch_setperm(backup, perm & 0777);
3967
3968#ifdef UNIX
3969 /*
3970 * Try to set the group of the backup same as the
3971 * original file. If this fails, set the protection
3972 * bits for the group same as the protection bits for
3973 * others.
3974 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003975 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003977 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978# endif
3979 )
3980 mch_setperm(backup,
3981 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003982# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003983 mch_copy_sec(fname, backup);
3984# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985#endif
3986
3987 /*
3988 * copy the file.
3989 */
3990 write_info.bw_fd = bfd;
3991 write_info.bw_buf = copybuf;
3992#ifdef HAS_BW_FLAGS
3993 write_info.bw_flags = FIO_NOCONVERT;
3994#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003995 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 BUFSIZE)) > 0)
3997 {
3998 if (buf_write_bytes(&write_info) == FAIL)
3999 {
4000 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4001 break;
4002 }
4003 ui_breakcheck();
4004 if (got_int)
4005 {
4006 errmsg = (char_u *)_(e_interr);
4007 break;
4008 }
4009 }
4010
4011 if (close(bfd) < 0 && errmsg == NULL)
4012 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4013 if (write_info.bw_len < 0)
4014 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4015#ifdef UNIX
4016 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4017#endif
4018#ifdef HAVE_ACL
4019 mch_set_acl(backup, acl);
4020#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004021#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004022 mch_copy_sec(fname, backup);
4023#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024 break;
4025 }
4026 }
4027 }
4028 nobackup:
4029 close(fd); /* ignore errors for closing read file */
4030 vim_free(copybuf);
4031
4032 if (backup == NULL && errmsg == NULL)
4033 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4034 /* ignore errors when forceit is TRUE */
4035 if ((some_error || errmsg != NULL) && !forceit)
4036 {
4037 retval = FAIL;
4038 goto fail;
4039 }
4040 errmsg = NULL;
4041 }
4042 else
4043 {
4044 char_u *dirp;
4045 char_u *p;
4046 char_u *rootname;
4047
4048 /*
4049 * Make a backup by renaming the original file.
4050 */
4051 /*
4052 * If 'cpoptions' includes the "W" flag, we don't want to
4053 * overwrite a read-only file. But rename may be possible
4054 * anyway, thus we need an extra check here.
4055 */
4056 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4057 {
4058 errnum = (char_u *)"E504: ";
4059 errmsg = (char_u *)_(err_readonly);
4060 goto fail;
4061 }
4062
4063 /*
4064 *
4065 * Form the backup file name - change path/fo.o.h to
4066 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4067 * that works is used.
4068 */
4069 dirp = p_bdir;
4070 while (*dirp)
4071 {
4072 /*
4073 * Isolate one directory name and make the backup file name.
4074 */
4075 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4076 rootname = get_file_in_dir(fname, IObuff);
4077 if (rootname == NULL)
4078 backup = NULL;
4079 else
4080 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004081 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004082 rootname, backup_ext, FALSE);
4083 vim_free(rootname);
4084 }
4085
4086 if (backup != NULL)
4087 {
4088 /*
4089 * If we are not going to keep the backup file, don't
4090 * delete an existing one, try to use another name.
4091 * Change one character, just before the extension.
4092 */
4093 if (!p_bk && mch_getperm(backup) >= 0)
4094 {
4095 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4096 if (p < backup) /* empty file name ??? */
4097 p = backup;
4098 *p = 'z';
4099 while (*p > 'a' && mch_getperm(backup) >= 0)
4100 --*p;
4101 /* They all exist??? Must be something wrong! */
4102 if (*p == 'a')
4103 {
4104 vim_free(backup);
4105 backup = NULL;
4106 }
4107 }
4108 }
4109 if (backup != NULL)
4110 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004112 * Delete any existing backup and move the current version
4113 * to the backup. For safety, we don't remove the backup
4114 * until the write has finished successfully. And if the
4115 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 */
4117 /*
4118 * If the renaming of the original file to the backup file
4119 * works, quit here.
4120 */
4121 if (vim_rename(fname, backup) == 0)
4122 break;
4123
4124 vim_free(backup); /* don't do the rename below */
4125 backup = NULL;
4126 }
4127 }
4128 if (backup == NULL && !forceit)
4129 {
4130 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4131 goto fail;
4132 }
4133 }
4134 }
4135
Bram Moolenaar53076832015-12-31 19:53:21 +01004136#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 /* When using ":w!" and the file was read-only: make it writable */
4138 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4139 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4140 {
4141 perm |= 0200;
4142 (void)mch_setperm(fname, perm);
4143 made_writable = TRUE;
4144 }
4145#endif
4146
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004147 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004148 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4149 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 {
4151 buf->b_p_ro = FALSE;
4152#ifdef FEAT_TITLE
4153 need_maketitle = TRUE; /* set window title later */
4154#endif
4155#ifdef FEAT_WINDOWS
4156 status_redraw_all(); /* redraw status lines later */
4157#endif
4158 }
4159
4160 if (end > buf->b_ml.ml_line_count)
4161 end = buf->b_ml.ml_line_count;
4162 if (buf->b_ml.ml_flags & ML_EMPTY)
4163 start = end + 1;
4164
4165 /*
4166 * If the original file is being overwritten, there is a small chance that
4167 * we crash in the middle of writing. Therefore the file is preserved now.
4168 * This makes all block numbers positive so that recovery does not need
4169 * the original file.
4170 * Don't do this if there is a backup file and we are exiting.
4171 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004172 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 && !(exiting && backup != NULL))
4174 {
4175 ml_preserve(buf, FALSE);
4176 if (got_int)
4177 {
4178 errmsg = (char_u *)_(e_interr);
4179 goto restore_backup;
4180 }
4181 }
4182
4183#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4184 /*
4185 * Before risking to lose the original file verify if there's
4186 * a resource fork to preserve, and if cannot be done warn
4187 * the users. This happens when overwriting without backups.
4188 */
4189 if (backup == NULL && overwriting && !append)
4190 if (mch_has_resource_fork(fname))
4191 {
4192 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4193 goto restore_backup;
4194 }
4195#endif
4196
4197#ifdef VMS
4198 vms_remove_version(fname); /* remove version */
4199#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004200 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 * multi-byte conversion. */
4202 wfname = fname;
4203
4204#ifdef FEAT_MBYTE
4205 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4206 if (eap != NULL && eap->force_enc != 0)
4207 {
4208 fenc = eap->cmd + eap->force_enc;
4209 fenc = enc_canonize(fenc);
4210 fenc_tofree = fenc;
4211 }
4212 else
4213 fenc = buf->b_p_fenc;
4214
4215 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004216 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004218 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219
4220 /*
4221 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4222 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4223 * Prepare the flags for it and allocate bw_conv_buf when needed.
4224 */
4225 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4226 {
4227 wb_flags = get_fio_flags(fenc);
4228 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4229 {
4230 /* Need to allocate a buffer to translate into. */
4231 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4232 write_info.bw_conv_buflen = bufsize * 2;
4233 else /* FIO_UCS4 */
4234 write_info.bw_conv_buflen = bufsize * 4;
4235 write_info.bw_conv_buf
4236 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4237 if (write_info.bw_conv_buf == NULL)
4238 end = 0;
4239 }
4240 }
4241
4242# ifdef WIN3264
4243 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4244 {
4245 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4246 write_info.bw_conv_buflen = bufsize * 4;
4247 write_info.bw_conv_buf
4248 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4249 if (write_info.bw_conv_buf == NULL)
4250 end = 0;
4251 }
4252# endif
4253
4254# ifdef MACOS_X
4255 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4256 {
4257 write_info.bw_conv_buflen = bufsize * 3;
4258 write_info.bw_conv_buf
4259 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4260 if (write_info.bw_conv_buf == NULL)
4261 end = 0;
4262 }
4263# endif
4264
4265# if defined(FEAT_EVAL) || defined(USE_ICONV)
4266 if (converted && wb_flags == 0)
4267 {
4268# ifdef USE_ICONV
4269 /*
4270 * Use iconv() conversion when conversion is needed and it's not done
4271 * internally.
4272 */
4273 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4274 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4275 if (write_info.bw_iconv_fd != (iconv_t)-1)
4276 {
4277 /* We're going to use iconv(), allocate a buffer to convert in. */
4278 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4279 write_info.bw_conv_buf
4280 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4281 if (write_info.bw_conv_buf == NULL)
4282 end = 0;
4283 write_info.bw_first = TRUE;
4284 }
4285# ifdef FEAT_EVAL
4286 else
4287# endif
4288# endif
4289
4290# ifdef FEAT_EVAL
4291 /*
4292 * When the file needs to be converted with 'charconvert' after
4293 * writing, write to a temp file instead and let the conversion
4294 * overwrite the original file.
4295 */
4296 if (*p_ccv != NUL)
4297 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004298 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299 if (wfname == NULL) /* Can't write without a tempfile! */
4300 {
4301 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4302 goto restore_backup;
4303 }
4304 }
4305# endif
4306 }
4307# endif
4308 if (converted && wb_flags == 0
4309# ifdef USE_ICONV
4310 && write_info.bw_iconv_fd == (iconv_t)-1
4311# endif
4312# ifdef FEAT_EVAL
4313 && wfname == fname
4314# endif
4315 )
4316 {
4317 if (!forceit)
4318 {
4319 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4320 goto restore_backup;
4321 }
4322 notconverted = TRUE;
4323 }
4324#endif
4325
4326 /*
4327 * Open the file "wfname" for writing.
4328 * We may try to open the file twice: If we can't write to the
4329 * file and forceit is TRUE we delete the existing file and try to create
4330 * a new one. If this still fails we may have lost the original file!
4331 * (this may happen when the user reached his quotum for number of files).
4332 * Appending will fail if the file does not exist and forceit is FALSE.
4333 */
4334 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4335 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4336 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004337 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338 {
4339 /*
4340 * A forced write will try to create a new file if the old one is
4341 * still readonly. This may also happen when the directory is
4342 * read-only. In that case the mch_remove() will fail.
4343 */
4344 if (errmsg == NULL)
4345 {
4346#ifdef UNIX
Bram Moolenaar8767f522016-07-01 17:17:39 +02004347 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348
4349 /* Don't delete the file when it's a hard or symbolic link. */
4350 if ((!newfile && st_old.st_nlink > 1)
4351 || (mch_lstat((char *)fname, &st) == 0
4352 && (st.st_dev != st_old.st_dev
4353 || st.st_ino != st_old.st_ino)))
4354 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4355 else
4356#endif
4357 {
4358 errmsg = (char_u *)_("E212: Can't open file for writing");
4359 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4360 && perm >= 0)
4361 {
4362#ifdef UNIX
4363 /* we write to the file, thus it should be marked
4364 writable after all */
4365 if (!(perm & 0200))
4366 made_writable = TRUE;
4367 perm |= 0200;
4368 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4369 perm &= 0777;
4370#endif
4371 if (!append) /* don't remove when appending */
4372 mch_remove(wfname);
4373 continue;
4374 }
4375 }
4376 }
4377
4378restore_backup:
4379 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004380 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381
4382 /*
4383 * If we failed to open the file, we don't need a backup. Throw it
4384 * away. If we moved or removed the original file try to put the
4385 * backup in its place.
4386 */
4387 if (backup != NULL && wfname == fname)
4388 {
4389 if (backup_copy)
4390 {
4391 /*
4392 * There is a small chance that we removed the original,
4393 * try to move the copy in its place.
4394 * This may not work if the vim_rename() fails.
4395 * In that case we leave the copy around.
4396 */
4397 /* If file does not exist, put the copy in its place */
4398 if (mch_stat((char *)fname, &st) < 0)
4399 vim_rename(backup, fname);
4400 /* if original file does exist throw away the copy */
4401 if (mch_stat((char *)fname, &st) >= 0)
4402 mch_remove(backup);
4403 }
4404 else
4405 {
4406 /* try to put the original file back */
4407 vim_rename(backup, fname);
4408 }
4409 }
4410
4411 /* if original file no longer exists give an extra warning */
4412 if (!newfile && mch_stat((char *)fname, &st) < 0)
4413 end = 0;
4414 }
4415
4416#ifdef FEAT_MBYTE
4417 if (wfname != fname)
4418 vim_free(wfname);
4419#endif
4420 goto fail;
4421 }
4422 errmsg = NULL;
4423
4424#if defined(MACOS_CLASSIC) || defined(WIN3264)
4425 /* TODO: Is it need for MACOS_X? (Dany) */
4426 /*
4427 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004428 * This is done in order to preserve the resource fork and the
4429 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430 */
4431 if (backup != NULL && overwriting && !append)
4432 {
4433 if (backup_copy)
4434 (void)mch_copy_file_attribute(wfname, backup);
4435 else
4436 (void)mch_copy_file_attribute(backup, wfname);
4437 }
4438
4439 if (!overwriting && !append)
4440 {
4441 if (buf->b_ffname != NULL)
4442 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004443 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 }
4445#endif
4446
4447 write_info.bw_fd = fd;
4448
4449#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004450 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004452 char_u *header;
4453 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004454
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004455 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4456 buf->b_p_key, &header, &header_len);
4457 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004458 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004459 else
4460 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004461 /* Write magic number, so that Vim knows how this file is
4462 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004463 write_info.bw_buf = header;
4464 write_info.bw_len = header_len;
4465 write_info.bw_flags = FIO_NOCONVERT;
4466 if (buf_write_bytes(&write_info) == FAIL)
4467 end = 0;
4468 wb_flags |= FIO_ENCRYPTED;
4469 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004470 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 }
4472#endif
4473
4474 write_info.bw_buf = buffer;
4475 nchars = 0;
4476
4477 /* use "++bin", "++nobin" or 'binary' */
4478 if (eap != NULL && eap->force_bin != 0)
4479 write_bin = (eap->force_bin == FORCE_BIN);
4480 else
4481 write_bin = buf->b_p_bin;
4482
4483#ifdef FEAT_MBYTE
4484 /*
4485 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004486 * Skip it when appending and the file already existed, the BOM only makes
4487 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004489 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 {
4491 write_info.bw_len = make_bom(buffer, fenc);
4492 if (write_info.bw_len > 0)
4493 {
4494 /* don't convert, do encryption */
4495 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4496 if (buf_write_bytes(&write_info) == FAIL)
4497 end = 0;
4498 else
4499 nchars += write_info.bw_len;
4500 }
4501 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004502 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503#endif
4504
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004505#ifdef FEAT_PERSISTENT_UNDO
4506 write_undo_file = (buf->b_p_udf && overwriting && !append
4507 && !filtering && reset_changed);
4508 if (write_undo_file)
4509 /* Prepare for computing the hash value of the text. */
4510 sha256_start(&sha_ctx);
4511#endif
4512
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513 write_info.bw_len = bufsize;
4514#ifdef HAS_BW_FLAGS
4515 write_info.bw_flags = wb_flags;
4516#endif
4517 fileformat = get_fileformat_force(buf, eap);
4518 s = buffer;
4519 len = 0;
4520 for (lnum = start; lnum <= end; ++lnum)
4521 {
4522 /*
4523 * The next while loop is done once for each character written.
4524 * Keep it fast!
4525 */
4526 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004527#ifdef FEAT_PERSISTENT_UNDO
4528 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004529 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004530#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 while ((c = *++ptr) != NUL)
4532 {
4533 if (c == NL)
4534 *s = NUL; /* replace newlines with NULs */
4535 else if (c == CAR && fileformat == EOL_MAC)
4536 *s = NL; /* Mac: replace CRs with NLs */
4537 else
4538 *s = c;
4539 ++s;
4540 if (++len != bufsize)
4541 continue;
4542 if (buf_write_bytes(&write_info) == FAIL)
4543 {
4544 end = 0; /* write error: break loop */
4545 break;
4546 }
4547 nchars += bufsize;
4548 s = buffer;
4549 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004550#ifdef FEAT_MBYTE
4551 write_info.bw_start_lnum = lnum;
4552#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 }
4554 /* write failed or last line has no EOL: stop here */
4555 if (end == 0
4556 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004557 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004558 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004559 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4560 {
4561 ++lnum; /* written the line, count it */
4562 no_eol = TRUE;
4563 break;
4564 }
4565 if (fileformat == EOL_UNIX)
4566 *s++ = NL;
4567 else
4568 {
4569 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4570 if (fileformat == EOL_DOS) /* write CR-NL */
4571 {
4572 if (++len == bufsize)
4573 {
4574 if (buf_write_bytes(&write_info) == FAIL)
4575 {
4576 end = 0; /* write error: break loop */
4577 break;
4578 }
4579 nchars += bufsize;
4580 s = buffer;
4581 len = 0;
4582 }
4583 *s++ = NL;
4584 }
4585 }
4586 if (++len == bufsize && end)
4587 {
4588 if (buf_write_bytes(&write_info) == FAIL)
4589 {
4590 end = 0; /* write error: break loop */
4591 break;
4592 }
4593 nchars += bufsize;
4594 s = buffer;
4595 len = 0;
4596
4597 ui_breakcheck();
4598 if (got_int)
4599 {
4600 end = 0; /* Interrupted, break loop */
4601 break;
4602 }
4603 }
4604#ifdef VMS
4605 /*
4606 * On VMS there is a problem: newlines get added when writing blocks
4607 * at a time. Fix it by writing a line at a time.
4608 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004609 * Explanation: VAX/DECC RTL insists that records in some RMS
4610 * structures end with a newline (carriage return) character, and if
4611 * they don't it adds one.
4612 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004613 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004614 if (buf->b_fab_rfm == FAB$C_VFC
4615 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004617 int b2write;
4618
4619 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4620 ? MIN(4096, bufsize)
4621 : MIN(buf->b_fab_mrs, bufsize));
4622
4623 b2write = len;
4624 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004625 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004626 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4627 if (buf_write_bytes(&write_info) == FAIL)
4628 {
4629 end = 0;
4630 break;
4631 }
4632 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633 }
4634 write_info.bw_len = bufsize;
4635 nchars += len;
4636 s = buffer;
4637 len = 0;
4638 }
4639#endif
4640 }
4641 if (len > 0 && end > 0)
4642 {
4643 write_info.bw_len = len;
4644 if (buf_write_bytes(&write_info) == FAIL)
4645 end = 0; /* write error */
4646 nchars += len;
4647 }
4648
4649#if defined(UNIX) && defined(HAVE_FSYNC)
4650 /* On many journalling file systems there is a bug that causes both the
4651 * original and the backup file to be lost when halting the system right
4652 * after writing the file. That's because only the meta-data is
4653 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004654 * been written to disk and we don't lose it.
4655 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004656 * (could be a pipe).
4657 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4658 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659 {
4660 errmsg = (char_u *)_("E667: Fsync failed");
4661 end = 0;
4662 }
4663#endif
4664
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004665#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004666 /* Probably need to set the security context. */
4667 if (!backup_copy)
4668 mch_copy_sec(backup, wfname);
4669#endif
4670
Bram Moolenaara5792f52005-11-23 21:25:05 +00004671#ifdef UNIX
4672 /* When creating a new file, set its owner/group to that of the original
4673 * file. Get the new device and inode number. */
4674 if (backup != NULL && !backup_copy)
4675 {
4676# ifdef HAVE_FCHOWN
Bram Moolenaar8767f522016-07-01 17:17:39 +02004677 stat_T st;
Bram Moolenaara5792f52005-11-23 21:25:05 +00004678
4679 /* don't change the owner when it's already OK, some systems remove
4680 * permission or ACL stuff */
4681 if (mch_stat((char *)wfname, &st) < 0
4682 || st.st_uid != st_old.st_uid
4683 || st.st_gid != st_old.st_gid)
4684 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004685 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004686 if (perm >= 0) /* set permission again, may have changed */
4687 (void)mch_setperm(wfname, perm);
4688 }
4689# endif
4690 buf_setino(buf);
4691 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004692 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004693 /* Set the inode when creating a new file. */
4694 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004695#endif
4696
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 if (close(fd) != 0)
4698 {
4699 errmsg = (char_u *)_("E512: Close failed");
4700 end = 0;
4701 }
4702
4703#ifdef UNIX
4704 if (made_writable)
4705 perm &= ~0200; /* reset 'w' bit for security reasons */
4706#endif
4707 if (perm >= 0) /* set perm. of new file same as old file */
4708 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709#ifdef HAVE_ACL
4710 /* Probably need to set the ACL before changing the user (can't set the
4711 * ACL on a file the user doesn't own). */
4712 if (!backup_copy)
4713 mch_set_acl(wfname, acl);
4714#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004715#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004716 if (buf->b_cryptstate != NULL)
4717 {
4718 crypt_free_state(buf->b_cryptstate);
4719 buf->b_cryptstate = NULL;
4720 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004721#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4724 if (wfname != fname)
4725 {
4726 /*
4727 * The file was written to a temp file, now it needs to be converted
4728 * with 'charconvert' to (overwrite) the output file.
4729 */
4730 if (end != 0)
4731 {
4732 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4733 wfname, fname) == FAIL)
4734 {
4735 write_info.bw_conv_error = TRUE;
4736 end = 0;
4737 }
4738 }
4739 mch_remove(wfname);
4740 vim_free(wfname);
4741 }
4742#endif
4743
4744 if (end == 0)
4745 {
4746 if (errmsg == NULL)
4747 {
4748#ifdef FEAT_MBYTE
4749 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004750 {
4751 if (write_info.bw_conv_error_lnum == 0)
4752 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4753 else
4754 {
4755 errmsg_allocated = TRUE;
4756 errmsg = alloc(300);
4757 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4758 (long)write_info.bw_conv_error_lnum);
4759 }
4760 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 else
4762#endif
4763 if (got_int)
4764 errmsg = (char_u *)_(e_interr);
4765 else
4766 errmsg = (char_u *)_("E514: write error (file system full?)");
4767 }
4768
4769 /*
4770 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004771 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 * original file when trying to make a backup when writing the file a
4773 * second time.
4774 * When "backup_copy" is set we need to copy the backup over the new
4775 * file. Otherwise rename the backup file.
4776 * If this is OK, don't give the extra warning message.
4777 */
4778 if (backup != NULL)
4779 {
4780 if (backup_copy)
4781 {
4782 /* This may take a while, if we were interrupted let the user
4783 * know we got the message. */
4784 if (got_int)
4785 {
4786 MSG(_(e_interr));
4787 out_flush();
4788 }
4789 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4790 {
4791 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004792 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4793 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 {
4795 /* copy the file. */
4796 write_info.bw_buf = smallbuf;
4797#ifdef HAS_BW_FLAGS
4798 write_info.bw_flags = FIO_NOCONVERT;
4799#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004800 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801 SMBUFSIZE)) > 0)
4802 if (buf_write_bytes(&write_info) == FAIL)
4803 break;
4804
4805 if (close(write_info.bw_fd) >= 0
4806 && write_info.bw_len == 0)
4807 end = 1; /* success */
4808 }
4809 close(fd); /* ignore errors for closing read file */
4810 }
4811 }
4812 else
4813 {
4814 if (vim_rename(backup, fname) == 0)
4815 end = 1;
4816 }
4817 }
4818 goto fail;
4819 }
4820
4821 lnum -= start; /* compute number of written lines */
4822 --no_wait_return; /* may wait for return now */
4823
4824#if !(defined(UNIX) || defined(VMS))
4825 fname = sfname; /* use shortname now, for the messages */
4826#endif
4827 if (!filtering)
4828 {
4829 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4830 c = FALSE;
4831#ifdef FEAT_MBYTE
4832 if (write_info.bw_conv_error)
4833 {
4834 STRCAT(IObuff, _(" CONVERSION ERROR"));
4835 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004836 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004837 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004838 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839 }
4840 else if (notconverted)
4841 {
4842 STRCAT(IObuff, _("[NOT converted]"));
4843 c = TRUE;
4844 }
4845 else if (converted)
4846 {
4847 STRCAT(IObuff, _("[converted]"));
4848 c = TRUE;
4849 }
4850#endif
4851 if (device)
4852 {
4853 STRCAT(IObuff, _("[Device]"));
4854 c = TRUE;
4855 }
4856 else if (newfile)
4857 {
4858 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4859 c = TRUE;
4860 }
4861 if (no_eol)
4862 {
4863 msg_add_eol();
4864 c = TRUE;
4865 }
4866 /* may add [unix/dos/mac] */
4867 if (msg_add_fileformat(fileformat))
4868 c = TRUE;
4869#ifdef FEAT_CRYPT
4870 if (wb_flags & FIO_ENCRYPTED)
4871 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004872 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 c = TRUE;
4874 }
4875#endif
4876 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4877 if (!shortmess(SHM_WRITE))
4878 {
4879 if (append)
4880 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4881 else
4882 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4883 }
4884
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004885 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 }
4887
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004888 /* When written everything correctly: reset 'modified'. Unless not
4889 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004890 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891#ifdef FEAT_MBYTE
4892 && !write_info.bw_conv_error
4893#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004894 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4895 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 {
4897 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004898#ifdef FEAT_AUTOCMD
4899 /* buf->b_changedtick is always incremented in unchanged() but that
4900 * should not trigger a TextChanged event. */
4901 if (last_changedtick + 1 == buf->b_changedtick
4902 && last_changedtick_buf == buf)
4903 last_changedtick = buf->b_changedtick;
4904#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004906 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907 }
4908
4909 /*
4910 * If written to the current file, update the timestamp of the swap file
4911 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4912 */
4913 if (overwriting)
4914 {
4915 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004916 if (append)
4917 buf->b_flags &= ~BF_NEW;
4918 else
4919 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920 }
4921
4922 /*
4923 * If we kept a backup until now, and we are in patch mode, then we make
4924 * the backup file our 'original' file.
4925 */
4926 if (*p_pm && dobackup)
4927 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004928 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929 fname, p_pm, FALSE);
4930
4931 if (backup != NULL)
4932 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004933 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934
4935 /*
4936 * If the original file does not exist yet
4937 * the current backup file becomes the original file
4938 */
4939 if (org == NULL)
4940 EMSG(_("E205: Patchmode: can't save original file"));
4941 else if (mch_stat(org, &st) < 0)
4942 {
4943 vim_rename(backup, (char_u *)org);
4944 vim_free(backup); /* don't delete the file */
4945 backup = NULL;
4946#ifdef UNIX
4947 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4948#endif
4949 }
4950 }
4951 /*
4952 * If there is no backup file, remember that a (new) file was
4953 * created.
4954 */
4955 else
4956 {
4957 int empty_fd;
4958
4959 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004960 || (empty_fd = mch_open(org,
4961 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004962 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 EMSG(_("E206: patchmode: can't touch empty original file"));
4964 else
4965 close(empty_fd);
4966 }
4967 if (org != NULL)
4968 {
4969 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4970 vim_free(org);
4971 }
4972 }
4973
4974 /*
4975 * Remove the backup unless 'backup' option is set
4976 */
4977 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4978 EMSG(_("E207: Can't delete backup file"));
4979
4980#ifdef FEAT_SUN_WORKSHOP
4981 if (usingSunWorkShop)
4982 workshop_file_saved((char *) ffname);
4983#endif
4984
4985 goto nofail;
4986
4987 /*
4988 * Finish up. We get here either after failure or success.
4989 */
4990fail:
4991 --no_wait_return; /* may wait for return now */
4992nofail:
4993
4994 /* Done saving, we accept changed buffer warnings again */
4995 buf->b_saving = FALSE;
4996
4997 vim_free(backup);
4998 if (buffer != smallbuf)
4999 vim_free(buffer);
5000#ifdef FEAT_MBYTE
5001 vim_free(fenc_tofree);
5002 vim_free(write_info.bw_conv_buf);
5003# ifdef USE_ICONV
5004 if (write_info.bw_iconv_fd != (iconv_t)-1)
5005 {
5006 iconv_close(write_info.bw_iconv_fd);
5007 write_info.bw_iconv_fd = (iconv_t)-1;
5008 }
5009# endif
5010#endif
5011#ifdef HAVE_ACL
5012 mch_free_acl(acl);
5013#endif
5014
5015 if (errmsg != NULL)
5016 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005017 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018
5019 attr = hl_attr(HLF_E); /* set highlight for error messages */
5020 msg_add_fname(buf,
5021#ifndef UNIX
5022 sfname
5023#else
5024 fname
5025#endif
5026 ); /* put file name in IObuff with quotes */
5027 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5028 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5029 /* If the error message has the form "is ...", put the error number in
5030 * front of the file name. */
5031 if (errnum != NULL)
5032 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005033 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 mch_memmove(IObuff, errnum, (size_t)numlen);
5035 }
5036 STRCAT(IObuff, errmsg);
5037 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005038 if (errmsg_allocated)
5039 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040
5041 retval = FAIL;
5042 if (end == 0)
5043 {
5044 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5045 attr | MSG_HIST);
5046 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5047 attr | MSG_HIST);
5048
5049 /* Update the timestamp to avoid an "overwrite changed file"
5050 * prompt when writing again. */
5051 if (mch_stat((char *)fname, &st_old) >= 0)
5052 {
5053 buf_store_time(buf, &st_old, fname);
5054 buf->b_mtime_read = buf->b_mtime;
5055 }
5056 }
5057 }
5058 msg_scroll = msg_save;
5059
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005060#ifdef FEAT_PERSISTENT_UNDO
5061 /*
5062 * When writing the whole file and 'undofile' is set, also write the undo
5063 * file.
5064 */
5065 if (retval == OK && write_undo_file)
5066 {
5067 char_u hash[UNDO_HASH_SIZE];
5068
5069 sha256_finish(&sha_ctx, hash);
5070 u_write_undo(NULL, FALSE, buf, hash);
5071 }
5072#endif
5073
Bram Moolenaar071d4272004-06-13 20:20:40 +00005074#ifdef FEAT_AUTOCMD
5075#ifdef FEAT_EVAL
5076 if (!should_abort(retval))
5077#else
5078 if (!got_int)
5079#endif
5080 {
5081 aco_save_T aco;
5082
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005083 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5084
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085 /*
5086 * Apply POST autocommands.
5087 * Careful: The autocommands may call buf_write() recursively!
5088 */
5089 aucmd_prepbuf(&aco, buf);
5090
5091 if (append)
5092 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5093 FALSE, curbuf, eap);
5094 else if (filtering)
5095 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5096 FALSE, curbuf, eap);
5097 else if (reset_changed && whole)
5098 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5099 FALSE, curbuf, eap);
5100 else
5101 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5102 FALSE, curbuf, eap);
5103
5104 /* restore curwin/curbuf and a few other things */
5105 aucmd_restbuf(&aco);
5106
5107#ifdef FEAT_EVAL
5108 if (aborting()) /* autocmds may abort script processing */
5109 retval = FALSE;
5110#endif
5111 }
5112#endif
5113
5114 got_int |= prev_got_int;
5115
5116#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5117 /* Update machine specific information. */
5118 mch_post_buffer_write(buf);
5119#endif
5120 return retval;
5121}
5122
5123/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005124 * Set the name of the current buffer. Use when the buffer doesn't have a
5125 * name and a ":r" or ":w" command with a file name is used.
5126 */
5127 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005128set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005129{
5130#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005131 buf_T *buf = curbuf;
5132
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005133 /* It's like the unnamed buffer is deleted.... */
5134 if (curbuf->b_p_bl)
5135 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5136 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5137# ifdef FEAT_EVAL
5138 if (aborting()) /* autocmds may abort script processing */
5139 return FAIL;
5140# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005141 if (curbuf != buf)
5142 {
5143 /* We are in another buffer now, don't do the renaming. */
5144 EMSG(_(e_auchangedbuf));
5145 return FAIL;
5146 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005147#endif
5148
5149 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5150 curbuf->b_flags |= BF_NOTEDITED;
5151
5152#ifdef FEAT_AUTOCMD
5153 /* ....and a new named one is created */
5154 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5155 if (curbuf->b_p_bl)
5156 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5157# ifdef FEAT_EVAL
5158 if (aborting()) /* autocmds may abort script processing */
5159 return FAIL;
5160# endif
5161
5162 /* Do filetype detection now if 'filetype' is empty. */
5163 if (*curbuf->b_p_ft == NUL)
5164 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005165 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005166 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005167 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005168 }
5169#endif
5170
5171 return OK;
5172}
5173
5174/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175 * Put file name into IObuff with quotes.
5176 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005177 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005178msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179{
5180 if (fname == NULL)
5181 fname = (char_u *)"-stdin-";
5182 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5183 IObuff[0] = '"';
5184 STRCAT(IObuff, "\" ");
5185}
5186
5187/*
5188 * Append message for text mode to IObuff.
5189 * Return TRUE if something appended.
5190 */
5191 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005192msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193{
5194#ifndef USE_CRNL
5195 if (eol_type == EOL_DOS)
5196 {
5197 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5198 return TRUE;
5199 }
5200#endif
5201#ifndef USE_CR
5202 if (eol_type == EOL_MAC)
5203 {
5204 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5205 return TRUE;
5206 }
5207#endif
5208#if defined(USE_CRNL) || defined(USE_CR)
5209 if (eol_type == EOL_UNIX)
5210 {
5211 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5212 return TRUE;
5213 }
5214#endif
5215 return FALSE;
5216}
5217
5218/*
5219 * Append line and character count to IObuff.
5220 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005221 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005222msg_add_lines(
5223 int insert_space,
5224 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005225 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005226{
5227 char_u *p;
5228
5229 p = IObuff + STRLEN(IObuff);
5230
5231 if (insert_space)
5232 *p++ = ' ';
5233 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005234 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5235 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236 else
5237 {
5238 if (lnum == 1)
5239 STRCPY(p, _("1 line, "));
5240 else
5241 sprintf((char *)p, _("%ld lines, "), lnum);
5242 p += STRLEN(p);
5243 if (nchars == 1)
5244 STRCPY(p, _("1 character"));
5245 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005246 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5247 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248 }
5249}
5250
5251/*
5252 * Append message for missing line separator to IObuff.
5253 */
5254 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005255msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005256{
5257 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5258}
5259
5260/*
5261 * Check modification time of file, before writing to it.
5262 * The size isn't checked, because using a tool like "gzip" takes care of
5263 * using the same timestamp but can't set the size.
5264 */
5265 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005266check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267{
5268 if (buf->b_mtime_read != 0
5269 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5270 {
5271 msg_scroll = TRUE; /* don't overwrite messages here */
5272 msg_silent = 0; /* must give this prompt */
5273 /* don't use emsg() here, don't want to flush the buffers */
5274 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5275 hl_attr(HLF_E));
5276 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5277 TRUE) == 'n')
5278 return FAIL;
5279 msg_scroll = FALSE; /* always overwrite the file message now */
5280 }
5281 return OK;
5282}
5283
5284 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005285time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005287#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5289 * the seconds. Since the roundoff is done when flushing the inode, the
5290 * time may change unexpectedly by one second!!! */
5291 return (t1 - t2 > 1 || t2 - t1 > 1);
5292#else
5293 return (t1 != t2);
5294#endif
5295}
5296
5297/*
5298 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005299 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005300 *
5301 * Return FAIL for failure, OK otherwise.
5302 */
5303 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005304buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005305{
5306 int wlen;
5307 char_u *buf = ip->bw_buf; /* data to write */
5308 int len = ip->bw_len; /* length of data */
5309#ifdef HAS_BW_FLAGS
5310 int flags = ip->bw_flags; /* extra flags */
5311#endif
5312
5313#ifdef FEAT_MBYTE
5314 /*
5315 * Skip conversion when writing the crypt magic number or the BOM.
5316 */
5317 if (!(flags & FIO_NOCONVERT))
5318 {
5319 char_u *p;
5320 unsigned c;
5321 int n;
5322
5323 if (flags & FIO_UTF8)
5324 {
5325 /*
5326 * Convert latin1 in the buffer to UTF-8 in the file.
5327 */
5328 p = ip->bw_conv_buf; /* translate to buffer */
5329 for (wlen = 0; wlen < len; ++wlen)
5330 p += utf_char2bytes(buf[wlen], p);
5331 buf = ip->bw_conv_buf;
5332 len = (int)(p - ip->bw_conv_buf);
5333 }
5334 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5335 {
5336 /*
5337 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5338 * Latin1 chars in the file.
5339 */
5340 if (flags & FIO_LATIN1)
5341 p = buf; /* translate in-place (can only get shorter) */
5342 else
5343 p = ip->bw_conv_buf; /* translate to buffer */
5344 for (wlen = 0; wlen < len; wlen += n)
5345 {
5346 if (wlen == 0 && ip->bw_restlen != 0)
5347 {
5348 int l;
5349
5350 /* Use remainder of previous call. Append the start of
5351 * buf[] to get a full sequence. Might still be too
5352 * short! */
5353 l = CONV_RESTLEN - ip->bw_restlen;
5354 if (l > len)
5355 l = len;
5356 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005357 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005358 if (n > ip->bw_restlen + len)
5359 {
5360 /* We have an incomplete byte sequence at the end to
5361 * be written. We can't convert it without the
5362 * remaining bytes. Keep them for the next call. */
5363 if (ip->bw_restlen + len > CONV_RESTLEN)
5364 return FAIL;
5365 ip->bw_restlen += len;
5366 break;
5367 }
5368 if (n > 1)
5369 c = utf_ptr2char(ip->bw_rest);
5370 else
5371 c = ip->bw_rest[0];
5372 if (n >= ip->bw_restlen)
5373 {
5374 n -= ip->bw_restlen;
5375 ip->bw_restlen = 0;
5376 }
5377 else
5378 {
5379 ip->bw_restlen -= n;
5380 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5381 (size_t)ip->bw_restlen);
5382 n = 0;
5383 }
5384 }
5385 else
5386 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005387 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388 if (n > len - wlen)
5389 {
5390 /* We have an incomplete byte sequence at the end to
5391 * be written. We can't convert it without the
5392 * remaining bytes. Keep them for the next call. */
5393 if (len - wlen > CONV_RESTLEN)
5394 return FAIL;
5395 ip->bw_restlen = len - wlen;
5396 mch_memmove(ip->bw_rest, buf + wlen,
5397 (size_t)ip->bw_restlen);
5398 break;
5399 }
5400 if (n > 1)
5401 c = utf_ptr2char(buf + wlen);
5402 else
5403 c = buf[wlen];
5404 }
5405
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005406 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5407 {
5408 ip->bw_conv_error = TRUE;
5409 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5410 }
5411 if (c == NL)
5412 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413 }
5414 if (flags & FIO_LATIN1)
5415 len = (int)(p - buf);
5416 else
5417 {
5418 buf = ip->bw_conv_buf;
5419 len = (int)(p - ip->bw_conv_buf);
5420 }
5421 }
5422
5423# ifdef WIN3264
5424 else if (flags & FIO_CODEPAGE)
5425 {
5426 /*
5427 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5428 * codepage.
5429 */
5430 char_u *from;
5431 size_t fromlen;
5432 char_u *to;
5433 int u8c;
5434 BOOL bad = FALSE;
5435 int needed;
5436
5437 if (ip->bw_restlen > 0)
5438 {
5439 /* Need to concatenate the remainder of the previous call and
5440 * the bytes of the current call. Use the end of the
5441 * conversion buffer for this. */
5442 fromlen = len + ip->bw_restlen;
5443 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5444 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5445 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5446 }
5447 else
5448 {
5449 from = buf;
5450 fromlen = len;
5451 }
5452
5453 to = ip->bw_conv_buf;
5454 if (enc_utf8)
5455 {
5456 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5457 * The buffer has been allocated to be big enough. */
5458 while (fromlen > 0)
5459 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005460 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461 if (n > (int)fromlen) /* incomplete byte sequence */
5462 break;
5463 u8c = utf_ptr2char(from);
5464 *to++ = (u8c & 0xff);
5465 *to++ = (u8c >> 8);
5466 fromlen -= n;
5467 from += n;
5468 }
5469
5470 /* Copy remainder to ip->bw_rest[] to be used for the next
5471 * call. */
5472 if (fromlen > CONV_RESTLEN)
5473 {
5474 /* weird overlong sequence */
5475 ip->bw_conv_error = TRUE;
5476 return FAIL;
5477 }
5478 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005479 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005480 }
5481 else
5482 {
5483 /* Convert from enc_codepage to UCS-2, to the start of the
5484 * buffer. The buffer has been allocated to be big enough. */
5485 ip->bw_restlen = 0;
5486 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005487 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 NULL, 0);
5489 if (needed == 0)
5490 {
5491 /* When conversion fails there may be a trailing byte. */
5492 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005493 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494 NULL, 0);
5495 if (needed == 0)
5496 {
5497 /* Conversion doesn't work. */
5498 ip->bw_conv_error = TRUE;
5499 return FAIL;
5500 }
5501 /* Save the trailing byte for the next call. */
5502 ip->bw_rest[0] = from[fromlen - 1];
5503 ip->bw_restlen = 1;
5504 }
5505 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005506 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 (LPWSTR)to, needed);
5508 if (needed == 0)
5509 {
5510 /* Safety check: Conversion doesn't work. */
5511 ip->bw_conv_error = TRUE;
5512 return FAIL;
5513 }
5514 to += needed * 2;
5515 }
5516
5517 fromlen = to - ip->bw_conv_buf;
5518 buf = to;
5519# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5520 if (FIO_GET_CP(flags) == CP_UTF8)
5521 {
5522 /* Convert from UCS-2 to UTF-8, using the remainder of the
5523 * conversion buffer. Fails when out of space. */
5524 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5525 {
5526 u8c = *from++;
5527 u8c += (*from++ << 8);
5528 to += utf_char2bytes(u8c, to);
5529 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5530 {
5531 ip->bw_conv_error = TRUE;
5532 return FAIL;
5533 }
5534 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005535 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536 }
5537 else
5538#endif
5539 {
5540 /* Convert from UCS-2 to the codepage, using the remainder of
5541 * the conversion buffer. If the conversion uses the default
5542 * character "0", the data doesn't fit in this encoding, so
5543 * fail. */
5544 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5545 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005546 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5547 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 if (bad)
5549 {
5550 ip->bw_conv_error = TRUE;
5551 return FAIL;
5552 }
5553 }
5554 }
5555# endif
5556
Bram Moolenaar56718732006-03-15 22:53:57 +00005557# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 else if (flags & FIO_MACROMAN)
5559 {
5560 /*
5561 * Convert UTF-8 or latin1 to Apple MacRoman.
5562 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 char_u *from;
5564 size_t fromlen;
5565
5566 if (ip->bw_restlen > 0)
5567 {
5568 /* Need to concatenate the remainder of the previous call and
5569 * the bytes of the current call. Use the end of the
5570 * conversion buffer for this. */
5571 fromlen = len + ip->bw_restlen;
5572 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5573 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5574 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5575 }
5576 else
5577 {
5578 from = buf;
5579 fromlen = len;
5580 }
5581
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005582 if (enc2macroman(from, fromlen,
5583 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5584 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 {
5586 ip->bw_conv_error = TRUE;
5587 return FAIL;
5588 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 }
5591# endif
5592
5593# ifdef USE_ICONV
5594 if (ip->bw_iconv_fd != (iconv_t)-1)
5595 {
5596 const char *from;
5597 size_t fromlen;
5598 char *to;
5599 size_t tolen;
5600
5601 /* Convert with iconv(). */
5602 if (ip->bw_restlen > 0)
5603 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005604 char *fp;
5605
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606 /* Need to concatenate the remainder of the previous call and
5607 * the bytes of the current call. Use the end of the
5608 * conversion buffer for this. */
5609 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005610 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5611 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5612 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5613 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 tolen = ip->bw_conv_buflen - fromlen;
5615 }
5616 else
5617 {
5618 from = (const char *)buf;
5619 fromlen = len;
5620 tolen = ip->bw_conv_buflen;
5621 }
5622 to = (char *)ip->bw_conv_buf;
5623
5624 if (ip->bw_first)
5625 {
5626 size_t save_len = tolen;
5627
5628 /* output the initial shift state sequence */
5629 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5630
5631 /* There is a bug in iconv() on Linux (which appears to be
5632 * wide-spread) which sets "to" to NULL and messes up "tolen".
5633 */
5634 if (to == NULL)
5635 {
5636 to = (char *)ip->bw_conv_buf;
5637 tolen = save_len;
5638 }
5639 ip->bw_first = FALSE;
5640 }
5641
5642 /*
5643 * If iconv() has an error or there is not enough room, fail.
5644 */
5645 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5646 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5647 || fromlen > CONV_RESTLEN)
5648 {
5649 ip->bw_conv_error = TRUE;
5650 return FAIL;
5651 }
5652
5653 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5654 if (fromlen > 0)
5655 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5656 ip->bw_restlen = (int)fromlen;
5657
5658 buf = ip->bw_conv_buf;
5659 len = (int)((char_u *)to - ip->bw_conv_buf);
5660 }
5661# endif
5662 }
5663#endif /* FEAT_MBYTE */
5664
5665#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005666 if (flags & FIO_ENCRYPTED)
5667 {
5668 /* Encrypt the data. Do it in-place if possible, otherwise use an
5669 * allocated buffer. */
5670 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5671 {
5672 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5673 }
5674 else
5675 {
5676 char_u *outbuf;
5677
5678 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5679 if (len == 0)
5680 return OK; /* Crypt layer is buffering, will flush later. */
5681 wlen = write_eintr(ip->bw_fd, outbuf, len);
5682 vim_free(outbuf);
5683 return (wlen < len) ? FAIL : OK;
5684 }
5685 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686#endif
5687
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005688 wlen = write_eintr(ip->bw_fd, buf, len);
5689 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690}
5691
5692#ifdef FEAT_MBYTE
5693/*
5694 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005695 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 */
5697 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005698ucs2bytes(
5699 unsigned c, /* in: character */
5700 char_u **pp, /* in/out: pointer to result */
5701 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702{
5703 char_u *p = *pp;
5704 int error = FALSE;
5705 int cc;
5706
5707
5708 if (flags & FIO_UCS4)
5709 {
5710 if (flags & FIO_ENDIAN_L)
5711 {
5712 *p++ = c;
5713 *p++ = (c >> 8);
5714 *p++ = (c >> 16);
5715 *p++ = (c >> 24);
5716 }
5717 else
5718 {
5719 *p++ = (c >> 24);
5720 *p++ = (c >> 16);
5721 *p++ = (c >> 8);
5722 *p++ = c;
5723 }
5724 }
5725 else if (flags & (FIO_UCS2 | FIO_UTF16))
5726 {
5727 if (c >= 0x10000)
5728 {
5729 if (flags & FIO_UTF16)
5730 {
5731 /* Make two words, ten bits of the character in each. First
5732 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5733 c -= 0x10000;
5734 if (c >= 0x100000)
5735 error = TRUE;
5736 cc = ((c >> 10) & 0x3ff) + 0xd800;
5737 if (flags & FIO_ENDIAN_L)
5738 {
5739 *p++ = cc;
5740 *p++ = ((unsigned)cc >> 8);
5741 }
5742 else
5743 {
5744 *p++ = ((unsigned)cc >> 8);
5745 *p++ = cc;
5746 }
5747 c = (c & 0x3ff) + 0xdc00;
5748 }
5749 else
5750 error = TRUE;
5751 }
5752 if (flags & FIO_ENDIAN_L)
5753 {
5754 *p++ = c;
5755 *p++ = (c >> 8);
5756 }
5757 else
5758 {
5759 *p++ = (c >> 8);
5760 *p++ = c;
5761 }
5762 }
5763 else /* Latin1 */
5764 {
5765 if (c >= 0x100)
5766 {
5767 error = TRUE;
5768 *p++ = 0xBF;
5769 }
5770 else
5771 *p++ = c;
5772 }
5773
5774 *pp = p;
5775 return error;
5776}
5777
5778/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005779 * Return TRUE if file encoding "fenc" requires conversion from or to
5780 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781 */
5782 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005783need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005785 int same_encoding;
5786 int enc_flags;
5787 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005789 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005790 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005791 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005792 fenc_flags = 0;
5793 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005794 else
5795 {
5796 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5797 * "ucs-4be", etc. */
5798 enc_flags = get_fio_flags(p_enc);
5799 fenc_flags = get_fio_flags(fenc);
5800 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5801 }
5802 if (same_encoding)
5803 {
5804 /* Specified encoding matches with 'encoding'. This requires
5805 * conversion when 'encoding' is Unicode but not UTF-8. */
5806 return enc_unicode != 0;
5807 }
5808
5809 /* Encodings differ. However, conversion is not needed when 'enc' is any
5810 * Unicode encoding and the file is UTF-8. */
5811 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812}
5813
5814/*
5815 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5816 * internal conversion.
5817 * if "ptr" is an empty string, use 'encoding'.
5818 */
5819 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005820get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821{
5822 int prop;
5823
5824 if (*ptr == NUL)
5825 ptr = p_enc;
5826
5827 prop = enc_canon_props(ptr);
5828 if (prop & ENC_UNICODE)
5829 {
5830 if (prop & ENC_2BYTE)
5831 {
5832 if (prop & ENC_ENDIAN_L)
5833 return FIO_UCS2 | FIO_ENDIAN_L;
5834 return FIO_UCS2;
5835 }
5836 if (prop & ENC_4BYTE)
5837 {
5838 if (prop & ENC_ENDIAN_L)
5839 return FIO_UCS4 | FIO_ENDIAN_L;
5840 return FIO_UCS4;
5841 }
5842 if (prop & ENC_2WORD)
5843 {
5844 if (prop & ENC_ENDIAN_L)
5845 return FIO_UTF16 | FIO_ENDIAN_L;
5846 return FIO_UTF16;
5847 }
5848 return FIO_UTF8;
5849 }
5850 if (prop & ENC_LATIN1)
5851 return FIO_LATIN1;
5852 /* must be ENC_DBCS, requires iconv() */
5853 return 0;
5854}
5855
5856#ifdef WIN3264
5857/*
5858 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5859 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5860 * Used for conversion between 'encoding' and 'fileencoding'.
5861 */
5862 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005863get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864{
5865 int cp;
5866
5867 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5868 if (!enc_utf8 && enc_codepage <= 0)
5869 return 0;
5870
5871 cp = encname2codepage(ptr);
5872 if (cp == 0)
5873 {
5874# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5875 if (STRCMP(ptr, "utf-8") == 0)
5876 cp = CP_UTF8;
5877 else
5878# endif
5879 return 0;
5880 }
5881 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5882}
5883#endif
5884
5885#ifdef MACOS_X
5886/*
5887 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5888 * needed for the internal conversion to/from utf-8 or latin1.
5889 */
5890 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005891get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892{
5893 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5894 && (enc_canon_props(ptr) & ENC_MACROMAN))
5895 return FIO_MACROMAN;
5896 return 0;
5897}
5898#endif
5899
5900/*
5901 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5902 * "size" must be at least 2.
5903 * Return the name of the encoding and set "*lenp" to the length.
5904 * Returns NULL when no BOM found.
5905 */
5906 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005907check_for_bom(
5908 char_u *p,
5909 long size,
5910 int *lenp,
5911 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912{
5913 char *name = NULL;
5914 int len = 2;
5915
5916 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005917 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918 {
5919 name = "utf-8"; /* EF BB BF */
5920 len = 3;
5921 }
5922 else if (p[0] == 0xff && p[1] == 0xfe)
5923 {
5924 if (size >= 4 && p[2] == 0 && p[3] == 0
5925 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5926 {
5927 name = "ucs-4le"; /* FF FE 00 00 */
5928 len = 4;
5929 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005930 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005932 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5933 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 name = "utf-16le"; /* FF FE */
5935 }
5936 else if (p[0] == 0xfe && p[1] == 0xff
5937 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5938 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005939 /* Default to utf-16, it works also for ucs-2 text. */
5940 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005942 else
5943 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 }
5945 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5946 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5947 {
5948 name = "ucs-4"; /* 00 00 FE FF */
5949 len = 4;
5950 }
5951
5952 *lenp = len;
5953 return (char_u *)name;
5954}
5955
5956/*
5957 * Generate a BOM in "buf[4]" for encoding "name".
5958 * Return the length of the BOM (zero when no BOM).
5959 */
5960 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005961make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962{
5963 int flags;
5964 char_u *p;
5965
5966 flags = get_fio_flags(name);
5967
5968 /* Can't put a BOM in a non-Unicode file. */
5969 if (flags == FIO_LATIN1 || flags == 0)
5970 return 0;
5971
5972 if (flags == FIO_UTF8) /* UTF-8 */
5973 {
5974 buf[0] = 0xef;
5975 buf[1] = 0xbb;
5976 buf[2] = 0xbf;
5977 return 3;
5978 }
5979 p = buf;
5980 (void)ucs2bytes(0xfeff, &p, flags);
5981 return (int)(p - buf);
5982}
5983#endif
5984
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005985#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005986 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987/*
5988 * Try to find a shortname by comparing the fullname with the current
5989 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005990 * Returns "full_path" or pointer into "full_path" if shortened.
5991 */
5992 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005993shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005994{
Bram Moolenaard9462e32011-04-11 21:35:11 +02005995 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005996 char_u *p = full_path;
5997
Bram Moolenaard9462e32011-04-11 21:35:11 +02005998 dirname = alloc(MAXPATHL);
5999 if (dirname == NULL)
6000 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006001 if (mch_dirname(dirname, MAXPATHL) == OK)
6002 {
6003 p = shorten_fname(full_path, dirname);
6004 if (p == NULL || *p == NUL)
6005 p = full_path;
6006 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006007 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006008 return p;
6009}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006010#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006011
6012/*
6013 * Try to find a shortname by comparing the fullname with the current
6014 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015 * Returns NULL if not shorter name possible, pointer into "full_path"
6016 * otherwise.
6017 */
6018 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006019shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020{
6021 int len;
6022 char_u *p;
6023
6024 if (full_path == NULL)
6025 return NULL;
6026 len = (int)STRLEN(dir_name);
6027 if (fnamencmp(dir_name, full_path, len) == 0)
6028 {
6029 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006030#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006032 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033 * slash, since C: by itself does not define a specific dir. In this
6034 * case p may already be correct. <negri>
6035 */
6036 if (!((len > 2) && (*(p - 2) == ':')))
6037#endif
6038 {
6039 if (vim_ispathsep(*p))
6040 ++p;
6041#ifndef VMS /* the path separator is always part of the path */
6042 else
6043 p = NULL;
6044#endif
6045 }
6046 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006047#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 /*
6049 * When using a file in the current drive, remove the drive name:
6050 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6051 * a floppy from "A:\dir" to "B:\dir".
6052 */
6053 else if (len > 3
6054 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6055 && full_path[1] == ':'
6056 && vim_ispathsep(full_path[2]))
6057 p = full_path + 2;
6058#endif
6059 else
6060 p = NULL;
6061 return p;
6062}
6063
6064/*
6065 * Shorten filenames for all buffers.
6066 * When "force" is TRUE: Use full path from now on for files currently being
6067 * edited, both for file name and swap file name. Try to shorten the file
6068 * names a bit, if safe to do so.
6069 * When "force" is FALSE: Only try to shorten absolute file names.
6070 * For buffers that have buftype "nofile" or "scratch": never change the file
6071 * name.
6072 */
6073 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006074shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075{
6076 char_u dirname[MAXPATHL];
6077 buf_T *buf;
6078 char_u *p;
6079
6080 mch_dirname(dirname, MAXPATHL);
6081 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6082 {
6083 if (buf->b_fname != NULL
6084#ifdef FEAT_QUICKFIX
6085 && !bt_nofile(buf)
6086#endif
6087 && !path_with_url(buf->b_fname)
6088 && (force
6089 || buf->b_sfname == NULL
6090 || mch_isFullName(buf->b_sfname)))
6091 {
6092 vim_free(buf->b_sfname);
6093 buf->b_sfname = NULL;
6094 p = shorten_fname(buf->b_ffname, dirname);
6095 if (p != NULL)
6096 {
6097 buf->b_sfname = vim_strsave(p);
6098 buf->b_fname = buf->b_sfname;
6099 }
6100 if (p == NULL || buf->b_fname == NULL)
6101 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006103
6104 /* Always make the swap file name a full path, a "nofile" buffer may
6105 * also have a swap file. */
6106 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107 }
6108#ifdef FEAT_WINDOWS
6109 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006110 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111#endif
6112}
6113
6114#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6115 || defined(FEAT_GUI_MSWIN) \
6116 || defined(FEAT_GUI_MAC) \
6117 || defined(PROTO)
6118/*
6119 * Shorten all filenames in "fnames[count]" by current directory.
6120 */
6121 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006122shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123{
6124 int i;
6125 char_u dirname[MAXPATHL];
6126 char_u *p;
6127
6128 if (fnames == NULL || count < 1)
6129 return;
6130 mch_dirname(dirname, sizeof(dirname));
6131 for (i = 0; i < count; ++i)
6132 {
6133 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6134 {
6135 /* shorten_fname() returns pointer in given "fnames[i]". If free
6136 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6137 * "p" first then free fnames[i]. */
6138 p = vim_strsave(p);
6139 vim_free(fnames[i]);
6140 fnames[i] = p;
6141 }
6142 }
6143}
6144#endif
6145
6146/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006147 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 * fo_o_h.ext for MSDOS or when shortname option set.
6149 *
6150 * Assumed that fname is a valid name found in the filesystem we assure that
6151 * the return value is a different name and ends in 'ext'.
6152 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6153 * characters otherwise.
6154 * Space for the returned name is allocated, must be freed later.
6155 * Returns NULL when out of memory.
6156 */
6157 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006158modname(
6159 char_u *fname,
6160 char_u *ext,
6161 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006163 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 fname, ext, prepend_dot);
6165}
6166
6167 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006168buf_modname(
6169 int shortname, /* use 8.3 file name */
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{
6174 char_u *retval;
6175 char_u *s;
6176 char_u *e;
6177 char_u *ptr;
6178 int fnamelen, extlen;
6179
6180 extlen = (int)STRLEN(ext);
6181
6182 /*
6183 * If there is no file name we must get the name of the current directory
6184 * (we need the full path in case :cd is used).
6185 */
6186 if (fname == NULL || *fname == NUL)
6187 {
6188 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6189 if (retval == NULL)
6190 return NULL;
6191 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6192 (fnamelen = (int)STRLEN(retval)) == 0)
6193 {
6194 vim_free(retval);
6195 return NULL;
6196 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006197 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 {
6199 retval[fnamelen++] = PATHSEP;
6200 retval[fnamelen] = NUL;
6201 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 }
6204 else
6205 {
6206 fnamelen = (int)STRLEN(fname);
6207 retval = alloc((unsigned)(fnamelen + extlen + 3));
6208 if (retval == NULL)
6209 return NULL;
6210 STRCPY(retval, fname);
6211#ifdef VMS
6212 vms_remove_version(retval); /* we do not need versions here */
6213#endif
6214 }
6215
6216 /*
6217 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6218 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6219 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6220 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6221 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006222 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006225#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006227#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006229#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 )
6231 if (*ptr == '.') /* replace '.' by '_' */
6232 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006234 {
6235 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239
6240 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6242 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243
6244 s = ptr + STRLEN(ptr);
6245
6246 /*
6247 * For 8.3 file names we may have to reduce the length.
6248 */
6249#ifdef USE_LONG_FNAME
6250 if (!USE_LONG_FNAME || shortname)
6251#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253#endif
6254 {
6255 /*
6256 * If there is no file name, or the file name ends in '/', and the
6257 * extension starts with '.', put a '_' before the dot, because just
6258 * ".ext" is invalid.
6259 */
6260 if (fname == NULL || *fname == NUL
6261 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6262 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 *s++ = '_';
6265 }
6266 /*
6267 * If the extension starts with '.', truncate the base name at 8
6268 * characters
6269 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006272 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 {
6274 s = ptr + 8;
6275 *s = '\0';
6276 }
6277 }
6278 /*
6279 * If the extension doesn't start with '.', and the file name
6280 * doesn't have an extension yet, append a '.'
6281 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 else if ((e = vim_strchr(ptr, '.')) == NULL)
6283 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 /*
6285 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006286 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 */
6288 else if ((int)STRLEN(e) + extlen > 4)
6289 s = e + 4 - extlen;
6290 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006291#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 /*
6293 * If there is no file name, and the extension starts with '.', put a
6294 * '_' before the dot, because just ".ext" may be invalid if it's on a
6295 * FAT partition, and on HPFS it doesn't matter.
6296 */
6297 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6298 *s++ = '_';
6299#endif
6300
6301 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006302 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 * ext can start with '.' and cannot exceed 3 more characters.
6304 */
6305 STRCPY(s, ext);
6306
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 /*
6308 * Prepend the dot.
6309 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006310 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311#ifdef USE_LONG_FNAME
6312 && USE_LONG_FNAME
6313#endif
6314 )
6315 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006316 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319
6320 /*
6321 * Check that, after appending the extension, the file name is really
6322 * different.
6323 */
6324 if (fname != NULL && STRCMP(fname, retval) == 0)
6325 {
6326 /* we search for a character that can be replaced by '_' */
6327 while (--s >= ptr)
6328 {
6329 if (*s != '_')
6330 {
6331 *s = '_';
6332 break;
6333 }
6334 }
6335 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6336 *ptr = 'v';
6337 }
6338 return retval;
6339}
6340
6341/*
6342 * Like fgets(), but if the file line is too long, it is truncated and the
6343 * rest of the line is thrown away. Returns TRUE for end-of-file.
6344 */
6345 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006346vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347{
6348 char *eof;
6349#define FGETS_SIZE 200
6350 char tbuf[FGETS_SIZE];
6351
6352 buf[size - 2] = NUL;
6353#ifdef USE_CR
6354 eof = fgets_cr((char *)buf, size, fp);
6355#else
6356 eof = fgets((char *)buf, size, fp);
6357#endif
6358 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6359 {
6360 buf[size - 1] = NUL; /* Truncate the line */
6361
6362 /* Now throw away the rest of the line: */
6363 do
6364 {
6365 tbuf[FGETS_SIZE - 2] = NUL;
6366#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006367 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006369 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370#endif
6371 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6372 }
6373 return (eof == NULL);
6374}
6375
6376#if defined(USE_CR) || defined(PROTO)
6377/*
6378 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6379 * Returns TRUE for end-of-file.
6380 * Only used for the Mac, because it's much slower than vim_fgets().
6381 */
6382 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006383tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384{
6385 int i = 0;
6386 int c;
6387 int eof = FALSE;
6388
6389 for (;;)
6390 {
6391 c = fgetc(fp);
6392 if (c == EOF)
6393 {
6394 eof = TRUE;
6395 break;
6396 }
6397 if (c == '\r')
6398 {
6399 /* Always store a NL for end-of-line. */
6400 if (i < size - 1)
6401 buf[i++] = '\n';
6402 c = fgetc(fp);
6403 if (c != '\n') /* Macintosh format: single CR. */
6404 ungetc(c, fp);
6405 break;
6406 }
6407 if (i < size - 1)
6408 buf[i++] = c;
6409 if (c == '\n')
6410 break;
6411 }
6412 buf[i] = NUL;
6413 return eof;
6414}
6415#endif
6416
6417/*
6418 * rename() only works if both files are on the same file system, this
6419 * function will (attempts to?) copy the file across if rename fails -- webb
6420 * Return -1 for failure, 0 for success.
6421 */
6422 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006423vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006424{
6425 int fd_in;
6426 int fd_out;
6427 int n;
6428 char *errmsg = NULL;
6429 char *buffer;
6430#ifdef AMIGA
6431 BPTR flock;
6432#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006433 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006434 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006435#ifdef HAVE_ACL
6436 vim_acl_T acl; /* ACL from original file */
6437#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006438 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439
6440 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006441 * When the names are identical, there is nothing to do. When they refer
6442 * to the same file (ignoring case and slash/backslash differences) but
6443 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 */
6445 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006446 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006447 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006448 use_tmp_file = TRUE;
6449 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006450 return 0;
6451 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452
6453 /*
6454 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6455 */
6456 if (mch_stat((char *)from, &st) < 0)
6457 return -1;
6458
Bram Moolenaar3576da72008-12-30 15:15:57 +00006459#ifdef UNIX
6460 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006461 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006462
6463 /* It's possible for the source and destination to be the same file.
6464 * This happens when "from" and "to" differ in case and are on a FAT32
6465 * filesystem. In that case go through a temp file name. */
6466 if (mch_stat((char *)to, &st_to) >= 0
6467 && st.st_dev == st_to.st_dev
6468 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006469 use_tmp_file = TRUE;
6470 }
6471#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006472#ifdef WIN3264
6473 {
6474 BY_HANDLE_FILE_INFORMATION info1, info2;
6475
6476 /* It's possible for the source and destination to be the same file.
6477 * In that case go through a temp file name. This makes rename("foo",
6478 * "./foo") a no-op (in a complicated way). */
6479 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6480 && win32_fileinfo(to, &info2) == FILEINFO_OK
6481 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6482 && info1.nFileIndexHigh == info2.nFileIndexHigh
6483 && info1.nFileIndexLow == info2.nFileIndexLow)
6484 use_tmp_file = TRUE;
6485 }
6486#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006487
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006488 if (use_tmp_file)
6489 {
6490 char tempname[MAXPATHL + 1];
6491
6492 /*
6493 * Find a name that doesn't exist and is in the same directory.
6494 * Rename "from" to "tempname" and then rename "tempname" to "to".
6495 */
6496 if (STRLEN(from) >= MAXPATHL - 5)
6497 return -1;
6498 STRCPY(tempname, from);
6499 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006500 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006501 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6502 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006503 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006504 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006505 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006506 if (mch_rename(tempname, (char *)to) == 0)
6507 return 0;
6508 /* Strange, the second step failed. Try moving the
6509 * file back and return failure. */
6510 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006511 return -1;
6512 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006513 /* If it fails for one temp name it will most likely fail
6514 * for any temp name, give up. */
6515 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006516 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006517 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006518 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006519 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006520
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 /*
6522 * Delete the "to" file, this is required on some systems to make the
6523 * mch_rename() work, on other systems it makes sure that we don't have
6524 * two files when the mch_rename() fails.
6525 */
6526
6527#ifdef AMIGA
6528 /*
6529 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6530 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006531 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 * deleting the "from" file (horror!) we lock it during the remove.
6533 *
6534 * When used for making a backup before writing the file: This should not
6535 * happen with ":w", because startscript() should detect this problem and
6536 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6537 * name. This problem does exist with ":w filename", but then the
6538 * original file will be somewhere else so the backup isn't really
6539 * important. If autoscripting is off the rename may fail.
6540 */
6541 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6542#endif
6543 mch_remove(to);
6544#ifdef AMIGA
6545 if (flock)
6546 UnLock(flock);
6547#endif
6548
6549 /*
6550 * First try a normal rename, return if it works.
6551 */
6552 if (mch_rename((char *)from, (char *)to) == 0)
6553 return 0;
6554
6555 /*
6556 * Rename() failed, try copying the file.
6557 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006558 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006559#ifdef HAVE_ACL
6560 /* For systems that support ACL: get the ACL from the original file. */
6561 acl = mch_get_acl(from);
6562#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6564 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006565 {
6566#ifdef HAVE_ACL
6567 mch_free_acl(acl);
6568#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006570 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006571
6572 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006573 fd_out = mch_open((char *)to,
6574 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 if (fd_out == -1)
6576 {
6577 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006578#ifdef HAVE_ACL
6579 mch_free_acl(acl);
6580#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 return -1;
6582 }
6583
6584 buffer = (char *)alloc(BUFSIZE);
6585 if (buffer == NULL)
6586 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006588 close(fd_in);
6589#ifdef HAVE_ACL
6590 mch_free_acl(acl);
6591#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 return -1;
6593 }
6594
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006595 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6596 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597 {
6598 errmsg = _("E208: Error writing to \"%s\"");
6599 break;
6600 }
6601
6602 vim_free(buffer);
6603 close(fd_in);
6604 if (close(fd_out) < 0)
6605 errmsg = _("E209: Error closing \"%s\"");
6606 if (n < 0)
6607 {
6608 errmsg = _("E210: Error reading \"%s\"");
6609 to = from;
6610 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006611#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006612 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006613#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006614#ifdef HAVE_ACL
6615 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006616 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006617#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006618#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006619 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006620#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 if (errmsg != NULL)
6622 {
6623 EMSG2(errmsg, to);
6624 return -1;
6625 }
6626 mch_remove(from);
6627 return 0;
6628}
6629
6630static int already_warned = FALSE;
6631
6632/*
6633 * Check if any not hidden buffer has been changed.
6634 * Postpone the check if there are characters in the stuff buffer, a global
6635 * command is being executed, a mapping is being executed or an autocommand is
6636 * busy.
6637 * Returns TRUE if some message was written (screen should be redrawn and
6638 * cursor positioned).
6639 */
6640 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006641check_timestamps(
6642 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643{
6644 buf_T *buf;
6645 int didit = 0;
6646 int n;
6647
6648 /* Don't check timestamps while system() or another low-level function may
6649 * cause us to lose and gain focus. */
6650 if (no_check_timestamps > 0)
6651 return FALSE;
6652
6653 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6654 * event and we would keep on checking if the file is steadily growing.
6655 * Do check again after typing something. */
6656 if (focus && did_check_timestamps)
6657 {
6658 need_check_timestamps = TRUE;
6659 return FALSE;
6660 }
6661
6662 if (!stuff_empty() || global_busy || !typebuf_typed()
6663#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006664 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665#endif
6666 )
6667 need_check_timestamps = TRUE; /* check later */
6668 else
6669 {
6670 ++no_wait_return;
6671 did_check_timestamps = TRUE;
6672 already_warned = FALSE;
6673 for (buf = firstbuf; buf != NULL; )
6674 {
6675 /* Only check buffers in a window. */
6676 if (buf->b_nwindows > 0)
6677 {
6678 n = buf_check_timestamp(buf, focus);
6679 if (didit < n)
6680 didit = n;
6681 if (n > 0 && !buf_valid(buf))
6682 {
6683 /* Autocommands have removed the buffer, start at the
6684 * first one again. */
6685 buf = firstbuf;
6686 continue;
6687 }
6688 }
6689 buf = buf->b_next;
6690 }
6691 --no_wait_return;
6692 need_check_timestamps = FALSE;
6693 if (need_wait_return && didit == 2)
6694 {
6695 /* make sure msg isn't overwritten */
6696 msg_puts((char_u *)"\n");
6697 out_flush();
6698 }
6699 }
6700 return didit;
6701}
6702
6703/*
6704 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6705 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6706 * empty.
6707 */
6708 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006709move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710{
6711 buf_T *tbuf = curbuf;
6712 int retval = OK;
6713 linenr_T lnum;
6714 char_u *p;
6715
6716 /* Copy the lines in "frombuf" to "tobuf". */
6717 curbuf = tobuf;
6718 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6719 {
6720 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6721 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6722 {
6723 vim_free(p);
6724 retval = FAIL;
6725 break;
6726 }
6727 vim_free(p);
6728 }
6729
6730 /* Delete all the lines in "frombuf". */
6731 if (retval != FAIL)
6732 {
6733 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006734 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6735 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 {
6737 /* Oops! We could try putting back the saved lines, but that
6738 * might fail again... */
6739 retval = FAIL;
6740 break;
6741 }
6742 }
6743
6744 curbuf = tbuf;
6745 return retval;
6746}
6747
6748/*
6749 * Check if buffer "buf" has been changed.
6750 * Also check if the file for a new buffer unexpectedly appeared.
6751 * return 1 if a changed buffer was found.
6752 * return 2 if a message has been displayed.
6753 * return 0 otherwise.
6754 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006756buf_check_timestamp(
6757 buf_T *buf,
6758 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006760 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 int stat_res;
6762 int retval = 0;
6763 char_u *path;
6764 char_u *tbuf;
6765 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006766 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 int helpmesg = FALSE;
6768 int reload = FALSE;
6769#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6770 int can_reload = FALSE;
6771#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006772 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 int orig_mode = buf->b_orig_mode;
6774#ifdef FEAT_GUI
6775 int save_mouse_correct = need_mouse_correct;
6776#endif
6777#ifdef FEAT_AUTOCMD
6778 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006779 int n;
6780 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006782 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783
6784 /* If there is no file name, the buffer is not loaded, 'buftype' is
6785 * set, we are in the middle of a save or being called recursively: ignore
6786 * this buffer. */
6787 if (buf->b_ffname == NULL
6788 || buf->b_ml.ml_mfp == NULL
6789#if defined(FEAT_QUICKFIX)
6790 || *buf->b_p_bt != NUL
6791#endif
6792 || buf->b_saving
6793#ifdef FEAT_AUTOCMD
6794 || busy
6795#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006796#ifdef FEAT_NETBEANS_INTG
6797 || isNetbeansBuffer(buf)
6798#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 )
6800 return 0;
6801
6802 if ( !(buf->b_flags & BF_NOTEDITED)
6803 && buf->b_mtime != 0
6804 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6805 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006806 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807#ifdef HAVE_ST_MODE
6808 || (int)st.st_mode != buf->b_orig_mode
6809#else
6810 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6811#endif
6812 ))
6813 {
6814 retval = 1;
6815
Bram Moolenaar316059c2006-01-14 21:18:42 +00006816 /* set b_mtime to stop further warnings (e.g., when executing
6817 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 if (stat_res < 0)
6819 {
6820 buf->b_mtime = 0;
6821 buf->b_orig_size = 0;
6822 buf->b_orig_mode = 0;
6823 }
6824 else
6825 buf_store_time(buf, &st, buf->b_ffname);
6826
6827 /* Don't do anything for a directory. Might contain the file
6828 * explorer. */
6829 if (mch_isdir(buf->b_fname))
6830 ;
6831
6832 /*
6833 * If 'autoread' is set, the buffer has no changes and the file still
6834 * exists, reload the buffer. Use the buffer-local option value if it
6835 * was set, the global option value otherwise.
6836 */
6837 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6838 && !bufIsChanged(buf) && stat_res >= 0)
6839 reload = TRUE;
6840 else
6841 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006842 if (stat_res < 0)
6843 reason = "deleted";
6844 else if (bufIsChanged(buf))
6845 reason = "conflict";
6846 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6847 reason = "changed";
6848 else if (orig_mode != buf->b_orig_mode)
6849 reason = "mode";
6850 else
6851 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006853#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 /*
6855 * Only give the warning if there are no FileChangedShell
6856 * autocommands.
6857 * Avoid being called recursively by setting "busy".
6858 */
6859 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006860# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006861 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6862 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006863# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006864 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6866 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006867 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868 busy = FALSE;
6869 if (n)
6870 {
6871 if (!buf_valid(buf))
6872 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006873# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006874 s = get_vim_var_str(VV_FCS_CHOICE);
6875 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6876 reload = TRUE;
6877 else if (STRCMP(s, "ask") == 0)
6878 n = FALSE;
6879 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006880# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006881 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006883 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884#endif
6885 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006886 if (*reason == 'd')
6887 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 else
6889 {
6890 helpmesg = TRUE;
6891#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6892 can_reload = TRUE;
6893#endif
6894 /*
6895 * Check if the file contents really changed to avoid
6896 * giving a warning when only the timestamp was set (e.g.,
6897 * checked out of CVS). Always warn when the buffer was
6898 * changed.
6899 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006900 if (reason[2] == 'n')
6901 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006903 mesg2 = _("See \":help W12\" for more info.");
6904 }
6905 else if (reason[1] == 'h')
6906 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006908 mesg2 = _("See \":help W11\" for more info.");
6909 }
6910 else if (*reason == 'm')
6911 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006913 mesg2 = _("See \":help W16\" for more info.");
6914 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006915 else
6916 /* Only timestamp changed, store it to avoid a warning
6917 * in check_mtime() later. */
6918 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 }
6920 }
6921 }
6922
6923 }
6924 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6925 && vim_fexists(buf->b_ffname))
6926 {
6927 retval = 1;
6928 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6929 buf->b_flags |= BF_NEW_W;
6930#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6931 can_reload = TRUE;
6932#endif
6933 }
6934
6935 if (mesg != NULL)
6936 {
6937 path = home_replace_save(buf, buf->b_fname);
6938 if (path != NULL)
6939 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006940 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 mesg2 = "";
6942 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6943 + STRLEN(mesg2) + 2));
6944 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006945#ifdef FEAT_EVAL
6946 /* Set warningmsg here, before the unimportant and output-specific
6947 * mesg2 has been appended. */
6948 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6949#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6951 if (can_reload)
6952 {
6953 if (*mesg2 != NUL)
6954 {
6955 STRCAT(tbuf, "\n");
6956 STRCAT(tbuf, mesg2);
6957 }
6958 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006959 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960 reload = TRUE;
6961 }
6962 else
6963#endif
6964 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6965 {
6966 if (*mesg2 != NUL)
6967 {
6968 STRCAT(tbuf, "; ");
6969 STRCAT(tbuf, mesg2);
6970 }
6971 EMSG(tbuf);
6972 retval = 2;
6973 }
6974 else
6975 {
Bram Moolenaared203462004-06-16 11:19:22 +00006976# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006978# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 {
6980 msg_start();
6981 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6982 if (*mesg2 != NUL)
6983 msg_puts_attr((char_u *)mesg2,
6984 hl_attr(HLF_W) + MSG_HIST);
6985 msg_clr_eos();
6986 (void)msg_end();
6987 if (emsg_silent == 0)
6988 {
6989 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00006990# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00006992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 /* give the user some time to think about it */
6994 ui_delay(1000L, TRUE);
6995
6996 /* don't redraw and erase the message */
6997 redraw_cmdline = FALSE;
6998 }
6999 }
7000 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 }
7002
7003 vim_free(path);
7004 vim_free(tbuf);
7005 }
7006 }
7007
7008 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007009 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007010 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007011 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007012#ifdef FEAT_PERSISTENT_UNDO
7013 if (buf->b_p_udf && buf->b_ffname != NULL)
7014 {
7015 char_u hash[UNDO_HASH_SIZE];
7016 buf_T *save_curbuf = curbuf;
7017
7018 /* Any existing undo file is unusable, write it now. */
7019 curbuf = buf;
7020 u_compute_hash(hash);
7021 u_write_undo(NULL, FALSE, buf, hash);
7022 curbuf = save_curbuf;
7023 }
7024#endif
7025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026
Bram Moolenaar56718732006-03-15 22:53:57 +00007027#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007028 /* Trigger FileChangedShell when the file was changed in any way. */
7029 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007030 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7031 buf->b_fname, buf->b_fname, FALSE, buf);
7032#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033#ifdef FEAT_GUI
7034 /* restore this in case an autocommand has set it; it would break
7035 * 'mousefocus' */
7036 need_mouse_correct = save_mouse_correct;
7037#endif
7038
7039 return retval;
7040}
7041
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007042/*
7043 * Reload a buffer that is already loaded.
7044 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007045 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7046 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007047 */
7048 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007049buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007050{
7051 exarg_T ea;
7052 pos_T old_cursor;
7053 linenr_T old_topline;
7054 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007055 buf_T *savebuf;
7056 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007057 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007058 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007059
7060 /* set curwin/curbuf for "buf" and save some things */
7061 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007062
7063 /* We only want to read the text from the file, not reset the syntax
7064 * highlighting, clear marks, diff status, etc. Force the fileformat
7065 * and encoding to be the same. */
7066 if (prep_exarg(&ea, buf) == OK)
7067 {
7068 old_cursor = curwin->w_cursor;
7069 old_topline = curwin->w_topline;
7070
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007071 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007072 {
7073 /* Save all the text, so that the reload can be undone.
7074 * Sync first so that this is a separate undo-able action. */
7075 u_sync(FALSE);
7076 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7077 flags |= READ_KEEP_UNDO;
7078 }
7079
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007080 /*
7081 * To behave like when a new file is edited (matters for
7082 * BufReadPost autocommands) we first need to delete the current
7083 * buffer contents. But if reading the file fails we should keep
7084 * the old contents. Can't use memory only, the file might be
7085 * too big. Use a hidden buffer to move the buffer contents to.
7086 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007087 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007088 savebuf = NULL;
7089 else
7090 {
7091 /* Allocate a buffer without putting it in the buffer list. */
7092 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007093 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007094 {
7095 /* Open the memline. */
7096 curbuf = savebuf;
7097 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007098 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007099 curbuf = buf;
7100 curwin->w_buffer = buf;
7101 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007102 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007103 || move_lines(buf, savebuf) == FAIL)
7104 {
7105 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7106 buf->b_fname);
7107 saved = FAIL;
7108 }
7109 }
7110
7111 if (saved == OK)
7112 {
7113 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7114#ifdef FEAT_AUTOCMD
7115 keep_filetype = TRUE; /* don't detect 'filetype' */
7116#endif
7117 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7118 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007119 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007120 {
7121#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7122 if (!aborting())
7123#endif
7124 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007125 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007126 {
7127 /* Put the text back from the save buffer. First
7128 * delete any lines that readfile() added. */
7129 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007130 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007131 break;
7132 (void)move_lines(savebuf, buf);
7133 }
7134 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007135 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007136 {
7137 /* Mark the buffer as unmodified and free undo info. */
7138 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007139 if ((flags & READ_KEEP_UNDO) == 0)
7140 {
7141 u_blockfree(buf);
7142 u_clearall(buf);
7143 }
7144 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007145 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007146 /* Mark all undo states as changed. */
7147 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007148 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007149 }
7150 }
7151 vim_free(ea.cmd);
7152
Bram Moolenaar8424a622006-04-19 21:23:36 +00007153 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 wipe_buffer(savebuf, FALSE);
7155
7156#ifdef FEAT_DIFF
7157 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007158 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007159#endif
7160
7161 /* Restore the topline and cursor position and check it (lines may
7162 * have been removed). */
7163 if (old_topline > curbuf->b_ml.ml_line_count)
7164 curwin->w_topline = curbuf->b_ml.ml_line_count;
7165 else
7166 curwin->w_topline = old_topline;
7167 curwin->w_cursor = old_cursor;
7168 check_cursor();
7169 update_topline();
7170#ifdef FEAT_AUTOCMD
7171 keep_filetype = FALSE;
7172#endif
7173#ifdef FEAT_FOLDING
7174 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007175 win_T *wp;
7176 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007177
7178 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007179 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007180 if (wp->w_buffer == curwin->w_buffer
7181 && !foldmethodIsManual(wp))
7182 foldUpdateAll(wp);
7183 }
7184#endif
7185 /* If the mode didn't change and 'readonly' was set, keep the old
7186 * value; the user probably used the ":view" command. But don't
7187 * reset it, might have had a read error. */
7188 if (orig_mode == curbuf->b_orig_mode)
7189 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007190
7191 /* Modelines must override settings done by autocommands. */
7192 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193 }
7194
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195 /* restore curwin/curbuf and a few other things */
7196 aucmd_restbuf(&aco);
7197 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198}
7199
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007201buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202{
7203 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007204 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205#ifdef HAVE_ST_MODE
7206 buf->b_orig_mode = (int)st->st_mode;
7207#else
7208 buf->b_orig_mode = mch_getperm(fname);
7209#endif
7210}
7211
7212/*
7213 * Adjust the line with missing eol, used for the next write.
7214 * Used for do_filter(), when the input lines for the filter are deleted.
7215 */
7216 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007217write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007219 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7220 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221}
7222
Bram Moolenaarda440d22016-01-16 21:27:23 +01007223#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7224/*
7225 * Delete "name" and everything in it, recursively.
7226 * return 0 for succes, -1 if some file was not deleted.
7227 */
7228 int
7229delete_recursive(char_u *name)
7230{
7231 int result = 0;
7232 char_u **files;
7233 int file_count;
7234 int i;
7235 char_u *exp;
7236
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007237 /* A symbolic link to a directory itself is deleted, not the directory it
7238 * points to. */
7239 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007240# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007241 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007242# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007243 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007244# endif
7245 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007246 {
7247 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7248 exp = vim_strsave(NameBuff);
7249 if (exp == NULL)
7250 return -1;
7251 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007252 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007253 {
7254 for (i = 0; i < file_count; ++i)
7255 if (delete_recursive(files[i]) != 0)
7256 result = -1;
7257 FreeWild(file_count, files);
7258 }
7259 else
7260 result = -1;
7261 vim_free(exp);
7262 (void)mch_rmdir(name);
7263 }
7264 else
7265 result = mch_remove(name) == 0 ? 0 : -1;
7266
7267 return result;
7268}
7269#endif
7270
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271#if defined(TEMPDIRNAMES) || defined(PROTO)
7272static long temp_count = 0; /* Temp filename counter. */
7273
7274/*
7275 * Delete the temp directory and all files it contains.
7276 */
7277 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007278vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 if (vim_tempdir != NULL)
7281 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007282 /* remove the trailing path separator */
7283 gettail(vim_tempdir)[-1] = NUL;
7284 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 vim_free(vim_tempdir);
7286 vim_tempdir = NULL;
7287 }
7288}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289
7290/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007291 * Directory "tempdir" was created. Expand this name to a full path and put
7292 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7293 * "tempdir" must be no longer than MAXPATHL.
7294 */
7295 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007296vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007297{
7298 char_u *buf;
7299
7300 buf = alloc((unsigned)MAXPATHL + 2);
7301 if (buf != NULL)
7302 {
7303 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7304 STRCPY(buf, tempdir);
7305# ifdef __EMX__
7306 if (vim_strchr(buf, '/') != NULL)
7307 STRCAT(buf, "/");
7308 else
7309# endif
7310 add_pathsep(buf);
7311 vim_tempdir = vim_strsave(buf);
7312 vim_free(buf);
7313 }
7314}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007315#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007316
7317/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318 * vim_tempname(): Return a unique name that can be used for a temp file.
7319 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007320 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7321 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 *
7323 * The returned pointer is to allocated memory.
7324 * The returned pointer is NULL if no valid name was found.
7325 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007327vim_tempname(
7328 int extra_char UNUSED, /* char to use in the name instead of '?' */
7329 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330{
7331#ifdef USE_TMPNAM
7332 char_u itmp[L_tmpnam]; /* use tmpnam() */
7333#else
7334 char_u itmp[TEMPNAMELEN];
7335#endif
7336
7337#ifdef TEMPDIRNAMES
7338 static char *(tempdirs[]) = {TEMPDIRNAMES};
7339 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007341 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342# endif
7343
7344 /*
7345 * This will create a directory for private use by this instance of Vim.
7346 * This is done once, and the same directory is used for all temp files.
7347 * This method avoids security problems because of symlink attacks et al.
7348 * It's also a bit faster, because we only need to check for an existing
7349 * file when creating the directory and not for each temp file.
7350 */
7351 if (vim_tempdir == NULL)
7352 {
7353 /*
7354 * Try the entries in TEMPDIRNAMES to create the temp directory.
7355 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007356 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007358# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007359 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007360 long nr;
7361 long off;
7362# endif
7363
Bram Moolenaare1a61992015-12-03 21:02:27 +01007364 /* Expand $TMP, leave room for "/v1100000/999999999".
7365 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007367 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007368 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007369 /* directory exists */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370# ifdef __EMX__
7371 /* If $TMP contains a forward slash (perhaps using bash or
7372 * tcsh), don't add a backslash, use a forward slash!
7373 * Adding 2 backslashes didn't work. */
7374 if (vim_strchr(itmp, '/') != NULL)
7375 STRCAT(itmp, "/");
7376 else
7377# endif
7378 add_pathsep(itmp);
7379
Bram Moolenaareaf03392009-11-17 11:08:52 +00007380# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007381 {
7382# if defined(UNIX) || defined(VMS)
7383 /* Make sure the umask doesn't remove the executable bit.
7384 * "repl" has been reported to use "177". */
7385 mode_t umask_save = umask(077);
7386# endif
7387 /* Leave room for filename */
7388 STRCAT(itmp, "vXXXXXX");
7389 if (mkdtemp((char *)itmp) != NULL)
7390 vim_settempdir(itmp);
7391# if defined(UNIX) || defined(VMS)
7392 (void)umask(umask_save);
7393# endif
7394 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007395# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007396 /* Get an arbitrary number of up to 6 digits. When it's
7397 * unlikely that it already exists it will be faster,
7398 * otherwise it doesn't matter. The use of mkdir() avoids any
7399 * security problems because of the predictable number. */
7400 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007401 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402
7403 /* Try up to 10000 different values until we find a name that
7404 * doesn't exist. */
7405 for (off = 0; off < 10000L; ++off)
7406 {
7407 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007408# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411
Bram Moolenaareaf03392009-11-17 11:08:52 +00007412 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7413# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414 /* If mkdir() does not set errno to EEXIST, check for
7415 * existing file here. There is a race condition then,
7416 * although it's fail-safe. */
7417 if (mch_stat((char *)itmp, &st) >= 0)
7418 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007419# endif
7420# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421 /* Make sure the umask doesn't remove the executable bit.
7422 * "repl" has been reported to use "177". */
7423 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007424# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007426# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 if (r == 0)
7430 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007431 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 break;
7433 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007434# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 /* If the mkdir() didn't fail because the file/dir exists,
7436 * we probably can't create any dir here, try another
7437 * place. */
7438 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007439# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 break;
7441 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007442# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 if (vim_tempdir != NULL)
7444 break;
7445 }
7446 }
7447 }
7448
7449 if (vim_tempdir != NULL)
7450 {
7451 /* There is no need to check if the file exists, because we own the
7452 * directory and nobody else creates a file in it. */
7453 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7454 return vim_strsave(itmp);
7455 }
7456
7457 return NULL;
7458
7459#else /* TEMPDIRNAMES */
7460
7461# ifdef WIN3264
7462 char szTempFile[_MAX_PATH + 1];
7463 char buf4[4];
7464 char_u *retval;
7465 char_u *p;
7466
7467 STRCPY(itmp, "");
7468 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007469 {
7470 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7471 szTempFile[1] = NUL;
7472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007473 strcpy(buf4, "VIM");
7474 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007475 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007477 if (!keep)
7478 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007479 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480
7481 /* Backslashes in a temp file name cause problems when filtering with
7482 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7483 * didn't set 'shellslash'. */
7484 retval = vim_strsave(itmp);
7485 if (*p_shcf == '-' || p_ssl)
7486 for (p = retval; *p; ++p)
7487 if (*p == '\\')
7488 *p = '/';
7489 return retval;
7490
7491# else /* WIN3264 */
7492
7493# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007494 char_u *p;
7495
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007497 p = tmpnam((char *)itmp);
7498 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 return NULL;
7500# else
7501 char_u *p;
7502
7503# ifdef VMS_TEMPNAM
7504 /* mktemp() is not working on VMS. It seems to be
7505 * a do-nothing function. Therefore we use tempnam().
7506 */
7507 sprintf((char *)itmp, "VIM%c", extra_char);
7508 p = (char_u *)tempnam("tmp:", (char *)itmp);
7509 if (p != NULL)
7510 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007511 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512 * and VIM will then be unable to find the file later */
7513 STRCPY(itmp, p);
7514 STRCAT(itmp, ".txt");
7515 free(p);
7516 }
7517 else
7518 return NULL;
7519# else
7520 STRCPY(itmp, TEMPNAME);
7521 if ((p = vim_strchr(itmp, '?')) != NULL)
7522 *p = extra_char;
7523 if (mktemp((char *)itmp) == NULL)
7524 return NULL;
7525# endif
7526# endif
7527
7528 return vim_strsave(itmp);
7529# endif /* WIN3264 */
7530#endif /* TEMPDIRNAMES */
7531}
7532
7533#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7534/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007535 * Convert all backslashes in fname to forward slashes in-place, unless when
7536 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537 */
7538 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007539forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540{
7541 char_u *p;
7542
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007543 if (path_with_url(fname))
7544 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545 for (p = fname; *p != NUL; ++p)
7546# ifdef FEAT_MBYTE
7547 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007548 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 ++p;
7550 else
7551# endif
7552 if (*p == '\\')
7553 *p = '/';
7554}
7555#endif
7556
7557
7558/*
7559 * Code for automatic commands.
7560 *
7561 * Only included when "FEAT_AUTOCMD" has been defined.
7562 */
7563
7564#if defined(FEAT_AUTOCMD) || defined(PROTO)
7565
7566/*
7567 * The autocommands are stored in a list for each event.
7568 * Autocommands for the same pattern, that are consecutive, are joined
7569 * together, to avoid having to match the pattern too often.
7570 * The result is an array of Autopat lists, which point to AutoCmd lists:
7571 *
7572 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7573 * Autopat.cmds Autopat.cmds
7574 * | |
7575 * V V
7576 * AutoCmd.next AutoCmd.next
7577 * | |
7578 * V V
7579 * AutoCmd.next NULL
7580 * |
7581 * V
7582 * NULL
7583 *
7584 * first_autopat[1] --> Autopat.next --> NULL
7585 * Autopat.cmds
7586 * |
7587 * V
7588 * AutoCmd.next
7589 * |
7590 * V
7591 * NULL
7592 * etc.
7593 *
7594 * The order of AutoCmds is important, this is the order in which they were
7595 * defined and will have to be executed.
7596 */
7597typedef struct AutoCmd
7598{
7599 char_u *cmd; /* The command to be executed (NULL
7600 when command has been removed) */
7601 char nested; /* If autocommands nest here */
7602 char last; /* last command in list */
7603#ifdef FEAT_EVAL
7604 scid_T scriptID; /* script ID where defined */
7605#endif
7606 struct AutoCmd *next; /* Next AutoCmd in list */
7607} AutoCmd;
7608
7609typedef struct AutoPat
7610{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611 char_u *pat; /* pattern as typed (NULL when pattern
7612 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007613 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614 AutoCmd *cmds; /* list of commands to do */
7615 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007616 int group; /* group ID */
7617 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007618 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007619 char allow_dirs; /* Pattern may match whole path */
7620 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621} AutoPat;
7622
7623static struct event_name
7624{
7625 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007626 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627} event_names[] =
7628{
7629 {"BufAdd", EVENT_BUFADD},
7630 {"BufCreate", EVENT_BUFADD},
7631 {"BufDelete", EVENT_BUFDELETE},
7632 {"BufEnter", EVENT_BUFENTER},
7633 {"BufFilePost", EVENT_BUFFILEPOST},
7634 {"BufFilePre", EVENT_BUFFILEPRE},
7635 {"BufHidden", EVENT_BUFHIDDEN},
7636 {"BufLeave", EVENT_BUFLEAVE},
7637 {"BufNew", EVENT_BUFNEW},
7638 {"BufNewFile", EVENT_BUFNEWFILE},
7639 {"BufRead", EVENT_BUFREADPOST},
7640 {"BufReadCmd", EVENT_BUFREADCMD},
7641 {"BufReadPost", EVENT_BUFREADPOST},
7642 {"BufReadPre", EVENT_BUFREADPRE},
7643 {"BufUnload", EVENT_BUFUNLOAD},
7644 {"BufWinEnter", EVENT_BUFWINENTER},
7645 {"BufWinLeave", EVENT_BUFWINLEAVE},
7646 {"BufWipeout", EVENT_BUFWIPEOUT},
7647 {"BufWrite", EVENT_BUFWRITEPRE},
7648 {"BufWritePost", EVENT_BUFWRITEPOST},
7649 {"BufWritePre", EVENT_BUFWRITEPRE},
7650 {"BufWriteCmd", EVENT_BUFWRITECMD},
7651 {"CmdwinEnter", EVENT_CMDWINENTER},
7652 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007653 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007654 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007655 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007656 {"CursorHold", EVENT_CURSORHOLD},
7657 {"CursorHoldI", EVENT_CURSORHOLDI},
7658 {"CursorMoved", EVENT_CURSORMOVED},
7659 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7661 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7663 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7664 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7665 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007666 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667 {"FileChangedRO", EVENT_FILECHANGEDRO},
7668 {"FileReadPost", EVENT_FILEREADPOST},
7669 {"FileReadPre", EVENT_FILEREADPRE},
7670 {"FileReadCmd", EVENT_FILEREADCMD},
7671 {"FileType", EVENT_FILETYPE},
7672 {"FileWritePost", EVENT_FILEWRITEPOST},
7673 {"FileWritePre", EVENT_FILEWRITEPRE},
7674 {"FileWriteCmd", EVENT_FILEWRITECMD},
7675 {"FilterReadPost", EVENT_FILTERREADPOST},
7676 {"FilterReadPre", EVENT_FILTERREADPRE},
7677 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7678 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7679 {"FocusGained", EVENT_FOCUSGAINED},
7680 {"FocusLost", EVENT_FOCUSLOST},
7681 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7682 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007683 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007684 {"InsertChange", EVENT_INSERTCHANGE},
7685 {"InsertEnter", EVENT_INSERTENTER},
7686 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007687 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007688 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007689 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007690 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7691 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007692 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007693 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007694 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007695 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7696 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007697 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007698 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007699 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 {"StdinReadPost", EVENT_STDINREADPOST},
7701 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007702 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007703 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007704 {"TabEnter", EVENT_TABENTER},
7705 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 {"TermChanged", EVENT_TERMCHANGED},
7707 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007708 {"TextChanged", EVENT_TEXTCHANGED},
7709 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710 {"User", EVENT_USER},
7711 {"VimEnter", EVENT_VIMENTER},
7712 {"VimLeave", EVENT_VIMLEAVE},
7713 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7714 {"WinEnter", EVENT_WINENTER},
7715 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007716 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007717 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007718};
7719
7720static AutoPat *first_autopat[NUM_EVENTS] =
7721{
7722 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
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,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007726 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007727 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728};
7729
7730/*
7731 * struct used to keep status while executing autocommands for an event.
7732 */
7733typedef struct AutoPatCmd
7734{
7735 AutoPat *curpat; /* next AutoPat to examine */
7736 AutoCmd *nextcmd; /* next AutoCmd to execute */
7737 int group; /* group being used */
7738 char_u *fname; /* fname to match with */
7739 char_u *sfname; /* sfname to match with */
7740 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007741 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007742 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7743 buf is deleted */
7744 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007745} AutoPatCmd;
7746
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007747static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007748
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749/*
7750 * augroups stores a list of autocmd group names.
7751 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007752static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7754
7755/*
7756 * The ID of the current group. Group 0 is the default one.
7757 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758static int current_augroup = AUGROUP_DEFAULT;
7759
7760static int au_need_clean = FALSE; /* need to delete marked patterns */
7761
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007762static void show_autocmd(AutoPat *ap, event_T event);
7763static void au_remove_pat(AutoPat *ap);
7764static void au_remove_cmds(AutoPat *ap);
7765static void au_cleanup(void);
7766static int au_new_group(char_u *name);
7767static void au_del_group(char_u *name);
7768static event_T event_name2nr(char_u *start, char_u **end);
7769static char_u *event_nr2name(event_T event);
7770static char_u *find_end_event(char_u *arg, int have_group);
7771static int event_ignored(event_T event);
7772static int au_get_grouparg(char_u **argp);
7773static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7774static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7775static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007776#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007777static 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 +01007778#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007780
Bram Moolenaar754b5602006-02-09 23:53:20 +00007781static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007782static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007783static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784
7785/*
7786 * Show the autocommands for one AutoPat.
7787 */
7788 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007789show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790{
7791 AutoCmd *ac;
7792
7793 /* Check for "got_int" (here and at various places below), which is set
7794 * when "q" has been hit for the "--more--" prompt */
7795 if (got_int)
7796 return;
7797 if (ap->pat == NULL) /* pattern has been removed */
7798 return;
7799
7800 msg_putchar('\n');
7801 if (got_int)
7802 return;
7803 if (event != last_event || ap->group != last_group)
7804 {
7805 if (ap->group != AUGROUP_DEFAULT)
7806 {
7807 if (AUGROUP_NAME(ap->group) == NULL)
7808 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7809 else
7810 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7811 msg_puts((char_u *)" ");
7812 }
7813 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7814 last_event = event;
7815 last_group = ap->group;
7816 msg_putchar('\n');
7817 if (got_int)
7818 return;
7819 }
7820 msg_col = 4;
7821 msg_outtrans(ap->pat);
7822
7823 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7824 {
7825 if (ac->cmd != NULL) /* skip removed commands */
7826 {
7827 if (msg_col >= 14)
7828 msg_putchar('\n');
7829 msg_col = 14;
7830 if (got_int)
7831 return;
7832 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007833#ifdef FEAT_EVAL
7834 if (p_verbose > 0)
7835 last_set_msg(ac->scriptID);
7836#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007837 if (got_int)
7838 return;
7839 if (ac->next != NULL)
7840 {
7841 msg_putchar('\n');
7842 if (got_int)
7843 return;
7844 }
7845 }
7846 }
7847}
7848
7849/*
7850 * Mark an autocommand pattern for deletion.
7851 */
7852 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007853au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854{
7855 vim_free(ap->pat);
7856 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007857 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007858 au_need_clean = TRUE;
7859}
7860
7861/*
7862 * Mark all commands for a pattern for deletion.
7863 */
7864 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007865au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866{
7867 AutoCmd *ac;
7868
7869 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7870 {
7871 vim_free(ac->cmd);
7872 ac->cmd = NULL;
7873 }
7874 au_need_clean = TRUE;
7875}
7876
7877/*
7878 * Cleanup autocommands and patterns that have been deleted.
7879 * This is only done when not executing autocommands.
7880 */
7881 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007882au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883{
7884 AutoPat *ap, **prev_ap;
7885 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007886 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887
7888 if (autocmd_busy || !au_need_clean)
7889 return;
7890
7891 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007892 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7893 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 {
7895 /* loop over all autocommand patterns */
7896 prev_ap = &(first_autopat[(int)event]);
7897 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7898 {
7899 /* loop over all commands for this pattern */
7900 prev_ac = &(ap->cmds);
7901 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7902 {
7903 /* remove the command if the pattern is to be deleted or when
7904 * the command has been marked for deletion */
7905 if (ap->pat == NULL || ac->cmd == NULL)
7906 {
7907 *prev_ac = ac->next;
7908 vim_free(ac->cmd);
7909 vim_free(ac);
7910 }
7911 else
7912 prev_ac = &(ac->next);
7913 }
7914
7915 /* remove the pattern if it has been marked for deletion */
7916 if (ap->pat == NULL)
7917 {
7918 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007919 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920 vim_free(ap);
7921 }
7922 else
7923 prev_ap = &(ap->next);
7924 }
7925 }
7926
7927 au_need_clean = FALSE;
7928}
7929
7930/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007931 * Called when buffer is freed, to remove/invalidate related buffer-local
7932 * autocmds.
7933 */
7934 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007935aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007936{
7937 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007938 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007939 AutoPatCmd *apc;
7940
7941 /* invalidate currently executing autocommands */
7942 for (apc = active_apc_list; apc; apc = apc->next)
7943 if (buf->b_fnum == apc->arg_bufnr)
7944 apc->arg_bufnr = 0;
7945
7946 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007947 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7948 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007949 /* loop over all autocommand patterns */
7950 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7951 if (ap->buflocal_nr == buf->b_fnum)
7952 {
7953 au_remove_pat(ap);
7954 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007955 {
7956 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007957 smsg((char_u *)
7958 _("auto-removing autocommand: %s <buffer=%d>"),
7959 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007960 verbose_leave();
7961 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007962 }
7963 au_cleanup();
7964}
7965
7966/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967 * Add an autocmd group name.
7968 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7969 */
7970 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007971au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007972{
7973 int i;
7974
7975 i = au_find_group(name);
7976 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7977 {
7978 /* First try using a free entry. */
7979 for (i = 0; i < augroups.ga_len; ++i)
7980 if (AUGROUP_NAME(i) == NULL)
7981 break;
7982 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7983 return AUGROUP_ERROR;
7984
7985 AUGROUP_NAME(i) = vim_strsave(name);
7986 if (AUGROUP_NAME(i) == NULL)
7987 return AUGROUP_ERROR;
7988 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007989 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007990 }
7991
7992 return i;
7993}
7994
7995 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007996au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997{
7998 int i;
7999
8000 i = au_find_group(name);
8001 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8002 EMSG2(_("E367: No such group: \"%s\""), name);
8003 else
8004 {
8005 vim_free(AUGROUP_NAME(i));
8006 AUGROUP_NAME(i) = NULL;
8007 }
8008}
8009
8010/*
8011 * Find the ID of an autocmd group name.
8012 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8013 */
8014 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008015au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016{
8017 int i;
8018
8019 for (i = 0; i < augroups.ga_len; ++i)
8020 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8021 return i;
8022 return AUGROUP_ERROR;
8023}
8024
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008025/*
8026 * Return TRUE if augroup "name" exists.
8027 */
8028 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008029au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008030{
8031 return au_find_group(name) != AUGROUP_ERROR;
8032}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008033
Bram Moolenaar071d4272004-06-13 20:20:40 +00008034/*
8035 * ":augroup {name}".
8036 */
8037 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008038do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008039{
8040 int i;
8041
8042 if (del_group)
8043 {
8044 if (*arg == NUL)
8045 EMSG(_(e_argreq));
8046 else
8047 au_del_group(arg);
8048 }
8049 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8050 current_augroup = AUGROUP_DEFAULT;
8051 else if (*arg) /* ":aug xxx": switch to group xxx */
8052 {
8053 i = au_new_group(arg);
8054 if (i != AUGROUP_ERROR)
8055 current_augroup = i;
8056 }
8057 else /* ":aug": list the group names */
8058 {
8059 msg_start();
8060 for (i = 0; i < augroups.ga_len; ++i)
8061 {
8062 if (AUGROUP_NAME(i) != NULL)
8063 {
8064 msg_puts(AUGROUP_NAME(i));
8065 msg_puts((char_u *)" ");
8066 }
8067 }
8068 msg_clr_eos();
8069 msg_end();
8070 }
8071}
8072
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008073#if defined(EXITFREE) || defined(PROTO)
8074 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008075free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008076{
8077 for (current_augroup = -1; current_augroup < augroups.ga_len;
8078 ++current_augroup)
8079 do_autocmd((char_u *)"", TRUE);
8080 ga_clear_strings(&augroups);
8081}
8082#endif
8083
Bram Moolenaar071d4272004-06-13 20:20:40 +00008084/*
8085 * Return the event number for event name "start".
8086 * Return NUM_EVENTS if the event name was not found.
8087 * Return a pointer to the next event name in "end".
8088 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008089 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008090event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008091{
8092 char_u *p;
8093 int i;
8094 int len;
8095
8096 /* the event name ends with end of line, a blank or a comma */
8097 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8098 ;
8099 for (i = 0; event_names[i].name != NULL; ++i)
8100 {
8101 len = (int)STRLEN(event_names[i].name);
8102 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8103 break;
8104 }
8105 if (*p == ',')
8106 ++p;
8107 *end = p;
8108 if (event_names[i].name == NULL)
8109 return NUM_EVENTS;
8110 return event_names[i].event;
8111}
8112
8113/*
8114 * Return the name for event "event".
8115 */
8116 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008117event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008118{
8119 int i;
8120
8121 for (i = 0; event_names[i].name != NULL; ++i)
8122 if (event_names[i].event == event)
8123 return (char_u *)event_names[i].name;
8124 return (char_u *)"Unknown";
8125}
8126
8127/*
8128 * Scan over the events. "*" stands for all events.
8129 */
8130 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008131find_end_event(
8132 char_u *arg,
8133 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008134{
8135 char_u *pat;
8136 char_u *p;
8137
8138 if (*arg == '*')
8139 {
8140 if (arg[1] && !vim_iswhite(arg[1]))
8141 {
8142 EMSG2(_("E215: Illegal character after *: %s"), arg);
8143 return NULL;
8144 }
8145 pat = arg + 1;
8146 }
8147 else
8148 {
8149 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8150 {
8151 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8152 {
8153 if (have_group)
8154 EMSG2(_("E216: No such event: %s"), pat);
8155 else
8156 EMSG2(_("E216: No such group or event: %s"), pat);
8157 return NULL;
8158 }
8159 }
8160 }
8161 return pat;
8162}
8163
8164/*
8165 * Return TRUE if "event" is included in 'eventignore'.
8166 */
8167 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008168event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008169{
8170 char_u *p = p_ei;
8171
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008172 while (*p != NUL)
8173 {
8174 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8175 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008176 if (event_name2nr(p, &p) == event)
8177 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008178 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179
8180 return FALSE;
8181}
8182
8183/*
8184 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8185 */
8186 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008187check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008188{
8189 char_u *p = p_ei;
8190
Bram Moolenaar071d4272004-06-13 20:20:40 +00008191 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008192 {
8193 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8194 {
8195 p += 3;
8196 if (*p == ',')
8197 ++p;
8198 }
8199 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008201 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008202
8203 return OK;
8204}
8205
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008206# if defined(FEAT_SYN_HL) || defined(PROTO)
8207
8208/*
8209 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8210 * buffer loaded into the window. "what" must start with a comma.
8211 * Returns the old value of 'eventignore' in allocated memory.
8212 */
8213 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008214au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008215{
8216 char_u *new_ei;
8217 char_u *save_ei;
8218
8219 save_ei = vim_strsave(p_ei);
8220 if (save_ei != NULL)
8221 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008222 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008223 if (new_ei != NULL)
8224 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008225 if (*what == ',' && *p_ei == NUL)
8226 STRCPY(new_ei, what + 1);
8227 else
8228 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008229 set_string_option_direct((char_u *)"ei", -1, new_ei,
8230 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008231 vim_free(new_ei);
8232 }
8233 }
8234 return save_ei;
8235}
8236
8237 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008238au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008239{
8240 if (old_ei != NULL)
8241 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008242 set_string_option_direct((char_u *)"ei", -1, old_ei,
8243 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008244 vim_free(old_ei);
8245 }
8246}
8247# endif /* FEAT_SYN_HL */
8248
Bram Moolenaar071d4272004-06-13 20:20:40 +00008249/*
8250 * do_autocmd() -- implements the :autocmd command. Can be used in the
8251 * following ways:
8252 *
8253 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8254 * will be automatically executed for <event>
8255 * when editing a file matching <pat>, in
8256 * the current group.
8257 * :autocmd <event> <pat> Show the auto-commands associated with
8258 * <event> and <pat>.
8259 * :autocmd <event> Show the auto-commands associated with
8260 * <event>.
8261 * :autocmd Show all auto-commands.
8262 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8263 * <event> and <pat>, and add the command
8264 * <cmd>, for the current group.
8265 * :autocmd! <event> <pat> Remove all auto-commands associated with
8266 * <event> and <pat> for the current group.
8267 * :autocmd! <event> Remove all auto-commands associated with
8268 * <event> for the current group.
8269 * :autocmd! Remove ALL auto-commands for the current
8270 * group.
8271 *
8272 * Multiple events and patterns may be given separated by commas. Here are
8273 * some examples:
8274 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8275 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8276 *
8277 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008278 *
8279 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008280 */
8281 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008282do_autocmd(char_u *arg, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008283{
8284 char_u *pat;
8285 char_u *envpat = NULL;
8286 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008287 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008288 int need_free = FALSE;
8289 int nested = FALSE;
8290 int group;
8291
8292 /*
8293 * Check for a legal group name. If not, use AUGROUP_ALL.
8294 */
8295 group = au_get_grouparg(&arg);
8296 if (arg == NULL) /* out of memory */
8297 return;
8298
8299 /*
8300 * Scan over the events.
8301 * If we find an illegal name, return here, don't do anything.
8302 */
8303 pat = find_end_event(arg, group != AUGROUP_ALL);
8304 if (pat == NULL)
8305 return;
8306
8307 /*
8308 * Scan over the pattern. Put a NUL at the end.
8309 */
8310 pat = skipwhite(pat);
8311 cmd = pat;
8312 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8313 cmd++;
8314 if (*cmd)
8315 *cmd++ = NUL;
8316
8317 /* Expand environment variables in the pattern. Set 'shellslash', we want
8318 * forward slashes here. */
8319 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8320 {
8321#ifdef BACKSLASH_IN_FILENAME
8322 int p_ssl_save = p_ssl;
8323
8324 p_ssl = TRUE;
8325#endif
8326 envpat = expand_env_save(pat);
8327#ifdef BACKSLASH_IN_FILENAME
8328 p_ssl = p_ssl_save;
8329#endif
8330 if (envpat != NULL)
8331 pat = envpat;
8332 }
8333
8334 /*
8335 * Check for "nested" flag.
8336 */
8337 cmd = skipwhite(cmd);
8338 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8339 {
8340 nested = TRUE;
8341 cmd = skipwhite(cmd + 6);
8342 }
8343
8344 /*
8345 * Find the start of the commands.
8346 * Expand <sfile> in it.
8347 */
8348 if (*cmd != NUL)
8349 {
8350 cmd = expand_sfile(cmd);
8351 if (cmd == NULL) /* some error */
8352 return;
8353 need_free = TRUE;
8354 }
8355
8356 /*
8357 * Print header when showing autocommands.
8358 */
8359 if (!forceit && *cmd == NUL)
8360 {
8361 /* Highlight title */
8362 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8363 }
8364
8365 /*
8366 * Loop over the events.
8367 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008368 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008369 last_group = AUGROUP_ERROR; /* for listing the group name */
8370 if (*arg == '*' || *arg == NUL)
8371 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008372 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8373 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008374 if (do_autocmd_event(event, pat,
8375 nested, cmd, forceit, group) == FAIL)
8376 break;
8377 }
8378 else
8379 {
8380 while (*arg && !vim_iswhite(*arg))
8381 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8382 nested, cmd, forceit, group) == FAIL)
8383 break;
8384 }
8385
8386 if (need_free)
8387 vim_free(cmd);
8388 vim_free(envpat);
8389}
8390
8391/*
8392 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8393 * The "argp" argument is advanced to the following argument.
8394 *
8395 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8396 */
8397 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008398au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008399{
8400 char_u *group_name;
8401 char_u *p;
8402 char_u *arg = *argp;
8403 int group = AUGROUP_ALL;
8404
8405 p = skiptowhite(arg);
8406 if (p > arg)
8407 {
8408 group_name = vim_strnsave(arg, (int)(p - arg));
8409 if (group_name == NULL) /* out of memory */
8410 return AUGROUP_ERROR;
8411 group = au_find_group(group_name);
8412 if (group == AUGROUP_ERROR)
8413 group = AUGROUP_ALL; /* no match, use all groups */
8414 else
8415 *argp = skipwhite(p); /* match, skip over group name */
8416 vim_free(group_name);
8417 }
8418 return group;
8419}
8420
8421/*
8422 * do_autocmd() for one event.
8423 * If *pat == NUL do for all patterns.
8424 * If *cmd == NUL show entries.
8425 * If forceit == TRUE delete entries.
8426 * If group is not AUGROUP_ALL, only use this group.
8427 */
8428 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008429do_autocmd_event(
8430 event_T event,
8431 char_u *pat,
8432 int nested,
8433 char_u *cmd,
8434 int forceit,
8435 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008436{
8437 AutoPat *ap;
8438 AutoPat **prev_ap;
8439 AutoCmd *ac;
8440 AutoCmd **prev_ac;
8441 int brace_level;
8442 char_u *endpat;
8443 int findgroup;
8444 int allgroups;
8445 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008446 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008447 int buflocal_nr;
8448 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008449
8450 if (group == AUGROUP_ALL)
8451 findgroup = current_augroup;
8452 else
8453 findgroup = group;
8454 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8455
8456 /*
8457 * Show or delete all patterns for an event.
8458 */
8459 if (*pat == NUL)
8460 {
8461 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8462 {
8463 if (forceit) /* delete the AutoPat, if it's in the current group */
8464 {
8465 if (ap->group == findgroup)
8466 au_remove_pat(ap);
8467 }
8468 else if (group == AUGROUP_ALL || ap->group == group)
8469 show_autocmd(ap, event);
8470 }
8471 }
8472
8473 /*
8474 * Loop through all the specified patterns.
8475 */
8476 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8477 {
8478 /*
8479 * Find end of the pattern.
8480 * Watch out for a comma in braces, like "*.\{obj,o\}".
8481 */
8482 brace_level = 0;
8483 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008484 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008485 {
8486 if (*endpat == '{')
8487 brace_level++;
8488 else if (*endpat == '}')
8489 brace_level--;
8490 }
8491 if (pat == endpat) /* ignore single comma */
8492 continue;
8493 patlen = (int)(endpat - pat);
8494
8495 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008496 * detect special <buflocal[=X]> buffer-local patterns
8497 */
8498 is_buflocal = FALSE;
8499 buflocal_nr = 0;
8500
Bram Moolenaar1e997822015-02-17 16:04:57 +01008501 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008502 && pat[patlen - 1] == '>')
8503 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008504 /* "<buffer...>": Error will be printed only for addition.
8505 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008506 is_buflocal = TRUE;
8507 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008508 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008509 buflocal_nr = curbuf->b_fnum;
8510 else if (patlen > 9 && pat[7] == '=')
8511 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008512 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8513 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008514 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008515 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008516 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008517 buflocal_nr = atoi((char *)pat + 8);
8518 }
8519 }
8520
8521 if (is_buflocal)
8522 {
8523 /* normalize pat into standard "<buffer>#N" form */
8524 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8525 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008526 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008527 }
8528
8529 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008530 * Find AutoPat entries with this pattern.
8531 */
8532 prev_ap = &first_autopat[(int)event];
8533 while ((ap = *prev_ap) != NULL)
8534 {
8535 if (ap->pat != NULL)
8536 {
8537 /* Accept a pattern when:
8538 * - a group was specified and it's that group, or a group was
8539 * not specified and it's the current group, or a group was
8540 * not specified and we are listing
8541 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008542 * - the pattern matches.
8543 * For <buffer[=X]>, this condition works because we normalize
8544 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 */
8546 if ((allgroups || ap->group == findgroup)
8547 && ap->patlen == patlen
8548 && STRNCMP(pat, ap->pat, patlen) == 0)
8549 {
8550 /*
8551 * Remove existing autocommands.
8552 * If adding any new autocmd's for this AutoPat, don't
8553 * delete the pattern from the autopat list, append to
8554 * this list.
8555 */
8556 if (forceit)
8557 {
8558 if (*cmd != NUL && ap->next == NULL)
8559 {
8560 au_remove_cmds(ap);
8561 break;
8562 }
8563 au_remove_pat(ap);
8564 }
8565
8566 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008567 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008568 */
8569 else if (*cmd == NUL)
8570 show_autocmd(ap, event);
8571
8572 /*
8573 * Add autocmd to this autopat, if it's the last one.
8574 */
8575 else if (ap->next == NULL)
8576 break;
8577 }
8578 }
8579 prev_ap = &ap->next;
8580 }
8581
8582 /*
8583 * Add a new command.
8584 */
8585 if (*cmd != NUL)
8586 {
8587 /*
8588 * If the pattern we want to add a command to does appear at the
8589 * end of the list (or not is not in the list at all), add the
8590 * pattern at the end of the list.
8591 */
8592 if (ap == NULL)
8593 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008594 /* refuse to add buffer-local ap if buffer number is invalid */
8595 if (is_buflocal && (buflocal_nr == 0
8596 || buflist_findnr(buflocal_nr) == NULL))
8597 {
8598 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8599 buflocal_nr);
8600 return FAIL;
8601 }
8602
Bram Moolenaar071d4272004-06-13 20:20:40 +00008603 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8604 if (ap == NULL)
8605 return FAIL;
8606 ap->pat = vim_strnsave(pat, patlen);
8607 ap->patlen = patlen;
8608 if (ap->pat == NULL)
8609 {
8610 vim_free(ap);
8611 return FAIL;
8612 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008613
8614 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008615 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008616 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008617 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008618 }
8619 else
8620 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008621 char_u *reg_pat;
8622
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008623 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008624 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008625 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008626 if (reg_pat != NULL)
8627 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008628 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008629 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008630 {
8631 vim_free(ap->pat);
8632 vim_free(ap);
8633 return FAIL;
8634 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008635 }
8636 ap->cmds = NULL;
8637 *prev_ap = ap;
8638 ap->next = NULL;
8639 if (group == AUGROUP_ALL)
8640 ap->group = current_augroup;
8641 else
8642 ap->group = group;
8643 }
8644
8645 /*
8646 * Add the autocmd at the end of the AutoCmd list.
8647 */
8648 prev_ac = &(ap->cmds);
8649 while ((ac = *prev_ac) != NULL)
8650 prev_ac = &ac->next;
8651 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8652 if (ac == NULL)
8653 return FAIL;
8654 ac->cmd = vim_strsave(cmd);
8655#ifdef FEAT_EVAL
8656 ac->scriptID = current_SID;
8657#endif
8658 if (ac->cmd == NULL)
8659 {
8660 vim_free(ac);
8661 return FAIL;
8662 }
8663 ac->next = NULL;
8664 *prev_ac = ac;
8665 ac->nested = nested;
8666 }
8667 }
8668
8669 au_cleanup(); /* may really delete removed patterns/commands now */
8670 return OK;
8671}
8672
8673/*
8674 * Implementation of ":doautocmd [group] event [fname]".
8675 * Return OK for success, FAIL for failure;
8676 */
8677 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008678do_doautocmd(
8679 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008680 int do_msg, /* give message for no matching autocmds? */
8681 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008682{
8683 char_u *fname;
8684 int nothing_done = TRUE;
8685 int group;
8686
Bram Moolenaar1610d052016-06-09 22:53:01 +02008687 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008688 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008689
Bram Moolenaar071d4272004-06-13 20:20:40 +00008690 /*
8691 * Check for a legal group name. If not, use AUGROUP_ALL.
8692 */
8693 group = au_get_grouparg(&arg);
8694 if (arg == NULL) /* out of memory */
8695 return FAIL;
8696
8697 if (*arg == '*')
8698 {
8699 EMSG(_("E217: Can't execute autocommands for ALL events"));
8700 return FAIL;
8701 }
8702
8703 /*
8704 * Scan over the events.
8705 * If we find an illegal name, return here, don't do anything.
8706 */
8707 fname = find_end_event(arg, group != AUGROUP_ALL);
8708 if (fname == NULL)
8709 return FAIL;
8710
8711 fname = skipwhite(fname);
8712
8713 /*
8714 * Loop over the events.
8715 */
8716 while (*arg && !vim_iswhite(*arg))
8717 if (apply_autocmds_group(event_name2nr(arg, &arg),
8718 fname, NULL, TRUE, group, curbuf, NULL))
8719 nothing_done = FALSE;
8720
8721 if (nothing_done && do_msg)
8722 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008723 if (did_something != NULL)
8724 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008725
8726#ifdef FEAT_EVAL
8727 return aborting() ? FAIL : OK;
8728#else
8729 return OK;
8730#endif
8731}
8732
8733/*
8734 * ":doautoall": execute autocommands for each loaded buffer.
8735 */
8736 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008737ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008738{
8739 int retval;
8740 aco_save_T aco;
8741 buf_T *buf;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008742 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008743 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008744 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008745
8746 /*
8747 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8748 * equal to curbuf, but for some buffers there may not be a window.
8749 * So we change the buffer for the current window for a moment. This
8750 * gives problems when the autocommands make changes to the list of
8751 * buffers or windows...
8752 */
8753 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8754 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008755 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008756 {
8757 /* find a window for this buffer and save some values */
8758 aucmd_prepbuf(&aco, buf);
8759
8760 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008761 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008762
Bram Moolenaar1610d052016-06-09 22:53:01 +02008763 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008764 {
8765 /* Execute the modeline settings, but don't set window-local
8766 * options if we are using the current window for another
8767 * buffer. */
8768 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8769 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008770
8771 /* restore the current window */
8772 aucmd_restbuf(&aco);
8773
8774 /* stop if there is some error or buffer was deleted */
8775 if (retval == FAIL || !buf_valid(buf))
8776 break;
8777 }
8778 }
8779
8780 check_cursor(); /* just in case lines got deleted */
8781}
8782
8783/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008784 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8785 * return TRUE and advance *argp to after it.
8786 * Thus return TRUE when do_modelines() should be called.
8787 */
8788 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008789check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008790{
8791 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8792 {
8793 *argp = skipwhite(*argp + 12);
8794 return FALSE;
8795 }
8796 return TRUE;
8797}
8798
8799/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008800 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008801 * Search for a visible window containing the current buffer. If there isn't
8802 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008803 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008804 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008805 */
8806 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008807aucmd_prepbuf(
8808 aco_save_T *aco, /* structure to save values in */
8809 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008810{
8811 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008812#ifdef FEAT_WINDOWS
8813 int save_ea;
8814#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008815#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008816 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008817#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008818
8819 /* Find a window that is for the new buffer */
8820 if (buf == curbuf) /* be quick when buf is curbuf */
8821 win = curwin;
8822 else
8823#ifdef FEAT_WINDOWS
8824 for (win = firstwin; win != NULL; win = win->w_next)
8825 if (win->w_buffer == buf)
8826 break;
8827#else
8828 win = NULL;
8829#endif
8830
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008831 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8832 * back to using the current window. */
8833 if (win == NULL && aucmd_win == NULL)
8834 {
8835 win_alloc_aucmd_win();
8836 if (aucmd_win == NULL)
8837 win = curwin;
8838 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008839 if (win == NULL && aucmd_win_used)
8840 /* Strange recursive autocommand, fall back to using the current
8841 * window. Expect a few side effects... */
8842 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008843
8844 aco->save_curwin = curwin;
8845 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008846 if (win != NULL)
8847 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008848 /* There is a window for "buf" in the current tab page, make it the
8849 * curwin. This is preferred, it has the least side effects (esp. if
8850 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008851 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008852 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008853 }
8854 else
8855 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008856 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008857 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008858 * Anything related to a window (e.g., setting folds) may have
8859 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008860 aco->use_aucmd_win = TRUE;
8861 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008862 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008863 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008864 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008865 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008866
8867 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8868 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008869 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008870 aucmd_win->w_localdir = NULL;
8871 aco->globaldir = globaldir;
8872 globaldir = NULL;
8873
Bram Moolenaar071d4272004-06-13 20:20:40 +00008874
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008875#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008876 /* Split the current window, put the aucmd_win in the upper half.
8877 * We don't want the BufEnter or WinEnter autocommands. */
8878 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008879 make_snapshot(SNAP_AUCMD_IDX);
8880 save_ea = p_ea;
8881 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008882
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008883# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008884 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8885 save_acd = p_acd;
8886 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008887# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008888
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008889 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8890 (void)win_comp_pos(); /* recompute window positions */
8891 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008892# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008893 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008894# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008895 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008896#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008897 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008899 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008900 aco->new_curwin = curwin;
8901 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902}
8903
8904/*
8905 * Cleanup after executing autocommands for a (hidden) buffer.
8906 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008907 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 */
8909 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008910aucmd_restbuf(
8911 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008912{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008913#ifdef FEAT_WINDOWS
8914 int dummy;
8915#endif
8916
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008917 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008918 {
8919 --curbuf->b_nwindows;
8920#ifdef FEAT_WINDOWS
8921 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008922 * page. Do not trigger autocommands here. */
8923 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008924 if (curwin != aucmd_win)
8925 {
8926 tabpage_T *tp;
8927 win_T *wp;
8928
8929 FOR_ALL_TAB_WINDOWS(tp, wp)
8930 {
8931 if (wp == aucmd_win)
8932 {
8933 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008934 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008935 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008936 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008937 }
8938 }
8939 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008940win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008941
8942 /* Remove the window and frame from the tree of frames. */
8943 (void)winframe_remove(curwin, &dummy, NULL);
8944 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008945 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008946 last_status(FALSE); /* may need to remove last status line */
8947 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8948 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008949 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008950
8951 if (win_valid(aco->save_curwin))
8952 curwin = aco->save_curwin;
8953 else
8954 /* Hmm, original window disappeared. Just use the first one. */
8955 curwin = firstwin;
8956# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008957 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8958 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008959# endif
8960#else
8961 curwin = aco->save_curwin;
8962#endif
8963 curbuf = curwin->w_buffer;
8964
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008965 vim_free(globaldir);
8966 globaldir = aco->globaldir;
8967
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008968 /* the buffer contents may have changed */
8969 check_cursor();
8970 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8971 {
8972 curwin->w_topline = curbuf->b_ml.ml_line_count;
8973#ifdef FEAT_DIFF
8974 curwin->w_topfill = 0;
8975#endif
8976 }
8977#if defined(FEAT_GUI)
8978 /* Hide the scrollbars from the aucmd_win and update. */
8979 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8980 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8981 gui_may_update_scrollbars();
8982#endif
8983 }
8984 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008985 {
8986 /* restore curwin */
8987#ifdef FEAT_WINDOWS
8988 if (win_valid(aco->save_curwin))
8989#endif
8990 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008991 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008992 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008993 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008995 && curbuf != aco->new_curbuf
8996 && buf_valid(aco->new_curbuf)
8997 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008998 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02008999# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9000 if (curwin->w_s == &curbuf->b_s)
9001 curwin->w_s = &aco->new_curbuf->b_s;
9002# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009003 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009004 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005 curwin->w_buffer = curbuf;
9006 ++curbuf->b_nwindows;
9007 }
9008
9009 curwin = aco->save_curwin;
9010 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009011 /* In case the autocommand move the cursor to a position that that
9012 * not exist in curbuf. */
9013 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009014 }
9015 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009016}
9017
9018static int autocmd_nested = FALSE;
9019
9020/*
9021 * Execute autocommands for "event" and file name "fname".
9022 * Return TRUE if some commands were executed.
9023 */
9024 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009025apply_autocmds(
9026 event_T event,
9027 char_u *fname, /* NULL or empty means use actual file name */
9028 char_u *fname_io, /* fname to use for <afile> on cmdline */
9029 int force, /* when TRUE, ignore autocmd_busy */
9030 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031{
9032 return apply_autocmds_group(event, fname, fname_io, force,
9033 AUGROUP_ALL, buf, NULL);
9034}
9035
9036/*
9037 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9038 * setting v:filearg.
9039 */
9040 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009041apply_autocmds_exarg(
9042 event_T event,
9043 char_u *fname,
9044 char_u *fname_io,
9045 int force,
9046 buf_T *buf,
9047 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009048{
9049 return apply_autocmds_group(event, fname, fname_io, force,
9050 AUGROUP_ALL, buf, eap);
9051}
9052
9053/*
9054 * Like apply_autocmds(), but handles the caller's retval. If the script
9055 * processing is being aborted or if retval is FAIL when inside a try
9056 * conditional, no autocommands are executed. If otherwise the autocommands
9057 * cause the script to be aborted, retval is set to FAIL.
9058 */
9059 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009060apply_autocmds_retval(
9061 event_T event,
9062 char_u *fname, /* NULL or empty means use actual file name */
9063 char_u *fname_io, /* fname to use for <afile> on cmdline */
9064 int force, /* when TRUE, ignore autocmd_busy */
9065 buf_T *buf, /* buffer for <abuf> */
9066 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009067{
9068 int did_cmd;
9069
Bram Moolenaar1e015462005-09-25 22:16:38 +00009070#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009071 if (should_abort(*retval))
9072 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009073#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009074
9075 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9076 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009077 if (did_cmd
9078#ifdef FEAT_EVAL
9079 && aborting()
9080#endif
9081 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009082 *retval = FAIL;
9083 return did_cmd;
9084}
9085
Bram Moolenaard35f9712005-12-18 22:02:33 +00009086/*
9087 * Return TRUE when there is a CursorHold autocommand defined.
9088 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009089 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009090has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009091{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009092 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9093 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009094}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009095
9096/*
9097 * Return TRUE if the CursorHold event can be triggered.
9098 */
9099 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009100trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009101{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009102 int state;
9103
Bram Moolenaar05334432011-07-20 18:29:39 +02009104 if (!did_cursorhold
9105 && has_cursorhold()
9106 && !Recording
9107 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009108#ifdef FEAT_INS_EXPAND
9109 && !ins_compl_active()
9110#endif
9111 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009112 {
9113 state = get_real_state();
9114 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9115 return TRUE;
9116 }
9117 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009118}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009119
9120/*
9121 * Return TRUE when there is a CursorMoved autocommand defined.
9122 */
9123 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009124has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009125{
9126 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9127}
9128
9129/*
9130 * Return TRUE when there is a CursorMovedI autocommand defined.
9131 */
9132 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009133has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009134{
9135 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9136}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009137
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009138/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009139 * Return TRUE when there is a TextChanged autocommand defined.
9140 */
9141 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009142has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009143{
9144 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9145}
9146
9147/*
9148 * Return TRUE when there is a TextChangedI autocommand defined.
9149 */
9150 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009151has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009152{
9153 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9154}
9155
9156/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009157 * Return TRUE when there is an InsertCharPre autocommand defined.
9158 */
9159 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009160has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009161{
9162 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9163}
9164
Bram Moolenaard5005162014-08-22 23:05:54 +02009165/*
9166 * Return TRUE when there is an CmdUndefined autocommand defined.
9167 */
9168 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009169has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009170{
9171 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9172}
9173
9174/*
9175 * Return TRUE when there is an FuncUndefined autocommand defined.
9176 */
9177 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009178has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009179{
9180 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9181}
9182
Bram Moolenaar071d4272004-06-13 20:20:40 +00009183 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009184apply_autocmds_group(
9185 event_T event,
9186 char_u *fname, /* NULL or empty means use actual file name */
9187 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009188 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009189 int force, /* when TRUE, ignore autocmd_busy */
9190 int group, /* group ID, or AUGROUP_ALL */
9191 buf_T *buf, /* buffer for <abuf> */
9192 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009193{
9194 char_u *sfname = NULL; /* short file name */
9195 char_u *tail;
9196 int save_changed;
9197 buf_T *old_curbuf;
9198 int retval = FALSE;
9199 char_u *save_sourcing_name;
9200 linenr_T save_sourcing_lnum;
9201 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009202 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009203 int save_autocmd_bufnr;
9204 char_u *save_autocmd_match;
9205 int save_autocmd_busy;
9206 int save_autocmd_nested;
9207 static int nesting = 0;
9208 AutoPatCmd patcmd;
9209 AutoPat *ap;
9210#ifdef FEAT_EVAL
9211 scid_T save_current_SID;
9212 void *save_funccalp;
9213 char_u *save_cmdarg;
9214 long save_cmdbang;
9215#endif
9216 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009217#ifdef FEAT_PROFILE
9218 proftime_T wait_time;
9219#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009220 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009221
9222 /*
9223 * Quickly return if there are no autocommands for this event or
9224 * autocommands are blocked.
9225 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009226 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009227 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009228
9229 /*
9230 * When autocommands are busy, new autocommands are only executed when
9231 * explicitly enabled with the "nested" flag.
9232 */
9233 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009234 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235
9236#ifdef FEAT_EVAL
9237 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009238 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009239 * occurred or an exception was thrown but not caught.
9240 */
9241 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009242 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009243#endif
9244
9245 /*
9246 * FileChangedShell never nests, because it can create an endless loop.
9247 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009248 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9249 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009250 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009251
9252 /*
9253 * Ignore events in 'eventignore'.
9254 */
9255 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009256 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009257
9258 /*
9259 * Allow nesting of autocommands, but restrict the depth, because it's
9260 * possible to create an endless loop.
9261 */
9262 if (nesting == 10)
9263 {
9264 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009265 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009266 }
9267
9268 /*
9269 * Check if these autocommands are disabled. Used when doing ":all" or
9270 * ":ball".
9271 */
9272 if ( (autocmd_no_enter
9273 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9274 || (autocmd_no_leave
9275 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009276 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009277
9278 /*
9279 * Save the autocmd_* variables and info about the current buffer.
9280 */
9281 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009282 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009283 save_autocmd_bufnr = autocmd_bufnr;
9284 save_autocmd_match = autocmd_match;
9285 save_autocmd_busy = autocmd_busy;
9286 save_autocmd_nested = autocmd_nested;
9287 save_changed = curbuf->b_changed;
9288 old_curbuf = curbuf;
9289
9290 /*
9291 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009292 * Make a copy to avoid that changing a buffer name or directory makes it
9293 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009294 */
9295 if (fname_io == NULL)
9296 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009297 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009298 autocmd_fname = NULL;
9299 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009300 autocmd_fname = fname;
9301 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009302 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009303 else
9304 autocmd_fname = NULL;
9305 }
9306 else
9307 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009308 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009309 autocmd_fname = vim_strsave(autocmd_fname);
9310 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009311
9312 /*
9313 * Set the buffer number to be used for <abuf>.
9314 */
9315 if (buf == NULL)
9316 autocmd_bufnr = 0;
9317 else
9318 autocmd_bufnr = buf->b_fnum;
9319
9320 /*
9321 * When the file name is NULL or empty, use the file name of buffer "buf".
9322 * Always use the full path of the file name to match with, in case
9323 * "allow_dirs" is set.
9324 */
9325 if (fname == NULL || *fname == NUL)
9326 {
9327 if (buf == NULL)
9328 fname = NULL;
9329 else
9330 {
9331#ifdef FEAT_SYN_HL
9332 if (event == EVENT_SYNTAX)
9333 fname = buf->b_p_syn;
9334 else
9335#endif
9336 if (event == EVENT_FILETYPE)
9337 fname = buf->b_p_ft;
9338 else
9339 {
9340 if (buf->b_sfname != NULL)
9341 sfname = vim_strsave(buf->b_sfname);
9342 fname = buf->b_ffname;
9343 }
9344 }
9345 if (fname == NULL)
9346 fname = (char_u *)"";
9347 fname = vim_strsave(fname); /* make a copy, so we can change it */
9348 }
9349 else
9350 {
9351 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009352 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9353 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009354 if (event == EVENT_FILETYPE
9355 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009356 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009357 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009358 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009359 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009360 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009361 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009362 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009363 fname = vim_strsave(fname);
9364 else
9365 fname = FullName_save(fname, FALSE);
9366 }
9367 if (fname == NULL) /* out of memory */
9368 {
9369 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009370 retval = FALSE;
9371 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009372 }
9373
9374#ifdef BACKSLASH_IN_FILENAME
9375 /*
9376 * Replace all backslashes with forward slashes. This makes the
9377 * autocommand patterns portable between Unix and MS-DOS.
9378 */
9379 if (sfname != NULL)
9380 forward_slash(sfname);
9381 forward_slash(fname);
9382#endif
9383
9384#ifdef VMS
9385 /* remove version for correct match */
9386 if (sfname != NULL)
9387 vms_remove_version(sfname);
9388 vms_remove_version(fname);
9389#endif
9390
9391 /*
9392 * Set the name to be used for <amatch>.
9393 */
9394 autocmd_match = fname;
9395
9396
9397 /* Don't redraw while doing auto commands. */
9398 ++RedrawingDisabled;
9399 save_sourcing_name = sourcing_name;
9400 sourcing_name = NULL; /* don't free this one */
9401 save_sourcing_lnum = sourcing_lnum;
9402 sourcing_lnum = 0; /* no line number here */
9403
9404#ifdef FEAT_EVAL
9405 save_current_SID = current_SID;
9406
Bram Moolenaar05159a02005-02-26 23:04:13 +00009407# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009408 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009409 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9410# endif
9411
Bram Moolenaar071d4272004-06-13 20:20:40 +00009412 /* Don't use local function variables, if called from a function */
9413 save_funccalp = save_funccal();
9414#endif
9415
9416 /*
9417 * When starting to execute autocommands, save the search patterns.
9418 */
9419 if (!autocmd_busy)
9420 {
9421 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009422#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009423 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009424#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009425 {
9426 saveRedobuff();
9427 did_save_redobuff = TRUE;
9428 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009429 did_filetype = keep_filetype;
9430 }
9431
9432 /*
9433 * Note that we are applying autocmds. Some commands need to know.
9434 */
9435 autocmd_busy = TRUE;
9436 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9437 ++nesting; /* see matching decrement below */
9438
9439 /* Remember that FileType was triggered. Used for did_filetype(). */
9440 if (event == EVENT_FILETYPE)
9441 did_filetype = TRUE;
9442
9443 tail = gettail(fname);
9444
9445 /* Find first autocommand that matches */
9446 patcmd.curpat = first_autopat[(int)event];
9447 patcmd.nextcmd = NULL;
9448 patcmd.group = group;
9449 patcmd.fname = fname;
9450 patcmd.sfname = sfname;
9451 patcmd.tail = tail;
9452 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009453 patcmd.arg_bufnr = autocmd_bufnr;
9454 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009455 auto_next_pat(&patcmd, FALSE);
9456
9457 /* found one, start executing the autocommands */
9458 if (patcmd.curpat != NULL)
9459 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009460 /* add to active_apc_list */
9461 patcmd.next = active_apc_list;
9462 active_apc_list = &patcmd;
9463
Bram Moolenaar071d4272004-06-13 20:20:40 +00009464#ifdef FEAT_EVAL
9465 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009466 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009467 if (eap != NULL)
9468 {
9469 save_cmdarg = set_cmdarg(eap, NULL);
9470 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9471 }
9472 else
9473 save_cmdarg = NULL; /* avoid gcc warning */
9474#endif
9475 retval = TRUE;
9476 /* mark the last pattern, to avoid an endless loop when more patterns
9477 * are added when executing autocommands */
9478 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9479 ap->last = FALSE;
9480 ap->last = TRUE;
9481 check_lnums(TRUE); /* make sure cursor and topline are valid */
9482 do_cmdline(NULL, getnextac, (void *)&patcmd,
9483 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9484#ifdef FEAT_EVAL
9485 if (eap != NULL)
9486 {
9487 (void)set_cmdarg(NULL, save_cmdarg);
9488 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9489 }
9490#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009491 /* delete from active_apc_list */
9492 if (active_apc_list == &patcmd) /* just in case */
9493 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009494 }
9495
9496 --RedrawingDisabled;
9497 autocmd_busy = save_autocmd_busy;
9498 filechangeshell_busy = FALSE;
9499 autocmd_nested = save_autocmd_nested;
9500 vim_free(sourcing_name);
9501 sourcing_name = save_sourcing_name;
9502 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009503 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009504 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009505 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009506 autocmd_bufnr = save_autocmd_bufnr;
9507 autocmd_match = save_autocmd_match;
9508#ifdef FEAT_EVAL
9509 current_SID = save_current_SID;
9510 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009511# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009512 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009513 prof_child_exit(&wait_time);
9514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009515#endif
9516 vim_free(fname);
9517 vim_free(sfname);
9518 --nesting; /* see matching increment above */
9519
9520 /*
9521 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009522 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9523 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009524 */
9525 if (!autocmd_busy)
9526 {
9527 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009528 if (did_save_redobuff)
9529 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009530 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009531 while (au_pending_free_buf != NULL)
9532 {
9533 buf_T *b = au_pending_free_buf->b_next;
9534 vim_free(au_pending_free_buf);
9535 au_pending_free_buf = b;
9536 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009537 while (au_pending_free_win != NULL)
9538 {
9539 win_T *w = au_pending_free_win->w_next;
9540 vim_free(au_pending_free_win);
9541 au_pending_free_win = w;
9542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009543 }
9544
9545 /*
9546 * Some events don't set or reset the Changed flag.
9547 * Check if still in the same buffer!
9548 */
9549 if (curbuf == old_curbuf
9550 && (event == EVENT_BUFREADPOST
9551 || event == EVENT_BUFWRITEPOST
9552 || event == EVENT_FILEAPPENDPOST
9553 || event == EVENT_VIMLEAVE
9554 || event == EVENT_VIMLEAVEPRE))
9555 {
9556#ifdef FEAT_TITLE
9557 if (curbuf->b_changed != save_changed)
9558 need_maketitle = TRUE;
9559#endif
9560 curbuf->b_changed = save_changed;
9561 }
9562
9563 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009564
9565BYPASS_AU:
9566 /* When wiping out a buffer make sure all its buffer-local autocommands
9567 * are deleted. */
9568 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9569 aubuflocal_remove(buf);
9570
Bram Moolenaarc3691332016-04-20 12:49:49 +02009571 if (retval == OK && event == EVENT_FILETYPE)
9572 au_did_filetype = TRUE;
9573
Bram Moolenaar071d4272004-06-13 20:20:40 +00009574 return retval;
9575}
9576
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009577# ifdef FEAT_EVAL
9578static char_u *old_termresponse = NULL;
9579# endif
9580
9581/*
9582 * Block triggering autocommands until unblock_autocmd() is called.
9583 * Can be used recursively, so long as it's symmetric.
9584 */
9585 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009586block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009587{
9588# ifdef FEAT_EVAL
9589 /* Remember the value of v:termresponse. */
9590 if (autocmd_blocked == 0)
9591 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9592# endif
9593 ++autocmd_blocked;
9594}
9595
9596 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009597unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009598{
9599 --autocmd_blocked;
9600
9601# ifdef FEAT_EVAL
9602 /* When v:termresponse was set while autocommands were blocked, trigger
9603 * the autocommands now. Esp. useful when executing a shell command
9604 * during startup (vimdiff). */
9605 if (autocmd_blocked == 0
9606 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9607 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9608# endif
9609}
9610
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009611 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009612is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009613{
9614 return autocmd_blocked != 0;
9615}
9616
Bram Moolenaar071d4272004-06-13 20:20:40 +00009617/*
9618 * Find next autocommand pattern that matches.
9619 */
9620 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009621auto_next_pat(
9622 AutoPatCmd *apc,
9623 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009624{
9625 AutoPat *ap;
9626 AutoCmd *cp;
9627 char_u *name;
9628 char *s;
9629
9630 vim_free(sourcing_name);
9631 sourcing_name = NULL;
9632
9633 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9634 {
9635 apc->curpat = NULL;
9636
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009637 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009638 * the group matches. For buffer-local autocommands only check the
9639 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640 if (ap->pat != NULL && ap->cmds != NULL
9641 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9642 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009643 /* execution-condition */
9644 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009645 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009646 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009647 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009648 {
9649 name = event_nr2name(apc->event);
9650 s = _("%s Auto commands for \"%s\"");
9651 sourcing_name = alloc((unsigned)(STRLEN(s)
9652 + STRLEN(name) + ap->patlen + 1));
9653 if (sourcing_name != NULL)
9654 {
9655 sprintf((char *)sourcing_name, s,
9656 (char *)name, (char *)ap->pat);
9657 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009658 {
9659 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009660 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009661 verbose_leave();
9662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009663 }
9664
9665 apc->curpat = ap;
9666 apc->nextcmd = ap->cmds;
9667 /* mark last command */
9668 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9669 cp->last = FALSE;
9670 cp->last = TRUE;
9671 }
9672 line_breakcheck();
9673 if (apc->curpat != NULL) /* found a match */
9674 break;
9675 }
9676 if (stop_at_last && ap->last)
9677 break;
9678 }
9679}
9680
9681/*
9682 * Get next autocommand command.
9683 * Called by do_cmdline() to get the next line for ":if".
9684 * Returns allocated string, or NULL for end of autocommands.
9685 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009686 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009687getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009688{
9689 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9690 char_u *retval;
9691 AutoCmd *ac;
9692
9693 /* Can be called again after returning the last line. */
9694 if (acp->curpat == NULL)
9695 return NULL;
9696
9697 /* repeat until we find an autocommand to execute */
9698 for (;;)
9699 {
9700 /* skip removed commands */
9701 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9702 if (acp->nextcmd->last)
9703 acp->nextcmd = NULL;
9704 else
9705 acp->nextcmd = acp->nextcmd->next;
9706
9707 if (acp->nextcmd != NULL)
9708 break;
9709
9710 /* at end of commands, find next pattern that matches */
9711 if (acp->curpat->last)
9712 acp->curpat = NULL;
9713 else
9714 acp->curpat = acp->curpat->next;
9715 if (acp->curpat != NULL)
9716 auto_next_pat(acp, TRUE);
9717 if (acp->curpat == NULL)
9718 return NULL;
9719 }
9720
9721 ac = acp->nextcmd;
9722
9723 if (p_verbose >= 9)
9724 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009725 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009726 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009727 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009728 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009729 }
9730 retval = vim_strsave(ac->cmd);
9731 autocmd_nested = ac->nested;
9732#ifdef FEAT_EVAL
9733 current_SID = ac->scriptID;
9734#endif
9735 if (ac->last)
9736 acp->nextcmd = NULL;
9737 else
9738 acp->nextcmd = ac->next;
9739 return retval;
9740}
9741
9742/*
9743 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009744 * To account for buffer-local autocommands, function needs to know
9745 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 */
9747 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009748has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009749{
9750 AutoPat *ap;
9751 char_u *fname;
9752 char_u *tail = gettail(sfname);
9753 int retval = FALSE;
9754
9755 fname = FullName_save(sfname, FALSE);
9756 if (fname == NULL)
9757 return FALSE;
9758
9759#ifdef BACKSLASH_IN_FILENAME
9760 /*
9761 * Replace all backslashes with forward slashes. This makes the
9762 * autocommand patterns portable between Unix and MS-DOS.
9763 */
9764 sfname = vim_strsave(sfname);
9765 if (sfname != NULL)
9766 forward_slash(sfname);
9767 forward_slash(fname);
9768#endif
9769
9770 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9771 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009772 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009773 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009774 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009775 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009776 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009777 {
9778 retval = TRUE;
9779 break;
9780 }
9781
9782 vim_free(fname);
9783#ifdef BACKSLASH_IN_FILENAME
9784 vim_free(sfname);
9785#endif
9786
9787 return retval;
9788}
9789
9790#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9791/*
9792 * Function given to ExpandGeneric() to obtain the list of autocommand group
9793 * names.
9794 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009795 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009796get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009797{
9798 if (idx == augroups.ga_len) /* add "END" add the end */
9799 return (char_u *)"END";
9800 if (idx >= augroups.ga_len) /* end of list */
9801 return NULL;
9802 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9803 return (char_u *)"";
9804 return AUGROUP_NAME(idx); /* return a name */
9805}
9806
9807static int include_groups = FALSE;
9808
9809 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009810set_context_in_autocmd(
9811 expand_T *xp,
9812 char_u *arg,
9813 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009814{
9815 char_u *p;
9816 int group;
9817
9818 /* check for a group name, skip it if present */
9819 include_groups = FALSE;
9820 p = arg;
9821 group = au_get_grouparg(&arg);
9822 if (group == AUGROUP_ERROR)
9823 return NULL;
9824 /* If there only is a group name that's what we expand. */
9825 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9826 {
9827 arg = p;
9828 group = AUGROUP_ALL;
9829 }
9830
9831 /* skip over event name */
9832 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9833 if (*p == ',')
9834 arg = p + 1;
9835 if (*p == NUL)
9836 {
9837 if (group == AUGROUP_ALL)
9838 include_groups = TRUE;
9839 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9840 xp->xp_pattern = arg;
9841 return NULL;
9842 }
9843
9844 /* skip over pattern */
9845 arg = skipwhite(p);
9846 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9847 arg++;
9848 if (*arg)
9849 return arg; /* expand (next) command */
9850
9851 if (doautocmd)
9852 xp->xp_context = EXPAND_FILES; /* expand file names */
9853 else
9854 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9855 return NULL;
9856}
9857
9858/*
9859 * Function given to ExpandGeneric() to obtain the list of event names.
9860 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009861 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009862get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009863{
9864 if (idx < augroups.ga_len) /* First list group names, if wanted */
9865 {
9866 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9867 return (char_u *)""; /* skip deleted entries */
9868 return AUGROUP_NAME(idx); /* return a name */
9869 }
9870 return (char_u *)event_names[idx - augroups.ga_len].name;
9871}
9872
9873#endif /* FEAT_CMDL_COMPL */
9874
9875/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009876 * Return TRUE if autocmd is supported.
9877 */
9878 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009879autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009880{
9881 char_u *p;
9882
9883 return (event_name2nr(name, &p) != NUM_EVENTS);
9884}
9885
9886/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009887 * Return TRUE if an autocommand is defined for a group, event and
9888 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9889 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9890 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9891 * Used for:
9892 * exists("#Group") or
9893 * exists("#Group#Event") or
9894 * exists("#Group#Event#pat") or
9895 * exists("#Event") or
9896 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009897 */
9898 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009899au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009900{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009901 char_u *arg_save;
9902 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009903 char_u *event_name;
9904 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009905 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009906 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009907 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009908 int group;
9909 int retval = FALSE;
9910
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009911 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009912 arg_save = vim_strsave(arg);
9913 if (arg_save == NULL)
9914 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009915 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009916 if (p != NULL)
9917 *p++ = NUL;
9918
9919 /* First, look for an autocmd group name */
9920 group = au_find_group(arg_save);
9921 if (group == AUGROUP_ERROR)
9922 {
9923 /* Didn't match a group name, assume the first argument is an event. */
9924 group = AUGROUP_ALL;
9925 event_name = arg_save;
9926 }
9927 else
9928 {
9929 if (p == NULL)
9930 {
9931 /* "Group": group name is present and it's recognized */
9932 retval = TRUE;
9933 goto theend;
9934 }
9935
9936 /* Must be "Group#Event" or "Group#Event#pat". */
9937 event_name = p;
9938 p = vim_strchr(event_name, '#');
9939 if (p != NULL)
9940 *p++ = NUL; /* "Group#Event#pat" */
9941 }
9942
9943 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009944
9945 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009946 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009947
9948 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009949 if (event == NUM_EVENTS)
9950 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009951
9952 /* Find the first autocommand for this event.
9953 * If there isn't any, return FALSE;
9954 * If there is one and no pattern given, return TRUE; */
9955 ap = first_autopat[(int)event];
9956 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009957 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009958
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009959 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9960 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009961 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009962 buflocal_buf = curbuf;
9963
Bram Moolenaar071d4272004-06-13 20:20:40 +00009964 /* Check if there is an autocommand with the given pattern. */
9965 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009966 /* only use a pattern when it has not been removed and has commands. */
9967 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009968 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009969 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009970 && (pattern == NULL
9971 || (buflocal_buf == NULL
9972 ? fnamecmp(ap->pat, pattern) == 0
9973 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009974 {
9975 retval = TRUE;
9976 break;
9977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009978
Bram Moolenaar195d6352005-12-19 22:08:24 +00009979theend:
9980 vim_free(arg_save);
9981 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009982}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009983
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009984#else /* FEAT_AUTOCMD */
9985
9986/*
9987 * Prepare for executing commands for (hidden) buffer "buf".
9988 * This is the non-autocommand version, it simply saves "curbuf" and sets
9989 * "curbuf" and "curwin" to match "buf".
9990 */
9991 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01009992aucmd_prepbuf(
9993 aco_save_T *aco, /* structure to save values in */
9994 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009995{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009996 aco->save_curbuf = curbuf;
9997 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009998 curbuf = buf;
9999 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010000 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010001}
10002
10003/*
10004 * Restore after executing commands for a (hidden) buffer.
10005 * This is the non-autocommand version.
10006 */
10007 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010008aucmd_restbuf(
10009 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010010{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010011 --curbuf->b_nwindows;
10012 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010013 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010014 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010015}
10016
Bram Moolenaar071d4272004-06-13 20:20:40 +000010017#endif /* FEAT_AUTOCMD */
10018
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010019
Bram Moolenaar071d4272004-06-13 20:20:40 +000010020#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10021/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010022 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10023 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10024 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010025 * Used for autocommands and 'wildignore'.
10026 * Returns TRUE if there is a match, FALSE otherwise.
10027 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010028 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010029match_file_pat(
10030 char_u *pattern, /* pattern to match with */
10031 regprog_T **prog, /* pre-compiled regprog or NULL */
10032 char_u *fname, /* full path of file name */
10033 char_u *sfname, /* short file name or NULL */
10034 char_u *tail, /* tail of path */
10035 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010036{
10037 regmatch_T regmatch;
10038 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010040 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010041 if (prog != NULL)
10042 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010043 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010044 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010045
10046 /*
10047 * Try for a match with the pattern with:
10048 * 1. the full file name, when the pattern has a '/'.
10049 * 2. the short file name, when the pattern has a '/'.
10050 * 3. the tail of the file name, when the pattern has no '/'.
10051 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010052 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010053 && ((allow_dirs
10054 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10055 || (sfname != NULL
10056 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010057 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058 result = TRUE;
10059
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010060 if (prog != NULL)
10061 *prog = regmatch.regprog;
10062 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010063 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010064 return result;
10065}
10066#endif
10067
10068#if defined(FEAT_WILDIGN) || defined(PROTO)
10069/*
10070 * Return TRUE if a file matches with a pattern in "list".
10071 * "list" is a comma-separated list of patterns, like 'wildignore'.
10072 * "sfname" is the short file name or NULL, "ffname" the long file name.
10073 */
10074 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010075match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010076{
10077 char_u buf[100];
10078 char_u *tail;
10079 char_u *regpat;
10080 char allow_dirs;
10081 int match;
10082 char_u *p;
10083
10084 tail = gettail(sfname);
10085
10086 /* try all patterns in 'wildignore' */
10087 p = list;
10088 while (*p)
10089 {
10090 copy_option_part(&p, buf, 100, ",");
10091 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10092 if (regpat == NULL)
10093 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010094 match = match_file_pat(regpat, NULL, ffname, sfname,
10095 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010096 vim_free(regpat);
10097 if (match)
10098 return TRUE;
10099 }
10100 return FALSE;
10101}
10102#endif
10103
10104/*
10105 * Convert the given pattern "pat" which has shell style wildcards in it, into
10106 * a regular expression, and return the result in allocated memory. If there
10107 * is a directory path separator to be matched, then TRUE is put in
10108 * allow_dirs, otherwise FALSE is put there -- webb.
10109 * Handle backslashes before special characters, like "\*" and "\ ".
10110 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010111 * Returns NULL when out of memory.
10112 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010114file_pat_to_reg_pat(
10115 char_u *pat,
10116 char_u *pat_end, /* first char after pattern or NULL */
10117 char *allow_dirs, /* Result passed back out in here */
10118 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010119{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010120 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010121 char_u *endp;
10122 char_u *reg_pat;
10123 char_u *p;
10124 int i;
10125 int nested = 0;
10126 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010127
10128 if (allow_dirs != NULL)
10129 *allow_dirs = FALSE;
10130 if (pat_end == NULL)
10131 pat_end = pat + STRLEN(pat);
10132
Bram Moolenaar071d4272004-06-13 20:20:40 +000010133 for (p = pat; p < pat_end; p++)
10134 {
10135 switch (*p)
10136 {
10137 case '*':
10138 case '.':
10139 case ',':
10140 case '{':
10141 case '}':
10142 case '~':
10143 size += 2; /* extra backslash */
10144 break;
10145#ifdef BACKSLASH_IN_FILENAME
10146 case '\\':
10147 case '/':
10148 size += 4; /* could become "[\/]" */
10149 break;
10150#endif
10151 default:
10152 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010153# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010154 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010155 {
10156 ++p;
10157 ++size;
10158 }
10159# endif
10160 break;
10161 }
10162 }
10163 reg_pat = alloc(size + 1);
10164 if (reg_pat == NULL)
10165 return NULL;
10166
Bram Moolenaar071d4272004-06-13 20:20:40 +000010167 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010168
10169 if (pat[0] == '*')
10170 while (pat[0] == '*' && pat < pat_end - 1)
10171 pat++;
10172 else
10173 reg_pat[i++] = '^';
10174 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010175 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010176 {
10177 while (endp - pat > 0 && *endp == '*')
10178 endp--;
10179 add_dollar = FALSE;
10180 }
10181 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10182 {
10183 switch (*p)
10184 {
10185 case '*':
10186 reg_pat[i++] = '.';
10187 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010188 while (p[1] == '*') /* "**" matches like "*" */
10189 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190 break;
10191 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010192 case '~':
10193 reg_pat[i++] = '\\';
10194 reg_pat[i++] = *p;
10195 break;
10196 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010197 reg_pat[i++] = '.';
10198 break;
10199 case '\\':
10200 if (p[1] == NUL)
10201 break;
10202#ifdef BACKSLASH_IN_FILENAME
10203 if (!no_bslash)
10204 {
10205 /* translate:
10206 * "\x" to "\\x" e.g., "dir\file"
10207 * "\*" to "\\.*" e.g., "dir\*.c"
10208 * "\?" to "\\." e.g., "dir\??.c"
10209 * "\+" to "\+" e.g., "fileX\+.c"
10210 */
10211 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10212 && p[1] != '+')
10213 {
10214 reg_pat[i++] = '[';
10215 reg_pat[i++] = '\\';
10216 reg_pat[i++] = '/';
10217 reg_pat[i++] = ']';
10218 if (allow_dirs != NULL)
10219 *allow_dirs = TRUE;
10220 break;
10221 }
10222 }
10223#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010224 /* Undo escaping from ExpandEscape():
10225 * foo\?bar -> foo?bar
10226 * foo\%bar -> foo%bar
10227 * foo\,bar -> foo,bar
10228 * foo\ bar -> foo bar
10229 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010230 * regexp.
10231 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010232 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010233 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010234 if (*++p == '?'
10235#ifdef BACKSLASH_IN_FILENAME
10236 && no_bslash
10237#endif
10238 )
10239 reg_pat[i++] = '?';
10240 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010241 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010242 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010243 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010244 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10245 {
10246 reg_pat[i++] = '\\';
10247 reg_pat[i++] = '{';
10248 p += 2;
10249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010250 else
10251 {
10252 if (allow_dirs != NULL && vim_ispathsep(*p)
10253#ifdef BACKSLASH_IN_FILENAME
10254 && (!no_bslash || *p != '\\')
10255#endif
10256 )
10257 *allow_dirs = TRUE;
10258 reg_pat[i++] = '\\';
10259 reg_pat[i++] = *p;
10260 }
10261 break;
10262#ifdef BACKSLASH_IN_FILENAME
10263 case '/':
10264 reg_pat[i++] = '[';
10265 reg_pat[i++] = '\\';
10266 reg_pat[i++] = '/';
10267 reg_pat[i++] = ']';
10268 if (allow_dirs != NULL)
10269 *allow_dirs = TRUE;
10270 break;
10271#endif
10272 case '{':
10273 reg_pat[i++] = '\\';
10274 reg_pat[i++] = '(';
10275 nested++;
10276 break;
10277 case '}':
10278 reg_pat[i++] = '\\';
10279 reg_pat[i++] = ')';
10280 --nested;
10281 break;
10282 case ',':
10283 if (nested)
10284 {
10285 reg_pat[i++] = '\\';
10286 reg_pat[i++] = '|';
10287 }
10288 else
10289 reg_pat[i++] = ',';
10290 break;
10291 default:
10292# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010293 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010294 reg_pat[i++] = *p++;
10295 else
10296# endif
10297 if (allow_dirs != NULL && vim_ispathsep(*p))
10298 *allow_dirs = TRUE;
10299 reg_pat[i++] = *p;
10300 break;
10301 }
10302 }
10303 if (add_dollar)
10304 reg_pat[i++] = '$';
10305 reg_pat[i] = NUL;
10306 if (nested != 0)
10307 {
10308 if (nested < 0)
10309 EMSG(_("E219: Missing {."));
10310 else
10311 EMSG(_("E220: Missing }."));
10312 vim_free(reg_pat);
10313 reg_pat = NULL;
10314 }
10315 return reg_pat;
10316}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010317
10318#if defined(EINTR) || defined(PROTO)
10319/*
10320 * Version of read() that retries when interrupted by EINTR (possibly
10321 * by a SIGWINCH).
10322 */
10323 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010324read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010325{
10326 long ret;
10327
10328 for (;;)
10329 {
10330 ret = vim_read(fd, buf, bufsize);
10331 if (ret >= 0 || errno != EINTR)
10332 break;
10333 }
10334 return ret;
10335}
10336
10337/*
10338 * Version of write() that retries when interrupted by EINTR (possibly
10339 * by a SIGWINCH).
10340 */
10341 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010342write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010343{
10344 long ret = 0;
10345 long wlen;
10346
10347 /* Repeat the write() so long it didn't fail, other than being interrupted
10348 * by a signal. */
10349 while (ret < (long)bufsize)
10350 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010351 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010352 if (wlen < 0)
10353 {
10354 if (errno != EINTR)
10355 break;
10356 }
10357 else
10358 ret += wlen;
10359 }
10360 return ret;
10361}
10362#endif