blob: 23fe504527c000118072479d47a07aea4c7b9da7 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
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
30#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000032# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010033static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000034# endif
35#endif
36#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#endif
39#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020040static 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 +000041#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010042static int set_rw_fname(char_u *fname, char_u *sfname);
43static int msg_add_fileformat(int eol_type);
44static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020045static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010046static int time_differs(long t1, long t2);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010047static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
48static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000049
50# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000051# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000052# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000053
54#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
55# define HAS_BW_FLAGS
56# define FIO_LATIN1 0x01 /* convert Latin1 */
57# define FIO_UTF8 0x02 /* convert UTF-8 */
58# define FIO_UCS2 0x04 /* convert UCS-2 */
59# define FIO_UCS4 0x08 /* convert UCS-4 */
60# define FIO_UTF16 0x10 /* convert UTF-16 */
61# ifdef WIN3264
62# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
63# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
64# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
65# endif
Bram Moolenaard0573012017-10-28 21:11:06 +020066# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000067# define FIO_MACROMAN 0x20 /* convert MacRoman */
68# endif
69# define FIO_ENDIAN_L 0x80 /* little endian */
70# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
71# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
72# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
73# define FIO_ALL -1 /* allow all formats */
74#endif
75
76/* When converting, a read() or write() may leave some bytes to be converted
77 * for the next call. The value is guessed... */
78#define CONV_RESTLEN 30
79
80/* We have to guess how much a sequence of bytes may expand when converting
81 * with iconv() to be able to allocate a buffer. */
82#define ICONV_MULT 8
83
84/*
85 * Structure to pass arguments from buf_write() to buf_write_bytes().
86 */
87struct bw_info
88{
89 int bw_fd; /* file descriptor */
90 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000091 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000092#ifdef HAS_BW_FLAGS
93 int bw_flags; /* FIO_ flags */
94#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020095#ifdef FEAT_CRYPT
96 buf_T *bw_buffer; /* buffer being written */
97#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000098#ifdef FEAT_MBYTE
99 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
100 int bw_restlen; /* nr of bytes in bw_rest[] */
101 int bw_first; /* first write call */
102 char_u *bw_conv_buf; /* buffer for writing converted chars */
103 int bw_conv_buflen; /* size of bw_conv_buf */
104 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000105 linenr_T bw_conv_error_lnum; /* first line with error or zero */
106 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107# ifdef USE_ICONV
108 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
109# endif
110#endif
111};
112
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100113static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114
115#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100116static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
117static int ucs2bytes(unsigned c, char_u **pp, int flags);
118static int need_conversion(char_u *fenc);
119static int get_fio_flags(char_u *ptr);
120static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
121static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000122# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100123static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124# endif
Bram Moolenaard0573012017-10-28 21:11:06 +0200125# ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100126static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# endif
128#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000129static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000130
Bram Moolenaarc3691332016-04-20 12:49:49 +0200131/*
132 * Set by the apply_autocmds_group function if the given event is equal to
133 * EVENT_FILETYPE. Used by the readfile function in order to determine if
134 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
135 *
136 * Relying on this value requires one to reset it prior calling
137 * apply_autocmds_group.
138 */
139static int au_did_filetype INIT(= FALSE);
Bram Moolenaarc3691332016-04-20 12:49:49 +0200140
Bram Moolenaar071d4272004-06-13 20:20:40 +0000141 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100142filemess(
143 buf_T *buf,
144 char_u *name,
145 char_u *s,
146 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147{
148 int msg_scroll_save;
149
150 if (msg_silent != 0)
151 return;
152 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
153 /* If it's extremely long, truncate it. */
154 if (STRLEN(IObuff) > IOSIZE - 80)
155 IObuff[IOSIZE - 80] = NUL;
156 STRCAT(IObuff, s);
157 /*
158 * For the first message may have to start a new line.
159 * For further ones overwrite the previous one, reset msg_scroll before
160 * calling filemess().
161 */
162 msg_scroll_save = msg_scroll;
163 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
164 msg_scroll = FALSE;
165 if (!msg_scroll) /* wait a bit when overwriting an error msg */
166 check_for_delay(FALSE);
167 msg_start();
168 msg_scroll = msg_scroll_save;
169 msg_scrolled_ign = TRUE;
170 /* may truncate the message to avoid a hit-return prompt */
171 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
172 msg_clr_eos();
173 out_flush();
174 msg_scrolled_ign = FALSE;
175}
176
177/*
178 * Read lines from file "fname" into the buffer after line "from".
179 *
180 * 1. We allocate blocks with lalloc, as big as possible.
181 * 2. Each block is filled with characters from the file with a single read().
182 * 3. The lines are inserted in the buffer with ml_append().
183 *
184 * (caller must check that fname != NULL, unless READ_STDIN is used)
185 *
186 * "lines_to_skip" is the number of lines that must be skipped
187 * "lines_to_read" is the number of lines that are appended
188 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
189 *
190 * flags:
191 * READ_NEW starting to edit a new buffer
192 * READ_FILTER reading filter output
193 * READ_STDIN read from stdin instead of a file
194 * READ_BUFFER read from curbuf instead of a file (converting after reading
195 * stdin)
196 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200197 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200198 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000199 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100200 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000201 */
202 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100203readfile(
204 char_u *fname,
205 char_u *sfname,
206 linenr_T from,
207 linenr_T lines_to_skip,
208 linenr_T lines_to_read,
209 exarg_T *eap, /* can be NULL! */
210 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211{
212 int fd = 0;
213 int newfile = (flags & READ_NEW);
214 int check_readonly;
215 int filtering = (flags & READ_FILTER);
216 int read_stdin = (flags & READ_STDIN);
217 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200218 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000219 int set_options = newfile || read_buffer
220 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
222 colnr_T read_buf_col = 0; /* next char to read from this line */
223 char_u c;
224 linenr_T lnum = from;
225 char_u *ptr = NULL; /* pointer into read buffer */
226 char_u *buffer = NULL; /* read buffer */
227 char_u *new_buffer = NULL; /* init to shut up gcc */
228 char_u *line_start = NULL; /* init to shut up gcc */
229 int wasempty; /* buffer was empty before reading */
230 colnr_T len;
231 long size = 0;
232 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200233 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 int skip_read = FALSE;
235#ifdef FEAT_CRYPT
236 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200237 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200239#ifdef FEAT_PERSISTENT_UNDO
240 context_sha256_T sha_ctx;
241 int read_undo_file = FALSE;
242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243 int split = 0; /* number of split lines */
244#define UNKNOWN 0x0fffffff /* file size is unknown */
245 linenr_T linecnt;
246 int error = FALSE; /* errors encountered */
247 int ff_error = EOL_UNKNOWN; /* file format with errors */
248 long linerest = 0; /* remaining chars in line */
249#ifdef UNIX
250 int perm = 0;
251 int swap_mode = -1; /* protection bits for swap file */
252#else
253 int perm;
254#endif
255 int fileformat = 0; /* end-of-line format */
256 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200257 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 int file_readonly;
259 linenr_T skip_count = 0;
260 linenr_T read_count = 0;
261 int msg_save = msg_scroll;
262 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
263 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100264 int try_mac;
265 int try_dos;
266 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000267 int file_rewind = FALSE;
268#ifdef FEAT_MBYTE
269 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000270 linenr_T conv_error = 0; /* line nr with conversion error */
271 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000272 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
273 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000274 int bad_char_behavior = BAD_REPLACE;
275 /* BAD_KEEP, BAD_DROP or character to
276 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277 char_u *tmpname = NULL; /* name of 'charconvert' output file */
278 int fio_flags = 0;
279 char_u *fenc; /* fileencoding to use */
280 int fenc_alloced; /* fenc_next is in allocated memory */
281 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
282 int advance_fenc = FALSE;
283 long real_size = 0;
284# ifdef USE_ICONV
285 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
286# ifdef FEAT_EVAL
287 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
288 'charconvert' next */
289# endif
290# endif
291 int converted = FALSE; /* TRUE if conversion done */
292 int notconverted = FALSE; /* TRUE if conversion wanted but it
293 wasn't possible */
294 char_u conv_rest[CONV_RESTLEN];
295 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
296#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200297 buf_T *old_curbuf;
298 char_u *old_b_ffname;
299 char_u *old_b_fname;
300 int using_b_ffname;
301 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200302
Bram Moolenaarc3691332016-04-20 12:49:49 +0200303 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200304
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100305 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306
307 /*
308 * If there is no file name yet, use the one for the read file.
309 * BF_NOTEDITED is set to reflect this.
310 * Don't do this for a read from a filter.
311 * Only do this when 'cpoptions' contains the 'f' flag.
312 */
313 if (curbuf->b_ffname == NULL
314 && !filtering
315 && fname != NULL
316 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
317 && !(flags & READ_DUMMY))
318 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000319 if (set_rw_fname(fname, sfname) == FAIL)
320 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000321 }
322
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200323 /* Remember the initial values of curbuf, curbuf->b_ffname and
324 * curbuf->b_fname to detect whether they are altered as a result of
325 * executing nasty autocommands. Also check if "fname" and "sfname"
326 * point to one of these values. */
327 old_curbuf = curbuf;
328 old_b_ffname = curbuf->b_ffname;
329 old_b_fname = curbuf->b_fname;
330 using_b_ffname = (fname == curbuf->b_ffname)
331 || (sfname == curbuf->b_ffname);
332 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200333
Bram Moolenaardf177f62005-02-22 08:39:57 +0000334 /* After reading a file the cursor line changes but we don't want to
335 * display the line. */
336 ex_no_reprint = TRUE;
337
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000338 /* don't display the file info for another buffer now */
339 need_fileinfo = FALSE;
340
Bram Moolenaar071d4272004-06-13 20:20:40 +0000341 /*
342 * For Unix: Use the short file name whenever possible.
343 * Avoids problems with networks and when directory names are changed.
344 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
345 * another directory, which we don't detect.
346 */
347 if (sfname == NULL)
348 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200349#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 fname = sfname;
351#endif
352
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 /*
354 * The BufReadCmd and FileReadCmd events intercept the reading process by
355 * executing the associated commands instead.
356 */
357 if (!filtering && !read_stdin && !read_buffer)
358 {
359 pos_T pos;
360
361 pos = curbuf->b_op_start;
362
363 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
364 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
365 curbuf->b_op_start.col = 0;
366
367 if (newfile)
368 {
369 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
370 FALSE, curbuf, eap))
371#ifdef FEAT_EVAL
372 return aborting() ? FAIL : OK;
373#else
374 return OK;
375#endif
376 }
377 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
378 FALSE, NULL, eap))
379#ifdef FEAT_EVAL
380 return aborting() ? FAIL : OK;
381#else
382 return OK;
383#endif
384
385 curbuf->b_op_start = pos;
386 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387
388 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
389 msg_scroll = FALSE; /* overwrite previous file message */
390 else
391 msg_scroll = TRUE; /* don't overwrite previous file message */
392
393 /*
394 * If the name ends in a path separator, we can't open it. Check here,
395 * because reading the file may actually work, but then creating the swap
396 * file may destroy it! Reported on MS-DOS and Win 95.
397 * If the name is too long we might crash further on, quit here.
398 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000399 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000401 p = fname + STRLEN(fname);
402 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000403 {
404 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
405 msg_end();
406 msg_scroll = msg_save;
407 return FAIL;
408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 }
410
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200411 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200413#ifdef UNIX
414 /*
415 * On Unix it is possible to read a directory, so we have to
416 * check for it before the mch_open().
417 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 perm = mch_getperm(fname);
419 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 && !S_ISFIFO(perm) /* ... or fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 && !S_ISSOCK(perm) /* ... or socket */
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000422# ifdef OPEN_CHR_FILES
423 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
424 /* ... or a character special file named /dev/fd/<n> */
425# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 )
427 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100428 int retval = FAIL;
429
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100431 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100433 retval = NOTDONE;
434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 else
436 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
437 msg_end();
438 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100439 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200441#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100442#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000443 /*
444 * MS-Windows allows opening a device, but we will probably get stuck
445 * trying to read it.
446 */
447 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
448 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000449 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000450 msg_end();
451 msg_scroll = msg_save;
452 return FAIL;
453 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000454#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200455 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000456
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200457 /* Set default or forced 'fileformat' and 'binary'. */
458 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
460 /*
461 * When opening a new file we take the readonly flag from the file.
462 * Default is r/w, can be set to r/o below.
463 * Don't reset it when in readonly mode
464 * Only set/reset b_p_ro when BF_CHECK_RO is set.
465 */
466 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000467 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468 curbuf->b_p_ro = FALSE;
469
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200470 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200472 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 if (mch_stat((char *)fname, &st) >= 0)
474 {
475 buf_store_time(curbuf, &st, fname);
476 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477#ifdef UNIX
478 /*
479 * Use the protection bits of the original file for the swap file.
480 * This makes it possible for others to read the name of the
481 * edited file from the swapfile, but only if they can read the
482 * edited file.
483 * Remove the "write" and "execute" bits for group and others
484 * (they must not write the swapfile).
485 * Add the "read" and "write" bits for the user, otherwise we may
486 * not be able to write to the file ourselves.
487 * Setting the bits is done below, after creating the swap file.
488 */
489 swap_mode = (st.st_mode & 0644) | 0600;
490#endif
491#ifdef FEAT_CW_EDITOR
492 /* Get the FSSpec on MacOS
493 * TODO: Update it properly when the buffer name changes
494 */
495 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
496#endif
497#ifdef VMS
498 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000499 curbuf->b_fab_rat = st.st_fab_rat;
500 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501#endif
502 }
503 else
504 {
505 curbuf->b_mtime = 0;
506 curbuf->b_mtime_read = 0;
507 curbuf->b_orig_size = 0;
508 curbuf->b_orig_mode = 0;
509 }
510
511 /* Reset the "new file" flag. It will be set again below when the
512 * file doesn't exist. */
513 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
514 }
515
516/*
517 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100518 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 */
520 file_readonly = FALSE;
521 if (read_stdin)
522 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100523#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
525 setmode(0, O_BINARY);
526#endif
527 }
528 else if (!read_buffer)
529 {
530#ifdef USE_MCH_ACCESS
531 if (
532# ifdef UNIX
533 !(perm & 0222) ||
534# endif
535 mch_access((char *)fname, W_OK))
536 file_readonly = TRUE;
537 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
538#else
539 if (!newfile
540 || readonlymode
541 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
542 {
543 file_readonly = TRUE;
544 /* try to open ro */
545 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
546 }
547#endif
548 }
549
550 if (fd < 0) /* cannot open at all */
551 {
552#ifndef UNIX
553 int isdir_f;
554#endif
555 msg_scroll = msg_save;
556#ifndef UNIX
557 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100558 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 */
560 isdir_f = (mch_isdir(fname));
561 perm = mch_getperm(fname); /* check if the file exists */
562 if (isdir_f)
563 {
564 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
565 curbuf->b_p_ro = TRUE; /* must use "w!" now */
566 }
567 else
568#endif
569 if (newfile)
570 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200571 if (perm < 0
572#ifdef ENOENT
573 && errno == ENOENT
574#endif
575 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 {
577 /*
578 * Set the 'new-file' flag, so that when the file has
579 * been created by someone else, a ":w" will complain.
580 */
581 curbuf->b_flags |= BF_NEW;
582
583 /* Create a swap file now, so that other Vims are warned
584 * that we are editing this file. Don't do this for a
585 * "nofile" or "nowrite" buffer type. */
586#ifdef FEAT_QUICKFIX
587 if (!bt_dontwrite(curbuf))
588#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000589 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000591 /* SwapExists autocommand may mess things up */
592 if (curbuf != old_curbuf
593 || (using_b_ffname
594 && (old_b_ffname != curbuf->b_ffname))
595 || (using_b_fname
596 && (old_b_fname != curbuf->b_fname)))
597 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100598 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000599 return FAIL;
600 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000601 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000602 if (dir_of_file_exists(fname))
603 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
604 else
605 filemess(curbuf, sfname,
606 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607#ifdef FEAT_VIMINFO
608 /* Even though this is a new file, it might have been
609 * edited before and deleted. Get the old marks. */
610 check_marks_read();
611#endif
612#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200613 /* Set forced 'fileencoding'. */
614 if (eap != NULL)
615 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
618 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 /* remember the current fileformat */
620 save_file_ff(curbuf);
621
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100622#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 if (aborting()) /* autocmds may abort script processing */
624 return FAIL;
625#endif
626 return OK; /* a new file is not an error */
627 }
628 else
629 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000630 filemess(curbuf, sfname, (char_u *)(
631# ifdef EFBIG
632 (errno == EFBIG) ? _("[File too big]") :
633# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200634# ifdef EOVERFLOW
635 (errno == EOVERFLOW) ? _("[File too big]") :
636# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000637 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 curbuf->b_p_ro = TRUE; /* must use "w!" now */
639 }
640 }
641
642 return FAIL;
643 }
644
645 /*
646 * Only set the 'ro' flag for readonly files the first time they are
647 * loaded. Help files always get readonly mode
648 */
649 if ((check_readonly && file_readonly) || curbuf->b_help)
650 curbuf->b_p_ro = TRUE;
651
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000652 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000654 /* Don't change 'eol' if reading from buffer as it will already be
655 * correctly set when reading stdin. */
656 if (!read_buffer)
657 {
658 curbuf->b_p_eol = TRUE;
659 curbuf->b_start_eol = TRUE;
660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661#ifdef FEAT_MBYTE
662 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000663 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664#endif
665 }
666
667 /* Create a swap file now, so that other Vims are warned that we are
668 * editing this file.
669 * Don't do this for a "nofile" or "nowrite" buffer type. */
670#ifdef FEAT_QUICKFIX
671 if (!bt_dontwrite(curbuf))
672#endif
673 {
674 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000675 if (!read_stdin && (curbuf != old_curbuf
676 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
677 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
678 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100679 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000680 if (!read_buffer)
681 close(fd);
682 return FAIL;
683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684#ifdef UNIX
685 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000686 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
687 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100688 {
689 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
690
691 /*
692 * If the group-read bit is set but not the world-read bit, then
693 * the group must be equal to the group of the original file. If
694 * we can't make that happen then reset the group-read bit. This
695 * avoids making the swap file readable to more users when the
696 * primary group of the user is too permissive.
697 */
698 if ((swap_mode & 044) == 040)
699 {
700 stat_T swap_st;
701
702 if (mch_stat((char *)swap_fname, &swap_st) >= 0
703 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200704# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100705 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200706 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200707# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200708 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100709 swap_mode &= 0600;
710 }
711
712 (void)mch_setperm(swap_fname, (long)swap_mode);
713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714#endif
715 }
716
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000717#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 /* If "Quit" selected at ATTENTION dialog, don't load the file */
719 if (swap_exists_action == SEA_QUIT)
720 {
721 if (!read_buffer && !read_stdin)
722 close(fd);
723 return FAIL;
724 }
725#endif
726
727 ++no_wait_return; /* don't wait for return yet */
728
729 /*
730 * Set '[ mark to the line above where the lines go (line 1 if zero).
731 */
732 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
733 curbuf->b_op_start.col = 0;
734
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100735 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
736 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
737 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
738
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 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);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100769 /* autocommands may have changed it */
770 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
771 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
772 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
773
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774 if (msg_scrolled == n)
775 msg_scroll = m;
776
777#ifdef FEAT_EVAL
778 if (aborting()) /* autocmds may abort script processing */
779 {
780 --no_wait_return;
781 msg_scroll = msg_save;
782 curbuf->b_p_ro = TRUE; /* must use "w!" now */
783 return FAIL;
784 }
785#endif
786 /*
787 * Don't allow the autocommands to change the current buffer.
788 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000789 *
790 * Don't allow the autocommands to change the buffer name either
791 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792 */
793 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000794 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
795 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
797 {
798 --no_wait_return;
799 msg_scroll = msg_save;
800 if (fd < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100801 emsg(_("E200: *ReadPre autocommands made the file unreadable"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100803 emsg(_("E201: *ReadPre autocommands must not change current buffer"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 curbuf->b_p_ro = TRUE; /* must use "w!" now */
805 return FAIL;
806 }
807 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808
809 /* Autocommands may add lines to the file, need to check if it is empty */
810 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
811
812 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
813 {
814 /*
815 * Show the user that we are busy reading the input. Sometimes this
816 * may take a while. When reading from stdin another program may
817 * still be running, don't move the cursor to the last line, unless
818 * always using the GUI.
819 */
820 if (read_stdin)
821 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100822 if (!is_not_a_term())
823 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100825 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826#endif
827#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100828 /* Also write a message in the GUI window, if there is one. */
829 if (gui.in_use && !gui.dying && !gui.starting)
830 {
831 p = (char_u *)_("Reading from stdin...");
832 gui_write(p, (int)STRLEN(p));
833 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100835 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836 }
837 else if (!read_buffer)
838 filemess(curbuf, sfname, (char_u *)"", 0);
839 }
840
841 msg_scroll = FALSE; /* overwrite the file message */
842
843 /*
844 * Set linecnt now, before the "retry" caused by a wrong guess for
845 * fileformat, and after the autocommands, which may change them.
846 */
847 linecnt = curbuf->b_ml.ml_line_count;
848
849#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000850 /* "++bad=" argument. */
851 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000852 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000853 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000854 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000855 curbuf->b_bad_char = eap->bad_char;
856 }
857 else
858 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000859
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000861 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 */
863 if (eap != NULL && eap->force_enc != 0)
864 {
865 fenc = enc_canonize(eap->cmd + eap->force_enc);
866 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000867 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868 }
869 else if (curbuf->b_p_bin)
870 {
871 fenc = (char_u *)""; /* binary: don't convert */
872 fenc_alloced = FALSE;
873 }
874 else if (curbuf->b_help)
875 {
876 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000877 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878
879 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
880 * fails it must be latin1.
881 * Always do this when 'encoding' is "utf-8". Otherwise only do
882 * this when needed to avoid [converted] remarks all the time.
883 * It is needed when the first line contains non-ASCII characters.
884 * That is only in *.??x files. */
885 fenc = (char_u *)"latin1";
886 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000887 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000889 fc = fname[STRLEN(fname) - 1];
890 if (TOLOWER_ASC(fc) == 'x')
891 {
892 /* Read the first line (and a bit more). Immediately rewind to
893 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100894 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200895 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000896 for (p = firstline; p < firstline + len; ++p)
897 if (*p >= 0x80)
898 {
899 c = TRUE;
900 break;
901 }
902 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903 }
904
905 if (c)
906 {
907 fenc_next = fenc;
908 fenc = (char_u *)"utf-8";
909
910 /* When the file is utf-8 but a character doesn't fit in
911 * 'encoding' don't retry. In help text editing utf-8 bytes
912 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000913 if (!enc_utf8)
914 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 }
916 fenc_alloced = FALSE;
917 }
918 else if (*p_fencs == NUL)
919 {
920 fenc = curbuf->b_p_fenc; /* use format from buffer */
921 fenc_alloced = FALSE;
922 }
923 else
924 {
925 fenc_next = p_fencs; /* try items in 'fileencodings' */
926 fenc = next_fenc(&fenc_next);
927 fenc_alloced = TRUE;
928 }
929#endif
930
931 /*
932 * Jump back here to retry reading the file in different ways.
933 * Reasons to retry:
934 * - encoding conversion failed: try another one from "fenc_next"
935 * - BOM detected and fenc was set, need to setup conversion
936 * - "fileformat" check failed: try another
937 *
938 * Variables set for special retry actions:
939 * "file_rewind" Rewind the file to start reading it again.
940 * "advance_fenc" Advance "fenc" using "fenc_next".
941 * "skip_read" Re-use already read bytes (BOM detected).
942 * "did_iconv" iconv() conversion failed, try 'charconvert'.
943 * "keep_fileformat" Don't reset "fileformat".
944 *
945 * Other status indicators:
946 * "tmpname" When != NULL did conversion with 'charconvert'.
947 * Output file has to be deleted afterwards.
948 * "iconv_fd" When != -1 did conversion with iconv().
949 */
950retry:
951
952 if (file_rewind)
953 {
954 if (read_buffer)
955 {
956 read_buf_lnum = 1;
957 read_buf_col = 0;
958 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200959 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 {
961 /* Can't rewind the file, give up. */
962 error = TRUE;
963 goto failed;
964 }
965 /* Delete the previously read lines. */
966 while (lnum > from)
967 ml_delete(lnum--, FALSE);
968 file_rewind = FALSE;
969#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000970 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000971 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000973 curbuf->b_start_bomb = FALSE;
974 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000975 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976#endif
977 }
978
979 /*
980 * When retrying with another "fenc" and the first time "fileformat"
981 * will be reset.
982 */
983 if (keep_fileformat)
984 keep_fileformat = FALSE;
985 else
986 {
987 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000988 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000990 try_unix = try_dos = try_mac = FALSE;
991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 else if (curbuf->b_p_bin)
993 fileformat = EOL_UNIX; /* binary: use Unix format */
994 else if (*p_ffs == NUL)
995 fileformat = get_fileformat(curbuf);/* use format from buffer */
996 else
997 fileformat = EOL_UNKNOWN; /* detect from file */
998 }
999
1000#ifdef FEAT_MBYTE
1001# ifdef USE_ICONV
1002 if (iconv_fd != (iconv_t)-1)
1003 {
1004 /* aborted conversion with iconv(), close the descriptor */
1005 iconv_close(iconv_fd);
1006 iconv_fd = (iconv_t)-1;
1007 }
1008# endif
1009
1010 if (advance_fenc)
1011 {
1012 /*
1013 * Try the next entry in 'fileencodings'.
1014 */
1015 advance_fenc = FALSE;
1016
1017 if (eap != NULL && eap->force_enc != 0)
1018 {
1019 /* Conversion given with "++cc=" wasn't possible, read
1020 * without conversion. */
1021 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001022 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 if (fenc_alloced)
1024 vim_free(fenc);
1025 fenc = (char_u *)"";
1026 fenc_alloced = FALSE;
1027 }
1028 else
1029 {
1030 if (fenc_alloced)
1031 vim_free(fenc);
1032 if (fenc_next != NULL)
1033 {
1034 fenc = next_fenc(&fenc_next);
1035 fenc_alloced = (fenc_next != NULL);
1036 }
1037 else
1038 {
1039 fenc = (char_u *)"";
1040 fenc_alloced = FALSE;
1041 }
1042 }
1043 if (tmpname != NULL)
1044 {
1045 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001046 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 }
1048 }
1049
1050 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001051 * Conversion may be required when the encoding of the file is different
1052 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 */
1054 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001055 converted = need_conversion(fenc);
1056 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 {
1058
1059 /* "ucs-bom" means we need to check the first bytes of the file
1060 * for a BOM. */
1061 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1062 fio_flags = FIO_UCSBOM;
1063
1064 /*
1065 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1066 * done. This is handled below after read(). Prepare the
1067 * fio_flags to avoid having to parse the string each time.
1068 * Also check for Unicode to Latin1 conversion, because iconv()
1069 * appears not to handle this correctly. This works just like
1070 * conversion to UTF-8 except how the resulting character is put in
1071 * the buffer.
1072 */
1073 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1074 fio_flags = get_fio_flags(fenc);
1075
1076# ifdef WIN3264
1077 /*
1078 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1079 * is handled with MultiByteToWideChar().
1080 */
1081 if (fio_flags == 0)
1082 fio_flags = get_win_fio_flags(fenc);
1083# endif
1084
Bram Moolenaard0573012017-10-28 21:11:06 +02001085# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1087 if (fio_flags == 0)
1088 fio_flags = get_mac_fio_flags(fenc);
1089# endif
1090
1091# ifdef USE_ICONV
1092 /*
1093 * Try using iconv() if we can't convert internally.
1094 */
1095 if (fio_flags == 0
1096# ifdef FEAT_EVAL
1097 && !did_iconv
1098# endif
1099 )
1100 iconv_fd = (iconv_t)my_iconv_open(
1101 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1102# endif
1103
1104# ifdef FEAT_EVAL
1105 /*
1106 * Use the 'charconvert' expression when conversion is required
1107 * and we can't do it internally or with iconv().
1108 */
1109 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001110 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111# ifdef USE_ICONV
1112 && iconv_fd == (iconv_t)-1
1113# endif
1114 )
1115 {
1116# ifdef USE_ICONV
1117 did_iconv = FALSE;
1118# endif
1119 /* Skip conversion when it's already done (retry for wrong
1120 * "fileformat"). */
1121 if (tmpname == NULL)
1122 {
1123 tmpname = readfile_charconvert(fname, fenc, &fd);
1124 if (tmpname == NULL)
1125 {
1126 /* Conversion failed. Try another one. */
1127 advance_fenc = TRUE;
1128 if (fd < 0)
1129 {
1130 /* Re-opening the original file failed! */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001131 emsg(_("E202: Conversion made file unreadable!"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132 error = TRUE;
1133 goto failed;
1134 }
1135 goto retry;
1136 }
1137 }
1138 }
1139 else
1140# endif
1141 {
1142 if (fio_flags == 0
1143# ifdef USE_ICONV
1144 && iconv_fd == (iconv_t)-1
1145# endif
1146 )
1147 {
1148 /* Conversion wanted but we can't.
1149 * Try the next conversion in 'fileencodings' */
1150 advance_fenc = TRUE;
1151 goto retry;
1152 }
1153 }
1154 }
1155
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001156 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001158 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001159 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160#endif
1161
1162 if (!skip_read)
1163 {
1164 linerest = 0;
1165 filesize = 0;
1166 skip_count = lines_to_skip;
1167 read_count = lines_to_read;
1168#ifdef FEAT_MBYTE
1169 conv_restlen = 0;
1170#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001171#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001172 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1173 && curbuf->b_ffname != NULL
1174 && curbuf->b_p_udf
1175 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001176 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001177 && !read_stdin
1178 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001179 if (read_undo_file)
1180 sha256_start(&sha_ctx);
1181#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001182#ifdef FEAT_CRYPT
1183 if (curbuf->b_cryptstate != NULL)
1184 {
1185 /* Need to free the state, but keep the key, don't want to ask for
1186 * it again. */
1187 crypt_free_state(curbuf->b_cryptstate);
1188 curbuf->b_cryptstate = NULL;
1189 }
1190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 }
1192
1193 while (!error && !got_int)
1194 {
1195 /*
1196 * We allocate as much space for the file as we can get, plus
1197 * space for the old line plus room for one terminating NUL.
1198 * The amount is limited by the fact that read() only can read
1199 * upto max_unsigned characters (and other things).
1200 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001201 if (!skip_read)
1202 {
1203#if VIM_SIZEOF_INT > 2
1204# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
1205 size = SSIZE_MAX; /* use max I/O size, 52K */
1206# else
1207 /* Use buffer >= 64K. Add linerest to double the size if the
1208 * line gets very long, to avoid a lot of copying. But don't
1209 * read more than 1 Mbyte at a time, so we can be interrupted.
1210 */
1211 size = 0x10000L + linerest;
1212 if (size > 0x100000L)
1213 size = 0x100000L;
1214# endif
1215#else
1216 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1217#endif
1218 }
1219
1220 /* Protect against the argument of lalloc() going negative. */
1221 if (
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001222#if VIM_SIZEOF_INT <= 2
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001223 linerest >= 0x7ff0
1224#else
1225 size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL
1226#endif
1227 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228 {
1229 ++split;
1230 *ptr = NL; /* split line by inserting a NL */
1231 size = 1;
1232 }
1233 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 {
1235 if (!skip_read)
1236 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001237 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 {
1239 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1240 FALSE)) != NULL)
1241 break;
1242 }
1243 if (new_buffer == NULL)
1244 {
1245 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1246 error = TRUE;
1247 break;
1248 }
1249 if (linerest) /* copy characters from the previous buffer */
1250 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1251 vim_free(buffer);
1252 buffer = new_buffer;
1253 ptr = buffer + linerest;
1254 line_start = buffer;
1255
1256#ifdef FEAT_MBYTE
1257 /* May need room to translate into.
1258 * For iconv() we don't really know the required space, use a
1259 * factor ICONV_MULT.
1260 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1261 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1262 * become up to 4 bytes, size must be multiple of 2
1263 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1264 * multiple of 2
1265 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1266 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001267 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268# ifdef USE_ICONV
1269 if (iconv_fd != (iconv_t)-1)
1270 size = size / ICONV_MULT;
1271 else
1272# endif
1273 if (fio_flags & FIO_LATIN1)
1274 size = size / 2;
1275 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1276 size = (size * 2 / 3) & ~1;
1277 else if (fio_flags & FIO_UCS4)
1278 size = (size * 2 / 3) & ~3;
1279 else if (fio_flags == FIO_UCSBOM)
1280 size = size / ICONV_MULT; /* worst case */
1281# ifdef WIN3264
1282 else if (fio_flags & FIO_CODEPAGE)
1283 size = size / ICONV_MULT; /* also worst case */
1284# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001285# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 else if (fio_flags & FIO_MACROMAN)
1287 size = size / ICONV_MULT; /* also worst case */
1288# endif
1289#endif
1290
1291#ifdef FEAT_MBYTE
1292 if (conv_restlen > 0)
1293 {
1294 /* Insert unconverted bytes from previous line. */
1295 mch_memmove(ptr, conv_rest, conv_restlen);
1296 ptr += conv_restlen;
1297 size -= conv_restlen;
1298 }
1299#endif
1300
1301 if (read_buffer)
1302 {
1303 /*
1304 * Read bytes from curbuf. Used for converting text read
1305 * from stdin.
1306 */
1307 if (read_buf_lnum > from)
1308 size = 0;
1309 else
1310 {
1311 int n, ni;
1312 long tlen;
1313
1314 tlen = 0;
1315 for (;;)
1316 {
1317 p = ml_get(read_buf_lnum) + read_buf_col;
1318 n = (int)STRLEN(p);
1319 if ((int)tlen + n + 1 > size)
1320 {
1321 /* Filled up to "size", append partial line.
1322 * Change NL to NUL to reverse the effect done
1323 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001324 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 for (ni = 0; ni < n; ++ni)
1326 {
1327 if (p[ni] == NL)
1328 ptr[tlen++] = NUL;
1329 else
1330 ptr[tlen++] = p[ni];
1331 }
1332 read_buf_col += n;
1333 break;
1334 }
1335 else
1336 {
1337 /* Append whole line and new-line. Change NL
1338 * to NUL to reverse the effect done below. */
1339 for (ni = 0; ni < n; ++ni)
1340 {
1341 if (p[ni] == NL)
1342 ptr[tlen++] = NUL;
1343 else
1344 ptr[tlen++] = p[ni];
1345 }
1346 ptr[tlen++] = NL;
1347 read_buf_col = 0;
1348 if (++read_buf_lnum > from)
1349 {
1350 /* When the last line didn't have an
1351 * end-of-line don't add it now either. */
1352 if (!curbuf->b_p_eol)
1353 --tlen;
1354 size = tlen;
1355 break;
1356 }
1357 }
1358 }
1359 }
1360 }
1361 else
1362 {
1363 /*
1364 * Read bytes from the file.
1365 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001366 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 }
1368
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001369#ifdef FEAT_CRYPT
1370 /*
1371 * At start of file: Check for magic number of encryption.
1372 */
1373 if (filesize == 0 && size > 0)
1374 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1375 &filesize, newfile, sfname,
1376 &did_ask_for_key);
1377 /*
1378 * Decrypt the read bytes. This is done before checking for
1379 * EOF because the crypt layer may be buffering.
1380 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001381 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1382 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001383 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001384# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001385 if (crypt_works_inplace(curbuf->b_cryptstate))
1386 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001387# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001388 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
Bram Moolenaar987411d2019-01-18 22:48:34 +01001389# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001390 }
1391 else
1392 {
1393 char_u *newptr = NULL;
1394 int decrypted_size;
1395
1396 decrypted_size = crypt_decode_alloc(
1397 curbuf->b_cryptstate, ptr, size, &newptr);
1398
1399 /* If the crypt layer is buffering, not producing
1400 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001401 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001402 continue;
1403
1404 if (linerest == 0)
1405 {
1406 /* Simple case: reuse returned buffer (may be
1407 * NULL, checked later). */
1408 new_buffer = newptr;
1409 }
1410 else
1411 {
1412 long_u new_size;
1413
1414 /* Need new buffer to add bytes carried over. */
1415 new_size = (long_u)(decrypted_size + linerest + 1);
1416 new_buffer = lalloc(new_size, FALSE);
1417 if (new_buffer == NULL)
1418 {
1419 do_outofmem_msg(new_size);
1420 error = TRUE;
1421 break;
1422 }
1423
1424 mch_memmove(new_buffer, buffer, linerest);
1425 if (newptr != NULL)
1426 mch_memmove(new_buffer + linerest, newptr,
1427 decrypted_size);
1428 }
1429
1430 if (new_buffer != NULL)
1431 {
1432 vim_free(buffer);
1433 buffer = new_buffer;
1434 new_buffer = NULL;
1435 line_start = buffer;
1436 ptr = buffer + linerest;
1437 }
1438 size = decrypted_size;
1439 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01001440# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001441 }
1442#endif
1443
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444 if (size <= 0)
1445 {
1446 if (size < 0) /* read error */
1447 error = TRUE;
1448#ifdef FEAT_MBYTE
1449 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001450 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001451 /*
1452 * Reached end-of-file but some trailing bytes could
1453 * not be converted. Truncated file?
1454 */
1455
1456 /* When we did a conversion report an error. */
1457 if (fio_flags != 0
1458# ifdef USE_ICONV
1459 || iconv_fd != (iconv_t)-1
1460# endif
1461 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001462 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001463 if (can_retry)
1464 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001465 if (conv_error == 0)
1466 conv_error = curbuf->b_ml.ml_line_count
1467 - linecnt + 1;
1468 }
1469 /* Remember the first linenr with an illegal byte */
1470 else if (illegal_byte == 0)
1471 illegal_byte = curbuf->b_ml.ml_line_count
1472 - linecnt + 1;
1473 if (bad_char_behavior == BAD_DROP)
1474 {
1475 *(ptr - conv_restlen) = NUL;
1476 conv_restlen = 0;
1477 }
1478 else
1479 {
1480 /* Replace the trailing bytes with the replacement
1481 * character if we were converting; if we weren't,
1482 * leave the UTF8 checking code to do it, as it
1483 * works slightly differently. */
1484 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1485# ifdef USE_ICONV
1486 || iconv_fd != (iconv_t)-1
1487# endif
1488 ))
1489 {
1490 while (conv_restlen > 0)
1491 {
1492 *(--ptr) = bad_char_behavior;
1493 --conv_restlen;
1494 }
1495 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001496 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001497# ifdef USE_ICONV
1498 if (iconv_fd != (iconv_t)-1)
1499 {
1500 iconv_close(iconv_fd);
1501 iconv_fd = (iconv_t)-1;
1502 }
1503# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001504 }
1505 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506#endif
1507 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508 }
1509 skip_read = FALSE;
1510
1511#ifdef FEAT_MBYTE
1512 /*
1513 * At start of file (or after crypt magic number): Check for BOM.
1514 * Also check for a BOM for other Unicode encodings, but not after
1515 * converting with 'charconvert' or when a BOM has already been
1516 * found.
1517 */
1518 if ((filesize == 0
1519# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001520 || (cryptkey != NULL
1521 && filesize == crypt_get_header_len(
1522 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523# endif
1524 )
1525 && (fio_flags == FIO_UCSBOM
1526 || (!curbuf->b_p_bomb
1527 && tmpname == NULL
1528 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1529 {
1530 char_u *ccname;
1531 int blen;
1532
1533 /* no BOM detection in a short file or in binary mode */
1534 if (size < 2 || curbuf->b_p_bin)
1535 ccname = NULL;
1536 else
1537 ccname = check_for_bom(ptr, size, &blen,
1538 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1539 if (ccname != NULL)
1540 {
1541 /* Remove BOM from the text */
1542 filesize += blen;
1543 size -= blen;
1544 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001545 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001546 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001548 curbuf->b_start_bomb = TRUE;
1549 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 }
1551
1552 if (fio_flags == FIO_UCSBOM)
1553 {
1554 if (ccname == NULL)
1555 {
1556 /* No BOM detected: retry with next encoding. */
1557 advance_fenc = TRUE;
1558 }
1559 else
1560 {
1561 /* BOM detected: set "fenc" and jump back */
1562 if (fenc_alloced)
1563 vim_free(fenc);
1564 fenc = ccname;
1565 fenc_alloced = FALSE;
1566 }
1567 /* retry reading without getting new bytes or rewinding */
1568 skip_read = TRUE;
1569 goto retry;
1570 }
1571 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001572
1573 /* Include not converted bytes. */
1574 ptr -= conv_restlen;
1575 size += conv_restlen;
1576 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577#endif
1578 /*
1579 * Break here for a read error or end-of-file.
1580 */
1581 if (size <= 0)
1582 break;
1583
1584#ifdef FEAT_MBYTE
1585
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586# ifdef USE_ICONV
1587 if (iconv_fd != (iconv_t)-1)
1588 {
1589 /*
1590 * Attempt conversion of the read bytes to 'encoding' using
1591 * iconv().
1592 */
1593 const char *fromp;
1594 char *top;
1595 size_t from_size;
1596 size_t to_size;
1597
1598 fromp = (char *)ptr;
1599 from_size = size;
1600 ptr += size;
1601 top = (char *)ptr;
1602 to_size = real_size - size;
1603
1604 /*
1605 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001606 * another conversion. Except for when there is no
1607 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001609 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1610 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1612 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001613 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001614 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001615 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001616 if (conv_error == 0)
1617 conv_error = readfile_linenr(linecnt,
1618 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001619
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001620 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001621 ++fromp;
1622 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001623 if (bad_char_behavior == BAD_KEEP)
1624 {
1625 *top++ = *(fromp - 1);
1626 --to_size;
1627 }
1628 else if (bad_char_behavior != BAD_DROP)
1629 {
1630 *top++ = bad_char_behavior;
1631 --to_size;
1632 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001633 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634
1635 if (from_size > 0)
1636 {
1637 /* Some remaining characters, keep them for the next
1638 * round. */
1639 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1640 conv_restlen = (int)from_size;
1641 }
1642
1643 /* move the linerest to before the converted characters */
1644 line_start = ptr - linerest;
1645 mch_memmove(line_start, buffer, (size_t)linerest);
1646 size = (long)((char_u *)top - ptr);
1647 }
1648# endif
1649
1650# ifdef WIN3264
1651 if (fio_flags & FIO_CODEPAGE)
1652 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001653 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001654 WCHAR ucs2buf[3];
1655 int ucs2len;
1656 int codepage = FIO_GET_CP(fio_flags);
1657 int bytelen;
1658 int found_bad;
1659 char replstr[2];
1660
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 /*
1662 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001663 * a codepage, using standard MS-Windows functions. This
1664 * requires two steps:
1665 * 1. convert from 'fileencoding' to ucs-2
1666 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001668 * Because there may be illegal bytes AND an incomplete byte
1669 * sequence at the end, we may have to do the conversion one
1670 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001673 /* Replacement string for WideCharToMultiByte(). */
1674 if (bad_char_behavior > 0)
1675 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 replstr[0] = '?';
1678 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679
1680 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001681 * Move the bytes to the end of the buffer, so that we have
1682 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001684 src = ptr + real_size - size;
1685 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001687 /*
1688 * Do the conversion.
1689 */
1690 dst = ptr;
1691 size = size;
1692 while (size > 0)
1693 {
1694 found_bad = FALSE;
1695
1696# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1697 if (codepage == CP_UTF8)
1698 {
1699 /* Handle CP_UTF8 input ourselves to be able to handle
1700 * trailing bytes properly.
1701 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001702 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001703 if (bytelen > size)
1704 {
1705 /* Only got some bytes of a character. Normally
1706 * it's put in "conv_rest", but if it's too long
1707 * deal with it as if they were illegal bytes. */
1708 if (bytelen <= CONV_RESTLEN)
1709 break;
1710
1711 /* weird overlong byte sequence */
1712 bytelen = size;
1713 found_bad = TRUE;
1714 }
1715 else
1716 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001717 int u8c = utf_ptr2char(src);
1718
Bram Moolenaar86e01082005-12-29 22:45:34 +00001719 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001720 found_bad = TRUE;
1721 ucs2buf[0] = u8c;
1722 ucs2len = 1;
1723 }
1724 }
1725 else
1726# endif
1727 {
1728 /* We don't know how long the byte sequence is, try
1729 * from one to three bytes. */
1730 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1731 ++bytelen)
1732 {
1733 ucs2len = MultiByteToWideChar(codepage,
1734 MB_ERR_INVALID_CHARS,
1735 (LPCSTR)src, bytelen,
1736 ucs2buf, 3);
1737 if (ucs2len > 0)
1738 break;
1739 }
1740 if (ucs2len == 0)
1741 {
1742 /* If we have only one byte then it's probably an
1743 * incomplete byte sequence. Otherwise discard
1744 * one byte as a bad character. */
1745 if (size == 1)
1746 break;
1747 found_bad = TRUE;
1748 bytelen = 1;
1749 }
1750 }
1751
1752 if (!found_bad)
1753 {
1754 int i;
1755
1756 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1757 if (enc_utf8)
1758 {
1759 /* From UCS-2 to UTF-8. Cannot fail. */
1760 for (i = 0; i < ucs2len; ++i)
1761 dst += utf_char2bytes(ucs2buf[i], dst);
1762 }
1763 else
1764 {
1765 BOOL bad = FALSE;
1766 int dstlen;
1767
1768 /* From UCS-2 to "enc_codepage". If the
1769 * conversion uses the default character "?",
1770 * the data doesn't fit in this encoding. */
1771 dstlen = WideCharToMultiByte(enc_codepage, 0,
1772 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001773 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001774 replstr, &bad);
1775 if (bad)
1776 found_bad = TRUE;
1777 else
1778 dst += dstlen;
1779 }
1780 }
1781
1782 if (found_bad)
1783 {
1784 /* Deal with bytes we can't convert. */
1785 if (can_retry)
1786 goto rewind_retry;
1787 if (conv_error == 0)
1788 conv_error = readfile_linenr(linecnt, ptr, dst);
1789 if (bad_char_behavior != BAD_DROP)
1790 {
1791 if (bad_char_behavior == BAD_KEEP)
1792 {
1793 mch_memmove(dst, src, bytelen);
1794 dst += bytelen;
1795 }
1796 else
1797 *dst++ = bad_char_behavior;
1798 }
1799 }
1800
1801 src += bytelen;
1802 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001804
1805 if (size > 0)
1806 {
1807 /* An incomplete byte sequence remaining. */
1808 mch_memmove(conv_rest, src, size);
1809 conv_restlen = size;
1810 }
1811
1812 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001813 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 }
1815 else
1816# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001817# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 if (fio_flags & FIO_MACROMAN)
1819 {
1820 /*
1821 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001822 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001824 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 }
1827 else
1828# endif
1829 if (fio_flags != 0)
1830 {
1831 int u8c;
1832 char_u *dest;
1833 char_u *tail = NULL;
1834
1835 /*
1836 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1837 * "enc_utf8" not set: Convert Unicode to Latin1.
1838 * Go from end to start through the buffer, because the number
1839 * of bytes may increase.
1840 * "dest" points to after where the UTF-8 bytes go, "p" points
1841 * to after the next character to convert.
1842 */
1843 dest = ptr + real_size;
1844 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1845 {
1846 p = ptr + size;
1847 if (fio_flags == FIO_UTF8)
1848 {
1849 /* Check for a trailing incomplete UTF-8 sequence */
1850 tail = ptr + size - 1;
1851 while (tail > ptr && (*tail & 0xc0) == 0x80)
1852 --tail;
1853 if (tail + utf_byte2len(*tail) <= ptr + size)
1854 tail = NULL;
1855 else
1856 p = tail;
1857 }
1858 }
1859 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1860 {
1861 /* Check for a trailing byte */
1862 p = ptr + (size & ~1);
1863 if (size & 1)
1864 tail = p;
1865 if ((fio_flags & FIO_UTF16) && p > ptr)
1866 {
1867 /* Check for a trailing leading word */
1868 if (fio_flags & FIO_ENDIAN_L)
1869 {
1870 u8c = (*--p << 8);
1871 u8c += *--p;
1872 }
1873 else
1874 {
1875 u8c = *--p;
1876 u8c += (*--p << 8);
1877 }
1878 if (u8c >= 0xd800 && u8c <= 0xdbff)
1879 tail = p;
1880 else
1881 p += 2;
1882 }
1883 }
1884 else /* FIO_UCS4 */
1885 {
1886 /* Check for trailing 1, 2 or 3 bytes */
1887 p = ptr + (size & ~3);
1888 if (size & 3)
1889 tail = p;
1890 }
1891
1892 /* If there is a trailing incomplete sequence move it to
1893 * conv_rest[]. */
1894 if (tail != NULL)
1895 {
1896 conv_restlen = (int)((ptr + size) - tail);
1897 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1898 size -= conv_restlen;
1899 }
1900
1901
1902 while (p > ptr)
1903 {
1904 if (fio_flags & FIO_LATIN1)
1905 u8c = *--p;
1906 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1907 {
1908 if (fio_flags & FIO_ENDIAN_L)
1909 {
1910 u8c = (*--p << 8);
1911 u8c += *--p;
1912 }
1913 else
1914 {
1915 u8c = *--p;
1916 u8c += (*--p << 8);
1917 }
1918 if ((fio_flags & FIO_UTF16)
1919 && u8c >= 0xdc00 && u8c <= 0xdfff)
1920 {
1921 int u16c;
1922
1923 if (p == ptr)
1924 {
1925 /* Missing leading word. */
1926 if (can_retry)
1927 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001928 if (conv_error == 0)
1929 conv_error = readfile_linenr(linecnt,
1930 ptr, p);
1931 if (bad_char_behavior == BAD_DROP)
1932 continue;
1933 if (bad_char_behavior != BAD_KEEP)
1934 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 }
1936
1937 /* found second word of double-word, get the first
1938 * word and compute the resulting character */
1939 if (fio_flags & FIO_ENDIAN_L)
1940 {
1941 u16c = (*--p << 8);
1942 u16c += *--p;
1943 }
1944 else
1945 {
1946 u16c = *--p;
1947 u16c += (*--p << 8);
1948 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001949 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1950 + (u8c & 0x3ff);
1951
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 /* Check if the word is indeed a leading word. */
1953 if (u16c < 0xd800 || u16c > 0xdbff)
1954 {
1955 if (can_retry)
1956 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001957 if (conv_error == 0)
1958 conv_error = readfile_linenr(linecnt,
1959 ptr, p);
1960 if (bad_char_behavior == BAD_DROP)
1961 continue;
1962 if (bad_char_behavior != BAD_KEEP)
1963 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 }
1966 }
1967 else if (fio_flags & FIO_UCS4)
1968 {
1969 if (fio_flags & FIO_ENDIAN_L)
1970 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001971 u8c = (unsigned)*--p << 24;
1972 u8c += (unsigned)*--p << 16;
1973 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 u8c += *--p;
1975 }
1976 else /* big endian */
1977 {
1978 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001979 u8c += (unsigned)*--p << 8;
1980 u8c += (unsigned)*--p << 16;
1981 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982 }
1983 }
1984 else /* UTF-8 */
1985 {
1986 if (*--p < 0x80)
1987 u8c = *p;
1988 else
1989 {
1990 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001991 p -= len;
1992 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 if (len == 0)
1994 {
1995 /* Not a valid UTF-8 character, retry with
1996 * another fenc when possible, otherwise just
1997 * report the error. */
1998 if (can_retry)
1999 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002000 if (conv_error == 0)
2001 conv_error = readfile_linenr(linecnt,
2002 ptr, p);
2003 if (bad_char_behavior == BAD_DROP)
2004 continue;
2005 if (bad_char_behavior != BAD_KEEP)
2006 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 }
2009 }
2010 if (enc_utf8) /* produce UTF-8 */
2011 {
2012 dest -= utf_char2len(u8c);
2013 (void)utf_char2bytes(u8c, dest);
2014 }
2015 else /* produce Latin1 */
2016 {
2017 --dest;
2018 if (u8c >= 0x100)
2019 {
2020 /* character doesn't fit in latin1, retry with
2021 * another fenc when possible, otherwise just
2022 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002023 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002025 if (conv_error == 0)
2026 conv_error = readfile_linenr(linecnt, ptr, p);
2027 if (bad_char_behavior == BAD_DROP)
2028 ++dest;
2029 else if (bad_char_behavior == BAD_KEEP)
2030 *dest = u8c;
2031 else if (eap != NULL && eap->bad_char != 0)
2032 *dest = bad_char_behavior;
2033 else
2034 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 }
2036 else
2037 *dest = u8c;
2038 }
2039 }
2040
2041 /* move the linerest to before the converted characters */
2042 line_start = dest - linerest;
2043 mch_memmove(line_start, buffer, (size_t)linerest);
2044 size = (long)((ptr + real_size) - dest);
2045 ptr = dest;
2046 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002047 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002049 int incomplete_tail = FALSE;
2050
2051 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2052 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002054 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002055 int l;
2056
2057 if (todo <= 0)
2058 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 if (*p >= 0x80)
2060 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 /* A length of 1 means it's an illegal byte. Accept
2062 * an incomplete character at the end though, the next
2063 * read() will get the next bytes, we'll check it
2064 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002065 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002066 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002068 /* Avoid retrying with a different encoding when
2069 * a truncated file is more likely, or attempting
2070 * to read the rest of an incomplete sequence when
2071 * we have already done so. */
2072 if (p > ptr || filesize > 0)
2073 incomplete_tail = TRUE;
2074 /* Incomplete byte sequence, move it to conv_rest[]
2075 * and try to read the rest of it, unless we've
2076 * already done so. */
2077 if (p > ptr)
2078 {
2079 conv_restlen = todo;
2080 mch_memmove(conv_rest, p, conv_restlen);
2081 size -= conv_restlen;
2082 break;
2083 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002085 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002086 {
2087 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002088 * do that, unless at EOF where a truncated
2089 * file is more likely than a conversion error. */
2090 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002091 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002092# ifdef USE_ICONV
2093 /* When we did a conversion report an error. */
2094 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2095 conv_error = readfile_linenr(linecnt, ptr, p);
2096# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002097 /* Remember the first linenr with an illegal byte */
2098 if (conv_error == 0 && illegal_byte == 0)
2099 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002100
2101 /* Drop, keep or replace the bad byte. */
2102 if (bad_char_behavior == BAD_DROP)
2103 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002104 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002105 --p;
2106 --size;
2107 }
2108 else if (bad_char_behavior != BAD_KEEP)
2109 *p = bad_char_behavior;
2110 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002111 else
2112 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113 }
2114 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002115 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116 {
2117 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002119 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002121 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2122 /* iconv() failed, try 'charconvert' */
2123 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 else
2125# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002126 /* use next item from 'fileencodings' */
2127 advance_fenc = TRUE;
2128 file_rewind = TRUE;
2129 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130 }
2131 }
2132#endif
2133
2134 /* count the number of characters (after conversion!) */
2135 filesize += size;
2136
2137 /*
2138 * when reading the first part of a file: guess EOL type
2139 */
2140 if (fileformat == EOL_UNKNOWN)
2141 {
2142 /* First try finding a NL, for Dos and Unix */
2143 if (try_dos || try_unix)
2144 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002145 /* Reset the carriage return counter. */
2146 if (try_mac)
2147 try_mac = 1;
2148
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 for (p = ptr; p < ptr + size; ++p)
2150 {
2151 if (*p == NL)
2152 {
2153 if (!try_unix
2154 || (try_dos && p > ptr && p[-1] == CAR))
2155 fileformat = EOL_DOS;
2156 else
2157 fileformat = EOL_UNIX;
2158 break;
2159 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002160 else if (*p == CAR && try_mac)
2161 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 }
2163
2164 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2165 if (fileformat == EOL_UNIX && try_mac)
2166 {
2167 /* Need to reset the counters when retrying fenc. */
2168 try_mac = 1;
2169 try_unix = 1;
2170 for (; p >= ptr && *p != CAR; p--)
2171 ;
2172 if (p >= ptr)
2173 {
2174 for (p = ptr; p < ptr + size; ++p)
2175 {
2176 if (*p == NL)
2177 try_unix++;
2178 else if (*p == CAR)
2179 try_mac++;
2180 }
2181 if (try_mac > try_unix)
2182 fileformat = EOL_MAC;
2183 }
2184 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002185 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2186 /* Looking for CR but found no end-of-line markers at
2187 * all: use the default format. */
2188 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 }
2190
2191 /* No NL found: may use Mac format */
2192 if (fileformat == EOL_UNKNOWN && try_mac)
2193 fileformat = EOL_MAC;
2194
2195 /* Still nothing found? Use first format in 'ffs' */
2196 if (fileformat == EOL_UNKNOWN)
2197 fileformat = default_fileformat();
2198
2199 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002200 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201 set_fileformat(fileformat, OPT_LOCAL);
2202 }
2203 }
2204
2205 /*
2206 * This loop is executed once for every character read.
2207 * Keep it fast!
2208 */
2209 if (fileformat == EOL_MAC)
2210 {
2211 --ptr;
2212 while (++ptr, --size >= 0)
2213 {
2214 /* catch most common case first */
2215 if ((c = *ptr) != NUL && c != CAR && c != NL)
2216 continue;
2217 if (c == NUL)
2218 *ptr = NL; /* NULs are replaced by newlines! */
2219 else if (c == NL)
2220 *ptr = CAR; /* NLs are replaced by CRs! */
2221 else
2222 {
2223 if (skip_count == 0)
2224 {
2225 *ptr = NUL; /* end of line */
2226 len = (colnr_T) (ptr - line_start + 1);
2227 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2228 {
2229 error = TRUE;
2230 break;
2231 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002232#ifdef FEAT_PERSISTENT_UNDO
2233 if (read_undo_file)
2234 sha256_update(&sha_ctx, line_start, len);
2235#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 ++lnum;
2237 if (--read_count == 0)
2238 {
2239 error = TRUE; /* break loop */
2240 line_start = ptr; /* nothing left to write */
2241 break;
2242 }
2243 }
2244 else
2245 --skip_count;
2246 line_start = ptr + 1;
2247 }
2248 }
2249 }
2250 else
2251 {
2252 --ptr;
2253 while (++ptr, --size >= 0)
2254 {
2255 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2256 continue;
2257 if (c == NUL)
2258 *ptr = NL; /* NULs are replaced by newlines! */
2259 else
2260 {
2261 if (skip_count == 0)
2262 {
2263 *ptr = NUL; /* end of line */
2264 len = (colnr_T)(ptr - line_start + 1);
2265 if (fileformat == EOL_DOS)
2266 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002267 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002269 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270 ptr[-1] = NUL;
2271 --len;
2272 }
2273 /*
2274 * Reading in Dos format, but no CR-LF found!
2275 * When 'fileformats' includes "unix", delete all
2276 * the lines read so far and start all over again.
2277 * Otherwise give an error message later.
2278 */
2279 else if (ff_error != EOL_DOS)
2280 {
2281 if ( try_unix
2282 && !read_stdin
2283 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002284 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2285 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286 {
2287 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002288 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 set_fileformat(EOL_UNIX, OPT_LOCAL);
2290 file_rewind = TRUE;
2291 keep_fileformat = TRUE;
2292 goto retry;
2293 }
2294 ff_error = EOL_DOS;
2295 }
2296 }
2297 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2298 {
2299 error = TRUE;
2300 break;
2301 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002302#ifdef FEAT_PERSISTENT_UNDO
2303 if (read_undo_file)
2304 sha256_update(&sha_ctx, line_start, len);
2305#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 ++lnum;
2307 if (--read_count == 0)
2308 {
2309 error = TRUE; /* break loop */
2310 line_start = ptr; /* nothing left to write */
2311 break;
2312 }
2313 }
2314 else
2315 --skip_count;
2316 line_start = ptr + 1;
2317 }
2318 }
2319 }
2320 linerest = (long)(ptr - line_start);
2321 ui_breakcheck();
2322 }
2323
2324failed:
2325 /* not an error, max. number of lines reached */
2326 if (error && read_count == 0)
2327 error = FALSE;
2328
2329 /*
2330 * If we get EOF in the middle of a line, note the fact and
2331 * complete the line ourselves.
2332 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2333 */
2334 if (!error
2335 && !got_int
2336 && linerest != 0
2337 && !(!curbuf->b_p_bin
2338 && fileformat == EOL_DOS
2339 && *line_start == Ctrl_Z
2340 && ptr == line_start + 1))
2341 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002342 /* remember for when writing */
2343 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 curbuf->b_p_eol = FALSE;
2345 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002346 len = (colnr_T)(ptr - line_start + 1);
2347 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 error = TRUE;
2349 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002350 {
2351#ifdef FEAT_PERSISTENT_UNDO
2352 if (read_undo_file)
2353 sha256_update(&sha_ctx, line_start, len);
2354#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 }
2358
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002359 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 save_file_ff(curbuf); /* remember the current file format */
2361
2362#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002363 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002364 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002365 crypt_free_state(curbuf->b_cryptstate);
2366 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002367 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002368 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2369 crypt_free_key(cryptkey);
2370 /* Don't set cryptkey to NULL, it's used below as a flag that
2371 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372#endif
2373
2374#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002375 /* If editing a new file: set 'fenc' for the current buffer.
2376 * Also for ":read ++edit file". */
2377 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002379 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 if (fenc_alloced)
2381 vim_free(fenc);
2382# ifdef USE_ICONV
2383 if (iconv_fd != (iconv_t)-1)
2384 {
2385 iconv_close(iconv_fd);
2386 iconv_fd = (iconv_t)-1;
2387 }
2388# endif
2389#endif
2390
2391 if (!read_buffer && !read_stdin)
2392 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002393#ifdef HAVE_FD_CLOEXEC
2394 else
2395 {
2396 int fdflags = fcntl(fd, F_GETFD);
2397 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002398 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002399 }
2400#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401 vim_free(buffer);
2402
2403#ifdef HAVE_DUP
2404 if (read_stdin)
2405 {
2406 /* Use stderr for stdin, makes shell commands work. */
2407 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002408 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 }
2410#endif
2411
2412#ifdef FEAT_MBYTE
2413 if (tmpname != NULL)
2414 {
2415 mch_remove(tmpname); /* delete converted file */
2416 vim_free(tmpname);
2417 }
2418#endif
2419 --no_wait_return; /* may wait for return now */
2420
2421 /*
2422 * In recovery mode everything but autocommands is skipped.
2423 */
2424 if (!recoverymode)
2425 {
2426 /* need to delete the last line, which comes from the empty buffer */
2427 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2428 {
2429#ifdef FEAT_NETBEANS_INTG
2430 netbeansFireChanges = 0;
2431#endif
2432 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2433#ifdef FEAT_NETBEANS_INTG
2434 netbeansFireChanges = 1;
2435#endif
2436 --linecnt;
2437 }
2438 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2439 if (filesize == 0)
2440 linecnt = 0;
2441 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002442 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002444#ifdef FEAT_DIFF
2445 /* After reading the text into the buffer the diff info needs to
2446 * be updated. */
2447 diff_invalidate(curbuf);
2448#endif
2449#ifdef FEAT_FOLDING
2450 /* All folds in the window are invalid now. Mark them for update
2451 * before triggering autocommands. */
2452 foldUpdateAll(curwin);
2453#endif
2454 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 else if (linecnt) /* appended at least one line */
2456 appended_lines_mark(from, linecnt);
2457
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458#ifndef ALWAYS_USE_GUI
2459 /*
2460 * If we were reading from the same terminal as where messages go,
2461 * the screen will have been messed up.
2462 * Switch on raw mode now and clear the screen.
2463 */
2464 if (read_stdin)
2465 {
2466 settmode(TMODE_RAW); /* set to raw mode */
2467 starttermcap();
2468 screenclear();
2469 }
2470#endif
2471
2472 if (got_int)
2473 {
2474 if (!(flags & READ_DUMMY))
2475 {
2476 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2477 if (newfile)
2478 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2479 }
2480 msg_scroll = msg_save;
2481#ifdef FEAT_VIMINFO
2482 check_marks_read();
2483#endif
2484 return OK; /* an interrupt isn't really an error */
2485 }
2486
2487 if (!filtering && !(flags & READ_DUMMY))
2488 {
2489 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2490 c = FALSE;
2491
2492#ifdef UNIX
Bram Moolenaard569bb02018-08-11 13:57:20 +02002493 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 {
2495 STRCAT(IObuff, _("[fifo]"));
2496 c = TRUE;
2497 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002498 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 {
2500 STRCAT(IObuff, _("[socket]"));
2501 c = TRUE;
2502 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002503# ifdef OPEN_CHR_FILES
2504 if (S_ISCHR(perm)) /* or character special */
2505 {
2506 STRCAT(IObuff, _("[character special]"));
2507 c = TRUE;
2508 }
2509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510#endif
2511 if (curbuf->b_p_ro)
2512 {
2513 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2514 c = TRUE;
2515 }
2516 if (read_no_eol_lnum)
2517 {
2518 msg_add_eol();
2519 c = TRUE;
2520 }
2521 if (ff_error == EOL_DOS)
2522 {
2523 STRCAT(IObuff, _("[CR missing]"));
2524 c = TRUE;
2525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 if (split)
2527 {
2528 STRCAT(IObuff, _("[long lines split]"));
2529 c = TRUE;
2530 }
2531#ifdef FEAT_MBYTE
2532 if (notconverted)
2533 {
2534 STRCAT(IObuff, _("[NOT converted]"));
2535 c = TRUE;
2536 }
2537 else if (converted)
2538 {
2539 STRCAT(IObuff, _("[converted]"));
2540 c = TRUE;
2541 }
2542#endif
2543#ifdef FEAT_CRYPT
2544 if (cryptkey != NULL)
2545 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002546 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 c = TRUE;
2548 }
2549#endif
2550#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002551 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002553 sprintf((char *)IObuff + STRLEN(IObuff),
2554 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 c = TRUE;
2556 }
2557 else if (illegal_byte > 0)
2558 {
2559 sprintf((char *)IObuff + STRLEN(IObuff),
2560 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2561 c = TRUE;
2562 }
2563 else
2564#endif
2565 if (error)
2566 {
2567 STRCAT(IObuff, _("[READ ERRORS]"));
2568 c = TRUE;
2569 }
2570 if (msg_add_fileformat(fileformat))
2571 c = TRUE;
2572#ifdef FEAT_CRYPT
2573 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002574 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002575 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 else
2577#endif
2578 msg_add_lines(c, (long)linecnt, filesize);
2579
Bram Moolenaard23a8232018-02-10 18:45:26 +01002580 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 msg_scrolled_ign = TRUE;
2582#ifdef ALWAYS_USE_GUI
2583 /* Don't show the message when reading stdin, it would end up in a
2584 * message box (which might be shown when exiting!) */
2585 if (read_stdin || read_buffer)
2586 p = msg_may_trunc(FALSE, IObuff);
2587 else
2588#endif
2589 p = msg_trunc_attr(IObuff, FALSE, 0);
2590 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002591 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 /* Need to repeat the message after redrawing when:
2593 * - When reading from stdin (the screen will be cleared next).
2594 * - When restart_edit is set (otherwise there will be a delay
2595 * before redrawing).
2596 * - When the screen was scrolled but there is no wait-return
2597 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002598 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 msg_scrolled_ign = FALSE;
2600 }
2601
2602 /* with errors writing the file requires ":w!" */
2603 if (newfile && (error
2604#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002605 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002606 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002607#endif
2608 ))
2609 curbuf->b_p_ro = TRUE;
2610
2611 u_clearline(); /* cannot use "U" command after adding lines */
2612
2613 /*
2614 * In Ex mode: cursor at last new line.
2615 * Otherwise: cursor at first new line.
2616 */
2617 if (exmode_active)
2618 curwin->w_cursor.lnum = from + linecnt;
2619 else
2620 curwin->w_cursor.lnum = from + 1;
2621 check_cursor_lnum();
2622 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2623
2624 /*
2625 * Set '[ and '] marks to the newly read lines.
2626 */
2627 curbuf->b_op_start.lnum = from + 1;
2628 curbuf->b_op_start.col = 0;
2629 curbuf->b_op_end.lnum = from + linecnt;
2630 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002631
2632#ifdef WIN32
2633 /*
2634 * Work around a weird problem: When a file has two links (only
2635 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002636 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002637 * It's correct again after reading the file, thus reset the timestamp
2638 * here.
2639 */
2640 if (newfile && !read_stdin && !read_buffer
2641 && mch_stat((char *)fname, &st) >= 0)
2642 {
2643 buf_store_time(curbuf, &st, fname);
2644 curbuf->b_mtime_read = curbuf->b_mtime;
2645 }
2646#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 }
2648 msg_scroll = msg_save;
2649
2650#ifdef FEAT_VIMINFO
2651 /*
2652 * Get the marks before executing autocommands, so they can be used there.
2653 */
2654 check_marks_read();
2655#endif
2656
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002658 * We remember if the last line of the read didn't have
2659 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2660 * or writing the read again with 'binary' on. The latter is required
2661 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002663 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002665 /* When reloading a buffer put the cursor at the first line that is
2666 * different. */
2667 if (flags & READ_KEEP_UNDO)
2668 u_find_first_changed();
2669
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002670#ifdef FEAT_PERSISTENT_UNDO
2671 /*
2672 * When opening a new file locate undo info and read it.
2673 */
2674 if (read_undo_file)
2675 {
2676 char_u hash[UNDO_HASH_SIZE];
2677
2678 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002679 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002680 }
2681#endif
2682
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002683 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 {
2685 int m = msg_scroll;
2686 int n = msg_scrolled;
2687
2688 /* Save the fileformat now, otherwise the buffer will be considered
2689 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002690 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 save_file_ff(curbuf);
2692
2693 /*
2694 * The output from the autocommands should not overwrite anything and
2695 * should not be overwritten: Set msg_scroll, restore its value if no
2696 * output was done.
2697 */
2698 msg_scroll = TRUE;
2699 if (filtering)
2700 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2701 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002702 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002703 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2705 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002706 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2707 /*
2708 * EVENT_FILETYPE was not triggered but the buffer already has a
2709 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2710 */
2711 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2712 TRUE, curbuf);
2713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 else
2715 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2716 FALSE, NULL, eap);
2717 if (msg_scrolled == n)
2718 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002719# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 if (aborting()) /* autocmds may abort script processing */
2721 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002722# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724
2725 if (recoverymode && error)
2726 return FAIL;
2727 return OK;
2728}
2729
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002730#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002731/*
2732 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2733 * which is the name of files used for process substitution output by
2734 * some shells on some operating systems, e.g., bash on SunOS.
2735 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2736 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002737 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002738is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002739{
2740 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2741 && VIM_ISDIGIT(fname[8])
2742 && *skipdigits(fname + 9) == NUL
2743 && (fname[9] != NUL
2744 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2745}
2746#endif
2747
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002748#ifdef FEAT_MBYTE
2749
2750/*
2751 * From the current line count and characters read after that, estimate the
2752 * line number where we are now.
2753 * Used for error messages that include a line number.
2754 */
2755 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002756readfile_linenr(
2757 linenr_T linecnt, /* line count before reading more bytes */
2758 char_u *p, /* start of more bytes read */
2759 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002760{
2761 char_u *s;
2762 linenr_T lnum;
2763
2764 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2765 for (s = p; s < endp; ++s)
2766 if (*s == '\n')
2767 ++lnum;
2768 return lnum;
2769}
2770#endif
2771
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002773 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2774 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 * Returns OK or FAIL.
2776 */
2777 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002778prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002780 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002782 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002784 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785 if (eap->cmd == NULL)
2786 return FAIL;
2787
2788#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002789 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2790 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002791 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002793 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002795 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002796
2797 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002798 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002799 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 return OK;
2801}
2802
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002803/*
2804 * Set default or forced 'fileformat' and 'binary'.
2805 */
2806 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002807set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002808{
2809 /* set default 'fileformat' */
2810 if (set_options)
2811 {
2812 if (eap != NULL && eap->force_ff != 0)
2813 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2814 else if (*p_ffs != NUL)
2815 set_fileformat(default_fileformat(), OPT_LOCAL);
2816 }
2817
2818 /* set or reset 'binary' */
2819 if (eap != NULL && eap->force_bin != 0)
2820 {
2821 int oldval = curbuf->b_p_bin;
2822
2823 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2824 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2825 }
2826}
2827
2828#if defined(FEAT_MBYTE) || defined(PROTO)
2829/*
2830 * Set forced 'fileencoding'.
2831 */
2832 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002833set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002834{
2835 if (eap->force_enc != 0)
2836 {
2837 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2838
2839 if (fenc != NULL)
2840 set_string_option_direct((char_u *)"fenc", -1,
2841 fenc, OPT_FREE|OPT_LOCAL, 0);
2842 vim_free(fenc);
2843 }
2844}
2845
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846/*
2847 * Find next fileencoding to use from 'fileencodings'.
2848 * "pp" points to fenc_next. It's advanced to the next item.
2849 * When there are no more items, an empty string is returned and *pp is set to
2850 * NULL.
2851 * When *pp is not set to NULL, the result is in allocated memory.
2852 */
2853 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002854next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855{
2856 char_u *p;
2857 char_u *r;
2858
2859 if (**pp == NUL)
2860 {
2861 *pp = NULL;
2862 return (char_u *)"";
2863 }
2864 p = vim_strchr(*pp, ',');
2865 if (p == NULL)
2866 {
2867 r = enc_canonize(*pp);
2868 *pp += STRLEN(*pp);
2869 }
2870 else
2871 {
2872 r = vim_strnsave(*pp, (int)(p - *pp));
2873 *pp = p + 1;
2874 if (r != NULL)
2875 {
2876 p = enc_canonize(r);
2877 vim_free(r);
2878 r = p;
2879 }
2880 }
2881 if (r == NULL) /* out of memory */
2882 {
2883 r = (char_u *)"";
2884 *pp = NULL;
2885 }
2886 return r;
2887}
2888
2889# ifdef FEAT_EVAL
2890/*
2891 * Convert a file with the 'charconvert' expression.
2892 * This closes the file which is to be read, converts it and opens the
2893 * resulting file for reading.
2894 * Returns name of the resulting converted file (the caller should delete it
2895 * after reading it).
2896 * Returns NULL if the conversion failed ("*fdp" is not set) .
2897 */
2898 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002899readfile_charconvert(
2900 char_u *fname, /* name of input file */
2901 char_u *fenc, /* converted from */
2902 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903{
2904 char_u *tmpname;
2905 char_u *errmsg = NULL;
2906
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002907 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 if (tmpname == NULL)
2909 errmsg = (char_u *)_("Can't find temp file for conversion");
2910 else
2911 {
2912 close(*fdp); /* close the input file, ignore errors */
2913 *fdp = -1;
2914 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2915 fname, tmpname) == FAIL)
2916 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2917 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2918 O_RDONLY | O_EXTRA, 0)) < 0)
2919 errmsg = (char_u *)_("can't read output of 'charconvert'");
2920 }
2921
2922 if (errmsg != NULL)
2923 {
2924 /* Don't use emsg(), it breaks mappings, the retry with
2925 * another type of conversion might still work. */
2926 MSG(errmsg);
2927 if (tmpname != NULL)
2928 {
2929 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002930 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 }
2932 }
2933
2934 /* If the input file is closed, open it (caller should check for error). */
2935 if (*fdp < 0)
2936 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2937
2938 return tmpname;
2939}
2940# endif
2941
2942#endif
2943
2944#ifdef FEAT_VIMINFO
2945/*
2946 * Read marks for the current buffer from the viminfo file, when we support
2947 * buffer marks and the buffer has a name.
2948 */
2949 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002950check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951{
2952 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2953 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002954 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955
2956 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2957 * the ' parameter after opening a buffer. */
2958 curbuf->b_marks_read = TRUE;
2959}
2960#endif
2961
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002962#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002964 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2966 * *filesizep are updated.
2967 * Return the (new) encryption key, NULL for no encryption.
2968 */
2969 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002970check_for_cryptkey(
2971 char_u *cryptkey, /* previous encryption key or NULL */
2972 char_u *ptr, /* pointer to read bytes */
2973 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002974 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002975 int newfile, /* editing a new buffer */
2976 char_u *fname, /* file name to display */
2977 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002979 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002980 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002981
2982 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002984 /* Mark the buffer as read-only until the decryption has taken place.
2985 * Avoids accidentally overwriting the file with garbage. */
2986 curbuf->b_p_ro = TRUE;
2987
Bram Moolenaar2be79502014-08-13 21:58:28 +02002988 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002989 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002990 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 {
2992 if (*curbuf->b_p_key)
2993 cryptkey = curbuf->b_p_key;
2994 else
2995 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002996 /* When newfile is TRUE, store the typed key in the 'key'
2997 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002998 * Don't ask for the key again when first time Enter was hit.
2999 * Happens when retrying to detect encoding. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003000 smsg(_(need_key_msg), fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003001 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003002 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003003 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003004 *did_ask = TRUE;
3005
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006 /* check if empty key entered */
3007 if (cryptkey != NULL && *cryptkey == NUL)
3008 {
3009 if (cryptkey != curbuf->b_p_key)
3010 vim_free(cryptkey);
3011 cryptkey = NULL;
3012 }
3013 }
3014 }
3015
3016 if (cryptkey != NULL)
3017 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003018 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003019
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003020 curbuf->b_cryptstate = crypt_create_from_header(
3021 method, cryptkey, ptr);
3022 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003024 /* Remove cryptmethod specific header from the text. */
3025 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003026 if (*sizep <= header_len)
3027 /* invalid header, buffer can't be encrypted */
3028 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003029 *filesizep += header_len;
3030 *sizep -= header_len;
3031 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3032
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003033 /* Restore the read-only flag. */
3034 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 }
3036 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003037 /* When starting to edit a new file which does not have encryption, clear
3038 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003039 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3041
3042 return cryptkey;
3043}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003044#endif /* FEAT_CRYPT */
3045
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046#ifdef UNIX
3047 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003048set_file_time(
3049 char_u *fname,
3050 time_t atime, /* access time */
3051 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052{
3053# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3054 struct utimbuf buf;
3055
3056 buf.actime = atime;
3057 buf.modtime = mtime;
3058 (void)utime((char *)fname, &buf);
3059# else
3060# if defined(HAVE_UTIMES)
3061 struct timeval tvp[2];
3062
3063 tvp[0].tv_sec = atime;
3064 tvp[0].tv_usec = 0;
3065 tvp[1].tv_sec = mtime;
3066 tvp[1].tv_usec = 0;
3067# ifdef NeXT
3068 (void)utimes((char *)fname, tvp);
3069# else
3070 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3071# endif
3072# endif
3073# endif
3074}
3075#endif /* UNIX */
3076
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003077#if defined(VMS) && !defined(MIN)
3078/* Older DECC compiler for VAX doesn't define MIN() */
3079# define MIN(a, b) ((a) < (b) ? (a) : (b))
3080#endif
3081
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003083 * Return TRUE if a file appears to be read-only from the file permissions.
3084 */
3085 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003086check_file_readonly(
3087 char_u *fname, /* full path to file */
3088 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003089{
3090#ifndef USE_MCH_ACCESS
3091 int fd = 0;
3092#endif
3093
3094 return (
3095#ifdef USE_MCH_ACCESS
3096# ifdef UNIX
3097 (perm & 0222) == 0 ||
3098# endif
3099 mch_access((char *)fname, W_OK)
3100#else
3101 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3102 ? TRUE : (close(fd), FALSE)
3103#endif
3104 );
3105}
3106
3107
3108/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003109 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 *
3111 * We do our own buffering here because fwrite() is so slow.
3112 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003113 * If "forceit" is true, we don't care for errors when attempting backups.
3114 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003115 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003116 *
3117 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3118 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 *
3120 * This function must NOT use NameBuff (because it's called by autowrite()).
3121 *
3122 * return FAIL for failure, OK otherwise
3123 */
3124 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003125buf_write(
3126 buf_T *buf,
3127 char_u *fname,
3128 char_u *sfname,
3129 linenr_T start,
3130 linenr_T end,
3131 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003133 int append, /* append to the file */
3134 int forceit,
3135 int reset_changed,
3136 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137{
3138 int fd;
3139 char_u *backup = NULL;
3140 int backup_copy = FALSE; /* copy the original file? */
3141 int dobackup;
3142 char_u *ffname;
3143 char_u *wfname = NULL; /* name of file to write to */
3144 char_u *s;
3145 char_u *ptr;
3146 char_u c;
3147 int len;
3148 linenr_T lnum;
3149 long nchars;
3150 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003151 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152 char_u *errnum = NULL;
3153 char_u *buffer;
3154 char_u smallbuf[SMBUFSIZE];
3155 char_u *backup_ext;
3156 int bufsize;
3157 long perm; /* file permissions */
3158 int retval = OK;
3159 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3160 int msg_save = msg_scroll;
3161 int overwriting; /* TRUE if writing over original */
3162 int no_eol = FALSE; /* no end-of-line written */
3163 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003164 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003166 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167 int file_readonly = FALSE; /* overwritten file is read-only */
3168 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003169#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 int made_writable = FALSE; /* 'w' bit has been set */
3171#endif
3172 /* writing everything */
3173 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 int attr;
3176 int fileformat;
3177 int write_bin;
3178 struct bw_info write_info; /* info for buf_write_bytes() */
3179#ifdef FEAT_MBYTE
3180 int converted = FALSE;
3181 int notconverted = FALSE;
3182 char_u *fenc; /* effective 'fileencoding' */
3183 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3184#endif
3185#ifdef HAS_BW_FLAGS
3186 int wb_flags = 0;
3187#endif
3188#ifdef HAVE_ACL
3189 vim_acl_T acl = NULL; /* ACL copied from original file to
3190 backup or new file */
3191#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003192#ifdef FEAT_PERSISTENT_UNDO
3193 int write_undo_file = FALSE;
3194 context_sha256_T sha_ctx;
3195#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003196 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197
3198 if (fname == NULL || *fname == NUL) /* safety check */
3199 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003200 if (buf->b_ml.ml_mfp == NULL)
3201 {
3202 /* This can happen during startup when there is a stray "w" in the
3203 * vimrc file. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003204 emsg(_(e_emptybuf));
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003205 return FAIL;
3206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207
3208 /*
3209 * Disallow writing from .exrc and .vimrc in current directory for
3210 * security reasons.
3211 */
3212 if (check_secure())
3213 return FAIL;
3214
3215 /* Avoid a crash for a long name. */
3216 if (STRLEN(fname) >= MAXPATHL)
3217 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003218 emsg(_(e_longname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 return FAIL;
3220 }
3221
3222#ifdef FEAT_MBYTE
3223 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3224 write_info.bw_conv_buf = NULL;
3225 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003226 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227 write_info.bw_restlen = 0;
3228# ifdef USE_ICONV
3229 write_info.bw_iconv_fd = (iconv_t)-1;
3230# endif
3231#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003232#ifdef FEAT_CRYPT
3233 write_info.bw_buffer = buf;
3234#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235
Bram Moolenaardf177f62005-02-22 08:39:57 +00003236 /* After writing a file changedtick changes but we don't want to display
3237 * the line. */
3238 ex_no_reprint = TRUE;
3239
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 /*
3241 * If there is no file name yet, use the one for the written file.
3242 * BF_NOTEDITED is set to reflect this (in case the write fails).
3243 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003244 * Don't do this when appending.
3245 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003247 if (buf->b_ffname == NULL
3248 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 && whole
3250 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003251#ifdef FEAT_QUICKFIX
3252 && !bt_nofile(buf)
3253#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003255 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3257 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003258 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003260 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 }
3262
3263 if (sfname == NULL)
3264 sfname = fname;
3265 /*
3266 * For Unix: Use the short file name whenever possible.
3267 * Avoids problems with networks and when directory names are changed.
3268 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3269 * another directory, which we don't detect
3270 */
3271 ffname = fname; /* remember full fname */
3272#ifdef UNIX
3273 fname = sfname;
3274#endif
3275
3276 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3277 overwriting = TRUE;
3278 else
3279 overwriting = FALSE;
3280
3281 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003282 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283
3284 ++no_wait_return; /* don't wait for return yet */
3285
3286 /*
3287 * Set '[ and '] marks to the lines to be written.
3288 */
3289 buf->b_op_start.lnum = start;
3290 buf->b_op_start.col = 0;
3291 buf->b_op_end.lnum = end;
3292 buf->b_op_end.col = 0;
3293
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 {
3295 aco_save_T aco;
3296 int buf_ffname = FALSE;
3297 int buf_sfname = FALSE;
3298 int buf_fname_f = FALSE;
3299 int buf_fname_s = FALSE;
3300 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003301 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003302 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003303 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304
3305 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003306 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307 * Set curbuf to the buffer to be written.
3308 * Careful: The autocommands may call buf_write() recursively!
3309 */
3310 if (ffname == buf->b_ffname)
3311 buf_ffname = TRUE;
3312 if (sfname == buf->b_sfname)
3313 buf_sfname = TRUE;
3314 if (fname == buf->b_ffname)
3315 buf_fname_f = TRUE;
3316 if (fname == buf->b_sfname)
3317 buf_fname_s = TRUE;
3318
3319 /* set curwin/curbuf to buf and save a few things */
3320 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003321 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322
3323 if (append)
3324 {
3325 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3326 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003327 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003328#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003329 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003330 nofile_err = TRUE;
3331 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003332#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 }
3337 else if (filtering)
3338 {
3339 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3340 NULL, sfname, FALSE, curbuf, eap);
3341 }
3342 else if (reset_changed && whole)
3343 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003344 int was_changed = curbufIsChanged();
3345
3346 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3347 sfname, sfname, FALSE, curbuf, eap);
3348 if (did_cmd)
3349 {
3350 if (was_changed && !curbufIsChanged())
3351 {
3352 /* Written everything correctly and BufWriteCmd has reset
3353 * 'modified': Correct the undo information so that an
3354 * undo now sets 'modified'. */
3355 u_unchanged(curbuf);
3356 u_update_save_nr(curbuf);
3357 }
3358 }
3359 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003360 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003361#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003362 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003363 nofile_err = TRUE;
3364 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003365#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003366 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369 }
3370 else
3371 {
3372 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3373 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003374 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003375#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003376 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003377 nofile_err = TRUE;
3378 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003379#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003380 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003382 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383 }
3384
3385 /* restore curwin/curbuf and a few other things */
3386 aucmd_restbuf(&aco);
3387
3388 /*
3389 * In three situations we return here and don't write the file:
3390 * 1. the autocommands deleted or unloaded the buffer.
3391 * 2. The autocommands abort script processing.
3392 * 3. If one of the "Cmd" autocommands was executed.
3393 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003394 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003396 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003397 || did_cmd || nofile_err
3398#ifdef FEAT_EVAL
3399 || aborting()
3400#endif
3401 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402 {
3403 --no_wait_return;
3404 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003405 if (nofile_err)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003406 emsg(_("E676: No matching autocommands for acwrite buffer"));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003407
Bram Moolenaar1e015462005-09-25 22:16:38 +00003408 if (nofile_err
3409#ifdef FEAT_EVAL
3410 || aborting()
3411#endif
3412 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 /* An aborting error, interrupt or exception in the
3414 * autocommands. */
3415 return FAIL;
3416 if (did_cmd)
3417 {
3418 if (buf == NULL)
3419 /* The buffer was deleted. We assume it was written
3420 * (can't retry anyway). */
3421 return OK;
3422 if (overwriting)
3423 {
3424 /* Assume the buffer was written, update the timestamp. */
3425 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003426 if (append)
3427 buf->b_flags &= ~BF_NEW;
3428 else
3429 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003431 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003432 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 /* Buffer still changed, the autocommands didn't work
3434 * properly. */
3435 return FAIL;
3436 return OK;
3437 }
3438#ifdef FEAT_EVAL
3439 if (!aborting())
3440#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003441 emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 return FAIL;
3443 }
3444
3445 /*
3446 * The autocommands may have changed the number of lines in the file.
3447 * When writing the whole file, adjust the end.
3448 * When writing part of the file, assume that the autocommands only
3449 * changed the number of lines that are to be written (tricky!).
3450 */
3451 if (buf->b_ml.ml_line_count != old_line_count)
3452 {
3453 if (whole) /* write all */
3454 end = buf->b_ml.ml_line_count;
3455 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3456 end += buf->b_ml.ml_line_count - old_line_count;
3457 else /* less lines */
3458 {
3459 end -= old_line_count - buf->b_ml.ml_line_count;
3460 if (end < start)
3461 {
3462 --no_wait_return;
3463 msg_scroll = msg_save;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003464 emsg(_("E204: Autocommand changed number of lines in unexpected way"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 return FAIL;
3466 }
3467 }
3468 }
3469
3470 /*
3471 * The autocommands may have changed the name of the buffer, which may
3472 * be kept in fname, ffname and sfname.
3473 */
3474 if (buf_ffname)
3475 ffname = buf->b_ffname;
3476 if (buf_sfname)
3477 sfname = buf->b_sfname;
3478 if (buf_fname_f)
3479 fname = buf->b_ffname;
3480 if (buf_fname_s)
3481 fname = buf->b_sfname;
3482 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483
3484#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003485 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486 {
3487 if (whole)
3488 {
3489 /*
3490 * b_changed can be 0 after an undo, but we still need to write
3491 * the buffer to NetBeans.
3492 */
3493 if (buf->b_changed || isNetbeansModified(buf))
3494 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003495 --no_wait_return; /* may wait for return now */
3496 msg_scroll = msg_save;
3497 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498 return retval;
3499 }
3500 else
3501 {
3502 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003503 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 buffer = NULL;
3505 goto fail;
3506 }
3507 }
3508 else
3509 {
3510 errnum = (char_u *)"E657: ";
3511 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3512 buffer = NULL;
3513 goto fail;
3514 }
3515 }
3516#endif
3517
3518 if (shortmess(SHM_OVER) && !exiting)
3519 msg_scroll = FALSE; /* overwrite previous file message */
3520 else
3521 msg_scroll = TRUE; /* don't overwrite previous file message */
3522 if (!filtering)
3523 filemess(buf,
3524#ifndef UNIX
3525 sfname,
3526#else
3527 fname,
3528#endif
3529 (char_u *)"", 0); /* show that we are busy */
3530 msg_scroll = FALSE; /* always overwrite the file message now */
3531
3532 buffer = alloc(BUFSIZE);
3533 if (buffer == NULL) /* can't allocate big buffer, use small
3534 * one (to be able to write when out of
3535 * memory) */
3536 {
3537 buffer = smallbuf;
3538 bufsize = SMBUFSIZE;
3539 }
3540 else
3541 bufsize = BUFSIZE;
3542
3543 /*
3544 * Get information about original file (if there is one).
3545 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003546#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003547 st_old.st_dev = 0;
3548 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549 perm = -1;
3550 if (mch_stat((char *)fname, &st_old) < 0)
3551 newfile = TRUE;
3552 else
3553 {
3554 perm = st_old.st_mode;
3555 if (!S_ISREG(st_old.st_mode)) /* not a file */
3556 {
3557 if (S_ISDIR(st_old.st_mode))
3558 {
3559 errnum = (char_u *)"E502: ";
3560 errmsg = (char_u *)_("is a directory");
3561 goto fail;
3562 }
3563 if (mch_nodetype(fname) != NODE_WRITABLE)
3564 {
3565 errnum = (char_u *)"E503: ";
3566 errmsg = (char_u *)_("is not a file or writable device");
3567 goto fail;
3568 }
3569 /* It's a device of some kind (or a fifo) which we can write to
3570 * but for which we can't make a backup. */
3571 device = TRUE;
3572 newfile = TRUE;
3573 perm = -1;
3574 }
3575 }
3576#else /* !UNIX */
3577 /*
3578 * Check for a writable device name.
3579 */
3580 c = mch_nodetype(fname);
3581 if (c == NODE_OTHER)
3582 {
3583 errnum = (char_u *)"E503: ";
3584 errmsg = (char_u *)_("is not a file or writable device");
3585 goto fail;
3586 }
3587 if (c == NODE_WRITABLE)
3588 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003589# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003590 /* MS-Windows allows opening a device, but we will probably get stuck
3591 * trying to write to it. */
3592 if (!p_odev)
3593 {
3594 errnum = (char_u *)"E796: ";
3595 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3596 goto fail;
3597 }
3598# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 device = TRUE;
3600 newfile = TRUE;
3601 perm = -1;
3602 }
3603 else
3604 {
3605 perm = mch_getperm(fname);
3606 if (perm < 0)
3607 newfile = TRUE;
3608 else if (mch_isdir(fname))
3609 {
3610 errnum = (char_u *)"E502: ";
3611 errmsg = (char_u *)_("is a directory");
3612 goto fail;
3613 }
3614 if (overwriting)
3615 (void)mch_stat((char *)fname, &st_old);
3616 }
3617#endif /* !UNIX */
3618
3619 if (!device && !newfile)
3620 {
3621 /*
3622 * Check if the file is really writable (when renaming the file to
3623 * make a backup we won't discover it later).
3624 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003625 file_readonly = check_file_readonly(fname, (int)perm);
3626
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627 if (!forceit && file_readonly)
3628 {
3629 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3630 {
3631 errnum = (char_u *)"E504: ";
3632 errmsg = (char_u *)_(err_readonly);
3633 }
3634 else
3635 {
3636 errnum = (char_u *)"E505: ";
3637 errmsg = (char_u *)_("is read-only (add ! to override)");
3638 }
3639 goto fail;
3640 }
3641
3642 /*
3643 * Check if the timestamp hasn't changed since reading the file.
3644 */
3645 if (overwriting)
3646 {
3647 retval = check_mtime(buf, &st_old);
3648 if (retval == FAIL)
3649 goto fail;
3650 }
3651 }
3652
3653#ifdef HAVE_ACL
3654 /*
3655 * For systems that support ACL: get the ACL from the original file.
3656 */
3657 if (!newfile)
3658 acl = mch_get_acl(fname);
3659#endif
3660
3661 /*
3662 * If 'backupskip' is not empty, don't make a backup for some files.
3663 */
3664 dobackup = (p_wb || p_bk || *p_pm != NUL);
3665#ifdef FEAT_WILDIGN
3666 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3667 dobackup = FALSE;
3668#endif
3669
3670 /*
3671 * Save the value of got_int and reset it. We don't want a previous
3672 * interruption cancel writing, only hitting CTRL-C while writing should
3673 * abort it.
3674 */
3675 prev_got_int = got_int;
3676 got_int = FALSE;
3677
3678 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3679 buf->b_saving = TRUE;
3680
3681 /*
3682 * If we are not appending or filtering, the file exists, and the
3683 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3684 * When 'patchmode' is set also make a backup when appending.
3685 *
3686 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3687 * off. This helps when editing large files on almost-full disks.
3688 */
3689 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3690 {
3691#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003692 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693#endif
3694
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003695 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 backup_copy = TRUE;
3697#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003698 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 {
3700 int i;
3701
3702# ifdef UNIX
3703 /*
3704 * Don't rename the file when:
3705 * - it's a hard link
3706 * - it's a symbolic link
3707 * - we don't have write permission in the directory
3708 * - we can't set the owner/group of the new file
3709 */
3710 if (st_old.st_nlink > 1
3711 || mch_lstat((char *)fname, &st) < 0
3712 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003713 || st.st_ino != st_old.st_ino
3714# ifndef HAVE_FCHOWN
3715 || st.st_uid != st_old.st_uid
3716 || st.st_gid != st_old.st_gid
3717# endif
3718 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 backup_copy = TRUE;
3720 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003721# else
3722# ifdef WIN32
3723 /* On NTFS file systems hard links are possible. */
3724 if (mch_is_linked(fname))
3725 backup_copy = TRUE;
3726 else
3727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728# endif
3729 {
3730 /*
3731 * Check if we can create a file and set the owner/group to
3732 * the ones from the original file.
3733 * First find a file name that doesn't exist yet (use some
3734 * arbitrary numbers).
3735 */
3736 STRCPY(IObuff, fname);
3737 for (i = 4913; ; i += 123)
3738 {
3739 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003740 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 break;
3742 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743 fd = mch_open((char *)IObuff,
3744 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 if (fd < 0) /* can't write in directory */
3746 backup_copy = TRUE;
3747 else
3748 {
3749# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003750# ifdef HAVE_FCHOWN
Bram Moolenaar42335f52018-09-13 15:33:43 +02003751 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003752# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 if (mch_stat((char *)IObuff, &st) < 0
3754 || st.st_uid != st_old.st_uid
3755 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003756 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757 backup_copy = TRUE;
3758# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003759 /* Close the file before removing it, on MS-Windows we
3760 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003761 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003762 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003763# ifdef MSWIN
3764 /* MS-Windows may trigger a virus scanner to open the
3765 * file, we can't delete it then. Keep trying for half a
3766 * second. */
3767 {
3768 int try;
3769
3770 for (try = 0; try < 10; ++try)
3771 {
3772 if (mch_lstat((char *)IObuff, &st) < 0)
3773 break;
3774 ui_delay(50L, TRUE); /* wait 50 msec */
3775 mch_remove(IObuff);
3776 }
3777 }
3778# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 }
3780 }
3781 }
3782
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 /*
3784 * Break symlinks and/or hardlinks if we've been asked to.
3785 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003786 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003788# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 int lstat_res;
3790
3791 lstat_res = mch_lstat((char *)fname, &st);
3792
3793 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003794 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 && lstat_res == 0
3796 && st.st_ino != st_old.st_ino)
3797 backup_copy = FALSE;
3798
3799 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003800 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801 && st_old.st_nlink > 1
3802 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3803 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003804# else
3805# if defined(WIN32)
3806 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003807 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003808 backup_copy = FALSE;
3809
3810 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003811 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003812 backup_copy = FALSE;
3813# endif
3814# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816
3817#endif
3818
3819 /* make sure we have a valid backup extension to use */
3820 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 else
3823 backup_ext = p_bex;
3824
3825 if (backup_copy
3826 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3827 {
3828 int bfd;
3829 char_u *copybuf, *wp;
3830 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003831 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 char_u *dirp;
3833 char_u *rootname;
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003834#if defined(UNIX) || defined(WIN3264)
3835 char_u *p;
3836#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003837#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003839 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840#endif
3841
3842 copybuf = alloc(BUFSIZE + 1);
3843 if (copybuf == NULL)
3844 {
3845 some_error = TRUE; /* out of memory */
3846 goto nobackup;
3847 }
3848
3849 /*
3850 * Try to make the backup in each directory in the 'bdir' option.
3851 *
3852 * Unix semantics has it, that we may have a writable file,
3853 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3854 * - the directory is not writable,
3855 * - the file may be a symbolic link,
3856 * - the file may belong to another user/group, etc.
3857 *
3858 * For these reasons, the existing writable file must be truncated
3859 * and reused. Creation of a backup COPY will be attempted.
3860 */
3861 dirp = p_bdir;
3862 while (*dirp)
3863 {
3864#ifdef UNIX
3865 st_new.st_ino = 0;
3866 st_new.st_dev = 0;
3867 st_new.st_gid = 0;
3868#endif
3869
3870 /*
3871 * Isolate one directory name, using an entry in 'bdir'.
3872 */
3873 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003874
3875#if defined(UNIX) || defined(WIN3264)
3876 p = copybuf + STRLEN(copybuf);
3877 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
3878 // Ends with '//', use full path
3879 if ((p = make_percent_swname(copybuf, fname)) != NULL)
3880 {
3881 backup = modname(p, backup_ext, FALSE);
3882 vim_free(p);
3883 }
3884#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 rootname = get_file_in_dir(fname, copybuf);
3886 if (rootname == NULL)
3887 {
3888 some_error = TRUE; /* out of memory */
3889 goto nobackup;
3890 }
3891
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003892#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 did_set_shortname = FALSE;
3894#endif
3895
3896 /*
3897 * May try twice if 'shortname' not set.
3898 */
3899 for (;;)
3900 {
3901 /*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003902 * Make the backup file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003904 if (backup == NULL)
3905 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 rootname, backup_ext, FALSE);
3907 if (backup == NULL)
3908 {
3909 vim_free(rootname);
3910 some_error = TRUE; /* out of memory */
3911 goto nobackup;
3912 }
3913
3914 /*
3915 * Check if backup file already exists.
3916 */
3917 if (mch_stat((char *)backup, &st_new) >= 0)
3918 {
3919#ifdef UNIX
3920 /*
3921 * Check if backup file is same as original file.
3922 * May happen when modname() gave the same file back.
3923 * E.g. silly link, or file name-length reached.
3924 * If we don't check here, we either ruin the file
3925 * when copying or erase it after writing. jw.
3926 */
3927 if (st_new.st_dev == st_old.st_dev
3928 && st_new.st_ino == st_old.st_ino)
3929 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003930 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931 /*
3932 * may try again with 'shortname' set
3933 */
3934 if (!(buf->b_shortname || buf->b_p_sn))
3935 {
3936 buf->b_shortname = TRUE;
3937 did_set_shortname = TRUE;
3938 continue;
3939 }
3940 /* setting shortname didn't help */
3941 if (did_set_shortname)
3942 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 break;
3944 }
3945#endif
3946
3947 /*
3948 * If we are not going to keep the backup file, don't
3949 * delete an existing one, try to use another name.
3950 * Change one character, just before the extension.
3951 */
3952 if (!p_bk)
3953 {
3954 wp = backup + STRLEN(backup) - 1
3955 - STRLEN(backup_ext);
3956 if (wp < backup) /* empty file name ??? */
3957 wp = backup;
3958 *wp = 'z';
3959 while (*wp > 'a'
3960 && mch_stat((char *)backup, &st_new) >= 0)
3961 --*wp;
3962 /* They all exist??? Must be something wrong. */
3963 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003964 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 }
3966 }
3967 break;
3968 }
3969 vim_free(rootname);
3970
3971 /*
3972 * Try to create the backup file
3973 */
3974 if (backup != NULL)
3975 {
3976 /* remove old backup, if present */
3977 mch_remove(backup);
3978 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003979 * we were sleeping (symlink hacker attack?). Reset umask
3980 * if possible to avoid mch_setperm() below. */
3981#ifdef UNIX
3982 umask_save = umask(0);
3983#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003985 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3986 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003987#ifdef UNIX
3988 (void)umask(umask_save);
3989#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003990 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003991 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992 else
3993 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003994 /* Set file protection same as original file, but
3995 * strip s-bit. Only needed if umask() wasn't used
3996 * above. */
3997#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003999#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000 /*
4001 * Try to set the group of the backup same as the
4002 * original file. If this fails, set the protection
4003 * bits for the group same as the protection bits for
4004 * others.
4005 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004006 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004008 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009# endif
4010 )
4011 mch_setperm(backup,
4012 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004013# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004014 mch_copy_sec(fname, backup);
4015# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016#endif
4017
4018 /*
4019 * copy the file.
4020 */
4021 write_info.bw_fd = bfd;
4022 write_info.bw_buf = copybuf;
4023#ifdef HAS_BW_FLAGS
4024 write_info.bw_flags = FIO_NOCONVERT;
4025#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004026 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027 BUFSIZE)) > 0)
4028 {
4029 if (buf_write_bytes(&write_info) == FAIL)
4030 {
4031 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4032 break;
4033 }
4034 ui_breakcheck();
4035 if (got_int)
4036 {
4037 errmsg = (char_u *)_(e_interr);
4038 break;
4039 }
4040 }
4041
4042 if (close(bfd) < 0 && errmsg == NULL)
4043 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4044 if (write_info.bw_len < 0)
4045 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4046#ifdef UNIX
4047 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4048#endif
4049#ifdef HAVE_ACL
4050 mch_set_acl(backup, acl);
4051#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004052#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004053 mch_copy_sec(fname, backup);
4054#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 break;
4056 }
4057 }
4058 }
4059 nobackup:
4060 close(fd); /* ignore errors for closing read file */
4061 vim_free(copybuf);
4062
4063 if (backup == NULL && errmsg == NULL)
4064 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4065 /* ignore errors when forceit is TRUE */
4066 if ((some_error || errmsg != NULL) && !forceit)
4067 {
4068 retval = FAIL;
4069 goto fail;
4070 }
4071 errmsg = NULL;
4072 }
4073 else
4074 {
4075 char_u *dirp;
4076 char_u *p;
4077 char_u *rootname;
4078
4079 /*
4080 * Make a backup by renaming the original file.
4081 */
4082 /*
4083 * If 'cpoptions' includes the "W" flag, we don't want to
4084 * overwrite a read-only file. But rename may be possible
4085 * anyway, thus we need an extra check here.
4086 */
4087 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4088 {
4089 errnum = (char_u *)"E504: ";
4090 errmsg = (char_u *)_(err_readonly);
4091 goto fail;
4092 }
4093
4094 /*
4095 *
4096 * Form the backup file name - change path/fo.o.h to
4097 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4098 * that works is used.
4099 */
4100 dirp = p_bdir;
4101 while (*dirp)
4102 {
4103 /*
4104 * Isolate one directory name and make the backup file name.
4105 */
4106 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004107
4108#if defined(UNIX) || defined(WIN3264)
4109 p = IObuff + STRLEN(IObuff);
4110 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
4111 // path ends with '//', use full path
4112 if ((p = make_percent_swname(IObuff, fname)) != NULL)
4113 {
4114 backup = modname(p, backup_ext, FALSE);
4115 vim_free(p);
4116 }
4117#endif
4118 if (backup == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 {
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004120 rootname = get_file_in_dir(fname, IObuff);
4121 if (rootname == NULL)
4122 backup = NULL;
4123 else
4124 {
4125 backup = buf_modname(
4126 (buf->b_p_sn || buf->b_shortname),
4127 rootname, backup_ext, FALSE);
4128 vim_free(rootname);
4129 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 }
4131
4132 if (backup != NULL)
4133 {
4134 /*
4135 * If we are not going to keep the backup file, don't
4136 * delete an existing one, try to use another name.
4137 * Change one character, just before the extension.
4138 */
4139 if (!p_bk && mch_getperm(backup) >= 0)
4140 {
4141 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4142 if (p < backup) /* empty file name ??? */
4143 p = backup;
4144 *p = 'z';
4145 while (*p > 'a' && mch_getperm(backup) >= 0)
4146 --*p;
4147 /* They all exist??? Must be something wrong! */
4148 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004149 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 }
4151 }
4152 if (backup != NULL)
4153 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004155 * Delete any existing backup and move the current version
4156 * to the backup. For safety, we don't remove the backup
4157 * until the write has finished successfully. And if the
4158 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 */
4160 /*
4161 * If the renaming of the original file to the backup file
4162 * works, quit here.
4163 */
4164 if (vim_rename(fname, backup) == 0)
4165 break;
4166
Bram Moolenaard23a8232018-02-10 18:45:26 +01004167 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 }
4169 }
4170 if (backup == NULL && !forceit)
4171 {
4172 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4173 goto fail;
4174 }
4175 }
4176 }
4177
Bram Moolenaar53076832015-12-31 19:53:21 +01004178#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 /* When using ":w!" and the file was read-only: make it writable */
4180 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4181 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4182 {
4183 perm |= 0200;
4184 (void)mch_setperm(fname, perm);
4185 made_writable = TRUE;
4186 }
4187#endif
4188
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004189 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004190 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4191 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 {
4193 buf->b_p_ro = FALSE;
4194#ifdef FEAT_TITLE
4195 need_maketitle = TRUE; /* set window title later */
4196#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 }
4199
4200 if (end > buf->b_ml.ml_line_count)
4201 end = buf->b_ml.ml_line_count;
4202 if (buf->b_ml.ml_flags & ML_EMPTY)
4203 start = end + 1;
4204
4205 /*
4206 * If the original file is being overwritten, there is a small chance that
4207 * we crash in the middle of writing. Therefore the file is preserved now.
4208 * This makes all block numbers positive so that recovery does not need
4209 * the original file.
4210 * Don't do this if there is a backup file and we are exiting.
4211 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004212 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004213 && !(exiting && backup != NULL))
4214 {
4215 ml_preserve(buf, FALSE);
4216 if (got_int)
4217 {
4218 errmsg = (char_u *)_(e_interr);
4219 goto restore_backup;
4220 }
4221 }
4222
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223#ifdef VMS
4224 vms_remove_version(fname); /* remove version */
4225#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004226 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 * multi-byte conversion. */
4228 wfname = fname;
4229
4230#ifdef FEAT_MBYTE
4231 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4232 if (eap != NULL && eap->force_enc != 0)
4233 {
4234 fenc = eap->cmd + eap->force_enc;
4235 fenc = enc_canonize(fenc);
4236 fenc_tofree = fenc;
4237 }
4238 else
4239 fenc = buf->b_p_fenc;
4240
4241 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004242 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004244 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245
4246 /*
4247 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4248 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4249 * Prepare the flags for it and allocate bw_conv_buf when needed.
4250 */
4251 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4252 {
4253 wb_flags = get_fio_flags(fenc);
4254 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4255 {
4256 /* Need to allocate a buffer to translate into. */
4257 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4258 write_info.bw_conv_buflen = bufsize * 2;
4259 else /* FIO_UCS4 */
4260 write_info.bw_conv_buflen = bufsize * 4;
4261 write_info.bw_conv_buf
4262 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4263 if (write_info.bw_conv_buf == NULL)
4264 end = 0;
4265 }
4266 }
4267
4268# ifdef WIN3264
4269 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4270 {
4271 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4272 write_info.bw_conv_buflen = bufsize * 4;
4273 write_info.bw_conv_buf
4274 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4275 if (write_info.bw_conv_buf == NULL)
4276 end = 0;
4277 }
4278# endif
4279
Bram Moolenaard0573012017-10-28 21:11:06 +02004280# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4282 {
4283 write_info.bw_conv_buflen = bufsize * 3;
4284 write_info.bw_conv_buf
4285 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4286 if (write_info.bw_conv_buf == NULL)
4287 end = 0;
4288 }
4289# endif
4290
4291# if defined(FEAT_EVAL) || defined(USE_ICONV)
4292 if (converted && wb_flags == 0)
4293 {
4294# ifdef USE_ICONV
4295 /*
4296 * Use iconv() conversion when conversion is needed and it's not done
4297 * internally.
4298 */
4299 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4300 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4301 if (write_info.bw_iconv_fd != (iconv_t)-1)
4302 {
4303 /* We're going to use iconv(), allocate a buffer to convert in. */
4304 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4305 write_info.bw_conv_buf
4306 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4307 if (write_info.bw_conv_buf == NULL)
4308 end = 0;
4309 write_info.bw_first = TRUE;
4310 }
4311# ifdef FEAT_EVAL
4312 else
4313# endif
4314# endif
4315
4316# ifdef FEAT_EVAL
4317 /*
4318 * When the file needs to be converted with 'charconvert' after
4319 * writing, write to a temp file instead and let the conversion
4320 * overwrite the original file.
4321 */
4322 if (*p_ccv != NUL)
4323 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004324 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325 if (wfname == NULL) /* Can't write without a tempfile! */
4326 {
4327 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4328 goto restore_backup;
4329 }
4330 }
4331# endif
4332 }
4333# endif
4334 if (converted && wb_flags == 0
4335# ifdef USE_ICONV
4336 && write_info.bw_iconv_fd == (iconv_t)-1
4337# endif
4338# ifdef FEAT_EVAL
4339 && wfname == fname
4340# endif
4341 )
4342 {
4343 if (!forceit)
4344 {
4345 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4346 goto restore_backup;
4347 }
4348 notconverted = TRUE;
4349 }
4350#endif
4351
4352 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004353 * If conversion is taking place, we may first pretend to write and check
4354 * for conversion errors. Then loop again to write for real.
4355 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004357 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 {
4359 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004360 * There is no need to check conversion when:
4361 * - there is no conversion
4362 * - we make a backup file, that can be restored in case of conversion
4363 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004364 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004365#ifdef FEAT_MBYTE
4366 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004368 checking_conversion = FALSE;
4369
4370 if (checking_conversion)
4371 {
4372 /* Make sure we don't write anything. */
4373 fd = -1;
4374 write_info.bw_fd = fd;
4375 }
4376 else
4377 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004378#ifdef HAVE_FTRUNCATE
4379# define TRUNC_ON_OPEN 0
4380#else
4381# define TRUNC_ON_OPEN O_TRUNC
4382#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004383 /*
4384 * Open the file "wfname" for writing.
4385 * We may try to open the file twice: If we can't write to the file
4386 * and forceit is TRUE we delete the existing file and try to
4387 * create a new one. If this still fails we may have lost the
4388 * original file! (this may happen when the user reached his
4389 * quotum for number of files).
4390 * Appending will fail if the file does not exist and forceit is
4391 * FALSE.
4392 */
4393 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4394 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004395 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004396 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004397 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004398 /*
4399 * A forced write will try to create a new file if the old one
4400 * is still readonly. This may also happen when the directory
4401 * is read-only. In that case the mch_remove() will fail.
4402 */
4403 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004404 {
4405#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004406 stat_T st;
4407
4408 /* Don't delete the file when it's a hard or symbolic link.
4409 */
4410 if ((!newfile && st_old.st_nlink > 1)
4411 || (mch_lstat((char *)fname, &st) == 0
4412 && (st.st_dev != st_old.st_dev
4413 || st.st_ino != st_old.st_ino)))
4414 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4415 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004417 {
4418 errmsg = (char_u *)_("E212: Can't open file for writing");
4419 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4420 && perm >= 0)
4421 {
4422#ifdef UNIX
4423 /* we write to the file, thus it should be marked
4424 writable after all */
4425 if (!(perm & 0200))
4426 made_writable = TRUE;
4427 perm |= 0200;
4428 if (st_old.st_uid != getuid()
4429 || st_old.st_gid != getgid())
4430 perm &= 0777;
4431#endif
4432 if (!append) /* don't remove when appending */
4433 mch_remove(wfname);
4434 continue;
4435 }
4436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438
4439restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004441 stat_T st;
4442
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004444 * If we failed to open the file, we don't need a backup.
4445 * Throw it away. If we moved or removed the original file
4446 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004448 if (backup != NULL && wfname == fname)
4449 {
4450 if (backup_copy)
4451 {
4452 /*
4453 * There is a small chance that we removed the
4454 * original, try to move the copy in its place.
4455 * This may not work if the vim_rename() fails.
4456 * In that case we leave the copy around.
4457 */
4458 /* If file does not exist, put the copy in its
4459 * place */
4460 if (mch_stat((char *)fname, &st) < 0)
4461 vim_rename(backup, fname);
4462 /* if original file does exist throw away the copy
4463 */
4464 if (mch_stat((char *)fname, &st) >= 0)
4465 mch_remove(backup);
4466 }
4467 else
4468 {
4469 /* try to put the original file back */
4470 vim_rename(backup, fname);
4471 }
4472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004474 /* if original file no longer exists give an extra warning
4475 */
4476 if (!newfile && mch_stat((char *)fname, &st) < 0)
4477 end = 0;
4478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479
4480#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004481 if (wfname != fname)
4482 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004484 goto fail;
4485 }
4486 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004488#if defined(UNIX)
4489 {
4490 stat_T st;
4491
4492 /* Double check we are writing the intended file before making
4493 * any changes. */
4494 if (overwriting
4495 && (!dobackup || backup_copy)
4496 && fname == wfname
4497 && perm >= 0
4498 && mch_fstat(fd, &st) == 0
4499 && st.st_ino != st_old.st_ino)
4500 {
4501 close(fd);
4502 errmsg = (char_u *)_("E949: File changed while writing");
4503 goto fail;
4504 }
4505 }
4506#endif
4507#ifdef HAVE_FTRUNCATE
4508 if (!append)
Bram Moolenaar42335f52018-09-13 15:33:43 +02004509 vim_ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004510#endif
4511
Bram Moolenaard0573012017-10-28 21:11:06 +02004512#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004513 if (backup != NULL && overwriting && !append)
4514 {
4515 if (backup_copy)
4516 (void)mch_copy_file_attribute(wfname, backup);
4517 else
4518 (void)mch_copy_file_attribute(backup, wfname);
4519 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004521 if (!overwriting && !append)
4522 {
4523 if (buf->b_ffname != NULL)
4524 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4525 /* Should copy resource fork */
4526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527#endif
4528
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004530 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004532 char_u *header;
4533 int header_len;
4534
4535 buf->b_cryptstate = crypt_create_for_writing(
4536 crypt_get_method_nr(buf),
4537 buf->b_p_key, &header, &header_len);
4538 if (buf->b_cryptstate == NULL || header == NULL)
4539 end = 0;
4540 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004542 /* Write magic number, so that Vim knows how this file is
4543 * encrypted when reading it back. */
4544 write_info.bw_buf = header;
4545 write_info.bw_len = header_len;
4546 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004548 end = 0;
4549 wb_flags |= FIO_ENCRYPTED;
4550 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004553#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004554 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004555 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004557 write_info.bw_buf = buffer;
4558 nchars = 0;
4559
4560 /* use "++bin", "++nobin" or 'binary' */
4561 if (eap != NULL && eap->force_bin != 0)
4562 write_bin = (eap->force_bin == FORCE_BIN);
4563 else
4564 write_bin = buf->b_p_bin;
4565
4566#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004568 * The BOM is written just after the encryption magic number.
4569 * Skip it when appending and the file already existed, the BOM only
4570 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004572 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004574 write_info.bw_len = make_bom(buffer, fenc);
4575 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004577 /* don't convert, do encryption */
4578 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4579 if (buf_write_bytes(&write_info) == FAIL)
4580 end = 0;
4581 else
4582 nchars += write_info.bw_len;
4583 }
4584 }
4585 write_info.bw_start_lnum = start;
4586#endif
4587
4588#ifdef FEAT_PERSISTENT_UNDO
4589 write_undo_file = (buf->b_p_udf
4590 && overwriting
4591 && !append
4592 && !filtering
4593 && reset_changed
4594 && !checking_conversion);
4595 if (write_undo_file)
4596 /* Prepare for computing the hash value of the text. */
4597 sha256_start(&sha_ctx);
4598#endif
4599
4600 write_info.bw_len = bufsize;
4601#ifdef HAS_BW_FLAGS
4602 write_info.bw_flags = wb_flags;
4603#endif
4604 fileformat = get_fileformat_force(buf, eap);
4605 s = buffer;
4606 len = 0;
4607 for (lnum = start; lnum <= end; ++lnum)
4608 {
4609 /*
4610 * The next while loop is done once for each character written.
4611 * Keep it fast!
4612 */
4613 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4614#ifdef FEAT_PERSISTENT_UNDO
4615 if (write_undo_file)
4616 sha256_update(&sha_ctx, ptr + 1,
4617 (UINT32_T)(STRLEN(ptr + 1) + 1));
4618#endif
4619 while ((c = *++ptr) != NUL)
4620 {
4621 if (c == NL)
4622 *s = NUL; /* replace newlines with NULs */
4623 else if (c == CAR && fileformat == EOL_MAC)
4624 *s = NL; /* Mac: replace CRs with NLs */
4625 else
4626 *s = c;
4627 ++s;
4628 if (++len != bufsize)
4629 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004630 if (buf_write_bytes(&write_info) == FAIL)
4631 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004632 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004633 break;
4634 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004635 nchars += bufsize;
4636 s = buffer;
4637 len = 0;
4638#ifdef FEAT_MBYTE
4639 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004641 }
4642 /* write failed or last line has no EOL: stop here */
4643 if (end == 0
4644 || (lnum == end
4645 && (write_bin || !buf->b_p_fixeol)
4646 && (lnum == buf->b_no_eol_lnum
4647 || (lnum == buf->b_ml.ml_line_count
4648 && !buf->b_p_eol))))
4649 {
4650 ++lnum; /* written the line, count it */
4651 no_eol = TRUE;
4652 break;
4653 }
4654 if (fileformat == EOL_UNIX)
4655 *s++ = NL;
4656 else
4657 {
4658 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4659 if (fileformat == EOL_DOS) /* write CR-NL */
4660 {
4661 if (++len == bufsize)
4662 {
4663 if (buf_write_bytes(&write_info) == FAIL)
4664 {
4665 end = 0; /* write error: break loop */
4666 break;
4667 }
4668 nchars += bufsize;
4669 s = buffer;
4670 len = 0;
4671 }
4672 *s++ = NL;
4673 }
4674 }
4675 if (++len == bufsize && end)
4676 {
4677 if (buf_write_bytes(&write_info) == FAIL)
4678 {
4679 end = 0; /* write error: break loop */
4680 break;
4681 }
4682 nchars += bufsize;
4683 s = buffer;
4684 len = 0;
4685
4686 ui_breakcheck();
4687 if (got_int)
4688 {
4689 end = 0; /* Interrupted, break loop */
4690 break;
4691 }
4692 }
4693#ifdef VMS
4694 /*
4695 * On VMS there is a problem: newlines get added when writing
4696 * blocks at a time. Fix it by writing a line at a time.
4697 * This is much slower!
4698 * Explanation: VAX/DECC RTL insists that records in some RMS
4699 * structures end with a newline (carriage return) character, and
4700 * if they don't it adds one.
4701 * With other RMS structures it works perfect without this fix.
4702 */
4703 if (buf->b_fab_rfm == FAB$C_VFC
4704 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4705 {
4706 int b2write;
4707
4708 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4709 ? MIN(4096, bufsize)
4710 : MIN(buf->b_fab_mrs, bufsize));
4711
4712 b2write = len;
4713 while (b2write > 0)
4714 {
4715 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4716 if (buf_write_bytes(&write_info) == FAIL)
4717 {
4718 end = 0;
4719 break;
4720 }
4721 b2write -= MIN(b2write, buf->b_fab_mrs);
4722 }
4723 write_info.bw_len = bufsize;
4724 nchars += len;
4725 s = buffer;
4726 len = 0;
4727 }
4728#endif
4729 }
4730 if (len > 0 && end > 0)
4731 {
4732 write_info.bw_len = len;
4733 if (buf_write_bytes(&write_info) == FAIL)
4734 end = 0; /* write error */
4735 nchars += len;
4736 }
4737
4738 /* Stop when writing done or an error was encountered. */
4739 if (!checking_conversion || end == 0)
4740 break;
4741
4742 /* If no error happened until now, writing should be ok, so loop to
4743 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 }
4745
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004746 /* If we started writing, finish writing. Also when an error was
4747 * encountered. */
4748 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004750#if defined(UNIX) && defined(HAVE_FSYNC)
4751 /*
4752 * On many journalling file systems there is a bug that causes both the
4753 * original and the backup file to be lost when halting the system
4754 * right after writing the file. That's because only the meta-data is
4755 * journalled. Syncing the file slows down the system, but assures it
4756 * has been written to disk and we don't lose it.
4757 * For a device do try the fsync() but don't complain if it does not
4758 * work (could be a pipe).
4759 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4760 */
4761 if (p_fs && fsync(fd) != 0 && !device)
4762 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004763 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764 end = 0;
4765 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766#endif
4767
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004768#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004769 /* Probably need to set the security context. */
4770 if (!backup_copy)
4771 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004772#endif
4773
Bram Moolenaara5792f52005-11-23 21:25:05 +00004774#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004775 /* When creating a new file, set its owner/group to that of the
4776 * original file. Get the new device and inode number. */
4777 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004778 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004779# ifdef HAVE_FCHOWN
4780 stat_T st;
4781
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004782 /* Don't change the owner when it's already OK, some systems remove
4783 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004784 if (mch_stat((char *)wfname, &st) < 0
4785 || st.st_uid != st_old.st_uid
4786 || st.st_gid != st_old.st_gid)
4787 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004788 /* changing owner might not be possible */
Bram Moolenaar42335f52018-09-13 15:33:43 +02004789 vim_ignored = fchown(fd, st_old.st_uid, -1);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004790 /* if changing group fails clear the group permissions */
4791 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4792 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004793 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004794# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004795 buf_setino(buf);
4796 }
4797 else if (!buf->b_dev_valid)
4798 /* Set the inode when creating a new file. */
4799 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004800#endif
4801
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004802#ifdef UNIX
4803 if (made_writable)
4804 perm &= ~0200; /* reset 'w' bit for security reasons */
4805#endif
4806#ifdef HAVE_FCHMOD
4807 /* set permission of new file same as old file */
4808 if (perm >= 0)
4809 (void)mch_fsetperm(fd, perm);
4810#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004811 if (close(fd) != 0)
4812 {
4813 errmsg = (char_u *)_("E512: Close failed");
4814 end = 0;
4815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004817#ifndef HAVE_FCHMOD
4818 /* set permission of new file same as old file */
4819 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004820 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004821#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004823 /*
4824 * Probably need to set the ACL before changing the user (can't set the
4825 * ACL on a file the user doesn't own).
4826 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4827 * default), chmod() discards all part of a file's ACL that don't
4828 * represent the mode of the file. It's non-trivial for us to discover
4829 * whether we're in that situation, so we simply always re-set the ACL.
4830 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004831# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004832 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004833# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004834 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004836#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004837 if (buf->b_cryptstate != NULL)
4838 {
4839 crypt_free_state(buf->b_cryptstate);
4840 buf->b_cryptstate = NULL;
4841 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004842#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843
Bram Moolenaar071d4272004-06-13 20:20:40 +00004844#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004845 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004847 /*
4848 * The file was written to a temp file, now it needs to be
4849 * converted with 'charconvert' to (overwrite) the output file.
4850 */
4851 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004853 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4854 fenc, wfname, fname) == FAIL)
4855 {
4856 write_info.bw_conv_error = TRUE;
4857 end = 0;
4858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004860 mch_remove(wfname);
4861 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004864 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865
4866 if (end == 0)
4867 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004868 /*
4869 * Error encountered.
4870 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 if (errmsg == NULL)
4872 {
4873#ifdef FEAT_MBYTE
4874 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004875 {
4876 if (write_info.bw_conv_error_lnum == 0)
4877 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4878 else
4879 {
4880 errmsg_allocated = TRUE;
4881 errmsg = alloc(300);
4882 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4883 (long)write_info.bw_conv_error_lnum);
4884 }
4885 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 else
4887#endif
4888 if (got_int)
4889 errmsg = (char_u *)_(e_interr);
4890 else
4891 errmsg = (char_u *)_("E514: write error (file system full?)");
4892 }
4893
4894 /*
4895 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004896 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 * original file when trying to make a backup when writing the file a
4898 * second time.
4899 * When "backup_copy" is set we need to copy the backup over the new
4900 * file. Otherwise rename the backup file.
4901 * If this is OK, don't give the extra warning message.
4902 */
4903 if (backup != NULL)
4904 {
4905 if (backup_copy)
4906 {
4907 /* This may take a while, if we were interrupted let the user
4908 * know we got the message. */
4909 if (got_int)
4910 {
4911 MSG(_(e_interr));
4912 out_flush();
4913 }
4914 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4915 {
4916 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004917 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4918 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 {
4920 /* copy the file. */
4921 write_info.bw_buf = smallbuf;
4922#ifdef HAS_BW_FLAGS
4923 write_info.bw_flags = FIO_NOCONVERT;
4924#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004925 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 SMBUFSIZE)) > 0)
4927 if (buf_write_bytes(&write_info) == FAIL)
4928 break;
4929
4930 if (close(write_info.bw_fd) >= 0
4931 && write_info.bw_len == 0)
4932 end = 1; /* success */
4933 }
4934 close(fd); /* ignore errors for closing read file */
4935 }
4936 }
4937 else
4938 {
4939 if (vim_rename(backup, fname) == 0)
4940 end = 1;
4941 }
4942 }
4943 goto fail;
4944 }
4945
4946 lnum -= start; /* compute number of written lines */
4947 --no_wait_return; /* may wait for return now */
4948
4949#if !(defined(UNIX) || defined(VMS))
4950 fname = sfname; /* use shortname now, for the messages */
4951#endif
4952 if (!filtering)
4953 {
4954 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4955 c = FALSE;
4956#ifdef FEAT_MBYTE
4957 if (write_info.bw_conv_error)
4958 {
4959 STRCAT(IObuff, _(" CONVERSION ERROR"));
4960 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004961 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004962 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004963 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 }
4965 else if (notconverted)
4966 {
4967 STRCAT(IObuff, _("[NOT converted]"));
4968 c = TRUE;
4969 }
4970 else if (converted)
4971 {
4972 STRCAT(IObuff, _("[converted]"));
4973 c = TRUE;
4974 }
4975#endif
4976 if (device)
4977 {
4978 STRCAT(IObuff, _("[Device]"));
4979 c = TRUE;
4980 }
4981 else if (newfile)
4982 {
4983 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4984 c = TRUE;
4985 }
4986 if (no_eol)
4987 {
4988 msg_add_eol();
4989 c = TRUE;
4990 }
4991 /* may add [unix/dos/mac] */
4992 if (msg_add_fileformat(fileformat))
4993 c = TRUE;
4994#ifdef FEAT_CRYPT
4995 if (wb_flags & FIO_ENCRYPTED)
4996 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004997 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004998 c = TRUE;
4999 }
5000#endif
5001 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
5002 if (!shortmess(SHM_WRITE))
5003 {
5004 if (append)
5005 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5006 else
5007 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5008 }
5009
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005010 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011 }
5012
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005013 /* When written everything correctly: reset 'modified'. Unless not
5014 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005015 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016#ifdef FEAT_MBYTE
5017 && !write_info.bw_conv_error
5018#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005019 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5020 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 {
5022 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005023 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005024 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01005025 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
5026 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005028 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 }
5030
5031 /*
5032 * If written to the current file, update the timestamp of the swap file
5033 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5034 */
5035 if (overwriting)
5036 {
5037 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005038 if (append)
5039 buf->b_flags &= ~BF_NEW;
5040 else
5041 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 }
5043
5044 /*
5045 * If we kept a backup until now, and we are in patch mode, then we make
5046 * the backup file our 'original' file.
5047 */
5048 if (*p_pm && dobackup)
5049 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005050 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 fname, p_pm, FALSE);
5052
5053 if (backup != NULL)
5054 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005055 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056
5057 /*
5058 * If the original file does not exist yet
5059 * the current backup file becomes the original file
5060 */
5061 if (org == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005062 emsg(_("E205: Patchmode: can't save original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063 else if (mch_stat(org, &st) < 0)
5064 {
5065 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005066 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067#ifdef UNIX
5068 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5069#endif
5070 }
5071 }
5072 /*
5073 * If there is no backup file, remember that a (new) file was
5074 * created.
5075 */
5076 else
5077 {
5078 int empty_fd;
5079
5080 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005081 || (empty_fd = mch_open(org,
5082 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005083 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005084 emsg(_("E206: patchmode: can't touch empty original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085 else
5086 close(empty_fd);
5087 }
5088 if (org != NULL)
5089 {
5090 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5091 vim_free(org);
5092 }
5093 }
5094
5095 /*
5096 * Remove the backup unless 'backup' option is set
5097 */
5098 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005099 emsg(_("E207: Can't delete backup file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005100
Bram Moolenaar071d4272004-06-13 20:20:40 +00005101 goto nofail;
5102
5103 /*
5104 * Finish up. We get here either after failure or success.
5105 */
5106fail:
5107 --no_wait_return; /* may wait for return now */
5108nofail:
5109
5110 /* Done saving, we accept changed buffer warnings again */
5111 buf->b_saving = FALSE;
5112
5113 vim_free(backup);
5114 if (buffer != smallbuf)
5115 vim_free(buffer);
5116#ifdef FEAT_MBYTE
5117 vim_free(fenc_tofree);
5118 vim_free(write_info.bw_conv_buf);
5119# ifdef USE_ICONV
5120 if (write_info.bw_iconv_fd != (iconv_t)-1)
5121 {
5122 iconv_close(write_info.bw_iconv_fd);
5123 write_info.bw_iconv_fd = (iconv_t)-1;
5124 }
5125# endif
5126#endif
5127#ifdef HAVE_ACL
5128 mch_free_acl(acl);
5129#endif
5130
5131 if (errmsg != NULL)
5132 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005133 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005134
Bram Moolenaar8820b482017-03-16 17:23:31 +01005135 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136 msg_add_fname(buf,
5137#ifndef UNIX
5138 sfname
5139#else
5140 fname
5141#endif
5142 ); /* put file name in IObuff with quotes */
5143 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5144 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5145 /* If the error message has the form "is ...", put the error number in
5146 * front of the file name. */
5147 if (errnum != NULL)
5148 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005149 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150 mch_memmove(IObuff, errnum, (size_t)numlen);
5151 }
5152 STRCAT(IObuff, errmsg);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005153 emsg((char *)IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005154 if (errmsg_allocated)
5155 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156
5157 retval = FAIL;
5158 if (end == 0)
5159 {
5160 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5161 attr | MSG_HIST);
5162 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5163 attr | MSG_HIST);
5164
5165 /* Update the timestamp to avoid an "overwrite changed file"
5166 * prompt when writing again. */
5167 if (mch_stat((char *)fname, &st_old) >= 0)
5168 {
5169 buf_store_time(buf, &st_old, fname);
5170 buf->b_mtime_read = buf->b_mtime;
5171 }
5172 }
5173 }
5174 msg_scroll = msg_save;
5175
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005176#ifdef FEAT_PERSISTENT_UNDO
5177 /*
5178 * When writing the whole file and 'undofile' is set, also write the undo
5179 * file.
5180 */
5181 if (retval == OK && write_undo_file)
5182 {
5183 char_u hash[UNDO_HASH_SIZE];
5184
5185 sha256_finish(&sha_ctx, hash);
5186 u_write_undo(NULL, FALSE, buf, hash);
5187 }
5188#endif
5189
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190#ifdef FEAT_EVAL
5191 if (!should_abort(retval))
5192#else
5193 if (!got_int)
5194#endif
5195 {
5196 aco_save_T aco;
5197
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005198 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5199
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200 /*
5201 * Apply POST autocommands.
5202 * Careful: The autocommands may call buf_write() recursively!
5203 */
5204 aucmd_prepbuf(&aco, buf);
5205
5206 if (append)
5207 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5208 FALSE, curbuf, eap);
5209 else if (filtering)
5210 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5211 FALSE, curbuf, eap);
5212 else if (reset_changed && whole)
5213 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5214 FALSE, curbuf, eap);
5215 else
5216 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5217 FALSE, curbuf, eap);
5218
5219 /* restore curwin/curbuf and a few other things */
5220 aucmd_restbuf(&aco);
5221
5222#ifdef FEAT_EVAL
5223 if (aborting()) /* autocmds may abort script processing */
5224 retval = FALSE;
5225#endif
5226 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227
5228 got_int |= prev_got_int;
5229
Bram Moolenaar071d4272004-06-13 20:20:40 +00005230 return retval;
5231}
5232
5233/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005234 * Set the name of the current buffer. Use when the buffer doesn't have a
5235 * name and a ":r" or ":w" command with a file name is used.
5236 */
5237 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005238set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005239{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005240 buf_T *buf = curbuf;
5241
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005242 /* It's like the unnamed buffer is deleted.... */
5243 if (curbuf->b_p_bl)
5244 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5245 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005246#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005247 if (aborting()) /* autocmds may abort script processing */
5248 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005249#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005250 if (curbuf != buf)
5251 {
5252 /* We are in another buffer now, don't do the renaming. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005253 emsg(_(e_auchangedbuf));
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005254 return FAIL;
5255 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005256
5257 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5258 curbuf->b_flags |= BF_NOTEDITED;
5259
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005260 /* ....and a new named one is created */
5261 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5262 if (curbuf->b_p_bl)
5263 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005264#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005265 if (aborting()) /* autocmds may abort script processing */
5266 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005267#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005268
5269 /* Do filetype detection now if 'filetype' is empty. */
5270 if (*curbuf->b_p_ft == NUL)
5271 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005272 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005273 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005274 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005275 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005276
5277 return OK;
5278}
5279
5280/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281 * Put file name into IObuff with quotes.
5282 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005283 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005284msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285{
5286 if (fname == NULL)
5287 fname = (char_u *)"-stdin-";
5288 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5289 IObuff[0] = '"';
5290 STRCAT(IObuff, "\" ");
5291}
5292
5293/*
5294 * Append message for text mode to IObuff.
5295 * Return TRUE if something appended.
5296 */
5297 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005298msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299{
5300#ifndef USE_CRNL
5301 if (eol_type == EOL_DOS)
5302 {
5303 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5304 return TRUE;
5305 }
5306#endif
5307#ifndef USE_CR
5308 if (eol_type == EOL_MAC)
5309 {
5310 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5311 return TRUE;
5312 }
5313#endif
5314#if defined(USE_CRNL) || defined(USE_CR)
5315 if (eol_type == EOL_UNIX)
5316 {
5317 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5318 return TRUE;
5319 }
5320#endif
5321 return FALSE;
5322}
5323
5324/*
5325 * Append line and character count to IObuff.
5326 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005327 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005328msg_add_lines(
5329 int insert_space,
5330 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005331 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332{
5333 char_u *p;
5334
5335 p = IObuff + STRLEN(IObuff);
5336
5337 if (insert_space)
5338 *p++ = ' ';
5339 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005340 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01005341 "%ldL, %lldC", lnum, (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 else
5343 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005344 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005346 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5347 NGETTEXT("%lld character", "%lld characters", nchars),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01005348 (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349 }
5350}
5351
5352/*
5353 * Append message for missing line separator to IObuff.
5354 */
5355 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005356msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005357{
5358 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5359}
5360
5361/*
5362 * Check modification time of file, before writing to it.
5363 * The size isn't checked, because using a tool like "gzip" takes care of
5364 * using the same timestamp but can't set the size.
5365 */
5366 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005367check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368{
5369 if (buf->b_mtime_read != 0
5370 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5371 {
5372 msg_scroll = TRUE; /* don't overwrite messages here */
5373 msg_silent = 0; /* must give this prompt */
5374 /* don't use emsg() here, don't want to flush the buffers */
5375 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005376 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5378 TRUE) == 'n')
5379 return FAIL;
5380 msg_scroll = FALSE; /* always overwrite the file message now */
5381 }
5382 return OK;
5383}
5384
5385 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005386time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005388#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5390 * the seconds. Since the roundoff is done when flushing the inode, the
5391 * time may change unexpectedly by one second!!! */
5392 return (t1 - t2 > 1 || t2 - t1 > 1);
5393#else
5394 return (t1 != t2);
5395#endif
5396}
5397
5398/*
5399 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005400 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005401 *
5402 * Return FAIL for failure, OK otherwise.
5403 */
5404 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005405buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005406{
5407 int wlen;
5408 char_u *buf = ip->bw_buf; /* data to write */
5409 int len = ip->bw_len; /* length of data */
5410#ifdef HAS_BW_FLAGS
5411 int flags = ip->bw_flags; /* extra flags */
5412#endif
5413
5414#ifdef FEAT_MBYTE
5415 /*
5416 * Skip conversion when writing the crypt magic number or the BOM.
5417 */
5418 if (!(flags & FIO_NOCONVERT))
5419 {
5420 char_u *p;
5421 unsigned c;
5422 int n;
5423
5424 if (flags & FIO_UTF8)
5425 {
5426 /*
5427 * Convert latin1 in the buffer to UTF-8 in the file.
5428 */
5429 p = ip->bw_conv_buf; /* translate to buffer */
5430 for (wlen = 0; wlen < len; ++wlen)
5431 p += utf_char2bytes(buf[wlen], p);
5432 buf = ip->bw_conv_buf;
5433 len = (int)(p - ip->bw_conv_buf);
5434 }
5435 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5436 {
5437 /*
5438 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5439 * Latin1 chars in the file.
5440 */
5441 if (flags & FIO_LATIN1)
5442 p = buf; /* translate in-place (can only get shorter) */
5443 else
5444 p = ip->bw_conv_buf; /* translate to buffer */
5445 for (wlen = 0; wlen < len; wlen += n)
5446 {
5447 if (wlen == 0 && ip->bw_restlen != 0)
5448 {
5449 int l;
5450
5451 /* Use remainder of previous call. Append the start of
5452 * buf[] to get a full sequence. Might still be too
5453 * short! */
5454 l = CONV_RESTLEN - ip->bw_restlen;
5455 if (l > len)
5456 l = len;
5457 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005458 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459 if (n > ip->bw_restlen + len)
5460 {
5461 /* We have an incomplete byte sequence at the end to
5462 * be written. We can't convert it without the
5463 * remaining bytes. Keep them for the next call. */
5464 if (ip->bw_restlen + len > CONV_RESTLEN)
5465 return FAIL;
5466 ip->bw_restlen += len;
5467 break;
5468 }
5469 if (n > 1)
5470 c = utf_ptr2char(ip->bw_rest);
5471 else
5472 c = ip->bw_rest[0];
5473 if (n >= ip->bw_restlen)
5474 {
5475 n -= ip->bw_restlen;
5476 ip->bw_restlen = 0;
5477 }
5478 else
5479 {
5480 ip->bw_restlen -= n;
5481 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5482 (size_t)ip->bw_restlen);
5483 n = 0;
5484 }
5485 }
5486 else
5487 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005488 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489 if (n > len - wlen)
5490 {
5491 /* We have an incomplete byte sequence at the end to
5492 * be written. We can't convert it without the
5493 * remaining bytes. Keep them for the next call. */
5494 if (len - wlen > CONV_RESTLEN)
5495 return FAIL;
5496 ip->bw_restlen = len - wlen;
5497 mch_memmove(ip->bw_rest, buf + wlen,
5498 (size_t)ip->bw_restlen);
5499 break;
5500 }
5501 if (n > 1)
5502 c = utf_ptr2char(buf + wlen);
5503 else
5504 c = buf[wlen];
5505 }
5506
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005507 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5508 {
5509 ip->bw_conv_error = TRUE;
5510 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5511 }
5512 if (c == NL)
5513 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514 }
5515 if (flags & FIO_LATIN1)
5516 len = (int)(p - buf);
5517 else
5518 {
5519 buf = ip->bw_conv_buf;
5520 len = (int)(p - ip->bw_conv_buf);
5521 }
5522 }
5523
5524# ifdef WIN3264
5525 else if (flags & FIO_CODEPAGE)
5526 {
5527 /*
5528 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5529 * codepage.
5530 */
5531 char_u *from;
5532 size_t fromlen;
5533 char_u *to;
5534 int u8c;
5535 BOOL bad = FALSE;
5536 int needed;
5537
5538 if (ip->bw_restlen > 0)
5539 {
5540 /* Need to concatenate the remainder of the previous call and
5541 * the bytes of the current call. Use the end of the
5542 * conversion buffer for this. */
5543 fromlen = len + ip->bw_restlen;
5544 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5545 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5546 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5547 }
5548 else
5549 {
5550 from = buf;
5551 fromlen = len;
5552 }
5553
5554 to = ip->bw_conv_buf;
5555 if (enc_utf8)
5556 {
5557 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5558 * The buffer has been allocated to be big enough. */
5559 while (fromlen > 0)
5560 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005561 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 if (n > (int)fromlen) /* incomplete byte sequence */
5563 break;
5564 u8c = utf_ptr2char(from);
5565 *to++ = (u8c & 0xff);
5566 *to++ = (u8c >> 8);
5567 fromlen -= n;
5568 from += n;
5569 }
5570
5571 /* Copy remainder to ip->bw_rest[] to be used for the next
5572 * call. */
5573 if (fromlen > CONV_RESTLEN)
5574 {
5575 /* weird overlong sequence */
5576 ip->bw_conv_error = TRUE;
5577 return FAIL;
5578 }
5579 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005580 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005581 }
5582 else
5583 {
5584 /* Convert from enc_codepage to UCS-2, to the start of the
5585 * buffer. The buffer has been allocated to be big enough. */
5586 ip->bw_restlen = 0;
5587 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005588 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 NULL, 0);
5590 if (needed == 0)
5591 {
5592 /* When conversion fails there may be a trailing byte. */
5593 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005594 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595 NULL, 0);
5596 if (needed == 0)
5597 {
5598 /* Conversion doesn't work. */
5599 ip->bw_conv_error = TRUE;
5600 return FAIL;
5601 }
5602 /* Save the trailing byte for the next call. */
5603 ip->bw_rest[0] = from[fromlen - 1];
5604 ip->bw_restlen = 1;
5605 }
5606 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005607 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 (LPWSTR)to, needed);
5609 if (needed == 0)
5610 {
5611 /* Safety check: Conversion doesn't work. */
5612 ip->bw_conv_error = TRUE;
5613 return FAIL;
5614 }
5615 to += needed * 2;
5616 }
5617
5618 fromlen = to - ip->bw_conv_buf;
5619 buf = to;
5620# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5621 if (FIO_GET_CP(flags) == CP_UTF8)
5622 {
5623 /* Convert from UCS-2 to UTF-8, using the remainder of the
5624 * conversion buffer. Fails when out of space. */
5625 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5626 {
5627 u8c = *from++;
5628 u8c += (*from++ << 8);
5629 to += utf_char2bytes(u8c, to);
5630 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5631 {
5632 ip->bw_conv_error = TRUE;
5633 return FAIL;
5634 }
5635 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005636 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637 }
5638 else
5639#endif
5640 {
5641 /* Convert from UCS-2 to the codepage, using the remainder of
5642 * the conversion buffer. If the conversion uses the default
5643 * character "0", the data doesn't fit in this encoding, so
5644 * fail. */
5645 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5646 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005647 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5648 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 if (bad)
5650 {
5651 ip->bw_conv_error = TRUE;
5652 return FAIL;
5653 }
5654 }
5655 }
5656# endif
5657
Bram Moolenaar56718732006-03-15 22:53:57 +00005658# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659 else if (flags & FIO_MACROMAN)
5660 {
5661 /*
5662 * Convert UTF-8 or latin1 to Apple MacRoman.
5663 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 char_u *from;
5665 size_t fromlen;
5666
5667 if (ip->bw_restlen > 0)
5668 {
5669 /* Need to concatenate the remainder of the previous call and
5670 * the bytes of the current call. Use the end of the
5671 * conversion buffer for this. */
5672 fromlen = len + ip->bw_restlen;
5673 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5674 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5675 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5676 }
5677 else
5678 {
5679 from = buf;
5680 fromlen = len;
5681 }
5682
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005683 if (enc2macroman(from, fromlen,
5684 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5685 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686 {
5687 ip->bw_conv_error = TRUE;
5688 return FAIL;
5689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691 }
5692# endif
5693
5694# ifdef USE_ICONV
5695 if (ip->bw_iconv_fd != (iconv_t)-1)
5696 {
5697 const char *from;
5698 size_t fromlen;
5699 char *to;
5700 size_t tolen;
5701
5702 /* Convert with iconv(). */
5703 if (ip->bw_restlen > 0)
5704 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005705 char *fp;
5706
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 /* Need to concatenate the remainder of the previous call and
5708 * the bytes of the current call. Use the end of the
5709 * conversion buffer for this. */
5710 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005711 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5712 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5713 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5714 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715 tolen = ip->bw_conv_buflen - fromlen;
5716 }
5717 else
5718 {
5719 from = (const char *)buf;
5720 fromlen = len;
5721 tolen = ip->bw_conv_buflen;
5722 }
5723 to = (char *)ip->bw_conv_buf;
5724
5725 if (ip->bw_first)
5726 {
5727 size_t save_len = tolen;
5728
5729 /* output the initial shift state sequence */
5730 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5731
5732 /* There is a bug in iconv() on Linux (which appears to be
5733 * wide-spread) which sets "to" to NULL and messes up "tolen".
5734 */
5735 if (to == NULL)
5736 {
5737 to = (char *)ip->bw_conv_buf;
5738 tolen = save_len;
5739 }
5740 ip->bw_first = FALSE;
5741 }
5742
5743 /*
5744 * If iconv() has an error or there is not enough room, fail.
5745 */
5746 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5747 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5748 || fromlen > CONV_RESTLEN)
5749 {
5750 ip->bw_conv_error = TRUE;
5751 return FAIL;
5752 }
5753
5754 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5755 if (fromlen > 0)
5756 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5757 ip->bw_restlen = (int)fromlen;
5758
5759 buf = ip->bw_conv_buf;
5760 len = (int)((char_u *)to - ip->bw_conv_buf);
5761 }
5762# endif
5763 }
5764#endif /* FEAT_MBYTE */
5765
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005766 if (ip->bw_fd < 0)
5767 /* Only checking conversion, which is OK if we get here. */
5768 return OK;
5769
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005771 if (flags & FIO_ENCRYPTED)
5772 {
5773 /* Encrypt the data. Do it in-place if possible, otherwise use an
5774 * allocated buffer. */
Bram Moolenaar987411d2019-01-18 22:48:34 +01005775# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005776 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5777 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01005778# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005779 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
Bram Moolenaar987411d2019-01-18 22:48:34 +01005780# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005781 }
5782 else
5783 {
5784 char_u *outbuf;
5785
5786 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5787 if (len == 0)
5788 return OK; /* Crypt layer is buffering, will flush later. */
5789 wlen = write_eintr(ip->bw_fd, outbuf, len);
5790 vim_free(outbuf);
5791 return (wlen < len) ? FAIL : OK;
5792 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01005793# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795#endif
5796
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005797 wlen = write_eintr(ip->bw_fd, buf, len);
5798 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799}
5800
5801#ifdef FEAT_MBYTE
5802/*
5803 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005804 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 */
5806 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005807ucs2bytes(
5808 unsigned c, /* in: character */
5809 char_u **pp, /* in/out: pointer to result */
5810 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811{
5812 char_u *p = *pp;
5813 int error = FALSE;
5814 int cc;
5815
5816
5817 if (flags & FIO_UCS4)
5818 {
5819 if (flags & FIO_ENDIAN_L)
5820 {
5821 *p++ = c;
5822 *p++ = (c >> 8);
5823 *p++ = (c >> 16);
5824 *p++ = (c >> 24);
5825 }
5826 else
5827 {
5828 *p++ = (c >> 24);
5829 *p++ = (c >> 16);
5830 *p++ = (c >> 8);
5831 *p++ = c;
5832 }
5833 }
5834 else if (flags & (FIO_UCS2 | FIO_UTF16))
5835 {
5836 if (c >= 0x10000)
5837 {
5838 if (flags & FIO_UTF16)
5839 {
5840 /* Make two words, ten bits of the character in each. First
5841 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5842 c -= 0x10000;
5843 if (c >= 0x100000)
5844 error = TRUE;
5845 cc = ((c >> 10) & 0x3ff) + 0xd800;
5846 if (flags & FIO_ENDIAN_L)
5847 {
5848 *p++ = cc;
5849 *p++ = ((unsigned)cc >> 8);
5850 }
5851 else
5852 {
5853 *p++ = ((unsigned)cc >> 8);
5854 *p++ = cc;
5855 }
5856 c = (c & 0x3ff) + 0xdc00;
5857 }
5858 else
5859 error = TRUE;
5860 }
5861 if (flags & FIO_ENDIAN_L)
5862 {
5863 *p++ = c;
5864 *p++ = (c >> 8);
5865 }
5866 else
5867 {
5868 *p++ = (c >> 8);
5869 *p++ = c;
5870 }
5871 }
5872 else /* Latin1 */
5873 {
5874 if (c >= 0x100)
5875 {
5876 error = TRUE;
5877 *p++ = 0xBF;
5878 }
5879 else
5880 *p++ = c;
5881 }
5882
5883 *pp = p;
5884 return error;
5885}
5886
5887/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005888 * Return TRUE if file encoding "fenc" requires conversion from or to
5889 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890 */
5891 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005892need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005894 int same_encoding;
5895 int enc_flags;
5896 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005897
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005898 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005899 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005900 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005901 fenc_flags = 0;
5902 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005903 else
5904 {
5905 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5906 * "ucs-4be", etc. */
5907 enc_flags = get_fio_flags(p_enc);
5908 fenc_flags = get_fio_flags(fenc);
5909 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5910 }
5911 if (same_encoding)
5912 {
5913 /* Specified encoding matches with 'encoding'. This requires
5914 * conversion when 'encoding' is Unicode but not UTF-8. */
5915 return enc_unicode != 0;
5916 }
5917
5918 /* Encodings differ. However, conversion is not needed when 'enc' is any
5919 * Unicode encoding and the file is UTF-8. */
5920 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921}
5922
5923/*
5924 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5925 * internal conversion.
5926 * if "ptr" is an empty string, use 'encoding'.
5927 */
5928 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005929get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930{
5931 int prop;
5932
5933 if (*ptr == NUL)
5934 ptr = p_enc;
5935
5936 prop = enc_canon_props(ptr);
5937 if (prop & ENC_UNICODE)
5938 {
5939 if (prop & ENC_2BYTE)
5940 {
5941 if (prop & ENC_ENDIAN_L)
5942 return FIO_UCS2 | FIO_ENDIAN_L;
5943 return FIO_UCS2;
5944 }
5945 if (prop & ENC_4BYTE)
5946 {
5947 if (prop & ENC_ENDIAN_L)
5948 return FIO_UCS4 | FIO_ENDIAN_L;
5949 return FIO_UCS4;
5950 }
5951 if (prop & ENC_2WORD)
5952 {
5953 if (prop & ENC_ENDIAN_L)
5954 return FIO_UTF16 | FIO_ENDIAN_L;
5955 return FIO_UTF16;
5956 }
5957 return FIO_UTF8;
5958 }
5959 if (prop & ENC_LATIN1)
5960 return FIO_LATIN1;
5961 /* must be ENC_DBCS, requires iconv() */
5962 return 0;
5963}
5964
5965#ifdef WIN3264
5966/*
5967 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5968 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5969 * Used for conversion between 'encoding' and 'fileencoding'.
5970 */
5971 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005972get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973{
5974 int cp;
5975
5976 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5977 if (!enc_utf8 && enc_codepage <= 0)
5978 return 0;
5979
5980 cp = encname2codepage(ptr);
5981 if (cp == 0)
5982 {
5983# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5984 if (STRCMP(ptr, "utf-8") == 0)
5985 cp = CP_UTF8;
5986 else
5987# endif
5988 return 0;
5989 }
5990 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5991}
5992#endif
5993
Bram Moolenaard0573012017-10-28 21:11:06 +02005994#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995/*
5996 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5997 * needed for the internal conversion to/from utf-8 or latin1.
5998 */
5999 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006000get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001{
6002 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
6003 && (enc_canon_props(ptr) & ENC_MACROMAN))
6004 return FIO_MACROMAN;
6005 return 0;
6006}
6007#endif
6008
6009/*
6010 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6011 * "size" must be at least 2.
6012 * Return the name of the encoding and set "*lenp" to the length.
6013 * Returns NULL when no BOM found.
6014 */
6015 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006016check_for_bom(
6017 char_u *p,
6018 long size,
6019 int *lenp,
6020 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021{
6022 char *name = NULL;
6023 int len = 2;
6024
6025 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006026 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 {
6028 name = "utf-8"; /* EF BB BF */
6029 len = 3;
6030 }
6031 else if (p[0] == 0xff && p[1] == 0xfe)
6032 {
6033 if (size >= 4 && p[2] == 0 && p[3] == 0
6034 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6035 {
6036 name = "ucs-4le"; /* FF FE 00 00 */
6037 len = 4;
6038 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006039 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006041 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6042 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043 name = "utf-16le"; /* FF FE */
6044 }
6045 else if (p[0] == 0xfe && p[1] == 0xff
6046 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6047 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006048 /* Default to utf-16, it works also for ucs-2 text. */
6049 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006051 else
6052 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053 }
6054 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6055 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6056 {
6057 name = "ucs-4"; /* 00 00 FE FF */
6058 len = 4;
6059 }
6060
6061 *lenp = len;
6062 return (char_u *)name;
6063}
6064
6065/*
6066 * Generate a BOM in "buf[4]" for encoding "name".
6067 * Return the length of the BOM (zero when no BOM).
6068 */
6069 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006070make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071{
6072 int flags;
6073 char_u *p;
6074
6075 flags = get_fio_flags(name);
6076
6077 /* Can't put a BOM in a non-Unicode file. */
6078 if (flags == FIO_LATIN1 || flags == 0)
6079 return 0;
6080
6081 if (flags == FIO_UTF8) /* UTF-8 */
6082 {
6083 buf[0] = 0xef;
6084 buf[1] = 0xbb;
6085 buf[2] = 0xbf;
6086 return 3;
6087 }
6088 p = buf;
6089 (void)ucs2bytes(0xfeff, &p, flags);
6090 return (int)(p - buf);
6091}
6092#endif
6093
6094/*
6095 * Try to find a shortname by comparing the fullname with the current
6096 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006097 * Returns "full_path" or pointer into "full_path" if shortened.
6098 */
6099 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006100shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006101{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006102 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006103 char_u *p = full_path;
6104
Bram Moolenaard9462e32011-04-11 21:35:11 +02006105 dirname = alloc(MAXPATHL);
6106 if (dirname == NULL)
6107 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006108 if (mch_dirname(dirname, MAXPATHL) == OK)
6109 {
6110 p = shorten_fname(full_path, dirname);
6111 if (p == NULL || *p == NUL)
6112 p = full_path;
6113 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006114 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006115 return p;
6116}
6117
6118/*
6119 * Try to find a shortname by comparing the fullname with the current
6120 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 * Returns NULL if not shorter name possible, pointer into "full_path"
6122 * otherwise.
6123 */
6124 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006125shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126{
6127 int len;
6128 char_u *p;
6129
6130 if (full_path == NULL)
6131 return NULL;
6132 len = (int)STRLEN(dir_name);
6133 if (fnamencmp(dir_name, full_path, len) == 0)
6134 {
6135 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006136#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006138 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 * slash, since C: by itself does not define a specific dir. In this
6140 * case p may already be correct. <negri>
6141 */
6142 if (!((len > 2) && (*(p - 2) == ':')))
6143#endif
6144 {
6145 if (vim_ispathsep(*p))
6146 ++p;
6147#ifndef VMS /* the path separator is always part of the path */
6148 else
6149 p = NULL;
6150#endif
6151 }
6152 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006153#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 /*
6155 * When using a file in the current drive, remove the drive name:
6156 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6157 * a floppy from "A:\dir" to "B:\dir".
6158 */
6159 else if (len > 3
6160 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6161 && full_path[1] == ':'
6162 && vim_ispathsep(full_path[2]))
6163 p = full_path + 2;
6164#endif
6165 else
6166 p = NULL;
6167 return p;
6168}
6169
6170/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006171 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 * When "force" is TRUE: Use full path from now on for files currently being
6173 * edited, both for file name and swap file name. Try to shorten the file
6174 * names a bit, if safe to do so.
6175 * When "force" is FALSE: Only try to shorten absolute file names.
6176 * For buffers that have buftype "nofile" or "scratch": never change the file
6177 * name.
6178 */
6179 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006180shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6181{
6182 char_u *p;
6183
6184 if (buf->b_fname != NULL
6185#ifdef FEAT_QUICKFIX
6186 && !bt_nofile(buf)
6187#endif
6188 && !path_with_url(buf->b_fname)
6189 && (force
6190 || buf->b_sfname == NULL
6191 || mch_isFullName(buf->b_sfname)))
6192 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02006193 if (buf->b_sfname != buf->b_ffname)
6194 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02006195 p = shorten_fname(buf->b_ffname, dirname);
6196 if (p != NULL)
6197 {
6198 buf->b_sfname = vim_strsave(p);
6199 buf->b_fname = buf->b_sfname;
6200 }
6201 if (p == NULL || buf->b_fname == NULL)
6202 buf->b_fname = buf->b_ffname;
6203 }
6204}
6205
6206/*
6207 * Shorten filenames for all buffers.
6208 */
6209 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006210shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211{
6212 char_u dirname[MAXPATHL];
6213 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214
6215 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006216 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006218 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006219
6220 /* Always make the swap file name a full path, a "nofile" buffer may
6221 * also have a swap file. */
6222 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006225 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226}
6227
6228#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6229 || defined(FEAT_GUI_MSWIN) \
6230 || defined(FEAT_GUI_MAC) \
6231 || defined(PROTO)
6232/*
6233 * Shorten all filenames in "fnames[count]" by current directory.
6234 */
6235 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006236shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237{
6238 int i;
6239 char_u dirname[MAXPATHL];
6240 char_u *p;
6241
6242 if (fnames == NULL || count < 1)
6243 return;
6244 mch_dirname(dirname, sizeof(dirname));
6245 for (i = 0; i < count; ++i)
6246 {
6247 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6248 {
6249 /* shorten_fname() returns pointer in given "fnames[i]". If free
6250 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6251 * "p" first then free fnames[i]. */
6252 p = vim_strsave(p);
6253 vim_free(fnames[i]);
6254 fnames[i] = p;
6255 }
6256 }
6257}
6258#endif
6259
6260/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02006261 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 * fo_o_h.ext for MSDOS or when shortname option set.
6263 *
6264 * Assumed that fname is a valid name found in the filesystem we assure that
6265 * the return value is a different name and ends in 'ext'.
6266 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6267 * characters otherwise.
6268 * Space for the returned name is allocated, must be freed later.
6269 * Returns NULL when out of memory.
6270 */
6271 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006272modname(
6273 char_u *fname,
6274 char_u *ext,
6275 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006277 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 fname, ext, prepend_dot);
6279}
6280
6281 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006282buf_modname(
6283 int shortname, /* use 8.3 file name */
6284 char_u *fname,
6285 char_u *ext,
6286 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287{
6288 char_u *retval;
6289 char_u *s;
6290 char_u *e;
6291 char_u *ptr;
6292 int fnamelen, extlen;
6293
6294 extlen = (int)STRLEN(ext);
6295
6296 /*
6297 * If there is no file name we must get the name of the current directory
6298 * (we need the full path in case :cd is used).
6299 */
6300 if (fname == NULL || *fname == NUL)
6301 {
6302 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6303 if (retval == NULL)
6304 return NULL;
6305 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6306 (fnamelen = (int)STRLEN(retval)) == 0)
6307 {
6308 vim_free(retval);
6309 return NULL;
6310 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006311 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 {
6313 retval[fnamelen++] = PATHSEP;
6314 retval[fnamelen] = NUL;
6315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 }
6318 else
6319 {
6320 fnamelen = (int)STRLEN(fname);
6321 retval = alloc((unsigned)(fnamelen + extlen + 3));
6322 if (retval == NULL)
6323 return NULL;
6324 STRCPY(retval, fname);
6325#ifdef VMS
6326 vms_remove_version(retval); /* we do not need versions here */
6327#endif
6328 }
6329
6330 /*
6331 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6332 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6333 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6334 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6335 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006336 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006339#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006341#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006343#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 )
6345 if (*ptr == '.') /* replace '.' by '_' */
6346 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006348 {
6349 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353
6354 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6356 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357
6358 s = ptr + STRLEN(ptr);
6359
6360 /*
6361 * For 8.3 file names we may have to reduce the length.
6362 */
6363#ifdef USE_LONG_FNAME
6364 if (!USE_LONG_FNAME || shortname)
6365#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367#endif
6368 {
6369 /*
6370 * If there is no file name, or the file name ends in '/', and the
6371 * extension starts with '.', put a '_' before the dot, because just
6372 * ".ext" is invalid.
6373 */
6374 if (fname == NULL || *fname == NUL
6375 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6376 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 *s++ = '_';
6379 }
6380 /*
6381 * If the extension starts with '.', truncate the base name at 8
6382 * characters
6383 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006386 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 {
6388 s = ptr + 8;
6389 *s = '\0';
6390 }
6391 }
6392 /*
6393 * If the extension doesn't start with '.', and the file name
6394 * doesn't have an extension yet, append a '.'
6395 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 else if ((e = vim_strchr(ptr, '.')) == NULL)
6397 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 /*
6399 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006400 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 */
6402 else if ((int)STRLEN(e) + extlen > 4)
6403 s = e + 4 - extlen;
6404 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006405#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406 /*
6407 * If there is no file name, and the extension starts with '.', put a
6408 * '_' before the dot, because just ".ext" may be invalid if it's on a
6409 * FAT partition, and on HPFS it doesn't matter.
6410 */
6411 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6412 *s++ = '_';
6413#endif
6414
6415 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006416 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417 * ext can start with '.' and cannot exceed 3 more characters.
6418 */
6419 STRCPY(s, ext);
6420
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421 /*
6422 * Prepend the dot.
6423 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006424 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425#ifdef USE_LONG_FNAME
6426 && USE_LONG_FNAME
6427#endif
6428 )
6429 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006430 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433
6434 /*
6435 * Check that, after appending the extension, the file name is really
6436 * different.
6437 */
6438 if (fname != NULL && STRCMP(fname, retval) == 0)
6439 {
6440 /* we search for a character that can be replaced by '_' */
6441 while (--s >= ptr)
6442 {
6443 if (*s != '_')
6444 {
6445 *s = '_';
6446 break;
6447 }
6448 }
6449 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6450 *ptr = 'v';
6451 }
6452 return retval;
6453}
6454
6455/*
6456 * Like fgets(), but if the file line is too long, it is truncated and the
6457 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006458 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459 */
6460 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006461vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462{
6463 char *eof;
6464#define FGETS_SIZE 200
6465 char tbuf[FGETS_SIZE];
6466
6467 buf[size - 2] = NUL;
6468#ifdef USE_CR
6469 eof = fgets_cr((char *)buf, size, fp);
6470#else
6471 eof = fgets((char *)buf, size, fp);
6472#endif
6473 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6474 {
6475 buf[size - 1] = NUL; /* Truncate the line */
6476
6477 /* Now throw away the rest of the line: */
6478 do
6479 {
6480 tbuf[FGETS_SIZE - 2] = NUL;
6481#ifdef USE_CR
Bram Moolenaar42335f52018-09-13 15:33:43 +02006482 vim_ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483#else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006484 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485#endif
6486 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6487 }
6488 return (eof == NULL);
6489}
6490
6491#if defined(USE_CR) || defined(PROTO)
6492/*
6493 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6494 * Returns TRUE for end-of-file.
6495 * Only used for the Mac, because it's much slower than vim_fgets().
6496 */
6497 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006498tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499{
6500 int i = 0;
6501 int c;
6502 int eof = FALSE;
6503
6504 for (;;)
6505 {
6506 c = fgetc(fp);
6507 if (c == EOF)
6508 {
6509 eof = TRUE;
6510 break;
6511 }
6512 if (c == '\r')
6513 {
6514 /* Always store a NL for end-of-line. */
6515 if (i < size - 1)
6516 buf[i++] = '\n';
6517 c = fgetc(fp);
6518 if (c != '\n') /* Macintosh format: single CR. */
6519 ungetc(c, fp);
6520 break;
6521 }
6522 if (i < size - 1)
6523 buf[i++] = c;
6524 if (c == '\n')
6525 break;
6526 }
6527 buf[i] = NUL;
6528 return eof;
6529}
6530#endif
6531
6532/*
6533 * rename() only works if both files are on the same file system, this
6534 * function will (attempts to?) copy the file across if rename fails -- webb
6535 * Return -1 for failure, 0 for success.
6536 */
6537 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006538vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539{
6540 int fd_in;
6541 int fd_out;
6542 int n;
6543 char *errmsg = NULL;
6544 char *buffer;
6545#ifdef AMIGA
6546 BPTR flock;
6547#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006548 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006549 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006550#ifdef HAVE_ACL
6551 vim_acl_T acl; /* ACL from original file */
6552#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006553 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554
6555 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006556 * When the names are identical, there is nothing to do. When they refer
6557 * to the same file (ignoring case and slash/backslash differences) but
6558 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 */
6560 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006561 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006562 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006563 use_tmp_file = TRUE;
6564 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006565 return 0;
6566 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567
6568 /*
6569 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6570 */
6571 if (mch_stat((char *)from, &st) < 0)
6572 return -1;
6573
Bram Moolenaar3576da72008-12-30 15:15:57 +00006574#ifdef UNIX
6575 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006576 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006577
6578 /* It's possible for the source and destination to be the same file.
6579 * This happens when "from" and "to" differ in case and are on a FAT32
6580 * filesystem. In that case go through a temp file name. */
6581 if (mch_stat((char *)to, &st_to) >= 0
6582 && st.st_dev == st_to.st_dev
6583 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006584 use_tmp_file = TRUE;
6585 }
6586#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006587#ifdef WIN3264
6588 {
6589 BY_HANDLE_FILE_INFORMATION info1, info2;
6590
6591 /* It's possible for the source and destination to be the same file.
6592 * In that case go through a temp file name. This makes rename("foo",
6593 * "./foo") a no-op (in a complicated way). */
6594 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6595 && win32_fileinfo(to, &info2) == FILEINFO_OK
6596 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6597 && info1.nFileIndexHigh == info2.nFileIndexHigh
6598 && info1.nFileIndexLow == info2.nFileIndexLow)
6599 use_tmp_file = TRUE;
6600 }
6601#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006602
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006603 if (use_tmp_file)
6604 {
6605 char tempname[MAXPATHL + 1];
6606
6607 /*
6608 * Find a name that doesn't exist and is in the same directory.
6609 * Rename "from" to "tempname" and then rename "tempname" to "to".
6610 */
6611 if (STRLEN(from) >= MAXPATHL - 5)
6612 return -1;
6613 STRCPY(tempname, from);
6614 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006615 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006616 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6617 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006618 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006619 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006620 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006621 if (mch_rename(tempname, (char *)to) == 0)
6622 return 0;
6623 /* Strange, the second step failed. Try moving the
6624 * file back and return failure. */
6625 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006626 return -1;
6627 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006628 /* If it fails for one temp name it will most likely fail
6629 * for any temp name, give up. */
6630 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006631 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006632 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006633 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006634 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006635
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 /*
6637 * Delete the "to" file, this is required on some systems to make the
6638 * mch_rename() work, on other systems it makes sure that we don't have
6639 * two files when the mch_rename() fails.
6640 */
6641
6642#ifdef AMIGA
6643 /*
6644 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6645 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006646 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 * deleting the "from" file (horror!) we lock it during the remove.
6648 *
6649 * When used for making a backup before writing the file: This should not
6650 * happen with ":w", because startscript() should detect this problem and
6651 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6652 * name. This problem does exist with ":w filename", but then the
6653 * original file will be somewhere else so the backup isn't really
6654 * important. If autoscripting is off the rename may fail.
6655 */
6656 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6657#endif
6658 mch_remove(to);
6659#ifdef AMIGA
6660 if (flock)
6661 UnLock(flock);
6662#endif
6663
6664 /*
6665 * First try a normal rename, return if it works.
6666 */
6667 if (mch_rename((char *)from, (char *)to) == 0)
6668 return 0;
6669
6670 /*
6671 * Rename() failed, try copying the file.
6672 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006673 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006674#ifdef HAVE_ACL
6675 /* For systems that support ACL: get the ACL from the original file. */
6676 acl = mch_get_acl(from);
6677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6679 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006680 {
6681#ifdef HAVE_ACL
6682 mch_free_acl(acl);
6683#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006685 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006686
6687 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006688 fd_out = mch_open((char *)to,
6689 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 if (fd_out == -1)
6691 {
6692 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006693#ifdef HAVE_ACL
6694 mch_free_acl(acl);
6695#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 return -1;
6697 }
6698
6699 buffer = (char *)alloc(BUFSIZE);
6700 if (buffer == NULL)
6701 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006703 close(fd_in);
6704#ifdef HAVE_ACL
6705 mch_free_acl(acl);
6706#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 return -1;
6708 }
6709
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006710 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6711 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 {
6713 errmsg = _("E208: Error writing to \"%s\"");
6714 break;
6715 }
6716
6717 vim_free(buffer);
6718 close(fd_in);
6719 if (close(fd_out) < 0)
6720 errmsg = _("E209: Error closing \"%s\"");
6721 if (n < 0)
6722 {
6723 errmsg = _("E210: Error reading \"%s\"");
6724 to = from;
6725 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006726#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006727 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006728#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006729#ifdef HAVE_ACL
6730 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006731 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006732#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006733#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006734 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006735#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 if (errmsg != NULL)
6737 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006738 semsg(errmsg, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739 return -1;
6740 }
6741 mch_remove(from);
6742 return 0;
6743}
6744
6745static int already_warned = FALSE;
6746
6747/*
6748 * Check if any not hidden buffer has been changed.
6749 * Postpone the check if there are characters in the stuff buffer, a global
6750 * command is being executed, a mapping is being executed or an autocommand is
6751 * busy.
6752 * Returns TRUE if some message was written (screen should be redrawn and
6753 * cursor positioned).
6754 */
6755 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006756check_timestamps(
6757 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758{
6759 buf_T *buf;
6760 int didit = 0;
6761 int n;
6762
6763 /* Don't check timestamps while system() or another low-level function may
6764 * cause us to lose and gain focus. */
6765 if (no_check_timestamps > 0)
6766 return FALSE;
6767
6768 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6769 * event and we would keep on checking if the file is steadily growing.
6770 * Do check again after typing something. */
6771 if (focus && did_check_timestamps)
6772 {
6773 need_check_timestamps = TRUE;
6774 return FALSE;
6775 }
6776
6777 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006778 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 need_check_timestamps = TRUE; /* check later */
6780 else
6781 {
6782 ++no_wait_return;
6783 did_check_timestamps = TRUE;
6784 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006785 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 {
6787 /* Only check buffers in a window. */
6788 if (buf->b_nwindows > 0)
6789 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006790 bufref_T bufref;
6791
6792 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793 n = buf_check_timestamp(buf, focus);
6794 if (didit < n)
6795 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006796 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 {
6798 /* Autocommands have removed the buffer, start at the
6799 * first one again. */
6800 buf = firstbuf;
6801 continue;
6802 }
6803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 }
6805 --no_wait_return;
6806 need_check_timestamps = FALSE;
6807 if (need_wait_return && didit == 2)
6808 {
6809 /* make sure msg isn't overwritten */
6810 msg_puts((char_u *)"\n");
6811 out_flush();
6812 }
6813 }
6814 return didit;
6815}
6816
6817/*
6818 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6819 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6820 * empty.
6821 */
6822 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006823move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824{
6825 buf_T *tbuf = curbuf;
6826 int retval = OK;
6827 linenr_T lnum;
6828 char_u *p;
6829
6830 /* Copy the lines in "frombuf" to "tobuf". */
6831 curbuf = tobuf;
6832 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6833 {
6834 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6835 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6836 {
6837 vim_free(p);
6838 retval = FAIL;
6839 break;
6840 }
6841 vim_free(p);
6842 }
6843
6844 /* Delete all the lines in "frombuf". */
6845 if (retval != FAIL)
6846 {
6847 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006848 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6849 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 {
6851 /* Oops! We could try putting back the saved lines, but that
6852 * might fail again... */
6853 retval = FAIL;
6854 break;
6855 }
6856 }
6857
6858 curbuf = tbuf;
6859 return retval;
6860}
6861
6862/*
6863 * Check if buffer "buf" has been changed.
6864 * Also check if the file for a new buffer unexpectedly appeared.
6865 * return 1 if a changed buffer was found.
6866 * return 2 if a message has been displayed.
6867 * return 0 otherwise.
6868 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006870buf_check_timestamp(
6871 buf_T *buf,
6872 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006874 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 int stat_res;
6876 int retval = 0;
6877 char_u *path;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006878 char *tbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006880 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 int helpmesg = FALSE;
6882 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006883 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6885 int can_reload = FALSE;
6886#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006887 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 int orig_mode = buf->b_orig_mode;
6889#ifdef FEAT_GUI
6890 int save_mouse_correct = need_mouse_correct;
6891#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006893 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006894#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006895 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006896#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006897 bufref_T bufref;
6898
6899 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900
6901 /* If there is no file name, the buffer is not loaded, 'buftype' is
6902 * set, we are in the middle of a save or being called recursively: ignore
6903 * this buffer. */
6904 if (buf->b_ffname == NULL
6905 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02006906 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006909#ifdef FEAT_NETBEANS_INTG
6910 || isNetbeansBuffer(buf)
6911#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006912#ifdef FEAT_TERMINAL
6913 || buf->b_term != NULL
6914#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 )
6916 return 0;
6917
6918 if ( !(buf->b_flags & BF_NOTEDITED)
6919 && buf->b_mtime != 0
6920 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6921 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006922 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923#ifdef HAVE_ST_MODE
6924 || (int)st.st_mode != buf->b_orig_mode
6925#else
6926 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6927#endif
6928 ))
6929 {
6930 retval = 1;
6931
Bram Moolenaar386bc822018-07-07 18:34:12 +02006932 // set b_mtime to stop further warnings (e.g., when executing
6933 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 if (stat_res < 0)
6935 {
Bram Moolenaar386bc822018-07-07 18:34:12 +02006936 // When 'autoread' is set we'll check the file again to see if it
6937 // re-appears.
6938 buf->b_mtime = buf->b_p_ar;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 buf->b_orig_size = 0;
6940 buf->b_orig_mode = 0;
6941 }
6942 else
6943 buf_store_time(buf, &st, buf->b_ffname);
6944
6945 /* Don't do anything for a directory. Might contain the file
6946 * explorer. */
6947 if (mch_isdir(buf->b_fname))
6948 ;
6949
6950 /*
6951 * If 'autoread' is set, the buffer has no changes and the file still
6952 * exists, reload the buffer. Use the buffer-local option value if it
6953 * was set, the global option value otherwise.
6954 */
6955 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6956 && !bufIsChanged(buf) && stat_res >= 0)
6957 reload = TRUE;
6958 else
6959 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006960 if (stat_res < 0)
6961 reason = "deleted";
6962 else if (bufIsChanged(buf))
6963 reason = "conflict";
6964 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6965 reason = "changed";
6966 else if (orig_mode != buf->b_orig_mode)
6967 reason = "mode";
6968 else
6969 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970
6971 /*
6972 * Only give the warning if there are no FileChangedShell
6973 * autocommands.
6974 * Avoid being called recursively by setting "busy".
6975 */
6976 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006977#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006978 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6979 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006980#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006981 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6983 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006984 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 busy = FALSE;
6986 if (n)
6987 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006988 if (!bufref_valid(&bufref))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006989 emsg(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006990#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006991 s = get_vim_var_str(VV_FCS_CHOICE);
6992 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6993 reload = TRUE;
6994 else if (STRCMP(s, "ask") == 0)
6995 n = FALSE;
6996 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006997#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006998 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007000 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007002 if (*reason == 'd')
7003 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 else
7005 {
7006 helpmesg = TRUE;
7007#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7008 can_reload = TRUE;
7009#endif
7010 /*
7011 * Check if the file contents really changed to avoid
7012 * giving a warning when only the timestamp was set (e.g.,
7013 * checked out of CVS). Always warn when the buffer was
7014 * changed.
7015 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007016 if (reason[2] == 'n')
7017 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007018 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007019 mesg2 = _("See \":help W12\" for more info.");
7020 }
7021 else if (reason[1] == 'h')
7022 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007024 mesg2 = _("See \":help W11\" for more info.");
7025 }
7026 else if (*reason == 'm')
7027 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007029 mesg2 = _("See \":help W16\" for more info.");
7030 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007031 else
7032 /* Only timestamp changed, store it to avoid a warning
7033 * in check_mtime() later. */
7034 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 }
7036 }
7037 }
7038
7039 }
7040 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7041 && vim_fexists(buf->b_ffname))
7042 {
7043 retval = 1;
7044 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7045 buf->b_flags |= BF_NEW_W;
7046#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7047 can_reload = TRUE;
7048#endif
7049 }
7050
7051 if (mesg != NULL)
7052 {
7053 path = home_replace_save(buf, buf->b_fname);
7054 if (path != NULL)
7055 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007056 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 mesg2 = "";
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007058 tbuf = (char *)alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 + STRLEN(mesg2) + 2));
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007060 sprintf(tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007061#ifdef FEAT_EVAL
7062 /* Set warningmsg here, before the unimportant and output-specific
7063 * mesg2 has been appended. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007064 set_vim_var_string(VV_WARNINGMSG, (char_u *)tbuf, -1);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007065#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7067 if (can_reload)
7068 {
7069 if (*mesg2 != NUL)
7070 {
7071 STRCAT(tbuf, "\n");
7072 STRCAT(tbuf, mesg2);
7073 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007074 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"),
7075 (char_u *)tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007076 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 reload = TRUE;
7078 }
7079 else
7080#endif
7081 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7082 {
7083 if (*mesg2 != NUL)
7084 {
7085 STRCAT(tbuf, "; ");
7086 STRCAT(tbuf, mesg2);
7087 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007088 emsg(tbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 retval = 2;
7090 }
7091 else
7092 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 {
7095 msg_start();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007096 msg_puts_attr((char_u *)tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 if (*mesg2 != NUL)
7098 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007099 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 msg_clr_eos();
7101 (void)msg_end();
7102 if (emsg_silent == 0)
7103 {
7104 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007105#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007107#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 /* give the user some time to think about it */
7109 ui_delay(1000L, TRUE);
7110
7111 /* don't redraw and erase the message */
7112 redraw_cmdline = FALSE;
7113 }
7114 }
7115 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 }
7117
7118 vim_free(path);
7119 vim_free(tbuf);
7120 }
7121 }
7122
7123 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007124 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007125 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007126 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007127#ifdef FEAT_PERSISTENT_UNDO
7128 if (buf->b_p_udf && buf->b_ffname != NULL)
7129 {
7130 char_u hash[UNDO_HASH_SIZE];
7131 buf_T *save_curbuf = curbuf;
7132
7133 /* Any existing undo file is unusable, write it now. */
7134 curbuf = buf;
7135 u_compute_hash(hash);
7136 u_write_undo(NULL, FALSE, buf, hash);
7137 curbuf = save_curbuf;
7138 }
7139#endif
7140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007142 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007143 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007144 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7145 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146#ifdef FEAT_GUI
7147 /* restore this in case an autocommand has set it; it would break
7148 * 'mousefocus' */
7149 need_mouse_correct = save_mouse_correct;
7150#endif
7151
7152 return retval;
7153}
7154
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007155/*
7156 * Reload a buffer that is already loaded.
7157 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007158 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7159 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007160 */
7161 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007162buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007163{
7164 exarg_T ea;
7165 pos_T old_cursor;
7166 linenr_T old_topline;
7167 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007168 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007169 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007170 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007171 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007172 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007173
7174 /* set curwin/curbuf for "buf" and save some things */
7175 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007176
7177 /* We only want to read the text from the file, not reset the syntax
7178 * highlighting, clear marks, diff status, etc. Force the fileformat
7179 * and encoding to be the same. */
7180 if (prep_exarg(&ea, buf) == OK)
7181 {
7182 old_cursor = curwin->w_cursor;
7183 old_topline = curwin->w_topline;
7184
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007185 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007186 {
7187 /* Save all the text, so that the reload can be undone.
7188 * Sync first so that this is a separate undo-able action. */
7189 u_sync(FALSE);
7190 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7191 flags |= READ_KEEP_UNDO;
7192 }
7193
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007194 /*
7195 * To behave like when a new file is edited (matters for
7196 * BufReadPost autocommands) we first need to delete the current
7197 * buffer contents. But if reading the file fails we should keep
7198 * the old contents. Can't use memory only, the file might be
7199 * too big. Use a hidden buffer to move the buffer contents to.
7200 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007201 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007202 savebuf = NULL;
7203 else
7204 {
7205 /* Allocate a buffer without putting it in the buffer list. */
7206 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007207 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007208 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007209 {
7210 /* Open the memline. */
7211 curbuf = savebuf;
7212 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007213 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007214 curbuf = buf;
7215 curwin->w_buffer = buf;
7216 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007217 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007218 || move_lines(buf, savebuf) == FAIL)
7219 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007220 semsg(_("E462: Could not prepare for reloading \"%s\""),
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007221 buf->b_fname);
7222 saved = FAIL;
7223 }
7224 }
7225
7226 if (saved == OK)
7227 {
7228 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007229 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007230 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7231 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007232 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007233 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007234#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007235 if (!aborting())
7236#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007237 semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007238 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007239 {
7240 /* Put the text back from the save buffer. First
7241 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007242 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007243 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007244 break;
7245 (void)move_lines(savebuf, buf);
7246 }
7247 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007248 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007249 {
7250 /* Mark the buffer as unmodified and free undo info. */
7251 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007252 if ((flags & READ_KEEP_UNDO) == 0)
7253 {
7254 u_blockfree(buf);
7255 u_clearall(buf);
7256 }
7257 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007258 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007259 /* Mark all undo states as changed. */
7260 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007261 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007262 }
7263 }
7264 vim_free(ea.cmd);
7265
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007266 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007267 wipe_buffer(savebuf, FALSE);
7268
7269#ifdef FEAT_DIFF
7270 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007271 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007272#endif
7273
7274 /* Restore the topline and cursor position and check it (lines may
7275 * have been removed). */
7276 if (old_topline > curbuf->b_ml.ml_line_count)
7277 curwin->w_topline = curbuf->b_ml.ml_line_count;
7278 else
7279 curwin->w_topline = old_topline;
7280 curwin->w_cursor = old_cursor;
7281 check_cursor();
7282 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007283 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007284#ifdef FEAT_FOLDING
7285 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007286 win_T *wp;
7287 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007288
7289 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007290 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007291 if (wp->w_buffer == curwin->w_buffer
7292 && !foldmethodIsManual(wp))
7293 foldUpdateAll(wp);
7294 }
7295#endif
7296 /* If the mode didn't change and 'readonly' was set, keep the old
7297 * value; the user probably used the ":view" command. But don't
7298 * reset it, might have had a read error. */
7299 if (orig_mode == curbuf->b_orig_mode)
7300 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007301
7302 /* Modelines must override settings done by autocommands. */
7303 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007304 }
7305
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007306 /* restore curwin/curbuf and a few other things */
7307 aucmd_restbuf(&aco);
7308 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007309}
7310
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007312buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313{
7314 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007315 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316#ifdef HAVE_ST_MODE
7317 buf->b_orig_mode = (int)st->st_mode;
7318#else
7319 buf->b_orig_mode = mch_getperm(fname);
7320#endif
7321}
7322
7323/*
7324 * Adjust the line with missing eol, used for the next write.
7325 * Used for do_filter(), when the input lines for the filter are deleted.
7326 */
7327 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007328write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007330 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7331 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332}
7333
Bram Moolenaarda440d22016-01-16 21:27:23 +01007334#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7335/*
7336 * Delete "name" and everything in it, recursively.
7337 * return 0 for succes, -1 if some file was not deleted.
7338 */
7339 int
7340delete_recursive(char_u *name)
7341{
7342 int result = 0;
7343 char_u **files;
7344 int file_count;
7345 int i;
7346 char_u *exp;
7347
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007348 /* A symbolic link to a directory itself is deleted, not the directory it
7349 * points to. */
7350 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007351# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007352 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007353# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007354 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007355# endif
7356 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007357 {
7358 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7359 exp = vim_strsave(NameBuff);
7360 if (exp == NULL)
7361 return -1;
7362 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007363 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007364 {
7365 for (i = 0; i < file_count; ++i)
7366 if (delete_recursive(files[i]) != 0)
7367 result = -1;
7368 FreeWild(file_count, files);
7369 }
7370 else
7371 result = -1;
7372 vim_free(exp);
7373 (void)mch_rmdir(name);
7374 }
7375 else
7376 result = mch_remove(name) == 0 ? 0 : -1;
7377
7378 return result;
7379}
7380#endif
7381
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382#if defined(TEMPDIRNAMES) || defined(PROTO)
7383static long temp_count = 0; /* Temp filename counter. */
7384
7385/*
7386 * Delete the temp directory and all files it contains.
7387 */
7388 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007389vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 if (vim_tempdir != NULL)
7392 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007393 /* remove the trailing path separator */
7394 gettail(vim_tempdir)[-1] = NUL;
7395 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007396 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 }
7398}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399
7400/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007401 * Directory "tempdir" was created. Expand this name to a full path and put
7402 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7403 * "tempdir" must be no longer than MAXPATHL.
7404 */
7405 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007406vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007407{
7408 char_u *buf;
7409
7410 buf = alloc((unsigned)MAXPATHL + 2);
7411 if (buf != NULL)
7412 {
7413 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7414 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007415 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007416 vim_tempdir = vim_strsave(buf);
7417 vim_free(buf);
7418 }
7419}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007420#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007421
7422/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 * vim_tempname(): Return a unique name that can be used for a temp file.
7424 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007425 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7426 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 *
7428 * The returned pointer is to allocated memory.
7429 * The returned pointer is NULL if no valid name was found.
7430 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007432vim_tempname(
7433 int extra_char UNUSED, /* char to use in the name instead of '?' */
7434 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435{
7436#ifdef USE_TMPNAM
7437 char_u itmp[L_tmpnam]; /* use tmpnam() */
7438#else
7439 char_u itmp[TEMPNAMELEN];
7440#endif
7441
7442#ifdef TEMPDIRNAMES
7443 static char *(tempdirs[]) = {TEMPDIRNAMES};
7444 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007446 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447# endif
7448
7449 /*
7450 * This will create a directory for private use by this instance of Vim.
7451 * This is done once, and the same directory is used for all temp files.
7452 * This method avoids security problems because of symlink attacks et al.
7453 * It's also a bit faster, because we only need to check for an existing
7454 * file when creating the directory and not for each temp file.
7455 */
7456 if (vim_tempdir == NULL)
7457 {
7458 /*
7459 * Try the entries in TEMPDIRNAMES to create the temp directory.
7460 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007461 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007463# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007464 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007465 long nr;
7466 long off;
7467# endif
7468
Bram Moolenaare1a61992015-12-03 21:02:27 +01007469 /* Expand $TMP, leave room for "/v1100000/999999999".
7470 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007472 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007473 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007474 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007475 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476
Bram Moolenaareaf03392009-11-17 11:08:52 +00007477# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007478 {
7479# if defined(UNIX) || defined(VMS)
7480 /* Make sure the umask doesn't remove the executable bit.
7481 * "repl" has been reported to use "177". */
7482 mode_t umask_save = umask(077);
7483# endif
7484 /* Leave room for filename */
7485 STRCAT(itmp, "vXXXXXX");
7486 if (mkdtemp((char *)itmp) != NULL)
7487 vim_settempdir(itmp);
7488# if defined(UNIX) || defined(VMS)
7489 (void)umask(umask_save);
7490# endif
7491 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007492# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 /* Get an arbitrary number of up to 6 digits. When it's
7494 * unlikely that it already exists it will be faster,
7495 * otherwise it doesn't matter. The use of mkdir() avoids any
7496 * security problems because of the predictable number. */
7497 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007498 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499
7500 /* Try up to 10000 different values until we find a name that
7501 * doesn't exist. */
7502 for (off = 0; off < 10000L; ++off)
7503 {
7504 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007505# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007507# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508
Bram Moolenaareaf03392009-11-17 11:08:52 +00007509 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7510# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 /* If mkdir() does not set errno to EEXIST, check for
7512 * existing file here. There is a race condition then,
7513 * although it's fail-safe. */
7514 if (mch_stat((char *)itmp, &st) >= 0)
7515 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007516# endif
7517# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 /* Make sure the umask doesn't remove the executable bit.
7519 * "repl" has been reported to use "177". */
7520 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007521# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007523# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007525# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526 if (r == 0)
7527 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007528 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 break;
7530 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007531# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007532 /* If the mkdir() didn't fail because the file/dir exists,
7533 * we probably can't create any dir here, try another
7534 * place. */
7535 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007536# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537 break;
7538 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007539# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 if (vim_tempdir != NULL)
7541 break;
7542 }
7543 }
7544 }
7545
7546 if (vim_tempdir != NULL)
7547 {
7548 /* There is no need to check if the file exists, because we own the
7549 * directory and nobody else creates a file in it. */
7550 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7551 return vim_strsave(itmp);
7552 }
7553
7554 return NULL;
7555
7556#else /* TEMPDIRNAMES */
7557
7558# ifdef WIN3264
7559 char szTempFile[_MAX_PATH + 1];
7560 char buf4[4];
7561 char_u *retval;
7562 char_u *p;
7563
7564 STRCPY(itmp, "");
7565 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007566 {
7567 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7568 szTempFile[1] = NUL;
7569 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570 strcpy(buf4, "VIM");
7571 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007572 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007574 if (!keep)
7575 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007576 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577
7578 /* Backslashes in a temp file name cause problems when filtering with
7579 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7580 * didn't set 'shellslash'. */
7581 retval = vim_strsave(itmp);
7582 if (*p_shcf == '-' || p_ssl)
7583 for (p = retval; *p; ++p)
7584 if (*p == '\\')
7585 *p = '/';
7586 return retval;
7587
7588# else /* WIN3264 */
7589
7590# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007591 char_u *p;
7592
Bram Moolenaar071d4272004-06-13 20:20:40 +00007593 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007594 p = tmpnam((char *)itmp);
7595 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007596 return NULL;
7597# else
7598 char_u *p;
7599
7600# ifdef VMS_TEMPNAM
7601 /* mktemp() is not working on VMS. It seems to be
7602 * a do-nothing function. Therefore we use tempnam().
7603 */
7604 sprintf((char *)itmp, "VIM%c", extra_char);
7605 p = (char_u *)tempnam("tmp:", (char *)itmp);
7606 if (p != NULL)
7607 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007608 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 * and VIM will then be unable to find the file later */
7610 STRCPY(itmp, p);
7611 STRCAT(itmp, ".txt");
7612 free(p);
7613 }
7614 else
7615 return NULL;
7616# else
7617 STRCPY(itmp, TEMPNAME);
7618 if ((p = vim_strchr(itmp, '?')) != NULL)
7619 *p = extra_char;
7620 if (mktemp((char *)itmp) == NULL)
7621 return NULL;
7622# endif
7623# endif
7624
7625 return vim_strsave(itmp);
7626# endif /* WIN3264 */
7627#endif /* TEMPDIRNAMES */
7628}
7629
7630#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7631/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007632 * Convert all backslashes in fname to forward slashes in-place, unless when
7633 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634 */
7635 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007636forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637{
7638 char_u *p;
7639
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007640 if (path_with_url(fname))
7641 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642 for (p = fname; *p != NUL; ++p)
7643# ifdef FEAT_MBYTE
7644 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007645 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646 ++p;
7647 else
7648# endif
7649 if (*p == '\\')
7650 *p = '/';
7651}
7652#endif
7653
7654
7655/*
7656 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657 */
7658
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659/*
7660 * The autocommands are stored in a list for each event.
7661 * Autocommands for the same pattern, that are consecutive, are joined
7662 * together, to avoid having to match the pattern too often.
7663 * The result is an array of Autopat lists, which point to AutoCmd lists:
7664 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007665 * last_autopat[0] -----------------------------+
7666 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7668 * Autopat.cmds Autopat.cmds
7669 * | |
7670 * V V
7671 * AutoCmd.next AutoCmd.next
7672 * | |
7673 * V V
7674 * AutoCmd.next NULL
7675 * |
7676 * V
7677 * NULL
7678 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007679 * last_autopat[1] --------+
7680 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007681 * first_autopat[1] --> Autopat.next --> NULL
7682 * Autopat.cmds
7683 * |
7684 * V
7685 * AutoCmd.next
7686 * |
7687 * V
7688 * NULL
7689 * etc.
7690 *
7691 * The order of AutoCmds is important, this is the order in which they were
7692 * defined and will have to be executed.
7693 */
7694typedef struct AutoCmd
7695{
7696 char_u *cmd; /* The command to be executed (NULL
7697 when command has been removed) */
7698 char nested; /* If autocommands nest here */
7699 char last; /* last command in list */
7700#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007701 sctx_T script_ctx; /* script context where defined */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702#endif
7703 struct AutoCmd *next; /* Next AutoCmd in list */
7704} AutoCmd;
7705
7706typedef struct AutoPat
7707{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007708 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7709 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710 char_u *pat; /* pattern as typed (NULL when pattern
7711 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007712 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007714 int group; /* group ID */
7715 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007716 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007717 char allow_dirs; /* Pattern may match whole path */
7718 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719} AutoPat;
7720
7721static struct event_name
7722{
7723 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007724 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725} event_names[] =
7726{
7727 {"BufAdd", EVENT_BUFADD},
7728 {"BufCreate", EVENT_BUFADD},
7729 {"BufDelete", EVENT_BUFDELETE},
7730 {"BufEnter", EVENT_BUFENTER},
7731 {"BufFilePost", EVENT_BUFFILEPOST},
7732 {"BufFilePre", EVENT_BUFFILEPRE},
7733 {"BufHidden", EVENT_BUFHIDDEN},
7734 {"BufLeave", EVENT_BUFLEAVE},
7735 {"BufNew", EVENT_BUFNEW},
7736 {"BufNewFile", EVENT_BUFNEWFILE},
7737 {"BufRead", EVENT_BUFREADPOST},
7738 {"BufReadCmd", EVENT_BUFREADCMD},
7739 {"BufReadPost", EVENT_BUFREADPOST},
7740 {"BufReadPre", EVENT_BUFREADPRE},
7741 {"BufUnload", EVENT_BUFUNLOAD},
7742 {"BufWinEnter", EVENT_BUFWINENTER},
7743 {"BufWinLeave", EVENT_BUFWINLEAVE},
7744 {"BufWipeout", EVENT_BUFWIPEOUT},
7745 {"BufWrite", EVENT_BUFWRITEPRE},
7746 {"BufWritePost", EVENT_BUFWRITEPOST},
7747 {"BufWritePre", EVENT_BUFWRITEPRE},
7748 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007749 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007750 {"CmdlineEnter", EVENT_CMDLINEENTER},
7751 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 {"CmdwinEnter", EVENT_CMDWINENTER},
7753 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007754 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007755 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar60a68362018-04-30 15:40:48 +02007756 {"ColorSchemePre", EVENT_COLORSCHEMEPRE},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007757 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007758 {"CursorHold", EVENT_CURSORHOLD},
7759 {"CursorHoldI", EVENT_CURSORHOLDI},
7760 {"CursorMoved", EVENT_CURSORMOVED},
7761 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaare8fa05b2018-09-16 15:48:06 +02007762 {"DiffUpdated", EVENT_DIFFUPDATED},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007763 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007765 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7768 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7769 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7770 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007771 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772 {"FileChangedRO", EVENT_FILECHANGEDRO},
7773 {"FileReadPost", EVENT_FILEREADPOST},
7774 {"FileReadPre", EVENT_FILEREADPRE},
7775 {"FileReadCmd", EVENT_FILEREADCMD},
7776 {"FileType", EVENT_FILETYPE},
7777 {"FileWritePost", EVENT_FILEWRITEPOST},
7778 {"FileWritePre", EVENT_FILEWRITEPRE},
7779 {"FileWriteCmd", EVENT_FILEWRITECMD},
7780 {"FilterReadPost", EVENT_FILTERREADPOST},
7781 {"FilterReadPre", EVENT_FILTERREADPRE},
7782 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7783 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7784 {"FocusGained", EVENT_FOCUSGAINED},
7785 {"FocusLost", EVENT_FOCUSLOST},
7786 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7787 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007788 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007789 {"InsertChange", EVENT_INSERTCHANGE},
7790 {"InsertEnter", EVENT_INSERTENTER},
7791 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007792 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007793 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007794 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007795 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7796 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007797 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007799 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007800 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7801 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007802 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaar2b618522019-01-12 13:26:03 +01007803 {"SourcePre", EVENT_SOURCEPRE},
7804 {"SourcePost", EVENT_SOURCEPOST},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007805 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 {"StdinReadPost", EVENT_STDINREADPOST},
7807 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007808 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007809 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007810 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007811 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007812 {"TabEnter", EVENT_TABENTER},
7813 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007814 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007815 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007817 {"TextChanged", EVENT_TEXTCHANGED},
7818 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007819 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820 {"User", EVENT_USER},
7821 {"VimEnter", EVENT_VIMENTER},
7822 {"VimLeave", EVENT_VIMLEAVE},
7823 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007824 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007825 {"WinEnter", EVENT_WINENTER},
7826 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007827 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007828 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007829 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830};
7831
7832static AutoPat *first_autopat[NUM_EVENTS] =
7833{
7834 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7835 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7836 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7837 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007838 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007839 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007840};
7841
Bram Moolenaar462455e2017-11-10 21:53:11 +01007842static AutoPat *last_autopat[NUM_EVENTS] =
7843{
7844 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7845 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7846 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7847 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7848 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7849 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7850};
7851
Bram Moolenaar071d4272004-06-13 20:20:40 +00007852/*
7853 * struct used to keep status while executing autocommands for an event.
7854 */
7855typedef struct AutoPatCmd
7856{
7857 AutoPat *curpat; /* next AutoPat to examine */
7858 AutoCmd *nextcmd; /* next AutoCmd to execute */
7859 int group; /* group being used */
7860 char_u *fname; /* fname to match with */
7861 char_u *sfname; /* sfname to match with */
7862 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007863 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007864 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7865 buf is deleted */
7866 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867} AutoPatCmd;
7868
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007869static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007870
Bram Moolenaar071d4272004-06-13 20:20:40 +00007871/*
7872 * augroups stores a list of autocmd group names.
7873 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007874static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007875#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007876/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007877static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007878
7879/*
7880 * The ID of the current group. Group 0 is the default one.
7881 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882static int current_augroup = AUGROUP_DEFAULT;
7883
7884static int au_need_clean = FALSE; /* need to delete marked patterns */
7885
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007886static char_u *event_nr2name(event_T event);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007887static int au_get_grouparg(char_u **argp);
7888static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7889static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7890static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007891static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007893
Bram Moolenaar754b5602006-02-09 23:53:20 +00007894static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007896static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007898 static char_u *
7899get_deleted_augroup(void)
7900{
7901 if (deleted_augroup == NULL)
7902 deleted_augroup = (char_u *)_("--Deleted--");
7903 return deleted_augroup;
7904}
7905
Bram Moolenaar071d4272004-06-13 20:20:40 +00007906/*
7907 * Show the autocommands for one AutoPat.
7908 */
7909 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007910show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911{
7912 AutoCmd *ac;
7913
7914 /* Check for "got_int" (here and at various places below), which is set
7915 * when "q" has been hit for the "--more--" prompt */
7916 if (got_int)
7917 return;
7918 if (ap->pat == NULL) /* pattern has been removed */
7919 return;
7920
7921 msg_putchar('\n');
7922 if (got_int)
7923 return;
7924 if (event != last_event || ap->group != last_group)
7925 {
7926 if (ap->group != AUGROUP_DEFAULT)
7927 {
7928 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007929 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007931 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007932 msg_puts((char_u *)" ");
7933 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007934 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 last_event = event;
7936 last_group = ap->group;
7937 msg_putchar('\n');
7938 if (got_int)
7939 return;
7940 }
7941 msg_col = 4;
7942 msg_outtrans(ap->pat);
7943
7944 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7945 {
7946 if (ac->cmd != NULL) /* skip removed commands */
7947 {
7948 if (msg_col >= 14)
7949 msg_putchar('\n');
7950 msg_col = 14;
7951 if (got_int)
7952 return;
7953 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007954#ifdef FEAT_EVAL
7955 if (p_verbose > 0)
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007956 last_set_msg(ac->script_ctx);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958 if (got_int)
7959 return;
7960 if (ac->next != NULL)
7961 {
7962 msg_putchar('\n');
7963 if (got_int)
7964 return;
7965 }
7966 }
7967 }
7968}
7969
7970/*
7971 * Mark an autocommand pattern for deletion.
7972 */
7973 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007974au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007976 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007977 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007978 au_need_clean = TRUE;
7979}
7980
7981/*
7982 * Mark all commands for a pattern for deletion.
7983 */
7984 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007985au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007986{
7987 AutoCmd *ac;
7988
7989 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007990 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007991 au_need_clean = TRUE;
7992}
7993
7994/*
7995 * Cleanup autocommands and patterns that have been deleted.
7996 * This is only done when not executing autocommands.
7997 */
7998 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007999au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008000{
8001 AutoPat *ap, **prev_ap;
8002 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008003 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008004
8005 if (autocmd_busy || !au_need_clean)
8006 return;
8007
8008 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008009 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8010 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008011 {
8012 /* loop over all autocommand patterns */
8013 prev_ap = &(first_autopat[(int)event]);
8014 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8015 {
8016 /* loop over all commands for this pattern */
8017 prev_ac = &(ap->cmds);
8018 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8019 {
8020 /* remove the command if the pattern is to be deleted or when
8021 * the command has been marked for deletion */
8022 if (ap->pat == NULL || ac->cmd == NULL)
8023 {
8024 *prev_ac = ac->next;
8025 vim_free(ac->cmd);
8026 vim_free(ac);
8027 }
8028 else
8029 prev_ac = &(ac->next);
8030 }
8031
8032 /* remove the pattern if it has been marked for deletion */
8033 if (ap->pat == NULL)
8034 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008035 if (ap->next == NULL)
8036 {
8037 if (prev_ap == &(first_autopat[(int)event]))
8038 last_autopat[(int)event] = NULL;
8039 else
8040 /* this depends on the "next" field being the first in
8041 * the struct */
8042 last_autopat[(int)event] = (AutoPat *)prev_ap;
8043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008044 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008045 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046 vim_free(ap);
8047 }
8048 else
8049 prev_ap = &(ap->next);
8050 }
8051 }
8052
8053 au_need_clean = FALSE;
8054}
8055
8056/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008057 * Called when buffer is freed, to remove/invalidate related buffer-local
8058 * autocmds.
8059 */
8060 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008061aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008062{
8063 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008064 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008065 AutoPatCmd *apc;
8066
8067 /* invalidate currently executing autocommands */
8068 for (apc = active_apc_list; apc; apc = apc->next)
8069 if (buf->b_fnum == apc->arg_bufnr)
8070 apc->arg_bufnr = 0;
8071
8072 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008073 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8074 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008075 /* loop over all autocommand patterns */
8076 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8077 if (ap->buflocal_nr == buf->b_fnum)
8078 {
8079 au_remove_pat(ap);
8080 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008081 {
8082 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008083 smsg(_("auto-removing autocommand: %s <buffer=%d>"),
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008084 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008085 verbose_leave();
8086 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008087 }
8088 au_cleanup();
8089}
8090
8091/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092 * Add an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008093 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008094 */
8095 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008096au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097{
8098 int i;
8099
8100 i = au_find_group(name);
8101 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8102 {
8103 /* First try using a free entry. */
8104 for (i = 0; i < augroups.ga_len; ++i)
8105 if (AUGROUP_NAME(i) == NULL)
8106 break;
8107 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8108 return AUGROUP_ERROR;
8109
8110 AUGROUP_NAME(i) = vim_strsave(name);
8111 if (AUGROUP_NAME(i) == NULL)
8112 return AUGROUP_ERROR;
8113 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008114 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008115 }
8116
8117 return i;
8118}
8119
8120 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008121au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122{
8123 int i;
8124
8125 i = au_find_group(name);
8126 if (i == AUGROUP_ERROR) /* the group doesn't exist */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008127 semsg(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008128 else if (i == current_augroup)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008129 emsg(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008130 else
8131 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008132 event_T event;
8133 AutoPat *ap;
8134 int in_use = FALSE;
8135
8136 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8137 event = (event_T)((int)event + 1))
8138 {
8139 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008140 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008141 {
8142 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8143 in_use = TRUE;
8144 event = NUM_EVENTS;
8145 break;
8146 }
8147 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008148 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008149 if (in_use)
8150 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008151 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008152 }
8153 else
8154 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008155 }
8156}
8157
8158/*
8159 * Find the ID of an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008160 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008161 */
8162 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008163au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008164{
8165 int i;
8166
8167 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008168 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008169 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008170 return i;
8171 return AUGROUP_ERROR;
8172}
8173
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008174/*
8175 * Return TRUE if augroup "name" exists.
8176 */
8177 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008178au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008179{
8180 return au_find_group(name) != AUGROUP_ERROR;
8181}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008182
Bram Moolenaar071d4272004-06-13 20:20:40 +00008183/*
8184 * ":augroup {name}".
8185 */
8186 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008187do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008188{
8189 int i;
8190
8191 if (del_group)
8192 {
8193 if (*arg == NUL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008194 emsg(_(e_argreq));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008195 else
8196 au_del_group(arg);
8197 }
8198 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8199 current_augroup = AUGROUP_DEFAULT;
8200 else if (*arg) /* ":aug xxx": switch to group xxx */
8201 {
8202 i = au_new_group(arg);
8203 if (i != AUGROUP_ERROR)
8204 current_augroup = i;
8205 }
8206 else /* ":aug": list the group names */
8207 {
8208 msg_start();
8209 for (i = 0; i < augroups.ga_len; ++i)
8210 {
8211 if (AUGROUP_NAME(i) != NULL)
8212 {
8213 msg_puts(AUGROUP_NAME(i));
8214 msg_puts((char_u *)" ");
8215 }
8216 }
8217 msg_clr_eos();
8218 msg_end();
8219 }
8220}
8221
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008222#if defined(EXITFREE) || defined(PROTO)
8223 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008224free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008225{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008226 int i;
8227 char_u *s;
8228
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008229 for (current_augroup = -1; current_augroup < augroups.ga_len;
8230 ++current_augroup)
8231 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008232
8233 for (i = 0; i < augroups.ga_len; ++i)
8234 {
8235 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008236 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008237 vim_free(s);
8238 }
8239 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008240}
8241#endif
8242
Bram Moolenaar071d4272004-06-13 20:20:40 +00008243/*
8244 * Return the event number for event name "start".
8245 * Return NUM_EVENTS if the event name was not found.
8246 * Return a pointer to the next event name in "end".
8247 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008248 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008249event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008250{
8251 char_u *p;
8252 int i;
8253 int len;
8254
Bram Moolenaare99e8442016-07-26 20:43:40 +02008255 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008256 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008257 ;
8258 for (i = 0; event_names[i].name != NULL; ++i)
8259 {
8260 len = (int)STRLEN(event_names[i].name);
8261 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8262 break;
8263 }
8264 if (*p == ',')
8265 ++p;
8266 *end = p;
8267 if (event_names[i].name == NULL)
8268 return NUM_EVENTS;
8269 return event_names[i].event;
8270}
8271
8272/*
8273 * Return the name for event "event".
8274 */
8275 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008276event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008277{
8278 int i;
8279
8280 for (i = 0; event_names[i].name != NULL; ++i)
8281 if (event_names[i].event == event)
8282 return (char_u *)event_names[i].name;
8283 return (char_u *)"Unknown";
8284}
8285
8286/*
8287 * Scan over the events. "*" stands for all events.
8288 */
8289 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008290find_end_event(
8291 char_u *arg,
8292 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008293{
8294 char_u *pat;
8295 char_u *p;
8296
8297 if (*arg == '*')
8298 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008299 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008300 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008301 semsg(_("E215: Illegal character after *: %s"), arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008302 return NULL;
8303 }
8304 pat = arg + 1;
8305 }
8306 else
8307 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008308 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309 {
8310 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8311 {
8312 if (have_group)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008313 semsg(_("E216: No such event: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008314 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008315 semsg(_("E216: No such group or event: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008316 return NULL;
8317 }
8318 }
8319 }
8320 return pat;
8321}
8322
8323/*
8324 * Return TRUE if "event" is included in 'eventignore'.
8325 */
8326 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008327event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328{
8329 char_u *p = p_ei;
8330
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008331 while (*p != NUL)
8332 {
8333 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8334 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008335 if (event_name2nr(p, &p) == event)
8336 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008338
8339 return FALSE;
8340}
8341
8342/*
8343 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8344 */
8345 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008346check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008347{
8348 char_u *p = p_ei;
8349
Bram Moolenaar071d4272004-06-13 20:20:40 +00008350 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008351 {
8352 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8353 {
8354 p += 3;
8355 if (*p == ',')
8356 ++p;
8357 }
8358 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008359 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008360 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008361
8362 return OK;
8363}
8364
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008365# if defined(FEAT_SYN_HL) || defined(PROTO)
8366
8367/*
8368 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8369 * buffer loaded into the window. "what" must start with a comma.
8370 * Returns the old value of 'eventignore' in allocated memory.
8371 */
8372 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008373au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008374{
8375 char_u *new_ei;
8376 char_u *save_ei;
8377
8378 save_ei = vim_strsave(p_ei);
8379 if (save_ei != NULL)
8380 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008381 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008382 if (new_ei != NULL)
8383 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008384 if (*what == ',' && *p_ei == NUL)
8385 STRCPY(new_ei, what + 1);
8386 else
8387 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008388 set_string_option_direct((char_u *)"ei", -1, new_ei,
8389 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008390 vim_free(new_ei);
8391 }
8392 }
8393 return save_ei;
8394}
8395
8396 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008397au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008398{
8399 if (old_ei != NULL)
8400 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008401 set_string_option_direct((char_u *)"ei", -1, old_ei,
8402 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008403 vim_free(old_ei);
8404 }
8405}
8406# endif /* FEAT_SYN_HL */
8407
Bram Moolenaar071d4272004-06-13 20:20:40 +00008408/*
8409 * do_autocmd() -- implements the :autocmd command. Can be used in the
8410 * following ways:
8411 *
8412 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8413 * will be automatically executed for <event>
8414 * when editing a file matching <pat>, in
8415 * the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008416 * :autocmd <event> <pat> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417 * <event> and <pat>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008418 * :autocmd <event> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008419 * <event>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008420 * :autocmd Show all autocommands.
8421 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008422 * <event> and <pat>, and add the command
8423 * <cmd>, for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008424 * :autocmd! <event> <pat> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008425 * <event> and <pat> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008426 * :autocmd! <event> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008427 * <event> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008428 * :autocmd! Remove ALL autocommands for the current
Bram Moolenaar071d4272004-06-13 20:20:40 +00008429 * group.
8430 *
8431 * Multiple events and patterns may be given separated by commas. Here are
8432 * some examples:
8433 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8434 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8435 *
8436 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008437 *
8438 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008439 */
8440 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008441do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008442{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008443 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008444 char_u *pat;
8445 char_u *envpat = NULL;
8446 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008447 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008448 int need_free = FALSE;
8449 int nested = FALSE;
8450 int group;
8451
Bram Moolenaare99e8442016-07-26 20:43:40 +02008452 if (*arg == '|')
8453 {
8454 arg = (char_u *)"";
8455 group = AUGROUP_ALL; /* no argument, use all groups */
8456 }
8457 else
8458 {
8459 /*
8460 * Check for a legal group name. If not, use AUGROUP_ALL.
8461 */
8462 group = au_get_grouparg(&arg);
8463 if (arg == NULL) /* out of memory */
8464 return;
8465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008466
8467 /*
8468 * Scan over the events.
8469 * If we find an illegal name, return here, don't do anything.
8470 */
8471 pat = find_end_event(arg, group != AUGROUP_ALL);
8472 if (pat == NULL)
8473 return;
8474
Bram Moolenaar071d4272004-06-13 20:20:40 +00008475 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008476 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008477 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008478 pat = (char_u *)"";
8479 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008481 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008482 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008483 /*
8484 * Scan over the pattern. Put a NUL at the end.
8485 */
8486 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008487 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008488 cmd++;
8489 if (*cmd)
8490 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008491
Bram Moolenaare99e8442016-07-26 20:43:40 +02008492 /* Expand environment variables in the pattern. Set 'shellslash', we want
8493 * forward slashes here. */
8494 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8495 {
8496#ifdef BACKSLASH_IN_FILENAME
8497 int p_ssl_save = p_ssl;
8498
8499 p_ssl = TRUE;
8500#endif
8501 envpat = expand_env_save(pat);
8502#ifdef BACKSLASH_IN_FILENAME
8503 p_ssl = p_ssl_save;
8504#endif
8505 if (envpat != NULL)
8506 pat = envpat;
8507 }
8508
8509 /*
8510 * Check for "nested" flag.
8511 */
8512 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008513 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008514 {
8515 nested = TRUE;
8516 cmd = skipwhite(cmd + 6);
8517 }
8518
8519 /*
8520 * Find the start of the commands.
8521 * Expand <sfile> in it.
8522 */
8523 if (*cmd != NUL)
8524 {
8525 cmd = expand_sfile(cmd);
8526 if (cmd == NULL) /* some error */
8527 return;
8528 need_free = TRUE;
8529 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008530 }
8531
8532 /*
8533 * Print header when showing autocommands.
8534 */
8535 if (!forceit && *cmd == NUL)
8536 {
8537 /* Highlight title */
Bram Moolenaar8c555332018-06-22 21:30:31 +02008538 MSG_PUTS_TITLE(_("\n--- Autocommands ---"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008539 }
8540
8541 /*
8542 * Loop over the events.
8543 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008544 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008546 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008547 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008548 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8549 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008550 if (do_autocmd_event(event, pat,
8551 nested, cmd, forceit, group) == FAIL)
8552 break;
8553 }
8554 else
8555 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008556 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8558 nested, cmd, forceit, group) == FAIL)
8559 break;
8560 }
8561
8562 if (need_free)
8563 vim_free(cmd);
8564 vim_free(envpat);
8565}
8566
8567/*
8568 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8569 * The "argp" argument is advanced to the following argument.
8570 *
8571 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8572 */
8573 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008574au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008575{
8576 char_u *group_name;
8577 char_u *p;
8578 char_u *arg = *argp;
8579 int group = AUGROUP_ALL;
8580
Bram Moolenaar1c465442017-03-12 20:10:05 +01008581 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008582 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008583 if (p > arg)
8584 {
8585 group_name = vim_strnsave(arg, (int)(p - arg));
8586 if (group_name == NULL) /* out of memory */
8587 return AUGROUP_ERROR;
8588 group = au_find_group(group_name);
8589 if (group == AUGROUP_ERROR)
8590 group = AUGROUP_ALL; /* no match, use all groups */
8591 else
8592 *argp = skipwhite(p); /* match, skip over group name */
8593 vim_free(group_name);
8594 }
8595 return group;
8596}
8597
8598/*
8599 * do_autocmd() for one event.
8600 * If *pat == NUL do for all patterns.
8601 * If *cmd == NUL show entries.
8602 * If forceit == TRUE delete entries.
8603 * If group is not AUGROUP_ALL, only use this group.
8604 */
8605 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008606do_autocmd_event(
8607 event_T event,
8608 char_u *pat,
8609 int nested,
8610 char_u *cmd,
8611 int forceit,
8612 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008613{
8614 AutoPat *ap;
8615 AutoPat **prev_ap;
8616 AutoCmd *ac;
8617 AutoCmd **prev_ac;
8618 int brace_level;
8619 char_u *endpat;
8620 int findgroup;
8621 int allgroups;
8622 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008623 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008624 int buflocal_nr;
8625 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008626
8627 if (group == AUGROUP_ALL)
8628 findgroup = current_augroup;
8629 else
8630 findgroup = group;
8631 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8632
8633 /*
8634 * Show or delete all patterns for an event.
8635 */
8636 if (*pat == NUL)
8637 {
8638 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8639 {
8640 if (forceit) /* delete the AutoPat, if it's in the current group */
8641 {
8642 if (ap->group == findgroup)
8643 au_remove_pat(ap);
8644 }
8645 else if (group == AUGROUP_ALL || ap->group == group)
8646 show_autocmd(ap, event);
8647 }
8648 }
8649
8650 /*
8651 * Loop through all the specified patterns.
8652 */
8653 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8654 {
8655 /*
8656 * Find end of the pattern.
8657 * Watch out for a comma in braces, like "*.\{obj,o\}".
8658 */
8659 brace_level = 0;
8660 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008661 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008662 {
8663 if (*endpat == '{')
8664 brace_level++;
8665 else if (*endpat == '}')
8666 brace_level--;
8667 }
8668 if (pat == endpat) /* ignore single comma */
8669 continue;
8670 patlen = (int)(endpat - pat);
8671
8672 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008673 * detect special <buflocal[=X]> buffer-local patterns
8674 */
8675 is_buflocal = FALSE;
8676 buflocal_nr = 0;
8677
Bram Moolenaar1e997822015-02-17 16:04:57 +01008678 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008679 && pat[patlen - 1] == '>')
8680 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008681 /* "<buffer...>": Error will be printed only for addition.
8682 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008683 is_buflocal = TRUE;
8684 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008685 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008686 buflocal_nr = curbuf->b_fnum;
8687 else if (patlen > 9 && pat[7] == '=')
8688 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008689 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8690 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008691 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008692 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008693 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008694 buflocal_nr = atoi((char *)pat + 8);
8695 }
8696 }
8697
8698 if (is_buflocal)
8699 {
8700 /* normalize pat into standard "<buffer>#N" form */
8701 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8702 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008703 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008704 }
8705
8706 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008707 * Find AutoPat entries with this pattern. When adding a command it
8708 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008709 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008710 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8711 prev_ap = &last_autopat[(int)event];
8712 else
8713 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008714 while ((ap = *prev_ap) != NULL)
8715 {
8716 if (ap->pat != NULL)
8717 {
8718 /* Accept a pattern when:
8719 * - a group was specified and it's that group, or a group was
8720 * not specified and it's the current group, or a group was
8721 * not specified and we are listing
8722 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008723 * - the pattern matches.
8724 * For <buffer[=X]>, this condition works because we normalize
8725 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008726 */
8727 if ((allgroups || ap->group == findgroup)
8728 && ap->patlen == patlen
8729 && STRNCMP(pat, ap->pat, patlen) == 0)
8730 {
8731 /*
8732 * Remove existing autocommands.
8733 * If adding any new autocmd's for this AutoPat, don't
8734 * delete the pattern from the autopat list, append to
8735 * this list.
8736 */
8737 if (forceit)
8738 {
8739 if (*cmd != NUL && ap->next == NULL)
8740 {
8741 au_remove_cmds(ap);
8742 break;
8743 }
8744 au_remove_pat(ap);
8745 }
8746
8747 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008748 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008749 */
8750 else if (*cmd == NUL)
8751 show_autocmd(ap, event);
8752
8753 /*
8754 * Add autocmd to this autopat, if it's the last one.
8755 */
8756 else if (ap->next == NULL)
8757 break;
8758 }
8759 }
8760 prev_ap = &ap->next;
8761 }
8762
8763 /*
8764 * Add a new command.
8765 */
8766 if (*cmd != NUL)
8767 {
8768 /*
8769 * If the pattern we want to add a command to does appear at the
8770 * end of the list (or not is not in the list at all), add the
8771 * pattern at the end of the list.
8772 */
8773 if (ap == NULL)
8774 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008775 /* refuse to add buffer-local ap if buffer number is invalid */
8776 if (is_buflocal && (buflocal_nr == 0
8777 || buflist_findnr(buflocal_nr) == NULL))
8778 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008779 semsg(_("E680: <buffer=%d>: invalid buffer number "),
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008780 buflocal_nr);
8781 return FAIL;
8782 }
8783
Bram Moolenaar071d4272004-06-13 20:20:40 +00008784 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8785 if (ap == NULL)
8786 return FAIL;
8787 ap->pat = vim_strnsave(pat, patlen);
8788 ap->patlen = patlen;
8789 if (ap->pat == NULL)
8790 {
8791 vim_free(ap);
8792 return FAIL;
8793 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008794
8795 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008796 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008797 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008798 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008799 }
8800 else
8801 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008802 char_u *reg_pat;
8803
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008804 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008805 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008806 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008807 if (reg_pat != NULL)
8808 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008809 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008810 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008811 {
8812 vim_free(ap->pat);
8813 vim_free(ap);
8814 return FAIL;
8815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008816 }
8817 ap->cmds = NULL;
8818 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008819 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008820 ap->next = NULL;
8821 if (group == AUGROUP_ALL)
8822 ap->group = current_augroup;
8823 else
8824 ap->group = group;
8825 }
8826
8827 /*
8828 * Add the autocmd at the end of the AutoCmd list.
8829 */
8830 prev_ac = &(ap->cmds);
8831 while ((ac = *prev_ac) != NULL)
8832 prev_ac = &ac->next;
8833 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8834 if (ac == NULL)
8835 return FAIL;
8836 ac->cmd = vim_strsave(cmd);
8837#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02008838 ac->script_ctx = current_sctx;
8839 ac->script_ctx.sc_lnum += sourcing_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008840#endif
8841 if (ac->cmd == NULL)
8842 {
8843 vim_free(ac);
8844 return FAIL;
8845 }
8846 ac->next = NULL;
8847 *prev_ac = ac;
8848 ac->nested = nested;
8849 }
8850 }
8851
8852 au_cleanup(); /* may really delete removed patterns/commands now */
8853 return OK;
8854}
8855
8856/*
8857 * Implementation of ":doautocmd [group] event [fname]".
8858 * Return OK for success, FAIL for failure;
8859 */
8860 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008861do_doautocmd(
8862 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008863 int do_msg, /* give message for no matching autocmds? */
8864 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865{
8866 char_u *fname;
8867 int nothing_done = TRUE;
8868 int group;
8869
Bram Moolenaar1610d052016-06-09 22:53:01 +02008870 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008871 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008872
Bram Moolenaar071d4272004-06-13 20:20:40 +00008873 /*
8874 * Check for a legal group name. If not, use AUGROUP_ALL.
8875 */
8876 group = au_get_grouparg(&arg);
8877 if (arg == NULL) /* out of memory */
8878 return FAIL;
8879
8880 if (*arg == '*')
8881 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008882 emsg(_("E217: Can't execute autocommands for ALL events"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008883 return FAIL;
8884 }
8885
8886 /*
8887 * Scan over the events.
8888 * If we find an illegal name, return here, don't do anything.
8889 */
8890 fname = find_end_event(arg, group != AUGROUP_ALL);
8891 if (fname == NULL)
8892 return FAIL;
8893
8894 fname = skipwhite(fname);
8895
8896 /*
8897 * Loop over the events.
8898 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008899 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008900 if (apply_autocmds_group(event_name2nr(arg, &arg),
8901 fname, NULL, TRUE, group, curbuf, NULL))
8902 nothing_done = FALSE;
8903
8904 if (nothing_done && do_msg)
8905 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008906 if (did_something != NULL)
8907 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908
8909#ifdef FEAT_EVAL
8910 return aborting() ? FAIL : OK;
8911#else
8912 return OK;
8913#endif
8914}
8915
8916/*
8917 * ":doautoall": execute autocommands for each loaded buffer.
8918 */
8919 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008920ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008921{
8922 int retval;
8923 aco_save_T aco;
8924 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008925 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008926 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008927 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008928 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929
8930 /*
8931 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8932 * equal to curbuf, but for some buffers there may not be a window.
8933 * So we change the buffer for the current window for a moment. This
8934 * gives problems when the autocommands make changes to the list of
8935 * buffers or windows...
8936 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008937 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008939 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008940 {
8941 /* find a window for this buffer and save some values */
8942 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008943 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944
8945 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008946 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008947
Bram Moolenaar1610d052016-06-09 22:53:01 +02008948 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008949 {
8950 /* Execute the modeline settings, but don't set window-local
8951 * options if we are using the current window for another
8952 * buffer. */
8953 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955
8956 /* restore the current window */
8957 aucmd_restbuf(&aco);
8958
8959 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008960 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008961 break;
8962 }
8963 }
8964
8965 check_cursor(); /* just in case lines got deleted */
8966}
8967
8968/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008969 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8970 * return TRUE and advance *argp to after it.
8971 * Thus return TRUE when do_modelines() should be called.
8972 */
8973 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008974check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008975{
8976 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8977 {
8978 *argp = skipwhite(*argp + 12);
8979 return FALSE;
8980 }
8981 return TRUE;
8982}
8983
8984/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008985 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008986 * Search for a visible window containing the current buffer. If there isn't
8987 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008988 * Set "curbuf" and "curwin" to match "buf".
8989 */
8990 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008991aucmd_prepbuf(
8992 aco_save_T *aco, /* structure to save values in */
8993 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994{
8995 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008996 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008997#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008998 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008999#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009000
9001 /* Find a window that is for the new buffer */
9002 if (buf == curbuf) /* be quick when buf is curbuf */
9003 win = curwin;
9004 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009005 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 if (win->w_buffer == buf)
9007 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009009 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9010 * back to using the current window. */
9011 if (win == NULL && aucmd_win == NULL)
9012 {
9013 win_alloc_aucmd_win();
9014 if (aucmd_win == NULL)
9015 win = curwin;
9016 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009017 if (win == NULL && aucmd_win_used)
9018 /* Strange recursive autocommand, fall back to using the current
9019 * window. Expect a few side effects... */
9020 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009021
9022 aco->save_curwin = curwin;
9023 aco->save_curbuf = curbuf;
Bram Moolenaara42df592018-12-24 00:22:39 +01009024 aco->save_prevwin = prevwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 if (win != NULL)
9026 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009027 /* There is a window for "buf" in the current tab page, make it the
9028 * curwin. This is preferred, it has the least side effects (esp. if
9029 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009030 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009032 }
9033 else
9034 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009035 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009036 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009037 * Anything related to a window (e.g., setting folds) may have
9038 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009039 aco->use_aucmd_win = TRUE;
9040 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009041 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009042#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009043 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009044#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009045 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009046 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009047
9048 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9049 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009050 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009051 aco->globaldir = globaldir;
9052 globaldir = NULL;
9053
Bram Moolenaar071d4272004-06-13 20:20:40 +00009054
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009055 /* Split the current window, put the aucmd_win in the upper half.
9056 * We don't want the BufEnter or WinEnter autocommands. */
9057 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009058 make_snapshot(SNAP_AUCMD_IDX);
9059 save_ea = p_ea;
9060 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009061
Bram Moolenaar4033c552017-09-16 20:54:51 +02009062#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009063 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9064 save_acd = p_acd;
9065 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009066#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009067
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009068 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9069 (void)win_comp_pos(); /* recompute window positions */
9070 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009071#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009072 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009073#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009074 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009075 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009077 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009078 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009079 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080}
9081
9082/*
9083 * Cleanup after executing autocommands for a (hidden) buffer.
9084 * Restore the window as it was (if possible).
9085 */
9086 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009087aucmd_restbuf(
9088 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009089{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009090 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009091
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009092 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009093 {
9094 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009095 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009096 * page. Do not trigger autocommands here. */
9097 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009098 if (curwin != aucmd_win)
9099 {
9100 tabpage_T *tp;
9101 win_T *wp;
9102
9103 FOR_ALL_TAB_WINDOWS(tp, wp)
9104 {
9105 if (wp == aucmd_win)
9106 {
9107 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009108 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009109 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009110 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009111 }
9112 }
9113 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009114win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009115
9116 /* Remove the window and frame from the tree of frames. */
9117 (void)winframe_remove(curwin, &dummy, NULL);
9118 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009119 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009120 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009121
9122 if (!valid_tabpage_win(curtab))
9123 /* no valid window in current tabpage */
9124 close_tabpage(curtab);
9125
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009126 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9127 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009128 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009129
9130 if (win_valid(aco->save_curwin))
9131 curwin = aco->save_curwin;
9132 else
9133 /* Hmm, original window disappeared. Just use the first one. */
9134 curwin = firstwin;
Bram Moolenaara42df592018-12-24 00:22:39 +01009135 if (win_valid(aco->save_prevwin))
9136 prevwin = aco->save_prevwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009137#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009138 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9139 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009140#endif
9141 curbuf = curwin->w_buffer;
9142
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009143 vim_free(globaldir);
9144 globaldir = aco->globaldir;
9145
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009146 /* the buffer contents may have changed */
9147 check_cursor();
9148 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9149 {
9150 curwin->w_topline = curbuf->b_ml.ml_line_count;
9151#ifdef FEAT_DIFF
9152 curwin->w_topfill = 0;
9153#endif
9154 }
9155#if defined(FEAT_GUI)
9156 /* Hide the scrollbars from the aucmd_win and update. */
9157 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9158 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9159 gui_may_update_scrollbars();
9160#endif
9161 }
9162 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009163 {
9164 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009165 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009166 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009167 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009168 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009169 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009171 && curbuf != aco->new_curbuf.br_buf
9172 && bufref_valid(&aco->new_curbuf)
9173 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009174 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009175# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9176 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009177 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009178# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009179 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009180 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009181 curwin->w_buffer = curbuf;
9182 ++curbuf->b_nwindows;
9183 }
9184
9185 curwin = aco->save_curwin;
9186 curbuf = curwin->w_buffer;
Bram Moolenaara42df592018-12-24 00:22:39 +01009187 if (win_valid(aco->save_prevwin))
9188 prevwin = aco->save_prevwin;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009189 /* In case the autocommand move the cursor to a position that that
9190 * not exist in curbuf. */
9191 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009192 }
9193 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009194}
9195
9196static int autocmd_nested = FALSE;
9197
9198/*
9199 * Execute autocommands for "event" and file name "fname".
9200 * Return TRUE if some commands were executed.
9201 */
9202 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009203apply_autocmds(
9204 event_T event,
9205 char_u *fname, /* NULL or empty means use actual file name */
9206 char_u *fname_io, /* fname to use for <afile> on cmdline */
9207 int force, /* when TRUE, ignore autocmd_busy */
9208 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009209{
9210 return apply_autocmds_group(event, fname, fname_io, force,
9211 AUGROUP_ALL, buf, NULL);
9212}
9213
9214/*
9215 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9216 * setting v:filearg.
9217 */
9218 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009219apply_autocmds_exarg(
9220 event_T event,
9221 char_u *fname,
9222 char_u *fname_io,
9223 int force,
9224 buf_T *buf,
9225 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009226{
9227 return apply_autocmds_group(event, fname, fname_io, force,
9228 AUGROUP_ALL, buf, eap);
9229}
9230
9231/*
9232 * Like apply_autocmds(), but handles the caller's retval. If the script
9233 * processing is being aborted or if retval is FAIL when inside a try
9234 * conditional, no autocommands are executed. If otherwise the autocommands
9235 * cause the script to be aborted, retval is set to FAIL.
9236 */
9237 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009238apply_autocmds_retval(
9239 event_T event,
9240 char_u *fname, /* NULL or empty means use actual file name */
9241 char_u *fname_io, /* fname to use for <afile> on cmdline */
9242 int force, /* when TRUE, ignore autocmd_busy */
9243 buf_T *buf, /* buffer for <abuf> */
9244 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009245{
9246 int did_cmd;
9247
Bram Moolenaar1e015462005-09-25 22:16:38 +00009248#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009249 if (should_abort(*retval))
9250 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009251#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009252
9253 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9254 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009255 if (did_cmd
9256#ifdef FEAT_EVAL
9257 && aborting()
9258#endif
9259 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009260 *retval = FAIL;
9261 return did_cmd;
9262}
9263
Bram Moolenaard35f9712005-12-18 22:02:33 +00009264/*
9265 * Return TRUE when there is a CursorHold autocommand defined.
9266 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009267 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009268has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009270 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9271 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009272}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009273
9274/*
9275 * Return TRUE if the CursorHold event can be triggered.
9276 */
9277 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009278trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009279{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009280 int state;
9281
Bram Moolenaar05334432011-07-20 18:29:39 +02009282 if (!did_cursorhold
9283 && has_cursorhold()
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02009284 && reg_recording == 0
Bram Moolenaar05334432011-07-20 18:29:39 +02009285 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009286#ifdef FEAT_INS_EXPAND
9287 && !ins_compl_active()
9288#endif
9289 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009290 {
9291 state = get_real_state();
9292 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9293 return TRUE;
9294 }
9295 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009296}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009297
9298/*
9299 * Return TRUE when there is a CursorMoved autocommand defined.
9300 */
9301 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009302has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009303{
9304 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9305}
9306
9307/*
9308 * Return TRUE when there is a CursorMovedI autocommand defined.
9309 */
9310 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009311has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009312{
9313 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9314}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009315
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009316/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009317 * Return TRUE when there is a TextChanged autocommand defined.
9318 */
9319 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009320has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009321{
9322 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9323}
9324
9325/*
9326 * Return TRUE when there is a TextChangedI autocommand defined.
9327 */
9328 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009329has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009330{
9331 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9332}
9333
9334/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009335 * Return TRUE when there is a TextChangedP autocommand defined.
9336 */
9337 int
9338has_textchangedP(void)
9339{
9340 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9341}
9342
9343/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009344 * Return TRUE when there is an InsertCharPre autocommand defined.
9345 */
9346 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009347has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009348{
9349 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9350}
9351
Bram Moolenaard5005162014-08-22 23:05:54 +02009352/*
9353 * Return TRUE when there is an CmdUndefined autocommand defined.
9354 */
9355 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009356has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009357{
9358 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9359}
9360
9361/*
9362 * Return TRUE when there is an FuncUndefined autocommand defined.
9363 */
9364 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009365has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009366{
9367 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9368}
9369
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009370/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009371 * Return TRUE when there is a TextYankPost autocommand defined.
9372 */
9373 int
9374has_textyankpost(void)
9375{
9376 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9377}
9378
9379/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009380 * Execute autocommands for "event" and file name "fname".
9381 * Return TRUE if some commands were executed.
9382 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009383 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009384apply_autocmds_group(
9385 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009386 char_u *fname, /* NULL or empty means use actual file name */
9387 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009388 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009389 int force, /* when TRUE, ignore autocmd_busy */
9390 int group, /* group ID, or AUGROUP_ALL */
9391 buf_T *buf, /* buffer for <abuf> */
9392 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009393{
9394 char_u *sfname = NULL; /* short file name */
9395 char_u *tail;
9396 int save_changed;
9397 buf_T *old_curbuf;
9398 int retval = FALSE;
9399 char_u *save_sourcing_name;
9400 linenr_T save_sourcing_lnum;
9401 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009402 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009403 int save_autocmd_bufnr;
9404 char_u *save_autocmd_match;
9405 int save_autocmd_busy;
9406 int save_autocmd_nested;
9407 static int nesting = 0;
9408 AutoPatCmd patcmd;
9409 AutoPat *ap;
9410#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009411 sctx_T save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009412 funccal_entry_T funccal_entry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009413 char_u *save_cmdarg;
9414 long save_cmdbang;
9415#endif
9416 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009417#ifdef FEAT_PROFILE
9418 proftime_T wait_time;
9419#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009420 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009421 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009422 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009423
9424 /*
9425 * Quickly return if there are no autocommands for this event or
9426 * autocommands are blocked.
9427 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009428 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9429 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009430 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009431
9432 /*
9433 * When autocommands are busy, new autocommands are only executed when
9434 * explicitly enabled with the "nested" flag.
9435 */
9436 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009437 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009438
9439#ifdef FEAT_EVAL
9440 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009441 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009442 * occurred or an exception was thrown but not caught.
9443 */
9444 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009445 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009446#endif
9447
9448 /*
9449 * FileChangedShell never nests, because it can create an endless loop.
9450 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009451 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9452 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009453 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009454
9455 /*
9456 * Ignore events in 'eventignore'.
9457 */
9458 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009459 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009460
9461 /*
9462 * Allow nesting of autocommands, but restrict the depth, because it's
9463 * possible to create an endless loop.
9464 */
9465 if (nesting == 10)
9466 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009467 emsg(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009468 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009469 }
9470
9471 /*
9472 * Check if these autocommands are disabled. Used when doing ":all" or
9473 * ":ball".
9474 */
9475 if ( (autocmd_no_enter
9476 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9477 || (autocmd_no_leave
9478 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009479 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009480
9481 /*
9482 * Save the autocmd_* variables and info about the current buffer.
9483 */
9484 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009485 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009486 save_autocmd_bufnr = autocmd_bufnr;
9487 save_autocmd_match = autocmd_match;
9488 save_autocmd_busy = autocmd_busy;
9489 save_autocmd_nested = autocmd_nested;
9490 save_changed = curbuf->b_changed;
9491 old_curbuf = curbuf;
9492
9493 /*
9494 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009495 * Make a copy to avoid that changing a buffer name or directory makes it
9496 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009497 */
9498 if (fname_io == NULL)
9499 {
Bram Moolenaar60a68362018-04-30 15:40:48 +02009500 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
9501 || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009502 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009503 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009504 autocmd_fname = fname;
9505 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009506 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009507 else
9508 autocmd_fname = NULL;
9509 }
9510 else
9511 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009512 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009513 autocmd_fname = vim_strsave(autocmd_fname);
9514 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009515
9516 /*
9517 * Set the buffer number to be used for <abuf>.
9518 */
9519 if (buf == NULL)
9520 autocmd_bufnr = 0;
9521 else
9522 autocmd_bufnr = buf->b_fnum;
9523
9524 /*
9525 * When the file name is NULL or empty, use the file name of buffer "buf".
9526 * Always use the full path of the file name to match with, in case
9527 * "allow_dirs" is set.
9528 */
9529 if (fname == NULL || *fname == NUL)
9530 {
9531 if (buf == NULL)
9532 fname = NULL;
9533 else
9534 {
9535#ifdef FEAT_SYN_HL
9536 if (event == EVENT_SYNTAX)
9537 fname = buf->b_p_syn;
9538 else
9539#endif
9540 if (event == EVENT_FILETYPE)
9541 fname = buf->b_p_ft;
9542 else
9543 {
9544 if (buf->b_sfname != NULL)
9545 sfname = vim_strsave(buf->b_sfname);
9546 fname = buf->b_ffname;
9547 }
9548 }
9549 if (fname == NULL)
9550 fname = (char_u *)"";
9551 fname = vim_strsave(fname); /* make a copy, so we can change it */
9552 }
9553 else
9554 {
9555 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009556 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009557 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009558 if (event == EVENT_FILETYPE
9559 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009560 || event == EVENT_CMDLINECHANGED
9561 || event == EVENT_CMDLINEENTER
9562 || event == EVENT_CMDLINELEAVE
9563 || event == EVENT_CMDWINENTER
9564 || event == EVENT_CMDWINLEAVE
9565 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009566 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009567 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009568 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009569 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009570 || event == EVENT_COLORSCHEME
Bram Moolenaar60a68362018-04-30 15:40:48 +02009571 || event == EVENT_COLORSCHEMEPRE
Bram Moolenaar53744302015-07-17 17:38:22 +02009572 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009573 || event == EVENT_QUICKFIXCMDPOST
9574 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009575 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009576 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009577 autocmd_fname_full = TRUE; /* don't expand it later */
9578 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009579 else
9580 fname = FullName_save(fname, FALSE);
9581 }
9582 if (fname == NULL) /* out of memory */
9583 {
9584 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009585 retval = FALSE;
9586 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009587 }
9588
9589#ifdef BACKSLASH_IN_FILENAME
9590 /*
9591 * Replace all backslashes with forward slashes. This makes the
9592 * autocommand patterns portable between Unix and MS-DOS.
9593 */
9594 if (sfname != NULL)
9595 forward_slash(sfname);
9596 forward_slash(fname);
9597#endif
9598
9599#ifdef VMS
9600 /* remove version for correct match */
9601 if (sfname != NULL)
9602 vms_remove_version(sfname);
9603 vms_remove_version(fname);
9604#endif
9605
9606 /*
9607 * Set the name to be used for <amatch>.
9608 */
9609 autocmd_match = fname;
9610
9611
Bram Moolenaar8c555332018-06-22 21:30:31 +02009612 /* Don't redraw while doing autocommands. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009613 ++RedrawingDisabled;
9614 save_sourcing_name = sourcing_name;
9615 sourcing_name = NULL; /* don't free this one */
9616 save_sourcing_lnum = sourcing_lnum;
9617 sourcing_lnum = 0; /* no line number here */
9618
9619#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009620 save_current_sctx = current_sctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009621
Bram Moolenaar05159a02005-02-26 23:04:13 +00009622# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009623 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009624 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9625# endif
9626
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009627 // Don't use local function variables, if called from a function.
9628 save_funccal(&funccal_entry);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009629#endif
9630
9631 /*
9632 * When starting to execute autocommands, save the search patterns.
9633 */
9634 if (!autocmd_busy)
9635 {
9636 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009637#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009638 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009639#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009640 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009641 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009642 did_save_redobuff = TRUE;
9643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009644 did_filetype = keep_filetype;
9645 }
9646
9647 /*
9648 * Note that we are applying autocmds. Some commands need to know.
9649 */
9650 autocmd_busy = TRUE;
9651 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9652 ++nesting; /* see matching decrement below */
9653
9654 /* Remember that FileType was triggered. Used for did_filetype(). */
9655 if (event == EVENT_FILETYPE)
9656 did_filetype = TRUE;
9657
9658 tail = gettail(fname);
9659
9660 /* Find first autocommand that matches */
9661 patcmd.curpat = first_autopat[(int)event];
9662 patcmd.nextcmd = NULL;
9663 patcmd.group = group;
9664 patcmd.fname = fname;
9665 patcmd.sfname = sfname;
9666 patcmd.tail = tail;
9667 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009668 patcmd.arg_bufnr = autocmd_bufnr;
9669 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009670 auto_next_pat(&patcmd, FALSE);
9671
9672 /* found one, start executing the autocommands */
9673 if (patcmd.curpat != NULL)
9674 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009675 /* add to active_apc_list */
9676 patcmd.next = active_apc_list;
9677 active_apc_list = &patcmd;
9678
Bram Moolenaar071d4272004-06-13 20:20:40 +00009679#ifdef FEAT_EVAL
9680 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009681 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009682 if (eap != NULL)
9683 {
9684 save_cmdarg = set_cmdarg(eap, NULL);
9685 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9686 }
9687 else
9688 save_cmdarg = NULL; /* avoid gcc warning */
9689#endif
9690 retval = TRUE;
9691 /* mark the last pattern, to avoid an endless loop when more patterns
9692 * are added when executing autocommands */
9693 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9694 ap->last = FALSE;
9695 ap->last = TRUE;
9696 check_lnums(TRUE); /* make sure cursor and topline are valid */
9697 do_cmdline(NULL, getnextac, (void *)&patcmd,
9698 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9699#ifdef FEAT_EVAL
9700 if (eap != NULL)
9701 {
9702 (void)set_cmdarg(NULL, save_cmdarg);
9703 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9704 }
9705#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009706 /* delete from active_apc_list */
9707 if (active_apc_list == &patcmd) /* just in case */
9708 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009709 }
9710
9711 --RedrawingDisabled;
9712 autocmd_busy = save_autocmd_busy;
9713 filechangeshell_busy = FALSE;
9714 autocmd_nested = save_autocmd_nested;
9715 vim_free(sourcing_name);
9716 sourcing_name = save_sourcing_name;
9717 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009718 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009719 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009720 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009721 autocmd_bufnr = save_autocmd_bufnr;
9722 autocmd_match = save_autocmd_match;
9723#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009724 current_sctx = save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009725 restore_funccal();
Bram Moolenaar05159a02005-02-26 23:04:13 +00009726# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009727 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009728 prof_child_exit(&wait_time);
9729# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009730#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009731 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009732 vim_free(fname);
9733 vim_free(sfname);
9734 --nesting; /* see matching increment above */
9735
9736 /*
9737 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009738 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9739 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009740 */
9741 if (!autocmd_busy)
9742 {
9743 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009744 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009745 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009747 while (au_pending_free_buf != NULL)
9748 {
9749 buf_T *b = au_pending_free_buf->b_next;
9750 vim_free(au_pending_free_buf);
9751 au_pending_free_buf = b;
9752 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009753 while (au_pending_free_win != NULL)
9754 {
9755 win_T *w = au_pending_free_win->w_next;
9756 vim_free(au_pending_free_win);
9757 au_pending_free_win = w;
9758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009759 }
9760
9761 /*
9762 * Some events don't set or reset the Changed flag.
9763 * Check if still in the same buffer!
9764 */
9765 if (curbuf == old_curbuf
9766 && (event == EVENT_BUFREADPOST
9767 || event == EVENT_BUFWRITEPOST
9768 || event == EVENT_FILEAPPENDPOST
9769 || event == EVENT_VIMLEAVE
9770 || event == EVENT_VIMLEAVEPRE))
9771 {
9772#ifdef FEAT_TITLE
9773 if (curbuf->b_changed != save_changed)
9774 need_maketitle = TRUE;
9775#endif
9776 curbuf->b_changed = save_changed;
9777 }
9778
9779 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009780
9781BYPASS_AU:
9782 /* When wiping out a buffer make sure all its buffer-local autocommands
9783 * are deleted. */
9784 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9785 aubuflocal_remove(buf);
9786
Bram Moolenaarc3691332016-04-20 12:49:49 +02009787 if (retval == OK && event == EVENT_FILETYPE)
9788 au_did_filetype = TRUE;
9789
Bram Moolenaar071d4272004-06-13 20:20:40 +00009790 return retval;
9791}
9792
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009793# ifdef FEAT_EVAL
9794static char_u *old_termresponse = NULL;
9795# endif
9796
9797/*
9798 * Block triggering autocommands until unblock_autocmd() is called.
9799 * Can be used recursively, so long as it's symmetric.
9800 */
9801 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009802block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009803{
9804# ifdef FEAT_EVAL
9805 /* Remember the value of v:termresponse. */
9806 if (autocmd_blocked == 0)
9807 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9808# endif
9809 ++autocmd_blocked;
9810}
9811
9812 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009813unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009814{
9815 --autocmd_blocked;
9816
9817# ifdef FEAT_EVAL
9818 /* When v:termresponse was set while autocommands were blocked, trigger
9819 * the autocommands now. Esp. useful when executing a shell command
9820 * during startup (vimdiff). */
9821 if (autocmd_blocked == 0
9822 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9823 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9824# endif
9825}
9826
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009827 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009828is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009829{
9830 return autocmd_blocked != 0;
9831}
9832
Bram Moolenaar071d4272004-06-13 20:20:40 +00009833/*
9834 * Find next autocommand pattern that matches.
9835 */
9836 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009837auto_next_pat(
9838 AutoPatCmd *apc,
9839 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009840{
9841 AutoPat *ap;
9842 AutoCmd *cp;
9843 char_u *name;
9844 char *s;
9845
Bram Moolenaard23a8232018-02-10 18:45:26 +01009846 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009847
9848 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9849 {
9850 apc->curpat = NULL;
9851
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009852 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009853 * the group matches. For buffer-local autocommands only check the
9854 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009855 if (ap->pat != NULL && ap->cmds != NULL
9856 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9857 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009858 /* execution-condition */
9859 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009860 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009861 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009862 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009863 {
9864 name = event_nr2name(apc->event);
Bram Moolenaar8c555332018-06-22 21:30:31 +02009865 s = _("%s Autocommands for \"%s\"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009866 sourcing_name = alloc((unsigned)(STRLEN(s)
9867 + STRLEN(name) + ap->patlen + 1));
9868 if (sourcing_name != NULL)
9869 {
9870 sprintf((char *)sourcing_name, s,
9871 (char *)name, (char *)ap->pat);
9872 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009873 {
9874 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009875 smsg(_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009876 verbose_leave();
9877 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009878 }
9879
9880 apc->curpat = ap;
9881 apc->nextcmd = ap->cmds;
9882 /* mark last command */
9883 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9884 cp->last = FALSE;
9885 cp->last = TRUE;
9886 }
9887 line_breakcheck();
9888 if (apc->curpat != NULL) /* found a match */
9889 break;
9890 }
9891 if (stop_at_last && ap->last)
9892 break;
9893 }
9894}
9895
9896/*
9897 * Get next autocommand command.
9898 * Called by do_cmdline() to get the next line for ":if".
9899 * Returns allocated string, or NULL for end of autocommands.
9900 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009901 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009902getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009903{
9904 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9905 char_u *retval;
9906 AutoCmd *ac;
9907
9908 /* Can be called again after returning the last line. */
9909 if (acp->curpat == NULL)
9910 return NULL;
9911
9912 /* repeat until we find an autocommand to execute */
9913 for (;;)
9914 {
9915 /* skip removed commands */
9916 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9917 if (acp->nextcmd->last)
9918 acp->nextcmd = NULL;
9919 else
9920 acp->nextcmd = acp->nextcmd->next;
9921
9922 if (acp->nextcmd != NULL)
9923 break;
9924
9925 /* at end of commands, find next pattern that matches */
9926 if (acp->curpat->last)
9927 acp->curpat = NULL;
9928 else
9929 acp->curpat = acp->curpat->next;
9930 if (acp->curpat != NULL)
9931 auto_next_pat(acp, TRUE);
9932 if (acp->curpat == NULL)
9933 return NULL;
9934 }
9935
9936 ac = acp->nextcmd;
9937
9938 if (p_verbose >= 9)
9939 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009940 verbose_enter_scroll();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009941 smsg(_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009942 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009943 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009944 }
9945 retval = vim_strsave(ac->cmd);
9946 autocmd_nested = ac->nested;
9947#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009948 current_sctx = ac->script_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009949#endif
9950 if (ac->last)
9951 acp->nextcmd = NULL;
9952 else
9953 acp->nextcmd = ac->next;
9954 return retval;
9955}
9956
9957/*
9958 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009959 * To account for buffer-local autocommands, function needs to know
9960 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009961 */
9962 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009963has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009964{
9965 AutoPat *ap;
9966 char_u *fname;
9967 char_u *tail = gettail(sfname);
9968 int retval = FALSE;
9969
9970 fname = FullName_save(sfname, FALSE);
9971 if (fname == NULL)
9972 return FALSE;
9973
9974#ifdef BACKSLASH_IN_FILENAME
9975 /*
9976 * Replace all backslashes with forward slashes. This makes the
9977 * autocommand patterns portable between Unix and MS-DOS.
9978 */
9979 sfname = vim_strsave(sfname);
9980 if (sfname != NULL)
9981 forward_slash(sfname);
9982 forward_slash(fname);
9983#endif
9984
9985 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9986 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009987 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009988 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009989 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009990 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009991 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009992 {
9993 retval = TRUE;
9994 break;
9995 }
9996
9997 vim_free(fname);
9998#ifdef BACKSLASH_IN_FILENAME
9999 vim_free(sfname);
10000#endif
10001
10002 return retval;
10003}
10004
10005#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10006/*
10007 * Function given to ExpandGeneric() to obtain the list of autocommand group
10008 * names.
10009 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010010 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010011get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010012{
10013 if (idx == augroups.ga_len) /* add "END" add the end */
10014 return (char_u *)"END";
10015 if (idx >= augroups.ga_len) /* end of list */
10016 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010017 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010018 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010019 return (char_u *)"";
10020 return AUGROUP_NAME(idx); /* return a name */
10021}
10022
10023static int include_groups = FALSE;
10024
10025 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010026set_context_in_autocmd(
10027 expand_T *xp,
10028 char_u *arg,
10029 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010030{
10031 char_u *p;
10032 int group;
10033
10034 /* check for a group name, skip it if present */
10035 include_groups = FALSE;
10036 p = arg;
10037 group = au_get_grouparg(&arg);
10038 if (group == AUGROUP_ERROR)
10039 return NULL;
10040 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010041 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010042 {
10043 arg = p;
10044 group = AUGROUP_ALL;
10045 }
10046
10047 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010048 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010049 if (*p == ',')
10050 arg = p + 1;
10051 if (*p == NUL)
10052 {
10053 if (group == AUGROUP_ALL)
10054 include_groups = TRUE;
10055 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10056 xp->xp_pattern = arg;
10057 return NULL;
10058 }
10059
10060 /* skip over pattern */
10061 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010062 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010063 arg++;
10064 if (*arg)
10065 return arg; /* expand (next) command */
10066
10067 if (doautocmd)
10068 xp->xp_context = EXPAND_FILES; /* expand file names */
10069 else
10070 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10071 return NULL;
10072}
10073
10074/*
10075 * Function given to ExpandGeneric() to obtain the list of event names.
10076 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010077 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010078get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010079{
10080 if (idx < augroups.ga_len) /* First list group names, if wanted */
10081 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010082 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010083 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010084 return (char_u *)""; /* skip deleted entries */
10085 return AUGROUP_NAME(idx); /* return a name */
10086 }
10087 return (char_u *)event_names[idx - augroups.ga_len].name;
10088}
10089
10090#endif /* FEAT_CMDL_COMPL */
10091
10092/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010093 * Return TRUE if autocmd is supported.
10094 */
10095 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010096autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010097{
10098 char_u *p;
10099
10100 return (event_name2nr(name, &p) != NUM_EVENTS);
10101}
10102
10103/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010104 * Return TRUE if an autocommand is defined for a group, event and
10105 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10106 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10107 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10108 * Used for:
10109 * exists("#Group") or
10110 * exists("#Group#Event") or
10111 * exists("#Group#Event#pat") or
10112 * exists("#Event") or
10113 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010114 */
10115 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010116au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010117{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010118 char_u *arg_save;
10119 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010120 char_u *event_name;
10121 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010122 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010123 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010124 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010125 int group;
10126 int retval = FALSE;
10127
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010128 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010129 arg_save = vim_strsave(arg);
10130 if (arg_save == NULL)
10131 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010132 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010133 if (p != NULL)
10134 *p++ = NUL;
10135
10136 /* First, look for an autocmd group name */
10137 group = au_find_group(arg_save);
10138 if (group == AUGROUP_ERROR)
10139 {
10140 /* Didn't match a group name, assume the first argument is an event. */
10141 group = AUGROUP_ALL;
10142 event_name = arg_save;
10143 }
10144 else
10145 {
10146 if (p == NULL)
10147 {
10148 /* "Group": group name is present and it's recognized */
10149 retval = TRUE;
10150 goto theend;
10151 }
10152
10153 /* Must be "Group#Event" or "Group#Event#pat". */
10154 event_name = p;
10155 p = vim_strchr(event_name, '#');
10156 if (p != NULL)
10157 *p++ = NUL; /* "Group#Event#pat" */
10158 }
10159
10160 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010161
10162 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010163 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010164
10165 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010166 if (event == NUM_EVENTS)
10167 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010168
10169 /* Find the first autocommand for this event.
10170 * If there isn't any, return FALSE;
10171 * If there is one and no pattern given, return TRUE; */
10172 ap = first_autopat[(int)event];
10173 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010174 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010175
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010176 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10177 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010178 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010179 buflocal_buf = curbuf;
10180
Bram Moolenaar071d4272004-06-13 20:20:40 +000010181 /* Check if there is an autocommand with the given pattern. */
10182 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010183 /* only use a pattern when it has not been removed and has commands. */
10184 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010185 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010186 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010187 && (pattern == NULL
10188 || (buflocal_buf == NULL
10189 ? fnamecmp(ap->pat, pattern) == 0
10190 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010191 {
10192 retval = TRUE;
10193 break;
10194 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010195
Bram Moolenaar195d6352005-12-19 22:08:24 +000010196theend:
10197 vim_free(arg_save);
10198 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010199}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010200
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010201
10202/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010203 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10204 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10205 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010206 * Used for autocommands and 'wildignore'.
10207 * Returns TRUE if there is a match, FALSE otherwise.
10208 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010209 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010210match_file_pat(
10211 char_u *pattern, /* pattern to match with */
10212 regprog_T **prog, /* pre-compiled regprog or NULL */
10213 char_u *fname, /* full path of file name */
10214 char_u *sfname, /* short file name or NULL */
10215 char_u *tail, /* tail of path */
10216 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010217{
10218 regmatch_T regmatch;
10219 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010220
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010221 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010222 if (prog != NULL)
10223 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010224 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010225 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010226
10227 /*
10228 * Try for a match with the pattern with:
10229 * 1. the full file name, when the pattern has a '/'.
10230 * 2. the short file name, when the pattern has a '/'.
10231 * 3. the tail of the file name, when the pattern has no '/'.
10232 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010233 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010234 && ((allow_dirs
10235 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10236 || (sfname != NULL
10237 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010238 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010239 result = TRUE;
10240
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010241 if (prog != NULL)
10242 *prog = regmatch.regprog;
10243 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010244 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010245 return result;
10246}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010247
10248#if defined(FEAT_WILDIGN) || defined(PROTO)
10249/*
10250 * Return TRUE if a file matches with a pattern in "list".
10251 * "list" is a comma-separated list of patterns, like 'wildignore'.
10252 * "sfname" is the short file name or NULL, "ffname" the long file name.
10253 */
10254 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010255match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010256{
10257 char_u buf[100];
10258 char_u *tail;
10259 char_u *regpat;
10260 char allow_dirs;
10261 int match;
10262 char_u *p;
10263
10264 tail = gettail(sfname);
10265
10266 /* try all patterns in 'wildignore' */
10267 p = list;
10268 while (*p)
10269 {
10270 copy_option_part(&p, buf, 100, ",");
10271 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10272 if (regpat == NULL)
10273 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010274 match = match_file_pat(regpat, NULL, ffname, sfname,
10275 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010276 vim_free(regpat);
10277 if (match)
10278 return TRUE;
10279 }
10280 return FALSE;
10281}
10282#endif
10283
10284/*
10285 * Convert the given pattern "pat" which has shell style wildcards in it, into
10286 * a regular expression, and return the result in allocated memory. If there
10287 * is a directory path separator to be matched, then TRUE is put in
10288 * allow_dirs, otherwise FALSE is put there -- webb.
10289 * Handle backslashes before special characters, like "\*" and "\ ".
10290 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010291 * Returns NULL when out of memory.
10292 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010293 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010294file_pat_to_reg_pat(
10295 char_u *pat,
10296 char_u *pat_end, /* first char after pattern or NULL */
10297 char *allow_dirs, /* Result passed back out in here */
10298 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010299{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010300 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010301 char_u *endp;
10302 char_u *reg_pat;
10303 char_u *p;
10304 int i;
10305 int nested = 0;
10306 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010307
10308 if (allow_dirs != NULL)
10309 *allow_dirs = FALSE;
10310 if (pat_end == NULL)
10311 pat_end = pat + STRLEN(pat);
10312
Bram Moolenaar071d4272004-06-13 20:20:40 +000010313 for (p = pat; p < pat_end; p++)
10314 {
10315 switch (*p)
10316 {
10317 case '*':
10318 case '.':
10319 case ',':
10320 case '{':
10321 case '}':
10322 case '~':
10323 size += 2; /* extra backslash */
10324 break;
10325#ifdef BACKSLASH_IN_FILENAME
10326 case '\\':
10327 case '/':
10328 size += 4; /* could become "[\/]" */
10329 break;
10330#endif
10331 default:
10332 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010333# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010334 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010335 {
10336 ++p;
10337 ++size;
10338 }
10339# endif
10340 break;
10341 }
10342 }
10343 reg_pat = alloc(size + 1);
10344 if (reg_pat == NULL)
10345 return NULL;
10346
Bram Moolenaar071d4272004-06-13 20:20:40 +000010347 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010348
10349 if (pat[0] == '*')
10350 while (pat[0] == '*' && pat < pat_end - 1)
10351 pat++;
10352 else
10353 reg_pat[i++] = '^';
10354 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010355 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010356 {
10357 while (endp - pat > 0 && *endp == '*')
10358 endp--;
10359 add_dollar = FALSE;
10360 }
10361 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10362 {
10363 switch (*p)
10364 {
10365 case '*':
10366 reg_pat[i++] = '.';
10367 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010368 while (p[1] == '*') /* "**" matches like "*" */
10369 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010370 break;
10371 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010372 case '~':
10373 reg_pat[i++] = '\\';
10374 reg_pat[i++] = *p;
10375 break;
10376 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010377 reg_pat[i++] = '.';
10378 break;
10379 case '\\':
10380 if (p[1] == NUL)
10381 break;
10382#ifdef BACKSLASH_IN_FILENAME
10383 if (!no_bslash)
10384 {
10385 /* translate:
10386 * "\x" to "\\x" e.g., "dir\file"
10387 * "\*" to "\\.*" e.g., "dir\*.c"
10388 * "\?" to "\\." e.g., "dir\??.c"
10389 * "\+" to "\+" e.g., "fileX\+.c"
10390 */
10391 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10392 && p[1] != '+')
10393 {
10394 reg_pat[i++] = '[';
10395 reg_pat[i++] = '\\';
10396 reg_pat[i++] = '/';
10397 reg_pat[i++] = ']';
10398 if (allow_dirs != NULL)
10399 *allow_dirs = TRUE;
10400 break;
10401 }
10402 }
10403#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010404 /* Undo escaping from ExpandEscape():
10405 * foo\?bar -> foo?bar
10406 * foo\%bar -> foo%bar
10407 * foo\,bar -> foo,bar
10408 * foo\ bar -> foo bar
10409 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010410 * regexp.
10411 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010412 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010413 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010414 if (*++p == '?'
10415#ifdef BACKSLASH_IN_FILENAME
10416 && no_bslash
10417#endif
10418 )
10419 reg_pat[i++] = '?';
10420 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010421 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010422 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010423 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010424 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10425 {
10426 reg_pat[i++] = '\\';
10427 reg_pat[i++] = '{';
10428 p += 2;
10429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010430 else
10431 {
10432 if (allow_dirs != NULL && vim_ispathsep(*p)
10433#ifdef BACKSLASH_IN_FILENAME
10434 && (!no_bslash || *p != '\\')
10435#endif
10436 )
10437 *allow_dirs = TRUE;
10438 reg_pat[i++] = '\\';
10439 reg_pat[i++] = *p;
10440 }
10441 break;
10442#ifdef BACKSLASH_IN_FILENAME
10443 case '/':
10444 reg_pat[i++] = '[';
10445 reg_pat[i++] = '\\';
10446 reg_pat[i++] = '/';
10447 reg_pat[i++] = ']';
10448 if (allow_dirs != NULL)
10449 *allow_dirs = TRUE;
10450 break;
10451#endif
10452 case '{':
10453 reg_pat[i++] = '\\';
10454 reg_pat[i++] = '(';
10455 nested++;
10456 break;
10457 case '}':
10458 reg_pat[i++] = '\\';
10459 reg_pat[i++] = ')';
10460 --nested;
10461 break;
10462 case ',':
10463 if (nested)
10464 {
10465 reg_pat[i++] = '\\';
10466 reg_pat[i++] = '|';
10467 }
10468 else
10469 reg_pat[i++] = ',';
10470 break;
10471 default:
10472# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010473 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010474 reg_pat[i++] = *p++;
10475 else
10476# endif
10477 if (allow_dirs != NULL && vim_ispathsep(*p))
10478 *allow_dirs = TRUE;
10479 reg_pat[i++] = *p;
10480 break;
10481 }
10482 }
10483 if (add_dollar)
10484 reg_pat[i++] = '$';
10485 reg_pat[i] = NUL;
10486 if (nested != 0)
10487 {
10488 if (nested < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +010010489 emsg(_("E219: Missing {."));
Bram Moolenaar071d4272004-06-13 20:20:40 +000010490 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +010010491 emsg(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010492 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010493 }
10494 return reg_pat;
10495}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010496
10497#if defined(EINTR) || defined(PROTO)
10498/*
10499 * Version of read() that retries when interrupted by EINTR (possibly
10500 * by a SIGWINCH).
10501 */
10502 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010503read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010504{
10505 long ret;
10506
10507 for (;;)
10508 {
10509 ret = vim_read(fd, buf, bufsize);
10510 if (ret >= 0 || errno != EINTR)
10511 break;
10512 }
10513 return ret;
10514}
10515
10516/*
10517 * Version of write() that retries when interrupted by EINTR (possibly
10518 * by a SIGWINCH).
10519 */
10520 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010521write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010522{
10523 long ret = 0;
10524 long wlen;
10525
10526 /* Repeat the write() so long it didn't fail, other than being interrupted
10527 * by a signal. */
10528 while (ret < (long)bufsize)
10529 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010530 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010531 if (wlen < 0)
10532 {
10533 if (errno != EINTR)
10534 break;
10535 }
10536 else
10537 ret += wlen;
10538 }
10539 return ret;
10540}
10541#endif