blob: 0608625a4f80b9dd859b309e699ad1636e6bf04e [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 {
1384 if (crypt_works_inplace(curbuf->b_cryptstate))
1385 {
1386 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1387 }
1388 else
1389 {
1390 char_u *newptr = NULL;
1391 int decrypted_size;
1392
1393 decrypted_size = crypt_decode_alloc(
1394 curbuf->b_cryptstate, ptr, size, &newptr);
1395
1396 /* If the crypt layer is buffering, not producing
1397 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001398 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001399 continue;
1400
1401 if (linerest == 0)
1402 {
1403 /* Simple case: reuse returned buffer (may be
1404 * NULL, checked later). */
1405 new_buffer = newptr;
1406 }
1407 else
1408 {
1409 long_u new_size;
1410
1411 /* Need new buffer to add bytes carried over. */
1412 new_size = (long_u)(decrypted_size + linerest + 1);
1413 new_buffer = lalloc(new_size, FALSE);
1414 if (new_buffer == NULL)
1415 {
1416 do_outofmem_msg(new_size);
1417 error = TRUE;
1418 break;
1419 }
1420
1421 mch_memmove(new_buffer, buffer, linerest);
1422 if (newptr != NULL)
1423 mch_memmove(new_buffer + linerest, newptr,
1424 decrypted_size);
1425 }
1426
1427 if (new_buffer != NULL)
1428 {
1429 vim_free(buffer);
1430 buffer = new_buffer;
1431 new_buffer = NULL;
1432 line_start = buffer;
1433 ptr = buffer + linerest;
1434 }
1435 size = decrypted_size;
1436 }
1437 }
1438#endif
1439
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440 if (size <= 0)
1441 {
1442 if (size < 0) /* read error */
1443 error = TRUE;
1444#ifdef FEAT_MBYTE
1445 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001446 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001447 /*
1448 * Reached end-of-file but some trailing bytes could
1449 * not be converted. Truncated file?
1450 */
1451
1452 /* When we did a conversion report an error. */
1453 if (fio_flags != 0
1454# ifdef USE_ICONV
1455 || iconv_fd != (iconv_t)-1
1456# endif
1457 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001458 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001459 if (can_retry)
1460 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001461 if (conv_error == 0)
1462 conv_error = curbuf->b_ml.ml_line_count
1463 - linecnt + 1;
1464 }
1465 /* Remember the first linenr with an illegal byte */
1466 else if (illegal_byte == 0)
1467 illegal_byte = curbuf->b_ml.ml_line_count
1468 - linecnt + 1;
1469 if (bad_char_behavior == BAD_DROP)
1470 {
1471 *(ptr - conv_restlen) = NUL;
1472 conv_restlen = 0;
1473 }
1474 else
1475 {
1476 /* Replace the trailing bytes with the replacement
1477 * character if we were converting; if we weren't,
1478 * leave the UTF8 checking code to do it, as it
1479 * works slightly differently. */
1480 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1481# ifdef USE_ICONV
1482 || iconv_fd != (iconv_t)-1
1483# endif
1484 ))
1485 {
1486 while (conv_restlen > 0)
1487 {
1488 *(--ptr) = bad_char_behavior;
1489 --conv_restlen;
1490 }
1491 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001492 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001493# ifdef USE_ICONV
1494 if (iconv_fd != (iconv_t)-1)
1495 {
1496 iconv_close(iconv_fd);
1497 iconv_fd = (iconv_t)-1;
1498 }
1499# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001500 }
1501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502#endif
1503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 }
1505 skip_read = FALSE;
1506
1507#ifdef FEAT_MBYTE
1508 /*
1509 * At start of file (or after crypt magic number): Check for BOM.
1510 * Also check for a BOM for other Unicode encodings, but not after
1511 * converting with 'charconvert' or when a BOM has already been
1512 * found.
1513 */
1514 if ((filesize == 0
1515# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001516 || (cryptkey != NULL
1517 && filesize == crypt_get_header_len(
1518 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519# endif
1520 )
1521 && (fio_flags == FIO_UCSBOM
1522 || (!curbuf->b_p_bomb
1523 && tmpname == NULL
1524 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1525 {
1526 char_u *ccname;
1527 int blen;
1528
1529 /* no BOM detection in a short file or in binary mode */
1530 if (size < 2 || curbuf->b_p_bin)
1531 ccname = NULL;
1532 else
1533 ccname = check_for_bom(ptr, size, &blen,
1534 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1535 if (ccname != NULL)
1536 {
1537 /* Remove BOM from the text */
1538 filesize += blen;
1539 size -= blen;
1540 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001541 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001542 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001544 curbuf->b_start_bomb = TRUE;
1545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 }
1547
1548 if (fio_flags == FIO_UCSBOM)
1549 {
1550 if (ccname == NULL)
1551 {
1552 /* No BOM detected: retry with next encoding. */
1553 advance_fenc = TRUE;
1554 }
1555 else
1556 {
1557 /* BOM detected: set "fenc" and jump back */
1558 if (fenc_alloced)
1559 vim_free(fenc);
1560 fenc = ccname;
1561 fenc_alloced = FALSE;
1562 }
1563 /* retry reading without getting new bytes or rewinding */
1564 skip_read = TRUE;
1565 goto retry;
1566 }
1567 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001568
1569 /* Include not converted bytes. */
1570 ptr -= conv_restlen;
1571 size += conv_restlen;
1572 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573#endif
1574 /*
1575 * Break here for a read error or end-of-file.
1576 */
1577 if (size <= 0)
1578 break;
1579
1580#ifdef FEAT_MBYTE
1581
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582# ifdef USE_ICONV
1583 if (iconv_fd != (iconv_t)-1)
1584 {
1585 /*
1586 * Attempt conversion of the read bytes to 'encoding' using
1587 * iconv().
1588 */
1589 const char *fromp;
1590 char *top;
1591 size_t from_size;
1592 size_t to_size;
1593
1594 fromp = (char *)ptr;
1595 from_size = size;
1596 ptr += size;
1597 top = (char *)ptr;
1598 to_size = real_size - size;
1599
1600 /*
1601 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001602 * another conversion. Except for when there is no
1603 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001605 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1606 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1608 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001609 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001611 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 if (conv_error == 0)
1613 conv_error = readfile_linenr(linecnt,
1614 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001615
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001616 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001617 ++fromp;
1618 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001619 if (bad_char_behavior == BAD_KEEP)
1620 {
1621 *top++ = *(fromp - 1);
1622 --to_size;
1623 }
1624 else if (bad_char_behavior != BAD_DROP)
1625 {
1626 *top++ = bad_char_behavior;
1627 --to_size;
1628 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
1631 if (from_size > 0)
1632 {
1633 /* Some remaining characters, keep them for the next
1634 * round. */
1635 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1636 conv_restlen = (int)from_size;
1637 }
1638
1639 /* move the linerest to before the converted characters */
1640 line_start = ptr - linerest;
1641 mch_memmove(line_start, buffer, (size_t)linerest);
1642 size = (long)((char_u *)top - ptr);
1643 }
1644# endif
1645
1646# ifdef WIN3264
1647 if (fio_flags & FIO_CODEPAGE)
1648 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001649 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001650 WCHAR ucs2buf[3];
1651 int ucs2len;
1652 int codepage = FIO_GET_CP(fio_flags);
1653 int bytelen;
1654 int found_bad;
1655 char replstr[2];
1656
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 /*
1658 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001659 * a codepage, using standard MS-Windows functions. This
1660 * requires two steps:
1661 * 1. convert from 'fileencoding' to ucs-2
1662 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001664 * Because there may be illegal bytes AND an incomplete byte
1665 * sequence at the end, we may have to do the conversion one
1666 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001669 /* Replacement string for WideCharToMultiByte(). */
1670 if (bad_char_behavior > 0)
1671 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001673 replstr[0] = '?';
1674 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675
1676 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 * Move the bytes to the end of the buffer, so that we have
1678 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001680 src = ptr + real_size - size;
1681 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001683 /*
1684 * Do the conversion.
1685 */
1686 dst = ptr;
1687 size = size;
1688 while (size > 0)
1689 {
1690 found_bad = FALSE;
1691
1692# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1693 if (codepage == CP_UTF8)
1694 {
1695 /* Handle CP_UTF8 input ourselves to be able to handle
1696 * trailing bytes properly.
1697 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001698 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001699 if (bytelen > size)
1700 {
1701 /* Only got some bytes of a character. Normally
1702 * it's put in "conv_rest", but if it's too long
1703 * deal with it as if they were illegal bytes. */
1704 if (bytelen <= CONV_RESTLEN)
1705 break;
1706
1707 /* weird overlong byte sequence */
1708 bytelen = size;
1709 found_bad = TRUE;
1710 }
1711 else
1712 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001713 int u8c = utf_ptr2char(src);
1714
Bram Moolenaar86e01082005-12-29 22:45:34 +00001715 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 found_bad = TRUE;
1717 ucs2buf[0] = u8c;
1718 ucs2len = 1;
1719 }
1720 }
1721 else
1722# endif
1723 {
1724 /* We don't know how long the byte sequence is, try
1725 * from one to three bytes. */
1726 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1727 ++bytelen)
1728 {
1729 ucs2len = MultiByteToWideChar(codepage,
1730 MB_ERR_INVALID_CHARS,
1731 (LPCSTR)src, bytelen,
1732 ucs2buf, 3);
1733 if (ucs2len > 0)
1734 break;
1735 }
1736 if (ucs2len == 0)
1737 {
1738 /* If we have only one byte then it's probably an
1739 * incomplete byte sequence. Otherwise discard
1740 * one byte as a bad character. */
1741 if (size == 1)
1742 break;
1743 found_bad = TRUE;
1744 bytelen = 1;
1745 }
1746 }
1747
1748 if (!found_bad)
1749 {
1750 int i;
1751
1752 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1753 if (enc_utf8)
1754 {
1755 /* From UCS-2 to UTF-8. Cannot fail. */
1756 for (i = 0; i < ucs2len; ++i)
1757 dst += utf_char2bytes(ucs2buf[i], dst);
1758 }
1759 else
1760 {
1761 BOOL bad = FALSE;
1762 int dstlen;
1763
1764 /* From UCS-2 to "enc_codepage". If the
1765 * conversion uses the default character "?",
1766 * the data doesn't fit in this encoding. */
1767 dstlen = WideCharToMultiByte(enc_codepage, 0,
1768 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001769 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001770 replstr, &bad);
1771 if (bad)
1772 found_bad = TRUE;
1773 else
1774 dst += dstlen;
1775 }
1776 }
1777
1778 if (found_bad)
1779 {
1780 /* Deal with bytes we can't convert. */
1781 if (can_retry)
1782 goto rewind_retry;
1783 if (conv_error == 0)
1784 conv_error = readfile_linenr(linecnt, ptr, dst);
1785 if (bad_char_behavior != BAD_DROP)
1786 {
1787 if (bad_char_behavior == BAD_KEEP)
1788 {
1789 mch_memmove(dst, src, bytelen);
1790 dst += bytelen;
1791 }
1792 else
1793 *dst++ = bad_char_behavior;
1794 }
1795 }
1796
1797 src += bytelen;
1798 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001800
1801 if (size > 0)
1802 {
1803 /* An incomplete byte sequence remaining. */
1804 mch_memmove(conv_rest, src, size);
1805 conv_restlen = size;
1806 }
1807
1808 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001809 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 }
1811 else
1812# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001813# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 if (fio_flags & FIO_MACROMAN)
1815 {
1816 /*
1817 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001818 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001820 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 }
1823 else
1824# endif
1825 if (fio_flags != 0)
1826 {
1827 int u8c;
1828 char_u *dest;
1829 char_u *tail = NULL;
1830
1831 /*
1832 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1833 * "enc_utf8" not set: Convert Unicode to Latin1.
1834 * Go from end to start through the buffer, because the number
1835 * of bytes may increase.
1836 * "dest" points to after where the UTF-8 bytes go, "p" points
1837 * to after the next character to convert.
1838 */
1839 dest = ptr + real_size;
1840 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1841 {
1842 p = ptr + size;
1843 if (fio_flags == FIO_UTF8)
1844 {
1845 /* Check for a trailing incomplete UTF-8 sequence */
1846 tail = ptr + size - 1;
1847 while (tail > ptr && (*tail & 0xc0) == 0x80)
1848 --tail;
1849 if (tail + utf_byte2len(*tail) <= ptr + size)
1850 tail = NULL;
1851 else
1852 p = tail;
1853 }
1854 }
1855 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1856 {
1857 /* Check for a trailing byte */
1858 p = ptr + (size & ~1);
1859 if (size & 1)
1860 tail = p;
1861 if ((fio_flags & FIO_UTF16) && p > ptr)
1862 {
1863 /* Check for a trailing leading word */
1864 if (fio_flags & FIO_ENDIAN_L)
1865 {
1866 u8c = (*--p << 8);
1867 u8c += *--p;
1868 }
1869 else
1870 {
1871 u8c = *--p;
1872 u8c += (*--p << 8);
1873 }
1874 if (u8c >= 0xd800 && u8c <= 0xdbff)
1875 tail = p;
1876 else
1877 p += 2;
1878 }
1879 }
1880 else /* FIO_UCS4 */
1881 {
1882 /* Check for trailing 1, 2 or 3 bytes */
1883 p = ptr + (size & ~3);
1884 if (size & 3)
1885 tail = p;
1886 }
1887
1888 /* If there is a trailing incomplete sequence move it to
1889 * conv_rest[]. */
1890 if (tail != NULL)
1891 {
1892 conv_restlen = (int)((ptr + size) - tail);
1893 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1894 size -= conv_restlen;
1895 }
1896
1897
1898 while (p > ptr)
1899 {
1900 if (fio_flags & FIO_LATIN1)
1901 u8c = *--p;
1902 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1903 {
1904 if (fio_flags & FIO_ENDIAN_L)
1905 {
1906 u8c = (*--p << 8);
1907 u8c += *--p;
1908 }
1909 else
1910 {
1911 u8c = *--p;
1912 u8c += (*--p << 8);
1913 }
1914 if ((fio_flags & FIO_UTF16)
1915 && u8c >= 0xdc00 && u8c <= 0xdfff)
1916 {
1917 int u16c;
1918
1919 if (p == ptr)
1920 {
1921 /* Missing leading word. */
1922 if (can_retry)
1923 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001924 if (conv_error == 0)
1925 conv_error = readfile_linenr(linecnt,
1926 ptr, p);
1927 if (bad_char_behavior == BAD_DROP)
1928 continue;
1929 if (bad_char_behavior != BAD_KEEP)
1930 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 }
1932
1933 /* found second word of double-word, get the first
1934 * word and compute the resulting character */
1935 if (fio_flags & FIO_ENDIAN_L)
1936 {
1937 u16c = (*--p << 8);
1938 u16c += *--p;
1939 }
1940 else
1941 {
1942 u16c = *--p;
1943 u16c += (*--p << 8);
1944 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001945 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1946 + (u8c & 0x3ff);
1947
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 /* Check if the word is indeed a leading word. */
1949 if (u16c < 0xd800 || u16c > 0xdbff)
1950 {
1951 if (can_retry)
1952 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001953 if (conv_error == 0)
1954 conv_error = readfile_linenr(linecnt,
1955 ptr, p);
1956 if (bad_char_behavior == BAD_DROP)
1957 continue;
1958 if (bad_char_behavior != BAD_KEEP)
1959 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961 }
1962 }
1963 else if (fio_flags & FIO_UCS4)
1964 {
1965 if (fio_flags & FIO_ENDIAN_L)
1966 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001967 u8c = (unsigned)*--p << 24;
1968 u8c += (unsigned)*--p << 16;
1969 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 u8c += *--p;
1971 }
1972 else /* big endian */
1973 {
1974 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001975 u8c += (unsigned)*--p << 8;
1976 u8c += (unsigned)*--p << 16;
1977 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 }
1979 }
1980 else /* UTF-8 */
1981 {
1982 if (*--p < 0x80)
1983 u8c = *p;
1984 else
1985 {
1986 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001987 p -= len;
1988 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 if (len == 0)
1990 {
1991 /* Not a valid UTF-8 character, retry with
1992 * another fenc when possible, otherwise just
1993 * report the error. */
1994 if (can_retry)
1995 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001996 if (conv_error == 0)
1997 conv_error = readfile_linenr(linecnt,
1998 ptr, p);
1999 if (bad_char_behavior == BAD_DROP)
2000 continue;
2001 if (bad_char_behavior != BAD_KEEP)
2002 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002004 }
2005 }
2006 if (enc_utf8) /* produce UTF-8 */
2007 {
2008 dest -= utf_char2len(u8c);
2009 (void)utf_char2bytes(u8c, dest);
2010 }
2011 else /* produce Latin1 */
2012 {
2013 --dest;
2014 if (u8c >= 0x100)
2015 {
2016 /* character doesn't fit in latin1, retry with
2017 * another fenc when possible, otherwise just
2018 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002019 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002021 if (conv_error == 0)
2022 conv_error = readfile_linenr(linecnt, ptr, p);
2023 if (bad_char_behavior == BAD_DROP)
2024 ++dest;
2025 else if (bad_char_behavior == BAD_KEEP)
2026 *dest = u8c;
2027 else if (eap != NULL && eap->bad_char != 0)
2028 *dest = bad_char_behavior;
2029 else
2030 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 }
2032 else
2033 *dest = u8c;
2034 }
2035 }
2036
2037 /* move the linerest to before the converted characters */
2038 line_start = dest - linerest;
2039 mch_memmove(line_start, buffer, (size_t)linerest);
2040 size = (long)((ptr + real_size) - dest);
2041 ptr = dest;
2042 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002043 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002045 int incomplete_tail = FALSE;
2046
2047 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2048 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002050 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002051 int l;
2052
2053 if (todo <= 0)
2054 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 if (*p >= 0x80)
2056 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 /* A length of 1 means it's an illegal byte. Accept
2058 * an incomplete character at the end though, the next
2059 * read() will get the next bytes, we'll check it
2060 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002061 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002062 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002064 /* Avoid retrying with a different encoding when
2065 * a truncated file is more likely, or attempting
2066 * to read the rest of an incomplete sequence when
2067 * we have already done so. */
2068 if (p > ptr || filesize > 0)
2069 incomplete_tail = TRUE;
2070 /* Incomplete byte sequence, move it to conv_rest[]
2071 * and try to read the rest of it, unless we've
2072 * already done so. */
2073 if (p > ptr)
2074 {
2075 conv_restlen = todo;
2076 mch_memmove(conv_rest, p, conv_restlen);
2077 size -= conv_restlen;
2078 break;
2079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002081 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002082 {
2083 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002084 * do that, unless at EOF where a truncated
2085 * file is more likely than a conversion error. */
2086 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002087 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002088# ifdef USE_ICONV
2089 /* When we did a conversion report an error. */
2090 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2091 conv_error = readfile_linenr(linecnt, ptr, p);
2092# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002093 /* Remember the first linenr with an illegal byte */
2094 if (conv_error == 0 && illegal_byte == 0)
2095 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002096
2097 /* Drop, keep or replace the bad byte. */
2098 if (bad_char_behavior == BAD_DROP)
2099 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002100 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002101 --p;
2102 --size;
2103 }
2104 else if (bad_char_behavior != BAD_KEEP)
2105 *p = bad_char_behavior;
2106 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002107 else
2108 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 }
2110 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002111 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 {
2113 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002115 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002117 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2118 /* iconv() failed, try 'charconvert' */
2119 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 else
2121# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002122 /* use next item from 'fileencodings' */
2123 advance_fenc = TRUE;
2124 file_rewind = TRUE;
2125 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 }
2127 }
2128#endif
2129
2130 /* count the number of characters (after conversion!) */
2131 filesize += size;
2132
2133 /*
2134 * when reading the first part of a file: guess EOL type
2135 */
2136 if (fileformat == EOL_UNKNOWN)
2137 {
2138 /* First try finding a NL, for Dos and Unix */
2139 if (try_dos || try_unix)
2140 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002141 /* Reset the carriage return counter. */
2142 if (try_mac)
2143 try_mac = 1;
2144
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 for (p = ptr; p < ptr + size; ++p)
2146 {
2147 if (*p == NL)
2148 {
2149 if (!try_unix
2150 || (try_dos && p > ptr && p[-1] == CAR))
2151 fileformat = EOL_DOS;
2152 else
2153 fileformat = EOL_UNIX;
2154 break;
2155 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002156 else if (*p == CAR && try_mac)
2157 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 }
2159
2160 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2161 if (fileformat == EOL_UNIX && try_mac)
2162 {
2163 /* Need to reset the counters when retrying fenc. */
2164 try_mac = 1;
2165 try_unix = 1;
2166 for (; p >= ptr && *p != CAR; p--)
2167 ;
2168 if (p >= ptr)
2169 {
2170 for (p = ptr; p < ptr + size; ++p)
2171 {
2172 if (*p == NL)
2173 try_unix++;
2174 else if (*p == CAR)
2175 try_mac++;
2176 }
2177 if (try_mac > try_unix)
2178 fileformat = EOL_MAC;
2179 }
2180 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002181 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2182 /* Looking for CR but found no end-of-line markers at
2183 * all: use the default format. */
2184 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 }
2186
2187 /* No NL found: may use Mac format */
2188 if (fileformat == EOL_UNKNOWN && try_mac)
2189 fileformat = EOL_MAC;
2190
2191 /* Still nothing found? Use first format in 'ffs' */
2192 if (fileformat == EOL_UNKNOWN)
2193 fileformat = default_fileformat();
2194
2195 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002196 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 set_fileformat(fileformat, OPT_LOCAL);
2198 }
2199 }
2200
2201 /*
2202 * This loop is executed once for every character read.
2203 * Keep it fast!
2204 */
2205 if (fileformat == EOL_MAC)
2206 {
2207 --ptr;
2208 while (++ptr, --size >= 0)
2209 {
2210 /* catch most common case first */
2211 if ((c = *ptr) != NUL && c != CAR && c != NL)
2212 continue;
2213 if (c == NUL)
2214 *ptr = NL; /* NULs are replaced by newlines! */
2215 else if (c == NL)
2216 *ptr = CAR; /* NLs are replaced by CRs! */
2217 else
2218 {
2219 if (skip_count == 0)
2220 {
2221 *ptr = NUL; /* end of line */
2222 len = (colnr_T) (ptr - line_start + 1);
2223 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2224 {
2225 error = TRUE;
2226 break;
2227 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002228#ifdef FEAT_PERSISTENT_UNDO
2229 if (read_undo_file)
2230 sha256_update(&sha_ctx, line_start, len);
2231#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 ++lnum;
2233 if (--read_count == 0)
2234 {
2235 error = TRUE; /* break loop */
2236 line_start = ptr; /* nothing left to write */
2237 break;
2238 }
2239 }
2240 else
2241 --skip_count;
2242 line_start = ptr + 1;
2243 }
2244 }
2245 }
2246 else
2247 {
2248 --ptr;
2249 while (++ptr, --size >= 0)
2250 {
2251 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2252 continue;
2253 if (c == NUL)
2254 *ptr = NL; /* NULs are replaced by newlines! */
2255 else
2256 {
2257 if (skip_count == 0)
2258 {
2259 *ptr = NUL; /* end of line */
2260 len = (colnr_T)(ptr - line_start + 1);
2261 if (fileformat == EOL_DOS)
2262 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002263 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002265 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 ptr[-1] = NUL;
2267 --len;
2268 }
2269 /*
2270 * Reading in Dos format, but no CR-LF found!
2271 * When 'fileformats' includes "unix", delete all
2272 * the lines read so far and start all over again.
2273 * Otherwise give an error message later.
2274 */
2275 else if (ff_error != EOL_DOS)
2276 {
2277 if ( try_unix
2278 && !read_stdin
2279 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002280 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2281 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 {
2283 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002284 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 set_fileformat(EOL_UNIX, OPT_LOCAL);
2286 file_rewind = TRUE;
2287 keep_fileformat = TRUE;
2288 goto retry;
2289 }
2290 ff_error = EOL_DOS;
2291 }
2292 }
2293 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2294 {
2295 error = TRUE;
2296 break;
2297 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002298#ifdef FEAT_PERSISTENT_UNDO
2299 if (read_undo_file)
2300 sha256_update(&sha_ctx, line_start, len);
2301#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 ++lnum;
2303 if (--read_count == 0)
2304 {
2305 error = TRUE; /* break loop */
2306 line_start = ptr; /* nothing left to write */
2307 break;
2308 }
2309 }
2310 else
2311 --skip_count;
2312 line_start = ptr + 1;
2313 }
2314 }
2315 }
2316 linerest = (long)(ptr - line_start);
2317 ui_breakcheck();
2318 }
2319
2320failed:
2321 /* not an error, max. number of lines reached */
2322 if (error && read_count == 0)
2323 error = FALSE;
2324
2325 /*
2326 * If we get EOF in the middle of a line, note the fact and
2327 * complete the line ourselves.
2328 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2329 */
2330 if (!error
2331 && !got_int
2332 && linerest != 0
2333 && !(!curbuf->b_p_bin
2334 && fileformat == EOL_DOS
2335 && *line_start == Ctrl_Z
2336 && ptr == line_start + 1))
2337 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002338 /* remember for when writing */
2339 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 curbuf->b_p_eol = FALSE;
2341 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002342 len = (colnr_T)(ptr - line_start + 1);
2343 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 error = TRUE;
2345 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002346 {
2347#ifdef FEAT_PERSISTENT_UNDO
2348 if (read_undo_file)
2349 sha256_update(&sha_ctx, line_start, len);
2350#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 }
2354
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002355 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 save_file_ff(curbuf); /* remember the current file format */
2357
2358#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002359 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002360 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002361 crypt_free_state(curbuf->b_cryptstate);
2362 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002363 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002364 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2365 crypt_free_key(cryptkey);
2366 /* Don't set cryptkey to NULL, it's used below as a flag that
2367 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368#endif
2369
2370#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002371 /* If editing a new file: set 'fenc' for the current buffer.
2372 * Also for ":read ++edit file". */
2373 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002375 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 if (fenc_alloced)
2377 vim_free(fenc);
2378# ifdef USE_ICONV
2379 if (iconv_fd != (iconv_t)-1)
2380 {
2381 iconv_close(iconv_fd);
2382 iconv_fd = (iconv_t)-1;
2383 }
2384# endif
2385#endif
2386
2387 if (!read_buffer && !read_stdin)
2388 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002389#ifdef HAVE_FD_CLOEXEC
2390 else
2391 {
2392 int fdflags = fcntl(fd, F_GETFD);
2393 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002394 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002395 }
2396#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 vim_free(buffer);
2398
2399#ifdef HAVE_DUP
2400 if (read_stdin)
2401 {
2402 /* Use stderr for stdin, makes shell commands work. */
2403 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002404 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 }
2406#endif
2407
2408#ifdef FEAT_MBYTE
2409 if (tmpname != NULL)
2410 {
2411 mch_remove(tmpname); /* delete converted file */
2412 vim_free(tmpname);
2413 }
2414#endif
2415 --no_wait_return; /* may wait for return now */
2416
2417 /*
2418 * In recovery mode everything but autocommands is skipped.
2419 */
2420 if (!recoverymode)
2421 {
2422 /* need to delete the last line, which comes from the empty buffer */
2423 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2424 {
2425#ifdef FEAT_NETBEANS_INTG
2426 netbeansFireChanges = 0;
2427#endif
2428 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2429#ifdef FEAT_NETBEANS_INTG
2430 netbeansFireChanges = 1;
2431#endif
2432 --linecnt;
2433 }
2434 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2435 if (filesize == 0)
2436 linecnt = 0;
2437 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002438 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002440#ifdef FEAT_DIFF
2441 /* After reading the text into the buffer the diff info needs to
2442 * be updated. */
2443 diff_invalidate(curbuf);
2444#endif
2445#ifdef FEAT_FOLDING
2446 /* All folds in the window are invalid now. Mark them for update
2447 * before triggering autocommands. */
2448 foldUpdateAll(curwin);
2449#endif
2450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 else if (linecnt) /* appended at least one line */
2452 appended_lines_mark(from, linecnt);
2453
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454#ifndef ALWAYS_USE_GUI
2455 /*
2456 * If we were reading from the same terminal as where messages go,
2457 * the screen will have been messed up.
2458 * Switch on raw mode now and clear the screen.
2459 */
2460 if (read_stdin)
2461 {
2462 settmode(TMODE_RAW); /* set to raw mode */
2463 starttermcap();
2464 screenclear();
2465 }
2466#endif
2467
2468 if (got_int)
2469 {
2470 if (!(flags & READ_DUMMY))
2471 {
2472 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2473 if (newfile)
2474 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2475 }
2476 msg_scroll = msg_save;
2477#ifdef FEAT_VIMINFO
2478 check_marks_read();
2479#endif
2480 return OK; /* an interrupt isn't really an error */
2481 }
2482
2483 if (!filtering && !(flags & READ_DUMMY))
2484 {
2485 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2486 c = FALSE;
2487
2488#ifdef UNIX
Bram Moolenaard569bb02018-08-11 13:57:20 +02002489 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 {
2491 STRCAT(IObuff, _("[fifo]"));
2492 c = TRUE;
2493 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002494 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 {
2496 STRCAT(IObuff, _("[socket]"));
2497 c = TRUE;
2498 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002499# ifdef OPEN_CHR_FILES
2500 if (S_ISCHR(perm)) /* or character special */
2501 {
2502 STRCAT(IObuff, _("[character special]"));
2503 c = TRUE;
2504 }
2505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506#endif
2507 if (curbuf->b_p_ro)
2508 {
2509 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2510 c = TRUE;
2511 }
2512 if (read_no_eol_lnum)
2513 {
2514 msg_add_eol();
2515 c = TRUE;
2516 }
2517 if (ff_error == EOL_DOS)
2518 {
2519 STRCAT(IObuff, _("[CR missing]"));
2520 c = TRUE;
2521 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (split)
2523 {
2524 STRCAT(IObuff, _("[long lines split]"));
2525 c = TRUE;
2526 }
2527#ifdef FEAT_MBYTE
2528 if (notconverted)
2529 {
2530 STRCAT(IObuff, _("[NOT converted]"));
2531 c = TRUE;
2532 }
2533 else if (converted)
2534 {
2535 STRCAT(IObuff, _("[converted]"));
2536 c = TRUE;
2537 }
2538#endif
2539#ifdef FEAT_CRYPT
2540 if (cryptkey != NULL)
2541 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002542 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 c = TRUE;
2544 }
2545#endif
2546#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002547 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002549 sprintf((char *)IObuff + STRLEN(IObuff),
2550 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 c = TRUE;
2552 }
2553 else if (illegal_byte > 0)
2554 {
2555 sprintf((char *)IObuff + STRLEN(IObuff),
2556 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2557 c = TRUE;
2558 }
2559 else
2560#endif
2561 if (error)
2562 {
2563 STRCAT(IObuff, _("[READ ERRORS]"));
2564 c = TRUE;
2565 }
2566 if (msg_add_fileformat(fileformat))
2567 c = TRUE;
2568#ifdef FEAT_CRYPT
2569 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002570 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002571 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 else
2573#endif
2574 msg_add_lines(c, (long)linecnt, filesize);
2575
Bram Moolenaard23a8232018-02-10 18:45:26 +01002576 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 msg_scrolled_ign = TRUE;
2578#ifdef ALWAYS_USE_GUI
2579 /* Don't show the message when reading stdin, it would end up in a
2580 * message box (which might be shown when exiting!) */
2581 if (read_stdin || read_buffer)
2582 p = msg_may_trunc(FALSE, IObuff);
2583 else
2584#endif
2585 p = msg_trunc_attr(IObuff, FALSE, 0);
2586 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002587 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 /* Need to repeat the message after redrawing when:
2589 * - When reading from stdin (the screen will be cleared next).
2590 * - When restart_edit is set (otherwise there will be a delay
2591 * before redrawing).
2592 * - When the screen was scrolled but there is no wait-return
2593 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002594 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 msg_scrolled_ign = FALSE;
2596 }
2597
2598 /* with errors writing the file requires ":w!" */
2599 if (newfile && (error
2600#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002601 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002602 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603#endif
2604 ))
2605 curbuf->b_p_ro = TRUE;
2606
2607 u_clearline(); /* cannot use "U" command after adding lines */
2608
2609 /*
2610 * In Ex mode: cursor at last new line.
2611 * Otherwise: cursor at first new line.
2612 */
2613 if (exmode_active)
2614 curwin->w_cursor.lnum = from + linecnt;
2615 else
2616 curwin->w_cursor.lnum = from + 1;
2617 check_cursor_lnum();
2618 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2619
2620 /*
2621 * Set '[ and '] marks to the newly read lines.
2622 */
2623 curbuf->b_op_start.lnum = from + 1;
2624 curbuf->b_op_start.col = 0;
2625 curbuf->b_op_end.lnum = from + linecnt;
2626 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002627
2628#ifdef WIN32
2629 /*
2630 * Work around a weird problem: When a file has two links (only
2631 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002632 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002633 * It's correct again after reading the file, thus reset the timestamp
2634 * here.
2635 */
2636 if (newfile && !read_stdin && !read_buffer
2637 && mch_stat((char *)fname, &st) >= 0)
2638 {
2639 buf_store_time(curbuf, &st, fname);
2640 curbuf->b_mtime_read = curbuf->b_mtime;
2641 }
2642#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 }
2644 msg_scroll = msg_save;
2645
2646#ifdef FEAT_VIMINFO
2647 /*
2648 * Get the marks before executing autocommands, so they can be used there.
2649 */
2650 check_marks_read();
2651#endif
2652
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002654 * We remember if the last line of the read didn't have
2655 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2656 * or writing the read again with 'binary' on. The latter is required
2657 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002659 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002661 /* When reloading a buffer put the cursor at the first line that is
2662 * different. */
2663 if (flags & READ_KEEP_UNDO)
2664 u_find_first_changed();
2665
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002666#ifdef FEAT_PERSISTENT_UNDO
2667 /*
2668 * When opening a new file locate undo info and read it.
2669 */
2670 if (read_undo_file)
2671 {
2672 char_u hash[UNDO_HASH_SIZE];
2673
2674 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002675 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002676 }
2677#endif
2678
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002679 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 {
2681 int m = msg_scroll;
2682 int n = msg_scrolled;
2683
2684 /* Save the fileformat now, otherwise the buffer will be considered
2685 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002686 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 save_file_ff(curbuf);
2688
2689 /*
2690 * The output from the autocommands should not overwrite anything and
2691 * should not be overwritten: Set msg_scroll, restore its value if no
2692 * output was done.
2693 */
2694 msg_scroll = TRUE;
2695 if (filtering)
2696 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2697 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002698 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002699 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2701 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002702 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2703 /*
2704 * EVENT_FILETYPE was not triggered but the buffer already has a
2705 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2706 */
2707 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2708 TRUE, curbuf);
2709 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 else
2711 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2712 FALSE, NULL, eap);
2713 if (msg_scrolled == n)
2714 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002715# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 if (aborting()) /* autocmds may abort script processing */
2717 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720
2721 if (recoverymode && error)
2722 return FAIL;
2723 return OK;
2724}
2725
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002726#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002727/*
2728 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2729 * which is the name of files used for process substitution output by
2730 * some shells on some operating systems, e.g., bash on SunOS.
2731 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2732 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002733 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002734is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002735{
2736 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2737 && VIM_ISDIGIT(fname[8])
2738 && *skipdigits(fname + 9) == NUL
2739 && (fname[9] != NUL
2740 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2741}
2742#endif
2743
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002744#ifdef FEAT_MBYTE
2745
2746/*
2747 * From the current line count and characters read after that, estimate the
2748 * line number where we are now.
2749 * Used for error messages that include a line number.
2750 */
2751 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002752readfile_linenr(
2753 linenr_T linecnt, /* line count before reading more bytes */
2754 char_u *p, /* start of more bytes read */
2755 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002756{
2757 char_u *s;
2758 linenr_T lnum;
2759
2760 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2761 for (s = p; s < endp; ++s)
2762 if (*s == '\n')
2763 ++lnum;
2764 return lnum;
2765}
2766#endif
2767
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002769 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2770 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 * Returns OK or FAIL.
2772 */
2773 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002774prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002776 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002778 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002780 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 if (eap->cmd == NULL)
2782 return FAIL;
2783
2784#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002785 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2786 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002787 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002789 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002791 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002792
2793 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002794 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002795 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 return OK;
2797}
2798
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002799/*
2800 * Set default or forced 'fileformat' and 'binary'.
2801 */
2802 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002803set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002804{
2805 /* set default 'fileformat' */
2806 if (set_options)
2807 {
2808 if (eap != NULL && eap->force_ff != 0)
2809 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2810 else if (*p_ffs != NUL)
2811 set_fileformat(default_fileformat(), OPT_LOCAL);
2812 }
2813
2814 /* set or reset 'binary' */
2815 if (eap != NULL && eap->force_bin != 0)
2816 {
2817 int oldval = curbuf->b_p_bin;
2818
2819 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2820 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2821 }
2822}
2823
2824#if defined(FEAT_MBYTE) || defined(PROTO)
2825/*
2826 * Set forced 'fileencoding'.
2827 */
2828 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002829set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002830{
2831 if (eap->force_enc != 0)
2832 {
2833 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2834
2835 if (fenc != NULL)
2836 set_string_option_direct((char_u *)"fenc", -1,
2837 fenc, OPT_FREE|OPT_LOCAL, 0);
2838 vim_free(fenc);
2839 }
2840}
2841
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842/*
2843 * Find next fileencoding to use from 'fileencodings'.
2844 * "pp" points to fenc_next. It's advanced to the next item.
2845 * When there are no more items, an empty string is returned and *pp is set to
2846 * NULL.
2847 * When *pp is not set to NULL, the result is in allocated memory.
2848 */
2849 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002850next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851{
2852 char_u *p;
2853 char_u *r;
2854
2855 if (**pp == NUL)
2856 {
2857 *pp = NULL;
2858 return (char_u *)"";
2859 }
2860 p = vim_strchr(*pp, ',');
2861 if (p == NULL)
2862 {
2863 r = enc_canonize(*pp);
2864 *pp += STRLEN(*pp);
2865 }
2866 else
2867 {
2868 r = vim_strnsave(*pp, (int)(p - *pp));
2869 *pp = p + 1;
2870 if (r != NULL)
2871 {
2872 p = enc_canonize(r);
2873 vim_free(r);
2874 r = p;
2875 }
2876 }
2877 if (r == NULL) /* out of memory */
2878 {
2879 r = (char_u *)"";
2880 *pp = NULL;
2881 }
2882 return r;
2883}
2884
2885# ifdef FEAT_EVAL
2886/*
2887 * Convert a file with the 'charconvert' expression.
2888 * This closes the file which is to be read, converts it and opens the
2889 * resulting file for reading.
2890 * Returns name of the resulting converted file (the caller should delete it
2891 * after reading it).
2892 * Returns NULL if the conversion failed ("*fdp" is not set) .
2893 */
2894 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002895readfile_charconvert(
2896 char_u *fname, /* name of input file */
2897 char_u *fenc, /* converted from */
2898 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899{
2900 char_u *tmpname;
2901 char_u *errmsg = NULL;
2902
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002903 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 if (tmpname == NULL)
2905 errmsg = (char_u *)_("Can't find temp file for conversion");
2906 else
2907 {
2908 close(*fdp); /* close the input file, ignore errors */
2909 *fdp = -1;
2910 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2911 fname, tmpname) == FAIL)
2912 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2913 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2914 O_RDONLY | O_EXTRA, 0)) < 0)
2915 errmsg = (char_u *)_("can't read output of 'charconvert'");
2916 }
2917
2918 if (errmsg != NULL)
2919 {
2920 /* Don't use emsg(), it breaks mappings, the retry with
2921 * another type of conversion might still work. */
2922 MSG(errmsg);
2923 if (tmpname != NULL)
2924 {
2925 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002926 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 }
2928 }
2929
2930 /* If the input file is closed, open it (caller should check for error). */
2931 if (*fdp < 0)
2932 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2933
2934 return tmpname;
2935}
2936# endif
2937
2938#endif
2939
2940#ifdef FEAT_VIMINFO
2941/*
2942 * Read marks for the current buffer from the viminfo file, when we support
2943 * buffer marks and the buffer has a name.
2944 */
2945 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002946check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947{
2948 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2949 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002950 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951
2952 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2953 * the ' parameter after opening a buffer. */
2954 curbuf->b_marks_read = TRUE;
2955}
2956#endif
2957
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002958#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002960 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2962 * *filesizep are updated.
2963 * Return the (new) encryption key, NULL for no encryption.
2964 */
2965 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002966check_for_cryptkey(
2967 char_u *cryptkey, /* previous encryption key or NULL */
2968 char_u *ptr, /* pointer to read bytes */
2969 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002970 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002971 int newfile, /* editing a new buffer */
2972 char_u *fname, /* file name to display */
2973 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002975 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002976 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002977
2978 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002980 /* Mark the buffer as read-only until the decryption has taken place.
2981 * Avoids accidentally overwriting the file with garbage. */
2982 curbuf->b_p_ro = TRUE;
2983
Bram Moolenaar2be79502014-08-13 21:58:28 +02002984 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002985 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002986 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 {
2988 if (*curbuf->b_p_key)
2989 cryptkey = curbuf->b_p_key;
2990 else
2991 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002992 /* When newfile is TRUE, store the typed key in the 'key'
2993 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002994 * Don't ask for the key again when first time Enter was hit.
2995 * Happens when retrying to detect encoding. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002996 smsg(_(need_key_msg), fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002997 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002998 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002999 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003000 *did_ask = TRUE;
3001
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 /* check if empty key entered */
3003 if (cryptkey != NULL && *cryptkey == NUL)
3004 {
3005 if (cryptkey != curbuf->b_p_key)
3006 vim_free(cryptkey);
3007 cryptkey = NULL;
3008 }
3009 }
3010 }
3011
3012 if (cryptkey != NULL)
3013 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003014 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003015
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003016 curbuf->b_cryptstate = crypt_create_from_header(
3017 method, cryptkey, ptr);
3018 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003020 /* Remove cryptmethod specific header from the text. */
3021 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003022 if (*sizep <= header_len)
3023 /* invalid header, buffer can't be encrypted */
3024 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003025 *filesizep += header_len;
3026 *sizep -= header_len;
3027 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3028
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003029 /* Restore the read-only flag. */
3030 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 }
3032 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003033 /* When starting to edit a new file which does not have encryption, clear
3034 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003035 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3037
3038 return cryptkey;
3039}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003040#endif /* FEAT_CRYPT */
3041
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042#ifdef UNIX
3043 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003044set_file_time(
3045 char_u *fname,
3046 time_t atime, /* access time */
3047 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048{
3049# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3050 struct utimbuf buf;
3051
3052 buf.actime = atime;
3053 buf.modtime = mtime;
3054 (void)utime((char *)fname, &buf);
3055# else
3056# if defined(HAVE_UTIMES)
3057 struct timeval tvp[2];
3058
3059 tvp[0].tv_sec = atime;
3060 tvp[0].tv_usec = 0;
3061 tvp[1].tv_sec = mtime;
3062 tvp[1].tv_usec = 0;
3063# ifdef NeXT
3064 (void)utimes((char *)fname, tvp);
3065# else
3066 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3067# endif
3068# endif
3069# endif
3070}
3071#endif /* UNIX */
3072
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003073#if defined(VMS) && !defined(MIN)
3074/* Older DECC compiler for VAX doesn't define MIN() */
3075# define MIN(a, b) ((a) < (b) ? (a) : (b))
3076#endif
3077
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003079 * Return TRUE if a file appears to be read-only from the file permissions.
3080 */
3081 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003082check_file_readonly(
3083 char_u *fname, /* full path to file */
3084 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003085{
3086#ifndef USE_MCH_ACCESS
3087 int fd = 0;
3088#endif
3089
3090 return (
3091#ifdef USE_MCH_ACCESS
3092# ifdef UNIX
3093 (perm & 0222) == 0 ||
3094# endif
3095 mch_access((char *)fname, W_OK)
3096#else
3097 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3098 ? TRUE : (close(fd), FALSE)
3099#endif
3100 );
3101}
3102
3103
3104/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003105 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106 *
3107 * We do our own buffering here because fwrite() is so slow.
3108 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003109 * If "forceit" is true, we don't care for errors when attempting backups.
3110 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003111 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003112 *
3113 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3114 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115 *
3116 * This function must NOT use NameBuff (because it's called by autowrite()).
3117 *
3118 * return FAIL for failure, OK otherwise
3119 */
3120 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003121buf_write(
3122 buf_T *buf,
3123 char_u *fname,
3124 char_u *sfname,
3125 linenr_T start,
3126 linenr_T end,
3127 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003129 int append, /* append to the file */
3130 int forceit,
3131 int reset_changed,
3132 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133{
3134 int fd;
3135 char_u *backup = NULL;
3136 int backup_copy = FALSE; /* copy the original file? */
3137 int dobackup;
3138 char_u *ffname;
3139 char_u *wfname = NULL; /* name of file to write to */
3140 char_u *s;
3141 char_u *ptr;
3142 char_u c;
3143 int len;
3144 linenr_T lnum;
3145 long nchars;
3146 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003147 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 char_u *errnum = NULL;
3149 char_u *buffer;
3150 char_u smallbuf[SMBUFSIZE];
3151 char_u *backup_ext;
3152 int bufsize;
3153 long perm; /* file permissions */
3154 int retval = OK;
3155 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3156 int msg_save = msg_scroll;
3157 int overwriting; /* TRUE if writing over original */
3158 int no_eol = FALSE; /* no end-of-line written */
3159 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003160 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003162 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 int file_readonly = FALSE; /* overwritten file is read-only */
3164 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003165#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 int made_writable = FALSE; /* 'w' bit has been set */
3167#endif
3168 /* writing everything */
3169 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 int attr;
3172 int fileformat;
3173 int write_bin;
3174 struct bw_info write_info; /* info for buf_write_bytes() */
3175#ifdef FEAT_MBYTE
3176 int converted = FALSE;
3177 int notconverted = FALSE;
3178 char_u *fenc; /* effective 'fileencoding' */
3179 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3180#endif
3181#ifdef HAS_BW_FLAGS
3182 int wb_flags = 0;
3183#endif
3184#ifdef HAVE_ACL
3185 vim_acl_T acl = NULL; /* ACL copied from original file to
3186 backup or new file */
3187#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003188#ifdef FEAT_PERSISTENT_UNDO
3189 int write_undo_file = FALSE;
3190 context_sha256_T sha_ctx;
3191#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003192 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193
3194 if (fname == NULL || *fname == NUL) /* safety check */
3195 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003196 if (buf->b_ml.ml_mfp == NULL)
3197 {
3198 /* This can happen during startup when there is a stray "w" in the
3199 * vimrc file. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003200 emsg(_(e_emptybuf));
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003201 return FAIL;
3202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203
3204 /*
3205 * Disallow writing from .exrc and .vimrc in current directory for
3206 * security reasons.
3207 */
3208 if (check_secure())
3209 return FAIL;
3210
3211 /* Avoid a crash for a long name. */
3212 if (STRLEN(fname) >= MAXPATHL)
3213 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003214 emsg(_(e_longname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215 return FAIL;
3216 }
3217
3218#ifdef FEAT_MBYTE
3219 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3220 write_info.bw_conv_buf = NULL;
3221 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003222 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 write_info.bw_restlen = 0;
3224# ifdef USE_ICONV
3225 write_info.bw_iconv_fd = (iconv_t)-1;
3226# endif
3227#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003228#ifdef FEAT_CRYPT
3229 write_info.bw_buffer = buf;
3230#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231
Bram Moolenaardf177f62005-02-22 08:39:57 +00003232 /* After writing a file changedtick changes but we don't want to display
3233 * the line. */
3234 ex_no_reprint = TRUE;
3235
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 /*
3237 * If there is no file name yet, use the one for the written file.
3238 * BF_NOTEDITED is set to reflect this (in case the write fails).
3239 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003240 * Don't do this when appending.
3241 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003243 if (buf->b_ffname == NULL
3244 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 && whole
3246 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003247#ifdef FEAT_QUICKFIX
3248 && !bt_nofile(buf)
3249#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003251 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3253 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003254 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003256 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257 }
3258
3259 if (sfname == NULL)
3260 sfname = fname;
3261 /*
3262 * For Unix: Use the short file name whenever possible.
3263 * Avoids problems with networks and when directory names are changed.
3264 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3265 * another directory, which we don't detect
3266 */
3267 ffname = fname; /* remember full fname */
3268#ifdef UNIX
3269 fname = sfname;
3270#endif
3271
3272 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3273 overwriting = TRUE;
3274 else
3275 overwriting = FALSE;
3276
3277 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003278 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279
3280 ++no_wait_return; /* don't wait for return yet */
3281
3282 /*
3283 * Set '[ and '] marks to the lines to be written.
3284 */
3285 buf->b_op_start.lnum = start;
3286 buf->b_op_start.col = 0;
3287 buf->b_op_end.lnum = end;
3288 buf->b_op_end.col = 0;
3289
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 {
3291 aco_save_T aco;
3292 int buf_ffname = FALSE;
3293 int buf_sfname = FALSE;
3294 int buf_fname_f = FALSE;
3295 int buf_fname_s = FALSE;
3296 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003297 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003298 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003299 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300
3301 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003302 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 * Set curbuf to the buffer to be written.
3304 * Careful: The autocommands may call buf_write() recursively!
3305 */
3306 if (ffname == buf->b_ffname)
3307 buf_ffname = TRUE;
3308 if (sfname == buf->b_sfname)
3309 buf_sfname = TRUE;
3310 if (fname == buf->b_ffname)
3311 buf_fname_f = TRUE;
3312 if (fname == buf->b_sfname)
3313 buf_fname_s = TRUE;
3314
3315 /* set curwin/curbuf to buf and save a few things */
3316 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003317 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318
3319 if (append)
3320 {
3321 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3322 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003323 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003324#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003325 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003326 nofile_err = TRUE;
3327 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003328#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003329 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 }
3333 else if (filtering)
3334 {
3335 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3336 NULL, sfname, FALSE, curbuf, eap);
3337 }
3338 else if (reset_changed && whole)
3339 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003340 int was_changed = curbufIsChanged();
3341
3342 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3343 sfname, sfname, FALSE, curbuf, eap);
3344 if (did_cmd)
3345 {
3346 if (was_changed && !curbufIsChanged())
3347 {
3348 /* Written everything correctly and BufWriteCmd has reset
3349 * 'modified': Correct the undo information so that an
3350 * undo now sets 'modified'. */
3351 u_unchanged(curbuf);
3352 u_update_save_nr(curbuf);
3353 }
3354 }
3355 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003357#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003358 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 nofile_err = TRUE;
3360 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003361#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 }
3366 else
3367 {
3368 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3369 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003371#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003372 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003373 nofile_err = TRUE;
3374 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003375#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003376 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003377 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 }
3380
3381 /* restore curwin/curbuf and a few other things */
3382 aucmd_restbuf(&aco);
3383
3384 /*
3385 * In three situations we return here and don't write the file:
3386 * 1. the autocommands deleted or unloaded the buffer.
3387 * 2. The autocommands abort script processing.
3388 * 3. If one of the "Cmd" autocommands was executed.
3389 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003390 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003392 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003393 || did_cmd || nofile_err
3394#ifdef FEAT_EVAL
3395 || aborting()
3396#endif
3397 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 {
3399 --no_wait_return;
3400 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003401 if (nofile_err)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003402 emsg(_("E676: No matching autocommands for acwrite buffer"));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003403
Bram Moolenaar1e015462005-09-25 22:16:38 +00003404 if (nofile_err
3405#ifdef FEAT_EVAL
3406 || aborting()
3407#endif
3408 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 /* An aborting error, interrupt or exception in the
3410 * autocommands. */
3411 return FAIL;
3412 if (did_cmd)
3413 {
3414 if (buf == NULL)
3415 /* The buffer was deleted. We assume it was written
3416 * (can't retry anyway). */
3417 return OK;
3418 if (overwriting)
3419 {
3420 /* Assume the buffer was written, update the timestamp. */
3421 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003422 if (append)
3423 buf->b_flags &= ~BF_NEW;
3424 else
3425 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003427 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003428 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429 /* Buffer still changed, the autocommands didn't work
3430 * properly. */
3431 return FAIL;
3432 return OK;
3433 }
3434#ifdef FEAT_EVAL
3435 if (!aborting())
3436#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003437 emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 return FAIL;
3439 }
3440
3441 /*
3442 * The autocommands may have changed the number of lines in the file.
3443 * When writing the whole file, adjust the end.
3444 * When writing part of the file, assume that the autocommands only
3445 * changed the number of lines that are to be written (tricky!).
3446 */
3447 if (buf->b_ml.ml_line_count != old_line_count)
3448 {
3449 if (whole) /* write all */
3450 end = buf->b_ml.ml_line_count;
3451 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3452 end += buf->b_ml.ml_line_count - old_line_count;
3453 else /* less lines */
3454 {
3455 end -= old_line_count - buf->b_ml.ml_line_count;
3456 if (end < start)
3457 {
3458 --no_wait_return;
3459 msg_scroll = msg_save;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003460 emsg(_("E204: Autocommand changed number of lines in unexpected way"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 return FAIL;
3462 }
3463 }
3464 }
3465
3466 /*
3467 * The autocommands may have changed the name of the buffer, which may
3468 * be kept in fname, ffname and sfname.
3469 */
3470 if (buf_ffname)
3471 ffname = buf->b_ffname;
3472 if (buf_sfname)
3473 sfname = buf->b_sfname;
3474 if (buf_fname_f)
3475 fname = buf->b_ffname;
3476 if (buf_fname_s)
3477 fname = buf->b_sfname;
3478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479
3480#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003481 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 {
3483 if (whole)
3484 {
3485 /*
3486 * b_changed can be 0 after an undo, but we still need to write
3487 * the buffer to NetBeans.
3488 */
3489 if (buf->b_changed || isNetbeansModified(buf))
3490 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003491 --no_wait_return; /* may wait for return now */
3492 msg_scroll = msg_save;
3493 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 return retval;
3495 }
3496 else
3497 {
3498 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003499 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 buffer = NULL;
3501 goto fail;
3502 }
3503 }
3504 else
3505 {
3506 errnum = (char_u *)"E657: ";
3507 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3508 buffer = NULL;
3509 goto fail;
3510 }
3511 }
3512#endif
3513
3514 if (shortmess(SHM_OVER) && !exiting)
3515 msg_scroll = FALSE; /* overwrite previous file message */
3516 else
3517 msg_scroll = TRUE; /* don't overwrite previous file message */
3518 if (!filtering)
3519 filemess(buf,
3520#ifndef UNIX
3521 sfname,
3522#else
3523 fname,
3524#endif
3525 (char_u *)"", 0); /* show that we are busy */
3526 msg_scroll = FALSE; /* always overwrite the file message now */
3527
3528 buffer = alloc(BUFSIZE);
3529 if (buffer == NULL) /* can't allocate big buffer, use small
3530 * one (to be able to write when out of
3531 * memory) */
3532 {
3533 buffer = smallbuf;
3534 bufsize = SMBUFSIZE;
3535 }
3536 else
3537 bufsize = BUFSIZE;
3538
3539 /*
3540 * Get information about original file (if there is one).
3541 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003542#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003543 st_old.st_dev = 0;
3544 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 perm = -1;
3546 if (mch_stat((char *)fname, &st_old) < 0)
3547 newfile = TRUE;
3548 else
3549 {
3550 perm = st_old.st_mode;
3551 if (!S_ISREG(st_old.st_mode)) /* not a file */
3552 {
3553 if (S_ISDIR(st_old.st_mode))
3554 {
3555 errnum = (char_u *)"E502: ";
3556 errmsg = (char_u *)_("is a directory");
3557 goto fail;
3558 }
3559 if (mch_nodetype(fname) != NODE_WRITABLE)
3560 {
3561 errnum = (char_u *)"E503: ";
3562 errmsg = (char_u *)_("is not a file or writable device");
3563 goto fail;
3564 }
3565 /* It's a device of some kind (or a fifo) which we can write to
3566 * but for which we can't make a backup. */
3567 device = TRUE;
3568 newfile = TRUE;
3569 perm = -1;
3570 }
3571 }
3572#else /* !UNIX */
3573 /*
3574 * Check for a writable device name.
3575 */
3576 c = mch_nodetype(fname);
3577 if (c == NODE_OTHER)
3578 {
3579 errnum = (char_u *)"E503: ";
3580 errmsg = (char_u *)_("is not a file or writable device");
3581 goto fail;
3582 }
3583 if (c == NODE_WRITABLE)
3584 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003585# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003586 /* MS-Windows allows opening a device, but we will probably get stuck
3587 * trying to write to it. */
3588 if (!p_odev)
3589 {
3590 errnum = (char_u *)"E796: ";
3591 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3592 goto fail;
3593 }
3594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 device = TRUE;
3596 newfile = TRUE;
3597 perm = -1;
3598 }
3599 else
3600 {
3601 perm = mch_getperm(fname);
3602 if (perm < 0)
3603 newfile = TRUE;
3604 else if (mch_isdir(fname))
3605 {
3606 errnum = (char_u *)"E502: ";
3607 errmsg = (char_u *)_("is a directory");
3608 goto fail;
3609 }
3610 if (overwriting)
3611 (void)mch_stat((char *)fname, &st_old);
3612 }
3613#endif /* !UNIX */
3614
3615 if (!device && !newfile)
3616 {
3617 /*
3618 * Check if the file is really writable (when renaming the file to
3619 * make a backup we won't discover it later).
3620 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003621 file_readonly = check_file_readonly(fname, (int)perm);
3622
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 if (!forceit && file_readonly)
3624 {
3625 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3626 {
3627 errnum = (char_u *)"E504: ";
3628 errmsg = (char_u *)_(err_readonly);
3629 }
3630 else
3631 {
3632 errnum = (char_u *)"E505: ";
3633 errmsg = (char_u *)_("is read-only (add ! to override)");
3634 }
3635 goto fail;
3636 }
3637
3638 /*
3639 * Check if the timestamp hasn't changed since reading the file.
3640 */
3641 if (overwriting)
3642 {
3643 retval = check_mtime(buf, &st_old);
3644 if (retval == FAIL)
3645 goto fail;
3646 }
3647 }
3648
3649#ifdef HAVE_ACL
3650 /*
3651 * For systems that support ACL: get the ACL from the original file.
3652 */
3653 if (!newfile)
3654 acl = mch_get_acl(fname);
3655#endif
3656
3657 /*
3658 * If 'backupskip' is not empty, don't make a backup for some files.
3659 */
3660 dobackup = (p_wb || p_bk || *p_pm != NUL);
3661#ifdef FEAT_WILDIGN
3662 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3663 dobackup = FALSE;
3664#endif
3665
3666 /*
3667 * Save the value of got_int and reset it. We don't want a previous
3668 * interruption cancel writing, only hitting CTRL-C while writing should
3669 * abort it.
3670 */
3671 prev_got_int = got_int;
3672 got_int = FALSE;
3673
3674 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3675 buf->b_saving = TRUE;
3676
3677 /*
3678 * If we are not appending or filtering, the file exists, and the
3679 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3680 * When 'patchmode' is set also make a backup when appending.
3681 *
3682 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3683 * off. This helps when editing large files on almost-full disks.
3684 */
3685 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3686 {
3687#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003688 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689#endif
3690
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003691 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 backup_copy = TRUE;
3693#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003694 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695 {
3696 int i;
3697
3698# ifdef UNIX
3699 /*
3700 * Don't rename the file when:
3701 * - it's a hard link
3702 * - it's a symbolic link
3703 * - we don't have write permission in the directory
3704 * - we can't set the owner/group of the new file
3705 */
3706 if (st_old.st_nlink > 1
3707 || mch_lstat((char *)fname, &st) < 0
3708 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003709 || st.st_ino != st_old.st_ino
3710# ifndef HAVE_FCHOWN
3711 || st.st_uid != st_old.st_uid
3712 || st.st_gid != st_old.st_gid
3713# endif
3714 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 backup_copy = TRUE;
3716 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003717# else
3718# ifdef WIN32
3719 /* On NTFS file systems hard links are possible. */
3720 if (mch_is_linked(fname))
3721 backup_copy = TRUE;
3722 else
3723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724# endif
3725 {
3726 /*
3727 * Check if we can create a file and set the owner/group to
3728 * the ones from the original file.
3729 * First find a file name that doesn't exist yet (use some
3730 * arbitrary numbers).
3731 */
3732 STRCPY(IObuff, fname);
3733 for (i = 4913; ; i += 123)
3734 {
3735 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003736 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 break;
3738 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003739 fd = mch_open((char *)IObuff,
3740 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 if (fd < 0) /* can't write in directory */
3742 backup_copy = TRUE;
3743 else
3744 {
3745# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746# ifdef HAVE_FCHOWN
Bram Moolenaar42335f52018-09-13 15:33:43 +02003747 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 if (mch_stat((char *)IObuff, &st) < 0
3750 || st.st_uid != st_old.st_uid
3751 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003752 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 backup_copy = TRUE;
3754# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003755 /* Close the file before removing it, on MS-Windows we
3756 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003758 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003759# ifdef MSWIN
3760 /* MS-Windows may trigger a virus scanner to open the
3761 * file, we can't delete it then. Keep trying for half a
3762 * second. */
3763 {
3764 int try;
3765
3766 for (try = 0; try < 10; ++try)
3767 {
3768 if (mch_lstat((char *)IObuff, &st) < 0)
3769 break;
3770 ui_delay(50L, TRUE); /* wait 50 msec */
3771 mch_remove(IObuff);
3772 }
3773 }
3774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 }
3776 }
3777 }
3778
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 /*
3780 * Break symlinks and/or hardlinks if we've been asked to.
3781 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003782 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003784# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 int lstat_res;
3786
3787 lstat_res = mch_lstat((char *)fname, &st);
3788
3789 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003790 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 && lstat_res == 0
3792 && st.st_ino != st_old.st_ino)
3793 backup_copy = FALSE;
3794
3795 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003796 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 && st_old.st_nlink > 1
3798 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3799 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003800# else
3801# if defined(WIN32)
3802 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003803 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003804 backup_copy = FALSE;
3805
3806 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003807 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003808 backup_copy = FALSE;
3809# endif
3810# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812
3813#endif
3814
3815 /* make sure we have a valid backup extension to use */
3816 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 else
3819 backup_ext = p_bex;
3820
3821 if (backup_copy
3822 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3823 {
3824 int bfd;
3825 char_u *copybuf, *wp;
3826 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003827 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 char_u *dirp;
3829 char_u *rootname;
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003830#if defined(UNIX) || defined(WIN3264)
3831 char_u *p;
3832#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003833#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003835 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836#endif
3837
3838 copybuf = alloc(BUFSIZE + 1);
3839 if (copybuf == NULL)
3840 {
3841 some_error = TRUE; /* out of memory */
3842 goto nobackup;
3843 }
3844
3845 /*
3846 * Try to make the backup in each directory in the 'bdir' option.
3847 *
3848 * Unix semantics has it, that we may have a writable file,
3849 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3850 * - the directory is not writable,
3851 * - the file may be a symbolic link,
3852 * - the file may belong to another user/group, etc.
3853 *
3854 * For these reasons, the existing writable file must be truncated
3855 * and reused. Creation of a backup COPY will be attempted.
3856 */
3857 dirp = p_bdir;
3858 while (*dirp)
3859 {
3860#ifdef UNIX
3861 st_new.st_ino = 0;
3862 st_new.st_dev = 0;
3863 st_new.st_gid = 0;
3864#endif
3865
3866 /*
3867 * Isolate one directory name, using an entry in 'bdir'.
3868 */
3869 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003870
3871#if defined(UNIX) || defined(WIN3264)
3872 p = copybuf + STRLEN(copybuf);
3873 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
3874 // Ends with '//', use full path
3875 if ((p = make_percent_swname(copybuf, fname)) != NULL)
3876 {
3877 backup = modname(p, backup_ext, FALSE);
3878 vim_free(p);
3879 }
3880#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 rootname = get_file_in_dir(fname, copybuf);
3882 if (rootname == NULL)
3883 {
3884 some_error = TRUE; /* out of memory */
3885 goto nobackup;
3886 }
3887
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003888#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889 did_set_shortname = FALSE;
3890#endif
3891
3892 /*
3893 * May try twice if 'shortname' not set.
3894 */
3895 for (;;)
3896 {
3897 /*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003898 * Make the backup file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003900 if (backup == NULL)
3901 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 rootname, backup_ext, FALSE);
3903 if (backup == NULL)
3904 {
3905 vim_free(rootname);
3906 some_error = TRUE; /* out of memory */
3907 goto nobackup;
3908 }
3909
3910 /*
3911 * Check if backup file already exists.
3912 */
3913 if (mch_stat((char *)backup, &st_new) >= 0)
3914 {
3915#ifdef UNIX
3916 /*
3917 * Check if backup file is same as original file.
3918 * May happen when modname() gave the same file back.
3919 * E.g. silly link, or file name-length reached.
3920 * If we don't check here, we either ruin the file
3921 * when copying or erase it after writing. jw.
3922 */
3923 if (st_new.st_dev == st_old.st_dev
3924 && st_new.st_ino == st_old.st_ino)
3925 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003926 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927 /*
3928 * may try again with 'shortname' set
3929 */
3930 if (!(buf->b_shortname || buf->b_p_sn))
3931 {
3932 buf->b_shortname = TRUE;
3933 did_set_shortname = TRUE;
3934 continue;
3935 }
3936 /* setting shortname didn't help */
3937 if (did_set_shortname)
3938 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 break;
3940 }
3941#endif
3942
3943 /*
3944 * If we are not going to keep the backup file, don't
3945 * delete an existing one, try to use another name.
3946 * Change one character, just before the extension.
3947 */
3948 if (!p_bk)
3949 {
3950 wp = backup + STRLEN(backup) - 1
3951 - STRLEN(backup_ext);
3952 if (wp < backup) /* empty file name ??? */
3953 wp = backup;
3954 *wp = 'z';
3955 while (*wp > 'a'
3956 && mch_stat((char *)backup, &st_new) >= 0)
3957 --*wp;
3958 /* They all exist??? Must be something wrong. */
3959 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003960 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 }
3962 }
3963 break;
3964 }
3965 vim_free(rootname);
3966
3967 /*
3968 * Try to create the backup file
3969 */
3970 if (backup != NULL)
3971 {
3972 /* remove old backup, if present */
3973 mch_remove(backup);
3974 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003975 * we were sleeping (symlink hacker attack?). Reset umask
3976 * if possible to avoid mch_setperm() below. */
3977#ifdef UNIX
3978 umask_save = umask(0);
3979#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003981 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3982 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003983#ifdef UNIX
3984 (void)umask(umask_save);
3985#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003987 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 else
3989 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003990 /* Set file protection same as original file, but
3991 * strip s-bit. Only needed if umask() wasn't used
3992 * above. */
3993#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003995#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 /*
3997 * Try to set the group of the backup same as the
3998 * original file. If this fails, set the protection
3999 * bits for the group same as the protection bits for
4000 * others.
4001 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004002 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004004 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005# endif
4006 )
4007 mch_setperm(backup,
4008 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004009# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004010 mch_copy_sec(fname, backup);
4011# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012#endif
4013
4014 /*
4015 * copy the file.
4016 */
4017 write_info.bw_fd = bfd;
4018 write_info.bw_buf = copybuf;
4019#ifdef HAS_BW_FLAGS
4020 write_info.bw_flags = FIO_NOCONVERT;
4021#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004022 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023 BUFSIZE)) > 0)
4024 {
4025 if (buf_write_bytes(&write_info) == FAIL)
4026 {
4027 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4028 break;
4029 }
4030 ui_breakcheck();
4031 if (got_int)
4032 {
4033 errmsg = (char_u *)_(e_interr);
4034 break;
4035 }
4036 }
4037
4038 if (close(bfd) < 0 && errmsg == NULL)
4039 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4040 if (write_info.bw_len < 0)
4041 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4042#ifdef UNIX
4043 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4044#endif
4045#ifdef HAVE_ACL
4046 mch_set_acl(backup, acl);
4047#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004048#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004049 mch_copy_sec(fname, backup);
4050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 break;
4052 }
4053 }
4054 }
4055 nobackup:
4056 close(fd); /* ignore errors for closing read file */
4057 vim_free(copybuf);
4058
4059 if (backup == NULL && errmsg == NULL)
4060 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4061 /* ignore errors when forceit is TRUE */
4062 if ((some_error || errmsg != NULL) && !forceit)
4063 {
4064 retval = FAIL;
4065 goto fail;
4066 }
4067 errmsg = NULL;
4068 }
4069 else
4070 {
4071 char_u *dirp;
4072 char_u *p;
4073 char_u *rootname;
4074
4075 /*
4076 * Make a backup by renaming the original file.
4077 */
4078 /*
4079 * If 'cpoptions' includes the "W" flag, we don't want to
4080 * overwrite a read-only file. But rename may be possible
4081 * anyway, thus we need an extra check here.
4082 */
4083 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4084 {
4085 errnum = (char_u *)"E504: ";
4086 errmsg = (char_u *)_(err_readonly);
4087 goto fail;
4088 }
4089
4090 /*
4091 *
4092 * Form the backup file name - change path/fo.o.h to
4093 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4094 * that works is used.
4095 */
4096 dirp = p_bdir;
4097 while (*dirp)
4098 {
4099 /*
4100 * Isolate one directory name and make the backup file name.
4101 */
4102 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004103
4104#if defined(UNIX) || defined(WIN3264)
4105 p = IObuff + STRLEN(IObuff);
4106 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
4107 // path ends with '//', use full path
4108 if ((p = make_percent_swname(IObuff, fname)) != NULL)
4109 {
4110 backup = modname(p, backup_ext, FALSE);
4111 vim_free(p);
4112 }
4113#endif
4114 if (backup == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 {
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004116 rootname = get_file_in_dir(fname, IObuff);
4117 if (rootname == NULL)
4118 backup = NULL;
4119 else
4120 {
4121 backup = buf_modname(
4122 (buf->b_p_sn || buf->b_shortname),
4123 rootname, backup_ext, FALSE);
4124 vim_free(rootname);
4125 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 }
4127
4128 if (backup != NULL)
4129 {
4130 /*
4131 * If we are not going to keep the backup file, don't
4132 * delete an existing one, try to use another name.
4133 * Change one character, just before the extension.
4134 */
4135 if (!p_bk && mch_getperm(backup) >= 0)
4136 {
4137 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4138 if (p < backup) /* empty file name ??? */
4139 p = backup;
4140 *p = 'z';
4141 while (*p > 'a' && mch_getperm(backup) >= 0)
4142 --*p;
4143 /* They all exist??? Must be something wrong! */
4144 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004145 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 }
4147 }
4148 if (backup != NULL)
4149 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004151 * Delete any existing backup and move the current version
4152 * to the backup. For safety, we don't remove the backup
4153 * until the write has finished successfully. And if the
4154 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 */
4156 /*
4157 * If the renaming of the original file to the backup file
4158 * works, quit here.
4159 */
4160 if (vim_rename(fname, backup) == 0)
4161 break;
4162
Bram Moolenaard23a8232018-02-10 18:45:26 +01004163 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 }
4165 }
4166 if (backup == NULL && !forceit)
4167 {
4168 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4169 goto fail;
4170 }
4171 }
4172 }
4173
Bram Moolenaar53076832015-12-31 19:53:21 +01004174#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 /* When using ":w!" and the file was read-only: make it writable */
4176 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4177 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4178 {
4179 perm |= 0200;
4180 (void)mch_setperm(fname, perm);
4181 made_writable = TRUE;
4182 }
4183#endif
4184
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004185 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004186 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4187 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 {
4189 buf->b_p_ro = FALSE;
4190#ifdef FEAT_TITLE
4191 need_maketitle = TRUE; /* set window title later */
4192#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 }
4195
4196 if (end > buf->b_ml.ml_line_count)
4197 end = buf->b_ml.ml_line_count;
4198 if (buf->b_ml.ml_flags & ML_EMPTY)
4199 start = end + 1;
4200
4201 /*
4202 * If the original file is being overwritten, there is a small chance that
4203 * we crash in the middle of writing. Therefore the file is preserved now.
4204 * This makes all block numbers positive so that recovery does not need
4205 * the original file.
4206 * Don't do this if there is a backup file and we are exiting.
4207 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004208 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 && !(exiting && backup != NULL))
4210 {
4211 ml_preserve(buf, FALSE);
4212 if (got_int)
4213 {
4214 errmsg = (char_u *)_(e_interr);
4215 goto restore_backup;
4216 }
4217 }
4218
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219#ifdef VMS
4220 vms_remove_version(fname); /* remove version */
4221#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004222 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 * multi-byte conversion. */
4224 wfname = fname;
4225
4226#ifdef FEAT_MBYTE
4227 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4228 if (eap != NULL && eap->force_enc != 0)
4229 {
4230 fenc = eap->cmd + eap->force_enc;
4231 fenc = enc_canonize(fenc);
4232 fenc_tofree = fenc;
4233 }
4234 else
4235 fenc = buf->b_p_fenc;
4236
4237 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004238 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004240 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241
4242 /*
4243 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4244 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4245 * Prepare the flags for it and allocate bw_conv_buf when needed.
4246 */
4247 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4248 {
4249 wb_flags = get_fio_flags(fenc);
4250 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4251 {
4252 /* Need to allocate a buffer to translate into. */
4253 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4254 write_info.bw_conv_buflen = bufsize * 2;
4255 else /* FIO_UCS4 */
4256 write_info.bw_conv_buflen = bufsize * 4;
4257 write_info.bw_conv_buf
4258 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4259 if (write_info.bw_conv_buf == NULL)
4260 end = 0;
4261 }
4262 }
4263
4264# ifdef WIN3264
4265 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4266 {
4267 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4268 write_info.bw_conv_buflen = bufsize * 4;
4269 write_info.bw_conv_buf
4270 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4271 if (write_info.bw_conv_buf == NULL)
4272 end = 0;
4273 }
4274# endif
4275
Bram Moolenaard0573012017-10-28 21:11:06 +02004276# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4278 {
4279 write_info.bw_conv_buflen = bufsize * 3;
4280 write_info.bw_conv_buf
4281 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4282 if (write_info.bw_conv_buf == NULL)
4283 end = 0;
4284 }
4285# endif
4286
4287# if defined(FEAT_EVAL) || defined(USE_ICONV)
4288 if (converted && wb_flags == 0)
4289 {
4290# ifdef USE_ICONV
4291 /*
4292 * Use iconv() conversion when conversion is needed and it's not done
4293 * internally.
4294 */
4295 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4296 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4297 if (write_info.bw_iconv_fd != (iconv_t)-1)
4298 {
4299 /* We're going to use iconv(), allocate a buffer to convert in. */
4300 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4301 write_info.bw_conv_buf
4302 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4303 if (write_info.bw_conv_buf == NULL)
4304 end = 0;
4305 write_info.bw_first = TRUE;
4306 }
4307# ifdef FEAT_EVAL
4308 else
4309# endif
4310# endif
4311
4312# ifdef FEAT_EVAL
4313 /*
4314 * When the file needs to be converted with 'charconvert' after
4315 * writing, write to a temp file instead and let the conversion
4316 * overwrite the original file.
4317 */
4318 if (*p_ccv != NUL)
4319 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004320 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 if (wfname == NULL) /* Can't write without a tempfile! */
4322 {
4323 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4324 goto restore_backup;
4325 }
4326 }
4327# endif
4328 }
4329# endif
4330 if (converted && wb_flags == 0
4331# ifdef USE_ICONV
4332 && write_info.bw_iconv_fd == (iconv_t)-1
4333# endif
4334# ifdef FEAT_EVAL
4335 && wfname == fname
4336# endif
4337 )
4338 {
4339 if (!forceit)
4340 {
4341 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4342 goto restore_backup;
4343 }
4344 notconverted = TRUE;
4345 }
4346#endif
4347
4348 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004349 * If conversion is taking place, we may first pretend to write and check
4350 * for conversion errors. Then loop again to write for real.
4351 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004353 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004354 {
4355 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004356 * There is no need to check conversion when:
4357 * - there is no conversion
4358 * - we make a backup file, that can be restored in case of conversion
4359 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004361#ifdef FEAT_MBYTE
4362 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004364 checking_conversion = FALSE;
4365
4366 if (checking_conversion)
4367 {
4368 /* Make sure we don't write anything. */
4369 fd = -1;
4370 write_info.bw_fd = fd;
4371 }
4372 else
4373 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004374#ifdef HAVE_FTRUNCATE
4375# define TRUNC_ON_OPEN 0
4376#else
4377# define TRUNC_ON_OPEN O_TRUNC
4378#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004379 /*
4380 * Open the file "wfname" for writing.
4381 * We may try to open the file twice: If we can't write to the file
4382 * and forceit is TRUE we delete the existing file and try to
4383 * create a new one. If this still fails we may have lost the
4384 * original file! (this may happen when the user reached his
4385 * quotum for number of files).
4386 * Appending will fail if the file does not exist and forceit is
4387 * FALSE.
4388 */
4389 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4390 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004391 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004392 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004394 /*
4395 * A forced write will try to create a new file if the old one
4396 * is still readonly. This may also happen when the directory
4397 * is read-only. In that case the mch_remove() will fail.
4398 */
4399 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 {
4401#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004402 stat_T st;
4403
4404 /* Don't delete the file when it's a hard or symbolic link.
4405 */
4406 if ((!newfile && st_old.st_nlink > 1)
4407 || (mch_lstat((char *)fname, &st) == 0
4408 && (st.st_dev != st_old.st_dev
4409 || st.st_ino != st_old.st_ino)))
4410 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4411 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004413 {
4414 errmsg = (char_u *)_("E212: Can't open file for writing");
4415 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4416 && perm >= 0)
4417 {
4418#ifdef UNIX
4419 /* we write to the file, thus it should be marked
4420 writable after all */
4421 if (!(perm & 0200))
4422 made_writable = TRUE;
4423 perm |= 0200;
4424 if (st_old.st_uid != getuid()
4425 || st_old.st_gid != getgid())
4426 perm &= 0777;
4427#endif
4428 if (!append) /* don't remove when appending */
4429 mch_remove(wfname);
4430 continue;
4431 }
4432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434
4435restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004437 stat_T st;
4438
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004440 * If we failed to open the file, we don't need a backup.
4441 * Throw it away. If we moved or removed the original file
4442 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004444 if (backup != NULL && wfname == fname)
4445 {
4446 if (backup_copy)
4447 {
4448 /*
4449 * There is a small chance that we removed the
4450 * original, try to move the copy in its place.
4451 * This may not work if the vim_rename() fails.
4452 * In that case we leave the copy around.
4453 */
4454 /* If file does not exist, put the copy in its
4455 * place */
4456 if (mch_stat((char *)fname, &st) < 0)
4457 vim_rename(backup, fname);
4458 /* if original file does exist throw away the copy
4459 */
4460 if (mch_stat((char *)fname, &st) >= 0)
4461 mch_remove(backup);
4462 }
4463 else
4464 {
4465 /* try to put the original file back */
4466 vim_rename(backup, fname);
4467 }
4468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004470 /* if original file no longer exists give an extra warning
4471 */
4472 if (!newfile && mch_stat((char *)fname, &st) < 0)
4473 end = 0;
4474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475
4476#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004477 if (wfname != fname)
4478 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004480 goto fail;
4481 }
4482 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004484#if defined(UNIX)
4485 {
4486 stat_T st;
4487
4488 /* Double check we are writing the intended file before making
4489 * any changes. */
4490 if (overwriting
4491 && (!dobackup || backup_copy)
4492 && fname == wfname
4493 && perm >= 0
4494 && mch_fstat(fd, &st) == 0
4495 && st.st_ino != st_old.st_ino)
4496 {
4497 close(fd);
4498 errmsg = (char_u *)_("E949: File changed while writing");
4499 goto fail;
4500 }
4501 }
4502#endif
4503#ifdef HAVE_FTRUNCATE
4504 if (!append)
Bram Moolenaar42335f52018-09-13 15:33:43 +02004505 vim_ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004506#endif
4507
Bram Moolenaard0573012017-10-28 21:11:06 +02004508#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004509 if (backup != NULL && overwriting && !append)
4510 {
4511 if (backup_copy)
4512 (void)mch_copy_file_attribute(wfname, backup);
4513 else
4514 (void)mch_copy_file_attribute(backup, wfname);
4515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004517 if (!overwriting && !append)
4518 {
4519 if (buf->b_ffname != NULL)
4520 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4521 /* Should copy resource fork */
4522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523#endif
4524
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004526 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004528 char_u *header;
4529 int header_len;
4530
4531 buf->b_cryptstate = crypt_create_for_writing(
4532 crypt_get_method_nr(buf),
4533 buf->b_p_key, &header, &header_len);
4534 if (buf->b_cryptstate == NULL || header == NULL)
4535 end = 0;
4536 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004538 /* Write magic number, so that Vim knows how this file is
4539 * encrypted when reading it back. */
4540 write_info.bw_buf = header;
4541 write_info.bw_len = header_len;
4542 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 end = 0;
4545 wb_flags |= FIO_ENCRYPTED;
4546 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004549#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004551 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004553 write_info.bw_buf = buffer;
4554 nchars = 0;
4555
4556 /* use "++bin", "++nobin" or 'binary' */
4557 if (eap != NULL && eap->force_bin != 0)
4558 write_bin = (eap->force_bin == FORCE_BIN);
4559 else
4560 write_bin = buf->b_p_bin;
4561
4562#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004564 * The BOM is written just after the encryption magic number.
4565 * Skip it when appending and the file already existed, the BOM only
4566 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004568 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004570 write_info.bw_len = make_bom(buffer, fenc);
4571 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004573 /* don't convert, do encryption */
4574 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4575 if (buf_write_bytes(&write_info) == FAIL)
4576 end = 0;
4577 else
4578 nchars += write_info.bw_len;
4579 }
4580 }
4581 write_info.bw_start_lnum = start;
4582#endif
4583
4584#ifdef FEAT_PERSISTENT_UNDO
4585 write_undo_file = (buf->b_p_udf
4586 && overwriting
4587 && !append
4588 && !filtering
4589 && reset_changed
4590 && !checking_conversion);
4591 if (write_undo_file)
4592 /* Prepare for computing the hash value of the text. */
4593 sha256_start(&sha_ctx);
4594#endif
4595
4596 write_info.bw_len = bufsize;
4597#ifdef HAS_BW_FLAGS
4598 write_info.bw_flags = wb_flags;
4599#endif
4600 fileformat = get_fileformat_force(buf, eap);
4601 s = buffer;
4602 len = 0;
4603 for (lnum = start; lnum <= end; ++lnum)
4604 {
4605 /*
4606 * The next while loop is done once for each character written.
4607 * Keep it fast!
4608 */
4609 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4610#ifdef FEAT_PERSISTENT_UNDO
4611 if (write_undo_file)
4612 sha256_update(&sha_ctx, ptr + 1,
4613 (UINT32_T)(STRLEN(ptr + 1) + 1));
4614#endif
4615 while ((c = *++ptr) != NUL)
4616 {
4617 if (c == NL)
4618 *s = NUL; /* replace newlines with NULs */
4619 else if (c == CAR && fileformat == EOL_MAC)
4620 *s = NL; /* Mac: replace CRs with NLs */
4621 else
4622 *s = c;
4623 ++s;
4624 if (++len != bufsize)
4625 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004626 if (buf_write_bytes(&write_info) == FAIL)
4627 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004628 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004629 break;
4630 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004631 nchars += bufsize;
4632 s = buffer;
4633 len = 0;
4634#ifdef FEAT_MBYTE
4635 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004637 }
4638 /* write failed or last line has no EOL: stop here */
4639 if (end == 0
4640 || (lnum == end
4641 && (write_bin || !buf->b_p_fixeol)
4642 && (lnum == buf->b_no_eol_lnum
4643 || (lnum == buf->b_ml.ml_line_count
4644 && !buf->b_p_eol))))
4645 {
4646 ++lnum; /* written the line, count it */
4647 no_eol = TRUE;
4648 break;
4649 }
4650 if (fileformat == EOL_UNIX)
4651 *s++ = NL;
4652 else
4653 {
4654 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4655 if (fileformat == EOL_DOS) /* write CR-NL */
4656 {
4657 if (++len == bufsize)
4658 {
4659 if (buf_write_bytes(&write_info) == FAIL)
4660 {
4661 end = 0; /* write error: break loop */
4662 break;
4663 }
4664 nchars += bufsize;
4665 s = buffer;
4666 len = 0;
4667 }
4668 *s++ = NL;
4669 }
4670 }
4671 if (++len == bufsize && end)
4672 {
4673 if (buf_write_bytes(&write_info) == FAIL)
4674 {
4675 end = 0; /* write error: break loop */
4676 break;
4677 }
4678 nchars += bufsize;
4679 s = buffer;
4680 len = 0;
4681
4682 ui_breakcheck();
4683 if (got_int)
4684 {
4685 end = 0; /* Interrupted, break loop */
4686 break;
4687 }
4688 }
4689#ifdef VMS
4690 /*
4691 * On VMS there is a problem: newlines get added when writing
4692 * blocks at a time. Fix it by writing a line at a time.
4693 * This is much slower!
4694 * Explanation: VAX/DECC RTL insists that records in some RMS
4695 * structures end with a newline (carriage return) character, and
4696 * if they don't it adds one.
4697 * With other RMS structures it works perfect without this fix.
4698 */
4699 if (buf->b_fab_rfm == FAB$C_VFC
4700 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4701 {
4702 int b2write;
4703
4704 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4705 ? MIN(4096, bufsize)
4706 : MIN(buf->b_fab_mrs, bufsize));
4707
4708 b2write = len;
4709 while (b2write > 0)
4710 {
4711 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4712 if (buf_write_bytes(&write_info) == FAIL)
4713 {
4714 end = 0;
4715 break;
4716 }
4717 b2write -= MIN(b2write, buf->b_fab_mrs);
4718 }
4719 write_info.bw_len = bufsize;
4720 nchars += len;
4721 s = buffer;
4722 len = 0;
4723 }
4724#endif
4725 }
4726 if (len > 0 && end > 0)
4727 {
4728 write_info.bw_len = len;
4729 if (buf_write_bytes(&write_info) == FAIL)
4730 end = 0; /* write error */
4731 nchars += len;
4732 }
4733
4734 /* Stop when writing done or an error was encountered. */
4735 if (!checking_conversion || end == 0)
4736 break;
4737
4738 /* If no error happened until now, writing should be ok, so loop to
4739 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 }
4741
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004742 /* If we started writing, finish writing. Also when an error was
4743 * encountered. */
4744 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004746#if defined(UNIX) && defined(HAVE_FSYNC)
4747 /*
4748 * On many journalling file systems there is a bug that causes both the
4749 * original and the backup file to be lost when halting the system
4750 * right after writing the file. That's because only the meta-data is
4751 * journalled. Syncing the file slows down the system, but assures it
4752 * has been written to disk and we don't lose it.
4753 * For a device do try the fsync() but don't complain if it does not
4754 * work (could be a pipe).
4755 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4756 */
4757 if (p_fs && fsync(fd) != 0 && !device)
4758 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004759 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004760 end = 0;
4761 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762#endif
4763
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004764#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004765 /* Probably need to set the security context. */
4766 if (!backup_copy)
4767 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004768#endif
4769
Bram Moolenaara5792f52005-11-23 21:25:05 +00004770#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004771 /* When creating a new file, set its owner/group to that of the
4772 * original file. Get the new device and inode number. */
4773 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004774 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004775# ifdef HAVE_FCHOWN
4776 stat_T st;
4777
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004778 /* Don't change the owner when it's already OK, some systems remove
4779 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004780 if (mch_stat((char *)wfname, &st) < 0
4781 || st.st_uid != st_old.st_uid
4782 || st.st_gid != st_old.st_gid)
4783 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004784 /* changing owner might not be possible */
Bram Moolenaar42335f52018-09-13 15:33:43 +02004785 vim_ignored = fchown(fd, st_old.st_uid, -1);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004786 /* if changing group fails clear the group permissions */
4787 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4788 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004789 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004790# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004791 buf_setino(buf);
4792 }
4793 else if (!buf->b_dev_valid)
4794 /* Set the inode when creating a new file. */
4795 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004796#endif
4797
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004798#ifdef UNIX
4799 if (made_writable)
4800 perm &= ~0200; /* reset 'w' bit for security reasons */
4801#endif
4802#ifdef HAVE_FCHMOD
4803 /* set permission of new file same as old file */
4804 if (perm >= 0)
4805 (void)mch_fsetperm(fd, perm);
4806#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004807 if (close(fd) != 0)
4808 {
4809 errmsg = (char_u *)_("E512: Close failed");
4810 end = 0;
4811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004813#ifndef HAVE_FCHMOD
4814 /* set permission of new file same as old file */
4815 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004816 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004817#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004819 /*
4820 * Probably need to set the ACL before changing the user (can't set the
4821 * ACL on a file the user doesn't own).
4822 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4823 * default), chmod() discards all part of a file's ACL that don't
4824 * represent the mode of the file. It's non-trivial for us to discover
4825 * whether we're in that situation, so we simply always re-set the ACL.
4826 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004827# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004828 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004829# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004830 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004832#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004833 if (buf->b_cryptstate != NULL)
4834 {
4835 crypt_free_state(buf->b_cryptstate);
4836 buf->b_cryptstate = NULL;
4837 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004838#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004841 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004843 /*
4844 * The file was written to a temp file, now it needs to be
4845 * converted with 'charconvert' to (overwrite) the output file.
4846 */
4847 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004849 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4850 fenc, wfname, fname) == FAIL)
4851 {
4852 write_info.bw_conv_error = TRUE;
4853 end = 0;
4854 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004856 mch_remove(wfname);
4857 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861
4862 if (end == 0)
4863 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004864 /*
4865 * Error encountered.
4866 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 if (errmsg == NULL)
4868 {
4869#ifdef FEAT_MBYTE
4870 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004871 {
4872 if (write_info.bw_conv_error_lnum == 0)
4873 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4874 else
4875 {
4876 errmsg_allocated = TRUE;
4877 errmsg = alloc(300);
4878 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4879 (long)write_info.bw_conv_error_lnum);
4880 }
4881 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 else
4883#endif
4884 if (got_int)
4885 errmsg = (char_u *)_(e_interr);
4886 else
4887 errmsg = (char_u *)_("E514: write error (file system full?)");
4888 }
4889
4890 /*
4891 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004892 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 * original file when trying to make a backup when writing the file a
4894 * second time.
4895 * When "backup_copy" is set we need to copy the backup over the new
4896 * file. Otherwise rename the backup file.
4897 * If this is OK, don't give the extra warning message.
4898 */
4899 if (backup != NULL)
4900 {
4901 if (backup_copy)
4902 {
4903 /* This may take a while, if we were interrupted let the user
4904 * know we got the message. */
4905 if (got_int)
4906 {
4907 MSG(_(e_interr));
4908 out_flush();
4909 }
4910 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4911 {
4912 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004913 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4914 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 {
4916 /* copy the file. */
4917 write_info.bw_buf = smallbuf;
4918#ifdef HAS_BW_FLAGS
4919 write_info.bw_flags = FIO_NOCONVERT;
4920#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004921 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922 SMBUFSIZE)) > 0)
4923 if (buf_write_bytes(&write_info) == FAIL)
4924 break;
4925
4926 if (close(write_info.bw_fd) >= 0
4927 && write_info.bw_len == 0)
4928 end = 1; /* success */
4929 }
4930 close(fd); /* ignore errors for closing read file */
4931 }
4932 }
4933 else
4934 {
4935 if (vim_rename(backup, fname) == 0)
4936 end = 1;
4937 }
4938 }
4939 goto fail;
4940 }
4941
4942 lnum -= start; /* compute number of written lines */
4943 --no_wait_return; /* may wait for return now */
4944
4945#if !(defined(UNIX) || defined(VMS))
4946 fname = sfname; /* use shortname now, for the messages */
4947#endif
4948 if (!filtering)
4949 {
4950 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4951 c = FALSE;
4952#ifdef FEAT_MBYTE
4953 if (write_info.bw_conv_error)
4954 {
4955 STRCAT(IObuff, _(" CONVERSION ERROR"));
4956 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004957 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004958 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004959 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 }
4961 else if (notconverted)
4962 {
4963 STRCAT(IObuff, _("[NOT converted]"));
4964 c = TRUE;
4965 }
4966 else if (converted)
4967 {
4968 STRCAT(IObuff, _("[converted]"));
4969 c = TRUE;
4970 }
4971#endif
4972 if (device)
4973 {
4974 STRCAT(IObuff, _("[Device]"));
4975 c = TRUE;
4976 }
4977 else if (newfile)
4978 {
4979 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4980 c = TRUE;
4981 }
4982 if (no_eol)
4983 {
4984 msg_add_eol();
4985 c = TRUE;
4986 }
4987 /* may add [unix/dos/mac] */
4988 if (msg_add_fileformat(fileformat))
4989 c = TRUE;
4990#ifdef FEAT_CRYPT
4991 if (wb_flags & FIO_ENCRYPTED)
4992 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004993 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 c = TRUE;
4995 }
4996#endif
4997 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4998 if (!shortmess(SHM_WRITE))
4999 {
5000 if (append)
5001 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5002 else
5003 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5004 }
5005
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005006 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 }
5008
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005009 /* When written everything correctly: reset 'modified'. Unless not
5010 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005011 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012#ifdef FEAT_MBYTE
5013 && !write_info.bw_conv_error
5014#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005015 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5016 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 {
5018 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005019 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005020 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01005021 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
5022 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005024 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 }
5026
5027 /*
5028 * If written to the current file, update the timestamp of the swap file
5029 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5030 */
5031 if (overwriting)
5032 {
5033 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005034 if (append)
5035 buf->b_flags &= ~BF_NEW;
5036 else
5037 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 }
5039
5040 /*
5041 * If we kept a backup until now, and we are in patch mode, then we make
5042 * the backup file our 'original' file.
5043 */
5044 if (*p_pm && dobackup)
5045 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005046 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 fname, p_pm, FALSE);
5048
5049 if (backup != NULL)
5050 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005051 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052
5053 /*
5054 * If the original file does not exist yet
5055 * the current backup file becomes the original file
5056 */
5057 if (org == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005058 emsg(_("E205: Patchmode: can't save original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 else if (mch_stat(org, &st) < 0)
5060 {
5061 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005062 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063#ifdef UNIX
5064 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5065#endif
5066 }
5067 }
5068 /*
5069 * If there is no backup file, remember that a (new) file was
5070 * created.
5071 */
5072 else
5073 {
5074 int empty_fd;
5075
5076 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005077 || (empty_fd = mch_open(org,
5078 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005079 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005080 emsg(_("E206: patchmode: can't touch empty original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005081 else
5082 close(empty_fd);
5083 }
5084 if (org != NULL)
5085 {
5086 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5087 vim_free(org);
5088 }
5089 }
5090
5091 /*
5092 * Remove the backup unless 'backup' option is set
5093 */
5094 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005095 emsg(_("E207: Can't delete backup file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005096
Bram Moolenaar071d4272004-06-13 20:20:40 +00005097 goto nofail;
5098
5099 /*
5100 * Finish up. We get here either after failure or success.
5101 */
5102fail:
5103 --no_wait_return; /* may wait for return now */
5104nofail:
5105
5106 /* Done saving, we accept changed buffer warnings again */
5107 buf->b_saving = FALSE;
5108
5109 vim_free(backup);
5110 if (buffer != smallbuf)
5111 vim_free(buffer);
5112#ifdef FEAT_MBYTE
5113 vim_free(fenc_tofree);
5114 vim_free(write_info.bw_conv_buf);
5115# ifdef USE_ICONV
5116 if (write_info.bw_iconv_fd != (iconv_t)-1)
5117 {
5118 iconv_close(write_info.bw_iconv_fd);
5119 write_info.bw_iconv_fd = (iconv_t)-1;
5120 }
5121# endif
5122#endif
5123#ifdef HAVE_ACL
5124 mch_free_acl(acl);
5125#endif
5126
5127 if (errmsg != NULL)
5128 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005129 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005130
Bram Moolenaar8820b482017-03-16 17:23:31 +01005131 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005132 msg_add_fname(buf,
5133#ifndef UNIX
5134 sfname
5135#else
5136 fname
5137#endif
5138 ); /* put file name in IObuff with quotes */
5139 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5140 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5141 /* If the error message has the form "is ...", put the error number in
5142 * front of the file name. */
5143 if (errnum != NULL)
5144 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005145 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005146 mch_memmove(IObuff, errnum, (size_t)numlen);
5147 }
5148 STRCAT(IObuff, errmsg);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005149 emsg((char *)IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005150 if (errmsg_allocated)
5151 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005152
5153 retval = FAIL;
5154 if (end == 0)
5155 {
5156 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5157 attr | MSG_HIST);
5158 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5159 attr | MSG_HIST);
5160
5161 /* Update the timestamp to avoid an "overwrite changed file"
5162 * prompt when writing again. */
5163 if (mch_stat((char *)fname, &st_old) >= 0)
5164 {
5165 buf_store_time(buf, &st_old, fname);
5166 buf->b_mtime_read = buf->b_mtime;
5167 }
5168 }
5169 }
5170 msg_scroll = msg_save;
5171
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005172#ifdef FEAT_PERSISTENT_UNDO
5173 /*
5174 * When writing the whole file and 'undofile' is set, also write the undo
5175 * file.
5176 */
5177 if (retval == OK && write_undo_file)
5178 {
5179 char_u hash[UNDO_HASH_SIZE];
5180
5181 sha256_finish(&sha_ctx, hash);
5182 u_write_undo(NULL, FALSE, buf, hash);
5183 }
5184#endif
5185
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186#ifdef FEAT_EVAL
5187 if (!should_abort(retval))
5188#else
5189 if (!got_int)
5190#endif
5191 {
5192 aco_save_T aco;
5193
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005194 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5195
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 /*
5197 * Apply POST autocommands.
5198 * Careful: The autocommands may call buf_write() recursively!
5199 */
5200 aucmd_prepbuf(&aco, buf);
5201
5202 if (append)
5203 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5204 FALSE, curbuf, eap);
5205 else if (filtering)
5206 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5207 FALSE, curbuf, eap);
5208 else if (reset_changed && whole)
5209 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5210 FALSE, curbuf, eap);
5211 else
5212 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5213 FALSE, curbuf, eap);
5214
5215 /* restore curwin/curbuf and a few other things */
5216 aucmd_restbuf(&aco);
5217
5218#ifdef FEAT_EVAL
5219 if (aborting()) /* autocmds may abort script processing */
5220 retval = FALSE;
5221#endif
5222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223
5224 got_int |= prev_got_int;
5225
Bram Moolenaar071d4272004-06-13 20:20:40 +00005226 return retval;
5227}
5228
5229/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005230 * Set the name of the current buffer. Use when the buffer doesn't have a
5231 * name and a ":r" or ":w" command with a file name is used.
5232 */
5233 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005234set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005235{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005236 buf_T *buf = curbuf;
5237
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005238 /* It's like the unnamed buffer is deleted.... */
5239 if (curbuf->b_p_bl)
5240 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5241 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005242#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005243 if (aborting()) /* autocmds may abort script processing */
5244 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005245#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005246 if (curbuf != buf)
5247 {
5248 /* We are in another buffer now, don't do the renaming. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005249 emsg(_(e_auchangedbuf));
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005250 return FAIL;
5251 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005252
5253 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5254 curbuf->b_flags |= BF_NOTEDITED;
5255
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005256 /* ....and a new named one is created */
5257 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5258 if (curbuf->b_p_bl)
5259 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005260#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005261 if (aborting()) /* autocmds may abort script processing */
5262 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005263#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005264
5265 /* Do filetype detection now if 'filetype' is empty. */
5266 if (*curbuf->b_p_ft == NUL)
5267 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005268 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005269 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005270 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005271 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005272
5273 return OK;
5274}
5275
5276/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005277 * Put file name into IObuff with quotes.
5278 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005279 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005280msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281{
5282 if (fname == NULL)
5283 fname = (char_u *)"-stdin-";
5284 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5285 IObuff[0] = '"';
5286 STRCAT(IObuff, "\" ");
5287}
5288
5289/*
5290 * Append message for text mode to IObuff.
5291 * Return TRUE if something appended.
5292 */
5293 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005294msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295{
5296#ifndef USE_CRNL
5297 if (eol_type == EOL_DOS)
5298 {
5299 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5300 return TRUE;
5301 }
5302#endif
5303#ifndef USE_CR
5304 if (eol_type == EOL_MAC)
5305 {
5306 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5307 return TRUE;
5308 }
5309#endif
5310#if defined(USE_CRNL) || defined(USE_CR)
5311 if (eol_type == EOL_UNIX)
5312 {
5313 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5314 return TRUE;
5315 }
5316#endif
5317 return FALSE;
5318}
5319
5320/*
5321 * Append line and character count to IObuff.
5322 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005323 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005324msg_add_lines(
5325 int insert_space,
5326 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005327 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328{
5329 char_u *p;
5330
5331 p = IObuff + STRLEN(IObuff);
5332
5333 if (insert_space)
5334 *p++ = ' ';
5335 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005336 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005337 "%ldL, %lldC", lnum, (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005338 else
5339 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005340 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005342 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5343 NGETTEXT("%lld character", "%lld characters", nchars),
5344 (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 }
5346}
5347
5348/*
5349 * Append message for missing line separator to IObuff.
5350 */
5351 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005352msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5355}
5356
5357/*
5358 * Check modification time of file, before writing to it.
5359 * The size isn't checked, because using a tool like "gzip" takes care of
5360 * using the same timestamp but can't set the size.
5361 */
5362 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005363check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364{
5365 if (buf->b_mtime_read != 0
5366 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5367 {
5368 msg_scroll = TRUE; /* don't overwrite messages here */
5369 msg_silent = 0; /* must give this prompt */
5370 /* don't use emsg() here, don't want to flush the buffers */
5371 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005372 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5374 TRUE) == 'n')
5375 return FAIL;
5376 msg_scroll = FALSE; /* always overwrite the file message now */
5377 }
5378 return OK;
5379}
5380
5381 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005382time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005384#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5386 * the seconds. Since the roundoff is done when flushing the inode, the
5387 * time may change unexpectedly by one second!!! */
5388 return (t1 - t2 > 1 || t2 - t1 > 1);
5389#else
5390 return (t1 != t2);
5391#endif
5392}
5393
5394/*
5395 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005396 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397 *
5398 * Return FAIL for failure, OK otherwise.
5399 */
5400 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005401buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402{
5403 int wlen;
5404 char_u *buf = ip->bw_buf; /* data to write */
5405 int len = ip->bw_len; /* length of data */
5406#ifdef HAS_BW_FLAGS
5407 int flags = ip->bw_flags; /* extra flags */
5408#endif
5409
5410#ifdef FEAT_MBYTE
5411 /*
5412 * Skip conversion when writing the crypt magic number or the BOM.
5413 */
5414 if (!(flags & FIO_NOCONVERT))
5415 {
5416 char_u *p;
5417 unsigned c;
5418 int n;
5419
5420 if (flags & FIO_UTF8)
5421 {
5422 /*
5423 * Convert latin1 in the buffer to UTF-8 in the file.
5424 */
5425 p = ip->bw_conv_buf; /* translate to buffer */
5426 for (wlen = 0; wlen < len; ++wlen)
5427 p += utf_char2bytes(buf[wlen], p);
5428 buf = ip->bw_conv_buf;
5429 len = (int)(p - ip->bw_conv_buf);
5430 }
5431 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5432 {
5433 /*
5434 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5435 * Latin1 chars in the file.
5436 */
5437 if (flags & FIO_LATIN1)
5438 p = buf; /* translate in-place (can only get shorter) */
5439 else
5440 p = ip->bw_conv_buf; /* translate to buffer */
5441 for (wlen = 0; wlen < len; wlen += n)
5442 {
5443 if (wlen == 0 && ip->bw_restlen != 0)
5444 {
5445 int l;
5446
5447 /* Use remainder of previous call. Append the start of
5448 * buf[] to get a full sequence. Might still be too
5449 * short! */
5450 l = CONV_RESTLEN - ip->bw_restlen;
5451 if (l > len)
5452 l = len;
5453 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005454 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455 if (n > ip->bw_restlen + len)
5456 {
5457 /* We have an incomplete byte sequence at the end to
5458 * be written. We can't convert it without the
5459 * remaining bytes. Keep them for the next call. */
5460 if (ip->bw_restlen + len > CONV_RESTLEN)
5461 return FAIL;
5462 ip->bw_restlen += len;
5463 break;
5464 }
5465 if (n > 1)
5466 c = utf_ptr2char(ip->bw_rest);
5467 else
5468 c = ip->bw_rest[0];
5469 if (n >= ip->bw_restlen)
5470 {
5471 n -= ip->bw_restlen;
5472 ip->bw_restlen = 0;
5473 }
5474 else
5475 {
5476 ip->bw_restlen -= n;
5477 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5478 (size_t)ip->bw_restlen);
5479 n = 0;
5480 }
5481 }
5482 else
5483 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005484 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005485 if (n > len - wlen)
5486 {
5487 /* We have an incomplete byte sequence at the end to
5488 * be written. We can't convert it without the
5489 * remaining bytes. Keep them for the next call. */
5490 if (len - wlen > CONV_RESTLEN)
5491 return FAIL;
5492 ip->bw_restlen = len - wlen;
5493 mch_memmove(ip->bw_rest, buf + wlen,
5494 (size_t)ip->bw_restlen);
5495 break;
5496 }
5497 if (n > 1)
5498 c = utf_ptr2char(buf + wlen);
5499 else
5500 c = buf[wlen];
5501 }
5502
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005503 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5504 {
5505 ip->bw_conv_error = TRUE;
5506 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5507 }
5508 if (c == NL)
5509 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510 }
5511 if (flags & FIO_LATIN1)
5512 len = (int)(p - buf);
5513 else
5514 {
5515 buf = ip->bw_conv_buf;
5516 len = (int)(p - ip->bw_conv_buf);
5517 }
5518 }
5519
5520# ifdef WIN3264
5521 else if (flags & FIO_CODEPAGE)
5522 {
5523 /*
5524 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5525 * codepage.
5526 */
5527 char_u *from;
5528 size_t fromlen;
5529 char_u *to;
5530 int u8c;
5531 BOOL bad = FALSE;
5532 int needed;
5533
5534 if (ip->bw_restlen > 0)
5535 {
5536 /* Need to concatenate the remainder of the previous call and
5537 * the bytes of the current call. Use the end of the
5538 * conversion buffer for this. */
5539 fromlen = len + ip->bw_restlen;
5540 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5541 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5542 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5543 }
5544 else
5545 {
5546 from = buf;
5547 fromlen = len;
5548 }
5549
5550 to = ip->bw_conv_buf;
5551 if (enc_utf8)
5552 {
5553 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5554 * The buffer has been allocated to be big enough. */
5555 while (fromlen > 0)
5556 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005557 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 if (n > (int)fromlen) /* incomplete byte sequence */
5559 break;
5560 u8c = utf_ptr2char(from);
5561 *to++ = (u8c & 0xff);
5562 *to++ = (u8c >> 8);
5563 fromlen -= n;
5564 from += n;
5565 }
5566
5567 /* Copy remainder to ip->bw_rest[] to be used for the next
5568 * call. */
5569 if (fromlen > CONV_RESTLEN)
5570 {
5571 /* weird overlong sequence */
5572 ip->bw_conv_error = TRUE;
5573 return FAIL;
5574 }
5575 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005576 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 }
5578 else
5579 {
5580 /* Convert from enc_codepage to UCS-2, to the start of the
5581 * buffer. The buffer has been allocated to be big enough. */
5582 ip->bw_restlen = 0;
5583 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005584 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 NULL, 0);
5586 if (needed == 0)
5587 {
5588 /* When conversion fails there may be a trailing byte. */
5589 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005590 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 NULL, 0);
5592 if (needed == 0)
5593 {
5594 /* Conversion doesn't work. */
5595 ip->bw_conv_error = TRUE;
5596 return FAIL;
5597 }
5598 /* Save the trailing byte for the next call. */
5599 ip->bw_rest[0] = from[fromlen - 1];
5600 ip->bw_restlen = 1;
5601 }
5602 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005603 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005604 (LPWSTR)to, needed);
5605 if (needed == 0)
5606 {
5607 /* Safety check: Conversion doesn't work. */
5608 ip->bw_conv_error = TRUE;
5609 return FAIL;
5610 }
5611 to += needed * 2;
5612 }
5613
5614 fromlen = to - ip->bw_conv_buf;
5615 buf = to;
5616# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5617 if (FIO_GET_CP(flags) == CP_UTF8)
5618 {
5619 /* Convert from UCS-2 to UTF-8, using the remainder of the
5620 * conversion buffer. Fails when out of space. */
5621 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5622 {
5623 u8c = *from++;
5624 u8c += (*from++ << 8);
5625 to += utf_char2bytes(u8c, to);
5626 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5627 {
5628 ip->bw_conv_error = TRUE;
5629 return FAIL;
5630 }
5631 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005632 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 }
5634 else
5635#endif
5636 {
5637 /* Convert from UCS-2 to the codepage, using the remainder of
5638 * the conversion buffer. If the conversion uses the default
5639 * character "0", the data doesn't fit in this encoding, so
5640 * fail. */
5641 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5642 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005643 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5644 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 if (bad)
5646 {
5647 ip->bw_conv_error = TRUE;
5648 return FAIL;
5649 }
5650 }
5651 }
5652# endif
5653
Bram Moolenaar56718732006-03-15 22:53:57 +00005654# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655 else if (flags & FIO_MACROMAN)
5656 {
5657 /*
5658 * Convert UTF-8 or latin1 to Apple MacRoman.
5659 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 char_u *from;
5661 size_t fromlen;
5662
5663 if (ip->bw_restlen > 0)
5664 {
5665 /* Need to concatenate the remainder of the previous call and
5666 * the bytes of the current call. Use the end of the
5667 * conversion buffer for this. */
5668 fromlen = len + ip->bw_restlen;
5669 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5670 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5671 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5672 }
5673 else
5674 {
5675 from = buf;
5676 fromlen = len;
5677 }
5678
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005679 if (enc2macroman(from, fromlen,
5680 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5681 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005682 {
5683 ip->bw_conv_error = TRUE;
5684 return FAIL;
5685 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687 }
5688# endif
5689
5690# ifdef USE_ICONV
5691 if (ip->bw_iconv_fd != (iconv_t)-1)
5692 {
5693 const char *from;
5694 size_t fromlen;
5695 char *to;
5696 size_t tolen;
5697
5698 /* Convert with iconv(). */
5699 if (ip->bw_restlen > 0)
5700 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005701 char *fp;
5702
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703 /* Need to concatenate the remainder of the previous call and
5704 * the bytes of the current call. Use the end of the
5705 * conversion buffer for this. */
5706 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005707 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5708 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5709 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5710 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 tolen = ip->bw_conv_buflen - fromlen;
5712 }
5713 else
5714 {
5715 from = (const char *)buf;
5716 fromlen = len;
5717 tolen = ip->bw_conv_buflen;
5718 }
5719 to = (char *)ip->bw_conv_buf;
5720
5721 if (ip->bw_first)
5722 {
5723 size_t save_len = tolen;
5724
5725 /* output the initial shift state sequence */
5726 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5727
5728 /* There is a bug in iconv() on Linux (which appears to be
5729 * wide-spread) which sets "to" to NULL and messes up "tolen".
5730 */
5731 if (to == NULL)
5732 {
5733 to = (char *)ip->bw_conv_buf;
5734 tolen = save_len;
5735 }
5736 ip->bw_first = FALSE;
5737 }
5738
5739 /*
5740 * If iconv() has an error or there is not enough room, fail.
5741 */
5742 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5743 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5744 || fromlen > CONV_RESTLEN)
5745 {
5746 ip->bw_conv_error = TRUE;
5747 return FAIL;
5748 }
5749
5750 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5751 if (fromlen > 0)
5752 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5753 ip->bw_restlen = (int)fromlen;
5754
5755 buf = ip->bw_conv_buf;
5756 len = (int)((char_u *)to - ip->bw_conv_buf);
5757 }
5758# endif
5759 }
5760#endif /* FEAT_MBYTE */
5761
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005762 if (ip->bw_fd < 0)
5763 /* Only checking conversion, which is OK if we get here. */
5764 return OK;
5765
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005767 if (flags & FIO_ENCRYPTED)
5768 {
5769 /* Encrypt the data. Do it in-place if possible, otherwise use an
5770 * allocated buffer. */
5771 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5772 {
5773 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5774 }
5775 else
5776 {
5777 char_u *outbuf;
5778
5779 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5780 if (len == 0)
5781 return OK; /* Crypt layer is buffering, will flush later. */
5782 wlen = write_eintr(ip->bw_fd, outbuf, len);
5783 vim_free(outbuf);
5784 return (wlen < len) ? FAIL : OK;
5785 }
5786 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787#endif
5788
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005789 wlen = write_eintr(ip->bw_fd, buf, len);
5790 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791}
5792
5793#ifdef FEAT_MBYTE
5794/*
5795 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005796 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 */
5798 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005799ucs2bytes(
5800 unsigned c, /* in: character */
5801 char_u **pp, /* in/out: pointer to result */
5802 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803{
5804 char_u *p = *pp;
5805 int error = FALSE;
5806 int cc;
5807
5808
5809 if (flags & FIO_UCS4)
5810 {
5811 if (flags & FIO_ENDIAN_L)
5812 {
5813 *p++ = c;
5814 *p++ = (c >> 8);
5815 *p++ = (c >> 16);
5816 *p++ = (c >> 24);
5817 }
5818 else
5819 {
5820 *p++ = (c >> 24);
5821 *p++ = (c >> 16);
5822 *p++ = (c >> 8);
5823 *p++ = c;
5824 }
5825 }
5826 else if (flags & (FIO_UCS2 | FIO_UTF16))
5827 {
5828 if (c >= 0x10000)
5829 {
5830 if (flags & FIO_UTF16)
5831 {
5832 /* Make two words, ten bits of the character in each. First
5833 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5834 c -= 0x10000;
5835 if (c >= 0x100000)
5836 error = TRUE;
5837 cc = ((c >> 10) & 0x3ff) + 0xd800;
5838 if (flags & FIO_ENDIAN_L)
5839 {
5840 *p++ = cc;
5841 *p++ = ((unsigned)cc >> 8);
5842 }
5843 else
5844 {
5845 *p++ = ((unsigned)cc >> 8);
5846 *p++ = cc;
5847 }
5848 c = (c & 0x3ff) + 0xdc00;
5849 }
5850 else
5851 error = TRUE;
5852 }
5853 if (flags & FIO_ENDIAN_L)
5854 {
5855 *p++ = c;
5856 *p++ = (c >> 8);
5857 }
5858 else
5859 {
5860 *p++ = (c >> 8);
5861 *p++ = c;
5862 }
5863 }
5864 else /* Latin1 */
5865 {
5866 if (c >= 0x100)
5867 {
5868 error = TRUE;
5869 *p++ = 0xBF;
5870 }
5871 else
5872 *p++ = c;
5873 }
5874
5875 *pp = p;
5876 return error;
5877}
5878
5879/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005880 * Return TRUE if file encoding "fenc" requires conversion from or to
5881 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 */
5883 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005884need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005886 int same_encoding;
5887 int enc_flags;
5888 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005890 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005891 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005892 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005893 fenc_flags = 0;
5894 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005895 else
5896 {
5897 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5898 * "ucs-4be", etc. */
5899 enc_flags = get_fio_flags(p_enc);
5900 fenc_flags = get_fio_flags(fenc);
5901 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5902 }
5903 if (same_encoding)
5904 {
5905 /* Specified encoding matches with 'encoding'. This requires
5906 * conversion when 'encoding' is Unicode but not UTF-8. */
5907 return enc_unicode != 0;
5908 }
5909
5910 /* Encodings differ. However, conversion is not needed when 'enc' is any
5911 * Unicode encoding and the file is UTF-8. */
5912 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913}
5914
5915/*
5916 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5917 * internal conversion.
5918 * if "ptr" is an empty string, use 'encoding'.
5919 */
5920 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005921get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922{
5923 int prop;
5924
5925 if (*ptr == NUL)
5926 ptr = p_enc;
5927
5928 prop = enc_canon_props(ptr);
5929 if (prop & ENC_UNICODE)
5930 {
5931 if (prop & ENC_2BYTE)
5932 {
5933 if (prop & ENC_ENDIAN_L)
5934 return FIO_UCS2 | FIO_ENDIAN_L;
5935 return FIO_UCS2;
5936 }
5937 if (prop & ENC_4BYTE)
5938 {
5939 if (prop & ENC_ENDIAN_L)
5940 return FIO_UCS4 | FIO_ENDIAN_L;
5941 return FIO_UCS4;
5942 }
5943 if (prop & ENC_2WORD)
5944 {
5945 if (prop & ENC_ENDIAN_L)
5946 return FIO_UTF16 | FIO_ENDIAN_L;
5947 return FIO_UTF16;
5948 }
5949 return FIO_UTF8;
5950 }
5951 if (prop & ENC_LATIN1)
5952 return FIO_LATIN1;
5953 /* must be ENC_DBCS, requires iconv() */
5954 return 0;
5955}
5956
5957#ifdef WIN3264
5958/*
5959 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5960 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5961 * Used for conversion between 'encoding' and 'fileencoding'.
5962 */
5963 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005964get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965{
5966 int cp;
5967
5968 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5969 if (!enc_utf8 && enc_codepage <= 0)
5970 return 0;
5971
5972 cp = encname2codepage(ptr);
5973 if (cp == 0)
5974 {
5975# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5976 if (STRCMP(ptr, "utf-8") == 0)
5977 cp = CP_UTF8;
5978 else
5979# endif
5980 return 0;
5981 }
5982 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5983}
5984#endif
5985
Bram Moolenaard0573012017-10-28 21:11:06 +02005986#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987/*
5988 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5989 * needed for the internal conversion to/from utf-8 or latin1.
5990 */
5991 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005992get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993{
5994 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5995 && (enc_canon_props(ptr) & ENC_MACROMAN))
5996 return FIO_MACROMAN;
5997 return 0;
5998}
5999#endif
6000
6001/*
6002 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6003 * "size" must be at least 2.
6004 * Return the name of the encoding and set "*lenp" to the length.
6005 * Returns NULL when no BOM found.
6006 */
6007 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006008check_for_bom(
6009 char_u *p,
6010 long size,
6011 int *lenp,
6012 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013{
6014 char *name = NULL;
6015 int len = 2;
6016
6017 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006018 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019 {
6020 name = "utf-8"; /* EF BB BF */
6021 len = 3;
6022 }
6023 else if (p[0] == 0xff && p[1] == 0xfe)
6024 {
6025 if (size >= 4 && p[2] == 0 && p[3] == 0
6026 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6027 {
6028 name = "ucs-4le"; /* FF FE 00 00 */
6029 len = 4;
6030 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006031 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006033 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6034 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 name = "utf-16le"; /* FF FE */
6036 }
6037 else if (p[0] == 0xfe && p[1] == 0xff
6038 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6039 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006040 /* Default to utf-16, it works also for ucs-2 text. */
6041 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006043 else
6044 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045 }
6046 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6047 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6048 {
6049 name = "ucs-4"; /* 00 00 FE FF */
6050 len = 4;
6051 }
6052
6053 *lenp = len;
6054 return (char_u *)name;
6055}
6056
6057/*
6058 * Generate a BOM in "buf[4]" for encoding "name".
6059 * Return the length of the BOM (zero when no BOM).
6060 */
6061 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006062make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063{
6064 int flags;
6065 char_u *p;
6066
6067 flags = get_fio_flags(name);
6068
6069 /* Can't put a BOM in a non-Unicode file. */
6070 if (flags == FIO_LATIN1 || flags == 0)
6071 return 0;
6072
6073 if (flags == FIO_UTF8) /* UTF-8 */
6074 {
6075 buf[0] = 0xef;
6076 buf[1] = 0xbb;
6077 buf[2] = 0xbf;
6078 return 3;
6079 }
6080 p = buf;
6081 (void)ucs2bytes(0xfeff, &p, flags);
6082 return (int)(p - buf);
6083}
6084#endif
6085
6086/*
6087 * Try to find a shortname by comparing the fullname with the current
6088 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006089 * Returns "full_path" or pointer into "full_path" if shortened.
6090 */
6091 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006092shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006093{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006094 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006095 char_u *p = full_path;
6096
Bram Moolenaard9462e32011-04-11 21:35:11 +02006097 dirname = alloc(MAXPATHL);
6098 if (dirname == NULL)
6099 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006100 if (mch_dirname(dirname, MAXPATHL) == OK)
6101 {
6102 p = shorten_fname(full_path, dirname);
6103 if (p == NULL || *p == NUL)
6104 p = full_path;
6105 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006106 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006107 return p;
6108}
6109
6110/*
6111 * Try to find a shortname by comparing the fullname with the current
6112 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 * Returns NULL if not shorter name possible, pointer into "full_path"
6114 * otherwise.
6115 */
6116 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006117shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118{
6119 int len;
6120 char_u *p;
6121
6122 if (full_path == NULL)
6123 return NULL;
6124 len = (int)STRLEN(dir_name);
6125 if (fnamencmp(dir_name, full_path, len) == 0)
6126 {
6127 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006128#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006130 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 * slash, since C: by itself does not define a specific dir. In this
6132 * case p may already be correct. <negri>
6133 */
6134 if (!((len > 2) && (*(p - 2) == ':')))
6135#endif
6136 {
6137 if (vim_ispathsep(*p))
6138 ++p;
6139#ifndef VMS /* the path separator is always part of the path */
6140 else
6141 p = NULL;
6142#endif
6143 }
6144 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006145#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146 /*
6147 * When using a file in the current drive, remove the drive name:
6148 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6149 * a floppy from "A:\dir" to "B:\dir".
6150 */
6151 else if (len > 3
6152 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6153 && full_path[1] == ':'
6154 && vim_ispathsep(full_path[2]))
6155 p = full_path + 2;
6156#endif
6157 else
6158 p = NULL;
6159 return p;
6160}
6161
6162/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006163 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 * When "force" is TRUE: Use full path from now on for files currently being
6165 * edited, both for file name and swap file name. Try to shorten the file
6166 * names a bit, if safe to do so.
6167 * When "force" is FALSE: Only try to shorten absolute file names.
6168 * For buffers that have buftype "nofile" or "scratch": never change the file
6169 * name.
6170 */
6171 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006172shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6173{
6174 char_u *p;
6175
6176 if (buf->b_fname != NULL
6177#ifdef FEAT_QUICKFIX
6178 && !bt_nofile(buf)
6179#endif
6180 && !path_with_url(buf->b_fname)
6181 && (force
6182 || buf->b_sfname == NULL
6183 || mch_isFullName(buf->b_sfname)))
6184 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02006185 if (buf->b_sfname != buf->b_ffname)
6186 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02006187 p = shorten_fname(buf->b_ffname, dirname);
6188 if (p != NULL)
6189 {
6190 buf->b_sfname = vim_strsave(p);
6191 buf->b_fname = buf->b_sfname;
6192 }
6193 if (p == NULL || buf->b_fname == NULL)
6194 buf->b_fname = buf->b_ffname;
6195 }
6196}
6197
6198/*
6199 * Shorten filenames for all buffers.
6200 */
6201 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006202shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203{
6204 char_u dirname[MAXPATHL];
6205 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206
6207 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006208 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006210 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006211
6212 /* Always make the swap file name a full path, a "nofile" buffer may
6213 * also have a swap file. */
6214 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006217 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218}
6219
6220#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6221 || defined(FEAT_GUI_MSWIN) \
6222 || defined(FEAT_GUI_MAC) \
6223 || defined(PROTO)
6224/*
6225 * Shorten all filenames in "fnames[count]" by current directory.
6226 */
6227 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006228shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229{
6230 int i;
6231 char_u dirname[MAXPATHL];
6232 char_u *p;
6233
6234 if (fnames == NULL || count < 1)
6235 return;
6236 mch_dirname(dirname, sizeof(dirname));
6237 for (i = 0; i < count; ++i)
6238 {
6239 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6240 {
6241 /* shorten_fname() returns pointer in given "fnames[i]". If free
6242 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6243 * "p" first then free fnames[i]. */
6244 p = vim_strsave(p);
6245 vim_free(fnames[i]);
6246 fnames[i] = p;
6247 }
6248 }
6249}
6250#endif
6251
6252/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02006253 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 * fo_o_h.ext for MSDOS or when shortname option set.
6255 *
6256 * Assumed that fname is a valid name found in the filesystem we assure that
6257 * the return value is a different name and ends in 'ext'.
6258 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6259 * characters otherwise.
6260 * Space for the returned name is allocated, must be freed later.
6261 * Returns NULL when out of memory.
6262 */
6263 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006264modname(
6265 char_u *fname,
6266 char_u *ext,
6267 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006269 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 fname, ext, prepend_dot);
6271}
6272
6273 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006274buf_modname(
6275 int shortname, /* use 8.3 file name */
6276 char_u *fname,
6277 char_u *ext,
6278 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279{
6280 char_u *retval;
6281 char_u *s;
6282 char_u *e;
6283 char_u *ptr;
6284 int fnamelen, extlen;
6285
6286 extlen = (int)STRLEN(ext);
6287
6288 /*
6289 * If there is no file name we must get the name of the current directory
6290 * (we need the full path in case :cd is used).
6291 */
6292 if (fname == NULL || *fname == NUL)
6293 {
6294 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6295 if (retval == NULL)
6296 return NULL;
6297 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6298 (fnamelen = (int)STRLEN(retval)) == 0)
6299 {
6300 vim_free(retval);
6301 return NULL;
6302 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006303 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 {
6305 retval[fnamelen++] = PATHSEP;
6306 retval[fnamelen] = NUL;
6307 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 }
6310 else
6311 {
6312 fnamelen = (int)STRLEN(fname);
6313 retval = alloc((unsigned)(fnamelen + extlen + 3));
6314 if (retval == NULL)
6315 return NULL;
6316 STRCPY(retval, fname);
6317#ifdef VMS
6318 vms_remove_version(retval); /* we do not need versions here */
6319#endif
6320 }
6321
6322 /*
6323 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6324 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6325 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6326 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6327 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006328 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006331#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006333#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006335#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 )
6337 if (*ptr == '.') /* replace '.' by '_' */
6338 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006340 {
6341 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345
6346 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6348 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349
6350 s = ptr + STRLEN(ptr);
6351
6352 /*
6353 * For 8.3 file names we may have to reduce the length.
6354 */
6355#ifdef USE_LONG_FNAME
6356 if (!USE_LONG_FNAME || shortname)
6357#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359#endif
6360 {
6361 /*
6362 * If there is no file name, or the file name ends in '/', and the
6363 * extension starts with '.', put a '_' before the dot, because just
6364 * ".ext" is invalid.
6365 */
6366 if (fname == NULL || *fname == NUL
6367 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6368 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 *s++ = '_';
6371 }
6372 /*
6373 * If the extension starts with '.', truncate the base name at 8
6374 * characters
6375 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006378 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 {
6380 s = ptr + 8;
6381 *s = '\0';
6382 }
6383 }
6384 /*
6385 * If the extension doesn't start with '.', and the file name
6386 * doesn't have an extension yet, append a '.'
6387 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388 else if ((e = vim_strchr(ptr, '.')) == NULL)
6389 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 /*
6391 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006392 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393 */
6394 else if ((int)STRLEN(e) + extlen > 4)
6395 s = e + 4 - extlen;
6396 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006397#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 /*
6399 * If there is no file name, and the extension starts with '.', put a
6400 * '_' before the dot, because just ".ext" may be invalid if it's on a
6401 * FAT partition, and on HPFS it doesn't matter.
6402 */
6403 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6404 *s++ = '_';
6405#endif
6406
6407 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006408 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 * ext can start with '.' and cannot exceed 3 more characters.
6410 */
6411 STRCPY(s, ext);
6412
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 /*
6414 * Prepend the dot.
6415 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006416 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417#ifdef USE_LONG_FNAME
6418 && USE_LONG_FNAME
6419#endif
6420 )
6421 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006422 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006423 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006424 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425
6426 /*
6427 * Check that, after appending the extension, the file name is really
6428 * different.
6429 */
6430 if (fname != NULL && STRCMP(fname, retval) == 0)
6431 {
6432 /* we search for a character that can be replaced by '_' */
6433 while (--s >= ptr)
6434 {
6435 if (*s != '_')
6436 {
6437 *s = '_';
6438 break;
6439 }
6440 }
6441 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6442 *ptr = 'v';
6443 }
6444 return retval;
6445}
6446
6447/*
6448 * Like fgets(), but if the file line is too long, it is truncated and the
6449 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006450 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451 */
6452 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006453vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454{
6455 char *eof;
6456#define FGETS_SIZE 200
6457 char tbuf[FGETS_SIZE];
6458
6459 buf[size - 2] = NUL;
6460#ifdef USE_CR
6461 eof = fgets_cr((char *)buf, size, fp);
6462#else
6463 eof = fgets((char *)buf, size, fp);
6464#endif
6465 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6466 {
6467 buf[size - 1] = NUL; /* Truncate the line */
6468
6469 /* Now throw away the rest of the line: */
6470 do
6471 {
6472 tbuf[FGETS_SIZE - 2] = NUL;
6473#ifdef USE_CR
Bram Moolenaar42335f52018-09-13 15:33:43 +02006474 vim_ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475#else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006476 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477#endif
6478 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6479 }
6480 return (eof == NULL);
6481}
6482
6483#if defined(USE_CR) || defined(PROTO)
6484/*
6485 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6486 * Returns TRUE for end-of-file.
6487 * Only used for the Mac, because it's much slower than vim_fgets().
6488 */
6489 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006490tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491{
6492 int i = 0;
6493 int c;
6494 int eof = FALSE;
6495
6496 for (;;)
6497 {
6498 c = fgetc(fp);
6499 if (c == EOF)
6500 {
6501 eof = TRUE;
6502 break;
6503 }
6504 if (c == '\r')
6505 {
6506 /* Always store a NL for end-of-line. */
6507 if (i < size - 1)
6508 buf[i++] = '\n';
6509 c = fgetc(fp);
6510 if (c != '\n') /* Macintosh format: single CR. */
6511 ungetc(c, fp);
6512 break;
6513 }
6514 if (i < size - 1)
6515 buf[i++] = c;
6516 if (c == '\n')
6517 break;
6518 }
6519 buf[i] = NUL;
6520 return eof;
6521}
6522#endif
6523
6524/*
6525 * rename() only works if both files are on the same file system, this
6526 * function will (attempts to?) copy the file across if rename fails -- webb
6527 * Return -1 for failure, 0 for success.
6528 */
6529 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006530vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531{
6532 int fd_in;
6533 int fd_out;
6534 int n;
6535 char *errmsg = NULL;
6536 char *buffer;
6537#ifdef AMIGA
6538 BPTR flock;
6539#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006540 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006541 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006542#ifdef HAVE_ACL
6543 vim_acl_T acl; /* ACL from original file */
6544#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006545 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546
6547 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006548 * When the names are identical, there is nothing to do. When they refer
6549 * to the same file (ignoring case and slash/backslash differences) but
6550 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 */
6552 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006553 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006554 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006555 use_tmp_file = TRUE;
6556 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006557 return 0;
6558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559
6560 /*
6561 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6562 */
6563 if (mch_stat((char *)from, &st) < 0)
6564 return -1;
6565
Bram Moolenaar3576da72008-12-30 15:15:57 +00006566#ifdef UNIX
6567 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006568 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006569
6570 /* It's possible for the source and destination to be the same file.
6571 * This happens when "from" and "to" differ in case and are on a FAT32
6572 * filesystem. In that case go through a temp file name. */
6573 if (mch_stat((char *)to, &st_to) >= 0
6574 && st.st_dev == st_to.st_dev
6575 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006576 use_tmp_file = TRUE;
6577 }
6578#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006579#ifdef WIN3264
6580 {
6581 BY_HANDLE_FILE_INFORMATION info1, info2;
6582
6583 /* It's possible for the source and destination to be the same file.
6584 * In that case go through a temp file name. This makes rename("foo",
6585 * "./foo") a no-op (in a complicated way). */
6586 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6587 && win32_fileinfo(to, &info2) == FILEINFO_OK
6588 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6589 && info1.nFileIndexHigh == info2.nFileIndexHigh
6590 && info1.nFileIndexLow == info2.nFileIndexLow)
6591 use_tmp_file = TRUE;
6592 }
6593#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006594
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006595 if (use_tmp_file)
6596 {
6597 char tempname[MAXPATHL + 1];
6598
6599 /*
6600 * Find a name that doesn't exist and is in the same directory.
6601 * Rename "from" to "tempname" and then rename "tempname" to "to".
6602 */
6603 if (STRLEN(from) >= MAXPATHL - 5)
6604 return -1;
6605 STRCPY(tempname, from);
6606 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006607 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006608 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6609 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006610 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006611 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006612 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006613 if (mch_rename(tempname, (char *)to) == 0)
6614 return 0;
6615 /* Strange, the second step failed. Try moving the
6616 * file back and return failure. */
6617 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006618 return -1;
6619 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006620 /* If it fails for one temp name it will most likely fail
6621 * for any temp name, give up. */
6622 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006623 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006624 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006625 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006626 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006627
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 /*
6629 * Delete the "to" file, this is required on some systems to make the
6630 * mch_rename() work, on other systems it makes sure that we don't have
6631 * two files when the mch_rename() fails.
6632 */
6633
6634#ifdef AMIGA
6635 /*
6636 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6637 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006638 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 * deleting the "from" file (horror!) we lock it during the remove.
6640 *
6641 * When used for making a backup before writing the file: This should not
6642 * happen with ":w", because startscript() should detect this problem and
6643 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6644 * name. This problem does exist with ":w filename", but then the
6645 * original file will be somewhere else so the backup isn't really
6646 * important. If autoscripting is off the rename may fail.
6647 */
6648 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6649#endif
6650 mch_remove(to);
6651#ifdef AMIGA
6652 if (flock)
6653 UnLock(flock);
6654#endif
6655
6656 /*
6657 * First try a normal rename, return if it works.
6658 */
6659 if (mch_rename((char *)from, (char *)to) == 0)
6660 return 0;
6661
6662 /*
6663 * Rename() failed, try copying the file.
6664 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006665 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006666#ifdef HAVE_ACL
6667 /* For systems that support ACL: get the ACL from the original file. */
6668 acl = mch_get_acl(from);
6669#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6671 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006672 {
6673#ifdef HAVE_ACL
6674 mch_free_acl(acl);
6675#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006677 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006678
6679 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006680 fd_out = mch_open((char *)to,
6681 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 if (fd_out == -1)
6683 {
6684 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006685#ifdef HAVE_ACL
6686 mch_free_acl(acl);
6687#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 return -1;
6689 }
6690
6691 buffer = (char *)alloc(BUFSIZE);
6692 if (buffer == NULL)
6693 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006695 close(fd_in);
6696#ifdef HAVE_ACL
6697 mch_free_acl(acl);
6698#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 return -1;
6700 }
6701
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006702 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6703 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 {
6705 errmsg = _("E208: Error writing to \"%s\"");
6706 break;
6707 }
6708
6709 vim_free(buffer);
6710 close(fd_in);
6711 if (close(fd_out) < 0)
6712 errmsg = _("E209: Error closing \"%s\"");
6713 if (n < 0)
6714 {
6715 errmsg = _("E210: Error reading \"%s\"");
6716 to = from;
6717 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006718#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006719 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006720#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006721#ifdef HAVE_ACL
6722 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006723 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006724#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006725#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006726 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006727#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728 if (errmsg != NULL)
6729 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006730 semsg(errmsg, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 return -1;
6732 }
6733 mch_remove(from);
6734 return 0;
6735}
6736
6737static int already_warned = FALSE;
6738
6739/*
6740 * Check if any not hidden buffer has been changed.
6741 * Postpone the check if there are characters in the stuff buffer, a global
6742 * command is being executed, a mapping is being executed or an autocommand is
6743 * busy.
6744 * Returns TRUE if some message was written (screen should be redrawn and
6745 * cursor positioned).
6746 */
6747 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006748check_timestamps(
6749 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750{
6751 buf_T *buf;
6752 int didit = 0;
6753 int n;
6754
6755 /* Don't check timestamps while system() or another low-level function may
6756 * cause us to lose and gain focus. */
6757 if (no_check_timestamps > 0)
6758 return FALSE;
6759
6760 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6761 * event and we would keep on checking if the file is steadily growing.
6762 * Do check again after typing something. */
6763 if (focus && did_check_timestamps)
6764 {
6765 need_check_timestamps = TRUE;
6766 return FALSE;
6767 }
6768
6769 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006770 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 need_check_timestamps = TRUE; /* check later */
6772 else
6773 {
6774 ++no_wait_return;
6775 did_check_timestamps = TRUE;
6776 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006777 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 {
6779 /* Only check buffers in a window. */
6780 if (buf->b_nwindows > 0)
6781 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006782 bufref_T bufref;
6783
6784 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 n = buf_check_timestamp(buf, focus);
6786 if (didit < n)
6787 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006788 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 {
6790 /* Autocommands have removed the buffer, start at the
6791 * first one again. */
6792 buf = firstbuf;
6793 continue;
6794 }
6795 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796 }
6797 --no_wait_return;
6798 need_check_timestamps = FALSE;
6799 if (need_wait_return && didit == 2)
6800 {
6801 /* make sure msg isn't overwritten */
6802 msg_puts((char_u *)"\n");
6803 out_flush();
6804 }
6805 }
6806 return didit;
6807}
6808
6809/*
6810 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6811 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6812 * empty.
6813 */
6814 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006815move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816{
6817 buf_T *tbuf = curbuf;
6818 int retval = OK;
6819 linenr_T lnum;
6820 char_u *p;
6821
6822 /* Copy the lines in "frombuf" to "tobuf". */
6823 curbuf = tobuf;
6824 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6825 {
6826 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6827 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6828 {
6829 vim_free(p);
6830 retval = FAIL;
6831 break;
6832 }
6833 vim_free(p);
6834 }
6835
6836 /* Delete all the lines in "frombuf". */
6837 if (retval != FAIL)
6838 {
6839 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006840 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6841 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 {
6843 /* Oops! We could try putting back the saved lines, but that
6844 * might fail again... */
6845 retval = FAIL;
6846 break;
6847 }
6848 }
6849
6850 curbuf = tbuf;
6851 return retval;
6852}
6853
6854/*
6855 * Check if buffer "buf" has been changed.
6856 * Also check if the file for a new buffer unexpectedly appeared.
6857 * return 1 if a changed buffer was found.
6858 * return 2 if a message has been displayed.
6859 * return 0 otherwise.
6860 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006862buf_check_timestamp(
6863 buf_T *buf,
6864 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006866 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 int stat_res;
6868 int retval = 0;
6869 char_u *path;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006870 char *tbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006872 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 int helpmesg = FALSE;
6874 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006875 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6877 int can_reload = FALSE;
6878#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006879 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 int orig_mode = buf->b_orig_mode;
6881#ifdef FEAT_GUI
6882 int save_mouse_correct = need_mouse_correct;
6883#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006885 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006886#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006887 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006888#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006889 bufref_T bufref;
6890
6891 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892
6893 /* If there is no file name, the buffer is not loaded, 'buftype' is
6894 * set, we are in the middle of a save or being called recursively: ignore
6895 * this buffer. */
6896 if (buf->b_ffname == NULL
6897 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02006898 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006901#ifdef FEAT_NETBEANS_INTG
6902 || isNetbeansBuffer(buf)
6903#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006904#ifdef FEAT_TERMINAL
6905 || buf->b_term != NULL
6906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 )
6908 return 0;
6909
6910 if ( !(buf->b_flags & BF_NOTEDITED)
6911 && buf->b_mtime != 0
6912 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6913 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006914 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915#ifdef HAVE_ST_MODE
6916 || (int)st.st_mode != buf->b_orig_mode
6917#else
6918 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6919#endif
6920 ))
6921 {
6922 retval = 1;
6923
Bram Moolenaar386bc822018-07-07 18:34:12 +02006924 // set b_mtime to stop further warnings (e.g., when executing
6925 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 if (stat_res < 0)
6927 {
Bram Moolenaar386bc822018-07-07 18:34:12 +02006928 // When 'autoread' is set we'll check the file again to see if it
6929 // re-appears.
6930 buf->b_mtime = buf->b_p_ar;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 buf->b_orig_size = 0;
6932 buf->b_orig_mode = 0;
6933 }
6934 else
6935 buf_store_time(buf, &st, buf->b_ffname);
6936
6937 /* Don't do anything for a directory. Might contain the file
6938 * explorer. */
6939 if (mch_isdir(buf->b_fname))
6940 ;
6941
6942 /*
6943 * If 'autoread' is set, the buffer has no changes and the file still
6944 * exists, reload the buffer. Use the buffer-local option value if it
6945 * was set, the global option value otherwise.
6946 */
6947 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6948 && !bufIsChanged(buf) && stat_res >= 0)
6949 reload = TRUE;
6950 else
6951 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006952 if (stat_res < 0)
6953 reason = "deleted";
6954 else if (bufIsChanged(buf))
6955 reason = "conflict";
6956 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6957 reason = "changed";
6958 else if (orig_mode != buf->b_orig_mode)
6959 reason = "mode";
6960 else
6961 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962
6963 /*
6964 * Only give the warning if there are no FileChangedShell
6965 * autocommands.
6966 * Avoid being called recursively by setting "busy".
6967 */
6968 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006969#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006970 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6971 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006972#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006973 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6975 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006976 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 busy = FALSE;
6978 if (n)
6979 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006980 if (!bufref_valid(&bufref))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006981 emsg(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006982#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006983 s = get_vim_var_str(VV_FCS_CHOICE);
6984 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6985 reload = TRUE;
6986 else if (STRCMP(s, "ask") == 0)
6987 n = FALSE;
6988 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006989#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006990 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006992 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006994 if (*reason == 'd')
6995 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 else
6997 {
6998 helpmesg = TRUE;
6999#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7000 can_reload = TRUE;
7001#endif
7002 /*
7003 * Check if the file contents really changed to avoid
7004 * giving a warning when only the timestamp was set (e.g.,
7005 * checked out of CVS). Always warn when the buffer was
7006 * changed.
7007 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007008 if (reason[2] == 'n')
7009 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007011 mesg2 = _("See \":help W12\" for more info.");
7012 }
7013 else if (reason[1] == 'h')
7014 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007016 mesg2 = _("See \":help W11\" for more info.");
7017 }
7018 else if (*reason == 'm')
7019 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007021 mesg2 = _("See \":help W16\" for more info.");
7022 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007023 else
7024 /* Only timestamp changed, store it to avoid a warning
7025 * in check_mtime() later. */
7026 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 }
7028 }
7029 }
7030
7031 }
7032 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7033 && vim_fexists(buf->b_ffname))
7034 {
7035 retval = 1;
7036 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7037 buf->b_flags |= BF_NEW_W;
7038#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7039 can_reload = TRUE;
7040#endif
7041 }
7042
7043 if (mesg != NULL)
7044 {
7045 path = home_replace_save(buf, buf->b_fname);
7046 if (path != NULL)
7047 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007048 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049 mesg2 = "";
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007050 tbuf = (char *)alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 + STRLEN(mesg2) + 2));
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007052 sprintf(tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007053#ifdef FEAT_EVAL
7054 /* Set warningmsg here, before the unimportant and output-specific
7055 * mesg2 has been appended. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007056 set_vim_var_string(VV_WARNINGMSG, (char_u *)tbuf, -1);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007057#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7059 if (can_reload)
7060 {
7061 if (*mesg2 != NUL)
7062 {
7063 STRCAT(tbuf, "\n");
7064 STRCAT(tbuf, mesg2);
7065 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007066 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"),
7067 (char_u *)tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007068 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 reload = TRUE;
7070 }
7071 else
7072#endif
7073 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7074 {
7075 if (*mesg2 != NUL)
7076 {
7077 STRCAT(tbuf, "; ");
7078 STRCAT(tbuf, mesg2);
7079 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007080 emsg(tbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 retval = 2;
7082 }
7083 else
7084 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086 {
7087 msg_start();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007088 msg_puts_attr((char_u *)tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 if (*mesg2 != NUL)
7090 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007091 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 msg_clr_eos();
7093 (void)msg_end();
7094 if (emsg_silent == 0)
7095 {
7096 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007097#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007099#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 /* give the user some time to think about it */
7101 ui_delay(1000L, TRUE);
7102
7103 /* don't redraw and erase the message */
7104 redraw_cmdline = FALSE;
7105 }
7106 }
7107 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 }
7109
7110 vim_free(path);
7111 vim_free(tbuf);
7112 }
7113 }
7114
7115 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007116 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007118 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007119#ifdef FEAT_PERSISTENT_UNDO
7120 if (buf->b_p_udf && buf->b_ffname != NULL)
7121 {
7122 char_u hash[UNDO_HASH_SIZE];
7123 buf_T *save_curbuf = curbuf;
7124
7125 /* Any existing undo file is unusable, write it now. */
7126 curbuf = buf;
7127 u_compute_hash(hash);
7128 u_write_undo(NULL, FALSE, buf, hash);
7129 curbuf = save_curbuf;
7130 }
7131#endif
7132 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007134 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007135 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007136 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7137 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138#ifdef FEAT_GUI
7139 /* restore this in case an autocommand has set it; it would break
7140 * 'mousefocus' */
7141 need_mouse_correct = save_mouse_correct;
7142#endif
7143
7144 return retval;
7145}
7146
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007147/*
7148 * Reload a buffer that is already loaded.
7149 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007150 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7151 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007152 */
7153 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007154buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007155{
7156 exarg_T ea;
7157 pos_T old_cursor;
7158 linenr_T old_topline;
7159 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007160 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007161 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007162 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007163 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007164 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165
7166 /* set curwin/curbuf for "buf" and save some things */
7167 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007168
7169 /* We only want to read the text from the file, not reset the syntax
7170 * highlighting, clear marks, diff status, etc. Force the fileformat
7171 * and encoding to be the same. */
7172 if (prep_exarg(&ea, buf) == OK)
7173 {
7174 old_cursor = curwin->w_cursor;
7175 old_topline = curwin->w_topline;
7176
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007177 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007178 {
7179 /* Save all the text, so that the reload can be undone.
7180 * Sync first so that this is a separate undo-able action. */
7181 u_sync(FALSE);
7182 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7183 flags |= READ_KEEP_UNDO;
7184 }
7185
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007186 /*
7187 * To behave like when a new file is edited (matters for
7188 * BufReadPost autocommands) we first need to delete the current
7189 * buffer contents. But if reading the file fails we should keep
7190 * the old contents. Can't use memory only, the file might be
7191 * too big. Use a hidden buffer to move the buffer contents to.
7192 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007193 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007194 savebuf = NULL;
7195 else
7196 {
7197 /* Allocate a buffer without putting it in the buffer list. */
7198 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007199 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007200 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007201 {
7202 /* Open the memline. */
7203 curbuf = savebuf;
7204 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007205 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007206 curbuf = buf;
7207 curwin->w_buffer = buf;
7208 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007209 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007210 || move_lines(buf, savebuf) == FAIL)
7211 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007212 semsg(_("E462: Could not prepare for reloading \"%s\""),
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213 buf->b_fname);
7214 saved = FAIL;
7215 }
7216 }
7217
7218 if (saved == OK)
7219 {
7220 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007221 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007222 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7223 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007224 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007226#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007227 if (!aborting())
7228#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007229 semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007230 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231 {
7232 /* Put the text back from the save buffer. First
7233 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007234 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007235 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007236 break;
7237 (void)move_lines(savebuf, buf);
7238 }
7239 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007240 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007241 {
7242 /* Mark the buffer as unmodified and free undo info. */
7243 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007244 if ((flags & READ_KEEP_UNDO) == 0)
7245 {
7246 u_blockfree(buf);
7247 u_clearall(buf);
7248 }
7249 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007250 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007251 /* Mark all undo states as changed. */
7252 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007253 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007254 }
7255 }
7256 vim_free(ea.cmd);
7257
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007258 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007259 wipe_buffer(savebuf, FALSE);
7260
7261#ifdef FEAT_DIFF
7262 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007263 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007264#endif
7265
7266 /* Restore the topline and cursor position and check it (lines may
7267 * have been removed). */
7268 if (old_topline > curbuf->b_ml.ml_line_count)
7269 curwin->w_topline = curbuf->b_ml.ml_line_count;
7270 else
7271 curwin->w_topline = old_topline;
7272 curwin->w_cursor = old_cursor;
7273 check_cursor();
7274 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007275 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007276#ifdef FEAT_FOLDING
7277 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007278 win_T *wp;
7279 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007280
7281 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007282 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007283 if (wp->w_buffer == curwin->w_buffer
7284 && !foldmethodIsManual(wp))
7285 foldUpdateAll(wp);
7286 }
7287#endif
7288 /* If the mode didn't change and 'readonly' was set, keep the old
7289 * value; the user probably used the ":view" command. But don't
7290 * reset it, might have had a read error. */
7291 if (orig_mode == curbuf->b_orig_mode)
7292 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007293
7294 /* Modelines must override settings done by autocommands. */
7295 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007296 }
7297
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007298 /* restore curwin/curbuf and a few other things */
7299 aucmd_restbuf(&aco);
7300 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007301}
7302
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007304buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305{
7306 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007307 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007308#ifdef HAVE_ST_MODE
7309 buf->b_orig_mode = (int)st->st_mode;
7310#else
7311 buf->b_orig_mode = mch_getperm(fname);
7312#endif
7313}
7314
7315/*
7316 * Adjust the line with missing eol, used for the next write.
7317 * Used for do_filter(), when the input lines for the filter are deleted.
7318 */
7319 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007320write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007321{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007322 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7323 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324}
7325
Bram Moolenaarda440d22016-01-16 21:27:23 +01007326#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7327/*
7328 * Delete "name" and everything in it, recursively.
7329 * return 0 for succes, -1 if some file was not deleted.
7330 */
7331 int
7332delete_recursive(char_u *name)
7333{
7334 int result = 0;
7335 char_u **files;
7336 int file_count;
7337 int i;
7338 char_u *exp;
7339
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007340 /* A symbolic link to a directory itself is deleted, not the directory it
7341 * points to. */
7342 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007343# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007344 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007345# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007346 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007347# endif
7348 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007349 {
7350 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7351 exp = vim_strsave(NameBuff);
7352 if (exp == NULL)
7353 return -1;
7354 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007355 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007356 {
7357 for (i = 0; i < file_count; ++i)
7358 if (delete_recursive(files[i]) != 0)
7359 result = -1;
7360 FreeWild(file_count, files);
7361 }
7362 else
7363 result = -1;
7364 vim_free(exp);
7365 (void)mch_rmdir(name);
7366 }
7367 else
7368 result = mch_remove(name) == 0 ? 0 : -1;
7369
7370 return result;
7371}
7372#endif
7373
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374#if defined(TEMPDIRNAMES) || defined(PROTO)
7375static long temp_count = 0; /* Temp filename counter. */
7376
7377/*
7378 * Delete the temp directory and all files it contains.
7379 */
7380 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007381vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383 if (vim_tempdir != NULL)
7384 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007385 /* remove the trailing path separator */
7386 gettail(vim_tempdir)[-1] = NUL;
7387 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007388 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 }
7390}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391
7392/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007393 * Directory "tempdir" was created. Expand this name to a full path and put
7394 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7395 * "tempdir" must be no longer than MAXPATHL.
7396 */
7397 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007398vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007399{
7400 char_u *buf;
7401
7402 buf = alloc((unsigned)MAXPATHL + 2);
7403 if (buf != NULL)
7404 {
7405 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7406 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007407 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007408 vim_tempdir = vim_strsave(buf);
7409 vim_free(buf);
7410 }
7411}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007412#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007413
7414/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 * vim_tempname(): Return a unique name that can be used for a temp file.
7416 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007417 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7418 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 *
7420 * The returned pointer is to allocated memory.
7421 * The returned pointer is NULL if no valid name was found.
7422 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007424vim_tempname(
7425 int extra_char UNUSED, /* char to use in the name instead of '?' */
7426 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427{
7428#ifdef USE_TMPNAM
7429 char_u itmp[L_tmpnam]; /* use tmpnam() */
7430#else
7431 char_u itmp[TEMPNAMELEN];
7432#endif
7433
7434#ifdef TEMPDIRNAMES
7435 static char *(tempdirs[]) = {TEMPDIRNAMES};
7436 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007438 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439# endif
7440
7441 /*
7442 * This will create a directory for private use by this instance of Vim.
7443 * This is done once, and the same directory is used for all temp files.
7444 * This method avoids security problems because of symlink attacks et al.
7445 * It's also a bit faster, because we only need to check for an existing
7446 * file when creating the directory and not for each temp file.
7447 */
7448 if (vim_tempdir == NULL)
7449 {
7450 /*
7451 * Try the entries in TEMPDIRNAMES to create the temp directory.
7452 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007453 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007455# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007456 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007457 long nr;
7458 long off;
7459# endif
7460
Bram Moolenaare1a61992015-12-03 21:02:27 +01007461 /* Expand $TMP, leave room for "/v1100000/999999999".
7462 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007464 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007466 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007467 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468
Bram Moolenaareaf03392009-11-17 11:08:52 +00007469# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007470 {
7471# if defined(UNIX) || defined(VMS)
7472 /* Make sure the umask doesn't remove the executable bit.
7473 * "repl" has been reported to use "177". */
7474 mode_t umask_save = umask(077);
7475# endif
7476 /* Leave room for filename */
7477 STRCAT(itmp, "vXXXXXX");
7478 if (mkdtemp((char *)itmp) != NULL)
7479 vim_settempdir(itmp);
7480# if defined(UNIX) || defined(VMS)
7481 (void)umask(umask_save);
7482# endif
7483 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007484# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 /* Get an arbitrary number of up to 6 digits. When it's
7486 * unlikely that it already exists it will be faster,
7487 * otherwise it doesn't matter. The use of mkdir() avoids any
7488 * security problems because of the predictable number. */
7489 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007490 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491
7492 /* Try up to 10000 different values until we find a name that
7493 * doesn't exist. */
7494 for (off = 0; off < 10000L; ++off)
7495 {
7496 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007497# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007499# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500
Bram Moolenaareaf03392009-11-17 11:08:52 +00007501 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7502# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 /* If mkdir() does not set errno to EEXIST, check for
7504 * existing file here. There is a race condition then,
7505 * although it's fail-safe. */
7506 if (mch_stat((char *)itmp, &st) >= 0)
7507 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007508# endif
7509# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007510 /* Make sure the umask doesn't remove the executable bit.
7511 * "repl" has been reported to use "177". */
7512 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007513# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007515# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007516 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007517# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 if (r == 0)
7519 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007520 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007521 break;
7522 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007523# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524 /* If the mkdir() didn't fail because the file/dir exists,
7525 * we probably can't create any dir here, try another
7526 * place. */
7527 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 break;
7530 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007531# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007532 if (vim_tempdir != NULL)
7533 break;
7534 }
7535 }
7536 }
7537
7538 if (vim_tempdir != NULL)
7539 {
7540 /* There is no need to check if the file exists, because we own the
7541 * directory and nobody else creates a file in it. */
7542 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7543 return vim_strsave(itmp);
7544 }
7545
7546 return NULL;
7547
7548#else /* TEMPDIRNAMES */
7549
7550# ifdef WIN3264
7551 char szTempFile[_MAX_PATH + 1];
7552 char buf4[4];
7553 char_u *retval;
7554 char_u *p;
7555
7556 STRCPY(itmp, "");
7557 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007558 {
7559 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7560 szTempFile[1] = NUL;
7561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007562 strcpy(buf4, "VIM");
7563 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007564 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007566 if (!keep)
7567 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007568 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569
7570 /* Backslashes in a temp file name cause problems when filtering with
7571 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7572 * didn't set 'shellslash'. */
7573 retval = vim_strsave(itmp);
7574 if (*p_shcf == '-' || p_ssl)
7575 for (p = retval; *p; ++p)
7576 if (*p == '\\')
7577 *p = '/';
7578 return retval;
7579
7580# else /* WIN3264 */
7581
7582# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007583 char_u *p;
7584
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007586 p = tmpnam((char *)itmp);
7587 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007588 return NULL;
7589# else
7590 char_u *p;
7591
7592# ifdef VMS_TEMPNAM
7593 /* mktemp() is not working on VMS. It seems to be
7594 * a do-nothing function. Therefore we use tempnam().
7595 */
7596 sprintf((char *)itmp, "VIM%c", extra_char);
7597 p = (char_u *)tempnam("tmp:", (char *)itmp);
7598 if (p != NULL)
7599 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007600 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007601 * and VIM will then be unable to find the file later */
7602 STRCPY(itmp, p);
7603 STRCAT(itmp, ".txt");
7604 free(p);
7605 }
7606 else
7607 return NULL;
7608# else
7609 STRCPY(itmp, TEMPNAME);
7610 if ((p = vim_strchr(itmp, '?')) != NULL)
7611 *p = extra_char;
7612 if (mktemp((char *)itmp) == NULL)
7613 return NULL;
7614# endif
7615# endif
7616
7617 return vim_strsave(itmp);
7618# endif /* WIN3264 */
7619#endif /* TEMPDIRNAMES */
7620}
7621
7622#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7623/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007624 * Convert all backslashes in fname to forward slashes in-place, unless when
7625 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626 */
7627 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007628forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629{
7630 char_u *p;
7631
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007632 if (path_with_url(fname))
7633 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634 for (p = fname; *p != NUL; ++p)
7635# ifdef FEAT_MBYTE
7636 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007637 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007638 ++p;
7639 else
7640# endif
7641 if (*p == '\\')
7642 *p = '/';
7643}
7644#endif
7645
7646
7647/*
7648 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 */
7650
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651/*
7652 * The autocommands are stored in a list for each event.
7653 * Autocommands for the same pattern, that are consecutive, are joined
7654 * together, to avoid having to match the pattern too often.
7655 * The result is an array of Autopat lists, which point to AutoCmd lists:
7656 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007657 * last_autopat[0] -----------------------------+
7658 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7660 * Autopat.cmds Autopat.cmds
7661 * | |
7662 * V V
7663 * AutoCmd.next AutoCmd.next
7664 * | |
7665 * V V
7666 * AutoCmd.next NULL
7667 * |
7668 * V
7669 * NULL
7670 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007671 * last_autopat[1] --------+
7672 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673 * first_autopat[1] --> Autopat.next --> NULL
7674 * Autopat.cmds
7675 * |
7676 * V
7677 * AutoCmd.next
7678 * |
7679 * V
7680 * NULL
7681 * etc.
7682 *
7683 * The order of AutoCmds is important, this is the order in which they were
7684 * defined and will have to be executed.
7685 */
7686typedef struct AutoCmd
7687{
7688 char_u *cmd; /* The command to be executed (NULL
7689 when command has been removed) */
7690 char nested; /* If autocommands nest here */
7691 char last; /* last command in list */
7692#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007693 sctx_T script_ctx; /* script context where defined */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694#endif
7695 struct AutoCmd *next; /* Next AutoCmd in list */
7696} AutoCmd;
7697
7698typedef struct AutoPat
7699{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007700 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7701 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702 char_u *pat; /* pattern as typed (NULL when pattern
7703 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007704 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007706 int group; /* group ID */
7707 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007708 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007709 char allow_dirs; /* Pattern may match whole path */
7710 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007711} AutoPat;
7712
7713static struct event_name
7714{
7715 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007716 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717} event_names[] =
7718{
7719 {"BufAdd", EVENT_BUFADD},
7720 {"BufCreate", EVENT_BUFADD},
7721 {"BufDelete", EVENT_BUFDELETE},
7722 {"BufEnter", EVENT_BUFENTER},
7723 {"BufFilePost", EVENT_BUFFILEPOST},
7724 {"BufFilePre", EVENT_BUFFILEPRE},
7725 {"BufHidden", EVENT_BUFHIDDEN},
7726 {"BufLeave", EVENT_BUFLEAVE},
7727 {"BufNew", EVENT_BUFNEW},
7728 {"BufNewFile", EVENT_BUFNEWFILE},
7729 {"BufRead", EVENT_BUFREADPOST},
7730 {"BufReadCmd", EVENT_BUFREADCMD},
7731 {"BufReadPost", EVENT_BUFREADPOST},
7732 {"BufReadPre", EVENT_BUFREADPRE},
7733 {"BufUnload", EVENT_BUFUNLOAD},
7734 {"BufWinEnter", EVENT_BUFWINENTER},
7735 {"BufWinLeave", EVENT_BUFWINLEAVE},
7736 {"BufWipeout", EVENT_BUFWIPEOUT},
7737 {"BufWrite", EVENT_BUFWRITEPRE},
7738 {"BufWritePost", EVENT_BUFWRITEPOST},
7739 {"BufWritePre", EVENT_BUFWRITEPRE},
7740 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007741 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007742 {"CmdlineEnter", EVENT_CMDLINEENTER},
7743 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744 {"CmdwinEnter", EVENT_CMDWINENTER},
7745 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007746 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007747 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar60a68362018-04-30 15:40:48 +02007748 {"ColorSchemePre", EVENT_COLORSCHEMEPRE},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007749 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007750 {"CursorHold", EVENT_CURSORHOLD},
7751 {"CursorHoldI", EVENT_CURSORHOLDI},
7752 {"CursorMoved", EVENT_CURSORMOVED},
7753 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaare8fa05b2018-09-16 15:48:06 +02007754 {"DiffUpdated", EVENT_DIFFUPDATED},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007755 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007757 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7760 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7761 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7762 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007763 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 {"FileChangedRO", EVENT_FILECHANGEDRO},
7765 {"FileReadPost", EVENT_FILEREADPOST},
7766 {"FileReadPre", EVENT_FILEREADPRE},
7767 {"FileReadCmd", EVENT_FILEREADCMD},
7768 {"FileType", EVENT_FILETYPE},
7769 {"FileWritePost", EVENT_FILEWRITEPOST},
7770 {"FileWritePre", EVENT_FILEWRITEPRE},
7771 {"FileWriteCmd", EVENT_FILEWRITECMD},
7772 {"FilterReadPost", EVENT_FILTERREADPOST},
7773 {"FilterReadPre", EVENT_FILTERREADPRE},
7774 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7775 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7776 {"FocusGained", EVENT_FOCUSGAINED},
7777 {"FocusLost", EVENT_FOCUSLOST},
7778 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7779 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007780 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007781 {"InsertChange", EVENT_INSERTCHANGE},
7782 {"InsertEnter", EVENT_INSERTENTER},
7783 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007784 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007785 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007786 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007787 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7788 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007789 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007791 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007792 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7793 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007794 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaar2b618522019-01-12 13:26:03 +01007795 {"SourcePre", EVENT_SOURCEPRE},
7796 {"SourcePost", EVENT_SOURCEPOST},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007797 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 {"StdinReadPost", EVENT_STDINREADPOST},
7799 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007800 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007801 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007802 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007803 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007804 {"TabEnter", EVENT_TABENTER},
7805 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007807 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007808 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007809 {"TextChanged", EVENT_TEXTCHANGED},
7810 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007811 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812 {"User", EVENT_USER},
7813 {"VimEnter", EVENT_VIMENTER},
7814 {"VimLeave", EVENT_VIMLEAVE},
7815 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007816 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 {"WinEnter", EVENT_WINENTER},
7818 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007819 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007820 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007821 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007822};
7823
7824static AutoPat *first_autopat[NUM_EVENTS] =
7825{
7826 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7827 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7828 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7829 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007830 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007831 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832};
7833
Bram Moolenaar462455e2017-11-10 21:53:11 +01007834static AutoPat *last_autopat[NUM_EVENTS] =
7835{
7836 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7837 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7838 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7839 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7840 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7841 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7842};
7843
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844/*
7845 * struct used to keep status while executing autocommands for an event.
7846 */
7847typedef struct AutoPatCmd
7848{
7849 AutoPat *curpat; /* next AutoPat to examine */
7850 AutoCmd *nextcmd; /* next AutoCmd to execute */
7851 int group; /* group being used */
7852 char_u *fname; /* fname to match with */
7853 char_u *sfname; /* sfname to match with */
7854 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007855 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007856 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7857 buf is deleted */
7858 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859} AutoPatCmd;
7860
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007861static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007862
Bram Moolenaar071d4272004-06-13 20:20:40 +00007863/*
7864 * augroups stores a list of autocmd group names.
7865 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007866static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007868/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007869static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870
7871/*
7872 * The ID of the current group. Group 0 is the default one.
7873 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874static int current_augroup = AUGROUP_DEFAULT;
7875
7876static int au_need_clean = FALSE; /* need to delete marked patterns */
7877
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007878static char_u *event_nr2name(event_T event);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007879static int au_get_grouparg(char_u **argp);
7880static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7881static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7882static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007883static 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 +00007884
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007885
Bram Moolenaar754b5602006-02-09 23:53:20 +00007886static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007888static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007889
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007890 static char_u *
7891get_deleted_augroup(void)
7892{
7893 if (deleted_augroup == NULL)
7894 deleted_augroup = (char_u *)_("--Deleted--");
7895 return deleted_augroup;
7896}
7897
Bram Moolenaar071d4272004-06-13 20:20:40 +00007898/*
7899 * Show the autocommands for one AutoPat.
7900 */
7901 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007902show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903{
7904 AutoCmd *ac;
7905
7906 /* Check for "got_int" (here and at various places below), which is set
7907 * when "q" has been hit for the "--more--" prompt */
7908 if (got_int)
7909 return;
7910 if (ap->pat == NULL) /* pattern has been removed */
7911 return;
7912
7913 msg_putchar('\n');
7914 if (got_int)
7915 return;
7916 if (event != last_event || ap->group != last_group)
7917 {
7918 if (ap->group != AUGROUP_DEFAULT)
7919 {
7920 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007921 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007922 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007923 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007924 msg_puts((char_u *)" ");
7925 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007926 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007927 last_event = event;
7928 last_group = ap->group;
7929 msg_putchar('\n');
7930 if (got_int)
7931 return;
7932 }
7933 msg_col = 4;
7934 msg_outtrans(ap->pat);
7935
7936 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7937 {
7938 if (ac->cmd != NULL) /* skip removed commands */
7939 {
7940 if (msg_col >= 14)
7941 msg_putchar('\n');
7942 msg_col = 14;
7943 if (got_int)
7944 return;
7945 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007946#ifdef FEAT_EVAL
7947 if (p_verbose > 0)
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007948 last_set_msg(ac->script_ctx);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007949#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007950 if (got_int)
7951 return;
7952 if (ac->next != NULL)
7953 {
7954 msg_putchar('\n');
7955 if (got_int)
7956 return;
7957 }
7958 }
7959 }
7960}
7961
7962/*
7963 * Mark an autocommand pattern for deletion.
7964 */
7965 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007966au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007968 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007969 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970 au_need_clean = TRUE;
7971}
7972
7973/*
7974 * Mark all commands for a pattern for deletion.
7975 */
7976 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007977au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007978{
7979 AutoCmd *ac;
7980
7981 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007982 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007983 au_need_clean = TRUE;
7984}
7985
7986/*
7987 * Cleanup autocommands and patterns that have been deleted.
7988 * This is only done when not executing autocommands.
7989 */
7990 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007991au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992{
7993 AutoPat *ap, **prev_ap;
7994 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007995 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007996
7997 if (autocmd_busy || !au_need_clean)
7998 return;
7999
8000 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008001 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8002 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008003 {
8004 /* loop over all autocommand patterns */
8005 prev_ap = &(first_autopat[(int)event]);
8006 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8007 {
8008 /* loop over all commands for this pattern */
8009 prev_ac = &(ap->cmds);
8010 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8011 {
8012 /* remove the command if the pattern is to be deleted or when
8013 * the command has been marked for deletion */
8014 if (ap->pat == NULL || ac->cmd == NULL)
8015 {
8016 *prev_ac = ac->next;
8017 vim_free(ac->cmd);
8018 vim_free(ac);
8019 }
8020 else
8021 prev_ac = &(ac->next);
8022 }
8023
8024 /* remove the pattern if it has been marked for deletion */
8025 if (ap->pat == NULL)
8026 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008027 if (ap->next == NULL)
8028 {
8029 if (prev_ap == &(first_autopat[(int)event]))
8030 last_autopat[(int)event] = NULL;
8031 else
8032 /* this depends on the "next" field being the first in
8033 * the struct */
8034 last_autopat[(int)event] = (AutoPat *)prev_ap;
8035 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008036 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008037 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038 vim_free(ap);
8039 }
8040 else
8041 prev_ap = &(ap->next);
8042 }
8043 }
8044
8045 au_need_clean = FALSE;
8046}
8047
8048/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008049 * Called when buffer is freed, to remove/invalidate related buffer-local
8050 * autocmds.
8051 */
8052 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008053aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008054{
8055 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008056 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008057 AutoPatCmd *apc;
8058
8059 /* invalidate currently executing autocommands */
8060 for (apc = active_apc_list; apc; apc = apc->next)
8061 if (buf->b_fnum == apc->arg_bufnr)
8062 apc->arg_bufnr = 0;
8063
8064 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008065 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8066 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008067 /* loop over all autocommand patterns */
8068 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8069 if (ap->buflocal_nr == buf->b_fnum)
8070 {
8071 au_remove_pat(ap);
8072 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008073 {
8074 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008075 smsg(_("auto-removing autocommand: %s <buffer=%d>"),
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008076 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008077 verbose_leave();
8078 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008079 }
8080 au_cleanup();
8081}
8082
8083/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008084 * Add an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008085 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008086 */
8087 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008088au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008089{
8090 int i;
8091
8092 i = au_find_group(name);
8093 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8094 {
8095 /* First try using a free entry. */
8096 for (i = 0; i < augroups.ga_len; ++i)
8097 if (AUGROUP_NAME(i) == NULL)
8098 break;
8099 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8100 return AUGROUP_ERROR;
8101
8102 AUGROUP_NAME(i) = vim_strsave(name);
8103 if (AUGROUP_NAME(i) == NULL)
8104 return AUGROUP_ERROR;
8105 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008106 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008107 }
8108
8109 return i;
8110}
8111
8112 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008113au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008114{
8115 int i;
8116
8117 i = au_find_group(name);
8118 if (i == AUGROUP_ERROR) /* the group doesn't exist */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008119 semsg(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008120 else if (i == current_augroup)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008121 emsg(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122 else
8123 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008124 event_T event;
8125 AutoPat *ap;
8126 int in_use = FALSE;
8127
8128 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8129 event = (event_T)((int)event + 1))
8130 {
8131 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008132 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008133 {
8134 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8135 in_use = TRUE;
8136 event = NUM_EVENTS;
8137 break;
8138 }
8139 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008140 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008141 if (in_use)
8142 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008143 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008144 }
8145 else
8146 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008147 }
8148}
8149
8150/*
8151 * Find the ID of an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008152 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008153 */
8154 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008155au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008156{
8157 int i;
8158
8159 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008160 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008161 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008162 return i;
8163 return AUGROUP_ERROR;
8164}
8165
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008166/*
8167 * Return TRUE if augroup "name" exists.
8168 */
8169 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008170au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008171{
8172 return au_find_group(name) != AUGROUP_ERROR;
8173}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008174
Bram Moolenaar071d4272004-06-13 20:20:40 +00008175/*
8176 * ":augroup {name}".
8177 */
8178 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008179do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008180{
8181 int i;
8182
8183 if (del_group)
8184 {
8185 if (*arg == NUL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008186 emsg(_(e_argreq));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187 else
8188 au_del_group(arg);
8189 }
8190 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8191 current_augroup = AUGROUP_DEFAULT;
8192 else if (*arg) /* ":aug xxx": switch to group xxx */
8193 {
8194 i = au_new_group(arg);
8195 if (i != AUGROUP_ERROR)
8196 current_augroup = i;
8197 }
8198 else /* ":aug": list the group names */
8199 {
8200 msg_start();
8201 for (i = 0; i < augroups.ga_len; ++i)
8202 {
8203 if (AUGROUP_NAME(i) != NULL)
8204 {
8205 msg_puts(AUGROUP_NAME(i));
8206 msg_puts((char_u *)" ");
8207 }
8208 }
8209 msg_clr_eos();
8210 msg_end();
8211 }
8212}
8213
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008214#if defined(EXITFREE) || defined(PROTO)
8215 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008216free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008217{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008218 int i;
8219 char_u *s;
8220
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008221 for (current_augroup = -1; current_augroup < augroups.ga_len;
8222 ++current_augroup)
8223 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008224
8225 for (i = 0; i < augroups.ga_len; ++i)
8226 {
8227 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008228 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008229 vim_free(s);
8230 }
8231 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008232}
8233#endif
8234
Bram Moolenaar071d4272004-06-13 20:20:40 +00008235/*
8236 * Return the event number for event name "start".
8237 * Return NUM_EVENTS if the event name was not found.
8238 * Return a pointer to the next event name in "end".
8239 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008240 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008241event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242{
8243 char_u *p;
8244 int i;
8245 int len;
8246
Bram Moolenaare99e8442016-07-26 20:43:40 +02008247 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008248 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008249 ;
8250 for (i = 0; event_names[i].name != NULL; ++i)
8251 {
8252 len = (int)STRLEN(event_names[i].name);
8253 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8254 break;
8255 }
8256 if (*p == ',')
8257 ++p;
8258 *end = p;
8259 if (event_names[i].name == NULL)
8260 return NUM_EVENTS;
8261 return event_names[i].event;
8262}
8263
8264/*
8265 * Return the name for event "event".
8266 */
8267 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008268event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008269{
8270 int i;
8271
8272 for (i = 0; event_names[i].name != NULL; ++i)
8273 if (event_names[i].event == event)
8274 return (char_u *)event_names[i].name;
8275 return (char_u *)"Unknown";
8276}
8277
8278/*
8279 * Scan over the events. "*" stands for all events.
8280 */
8281 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008282find_end_event(
8283 char_u *arg,
8284 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008285{
8286 char_u *pat;
8287 char_u *p;
8288
8289 if (*arg == '*')
8290 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008291 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008292 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008293 semsg(_("E215: Illegal character after *: %s"), arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008294 return NULL;
8295 }
8296 pat = arg + 1;
8297 }
8298 else
8299 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008300 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008301 {
8302 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8303 {
8304 if (have_group)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008305 semsg(_("E216: No such event: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008306 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008307 semsg(_("E216: No such group or event: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 return NULL;
8309 }
8310 }
8311 }
8312 return pat;
8313}
8314
8315/*
8316 * Return TRUE if "event" is included in 'eventignore'.
8317 */
8318 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008319event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008320{
8321 char_u *p = p_ei;
8322
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008323 while (*p != NUL)
8324 {
8325 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8326 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008327 if (event_name2nr(p, &p) == event)
8328 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008330
8331 return FALSE;
8332}
8333
8334/*
8335 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8336 */
8337 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008338check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339{
8340 char_u *p = p_ei;
8341
Bram Moolenaar071d4272004-06-13 20:20:40 +00008342 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008343 {
8344 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8345 {
8346 p += 3;
8347 if (*p == ',')
8348 ++p;
8349 }
8350 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008351 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008353
8354 return OK;
8355}
8356
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008357# if defined(FEAT_SYN_HL) || defined(PROTO)
8358
8359/*
8360 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8361 * buffer loaded into the window. "what" must start with a comma.
8362 * Returns the old value of 'eventignore' in allocated memory.
8363 */
8364 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008365au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008366{
8367 char_u *new_ei;
8368 char_u *save_ei;
8369
8370 save_ei = vim_strsave(p_ei);
8371 if (save_ei != NULL)
8372 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008373 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008374 if (new_ei != NULL)
8375 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008376 if (*what == ',' && *p_ei == NUL)
8377 STRCPY(new_ei, what + 1);
8378 else
8379 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008380 set_string_option_direct((char_u *)"ei", -1, new_ei,
8381 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008382 vim_free(new_ei);
8383 }
8384 }
8385 return save_ei;
8386}
8387
8388 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008389au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008390{
8391 if (old_ei != NULL)
8392 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008393 set_string_option_direct((char_u *)"ei", -1, old_ei,
8394 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008395 vim_free(old_ei);
8396 }
8397}
8398# endif /* FEAT_SYN_HL */
8399
Bram Moolenaar071d4272004-06-13 20:20:40 +00008400/*
8401 * do_autocmd() -- implements the :autocmd command. Can be used in the
8402 * following ways:
8403 *
8404 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8405 * will be automatically executed for <event>
8406 * when editing a file matching <pat>, in
8407 * the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008408 * :autocmd <event> <pat> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008409 * <event> and <pat>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008410 * :autocmd <event> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008411 * <event>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008412 * :autocmd Show all autocommands.
8413 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008414 * <event> and <pat>, and add the command
8415 * <cmd>, for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008416 * :autocmd! <event> <pat> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417 * <event> and <pat> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008418 * :autocmd! <event> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008419 * <event> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008420 * :autocmd! Remove ALL autocommands for the current
Bram Moolenaar071d4272004-06-13 20:20:40 +00008421 * group.
8422 *
8423 * Multiple events and patterns may be given separated by commas. Here are
8424 * some examples:
8425 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8426 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8427 *
8428 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008429 *
8430 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008431 */
8432 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008433do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008434{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008435 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008436 char_u *pat;
8437 char_u *envpat = NULL;
8438 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008439 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 int need_free = FALSE;
8441 int nested = FALSE;
8442 int group;
8443
Bram Moolenaare99e8442016-07-26 20:43:40 +02008444 if (*arg == '|')
8445 {
8446 arg = (char_u *)"";
8447 group = AUGROUP_ALL; /* no argument, use all groups */
8448 }
8449 else
8450 {
8451 /*
8452 * Check for a legal group name. If not, use AUGROUP_ALL.
8453 */
8454 group = au_get_grouparg(&arg);
8455 if (arg == NULL) /* out of memory */
8456 return;
8457 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008458
8459 /*
8460 * Scan over the events.
8461 * If we find an illegal name, return here, don't do anything.
8462 */
8463 pat = find_end_event(arg, group != AUGROUP_ALL);
8464 if (pat == NULL)
8465 return;
8466
Bram Moolenaar071d4272004-06-13 20:20:40 +00008467 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008468 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008470 pat = (char_u *)"";
8471 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008472 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008473 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008474 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008475 /*
8476 * Scan over the pattern. Put a NUL at the end.
8477 */
8478 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008479 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008480 cmd++;
8481 if (*cmd)
8482 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008483
Bram Moolenaare99e8442016-07-26 20:43:40 +02008484 /* Expand environment variables in the pattern. Set 'shellslash', we want
8485 * forward slashes here. */
8486 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8487 {
8488#ifdef BACKSLASH_IN_FILENAME
8489 int p_ssl_save = p_ssl;
8490
8491 p_ssl = TRUE;
8492#endif
8493 envpat = expand_env_save(pat);
8494#ifdef BACKSLASH_IN_FILENAME
8495 p_ssl = p_ssl_save;
8496#endif
8497 if (envpat != NULL)
8498 pat = envpat;
8499 }
8500
8501 /*
8502 * Check for "nested" flag.
8503 */
8504 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008505 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008506 {
8507 nested = TRUE;
8508 cmd = skipwhite(cmd + 6);
8509 }
8510
8511 /*
8512 * Find the start of the commands.
8513 * Expand <sfile> in it.
8514 */
8515 if (*cmd != NUL)
8516 {
8517 cmd = expand_sfile(cmd);
8518 if (cmd == NULL) /* some error */
8519 return;
8520 need_free = TRUE;
8521 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008522 }
8523
8524 /*
8525 * Print header when showing autocommands.
8526 */
8527 if (!forceit && *cmd == NUL)
8528 {
8529 /* Highlight title */
Bram Moolenaar8c555332018-06-22 21:30:31 +02008530 MSG_PUTS_TITLE(_("\n--- Autocommands ---"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531 }
8532
8533 /*
8534 * Loop over the events.
8535 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008536 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008537 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008538 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008539 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008540 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8541 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008542 if (do_autocmd_event(event, pat,
8543 nested, cmd, forceit, group) == FAIL)
8544 break;
8545 }
8546 else
8547 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008548 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008549 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8550 nested, cmd, forceit, group) == FAIL)
8551 break;
8552 }
8553
8554 if (need_free)
8555 vim_free(cmd);
8556 vim_free(envpat);
8557}
8558
8559/*
8560 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8561 * The "argp" argument is advanced to the following argument.
8562 *
8563 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8564 */
8565 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008566au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008567{
8568 char_u *group_name;
8569 char_u *p;
8570 char_u *arg = *argp;
8571 int group = AUGROUP_ALL;
8572
Bram Moolenaar1c465442017-03-12 20:10:05 +01008573 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008574 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008575 if (p > arg)
8576 {
8577 group_name = vim_strnsave(arg, (int)(p - arg));
8578 if (group_name == NULL) /* out of memory */
8579 return AUGROUP_ERROR;
8580 group = au_find_group(group_name);
8581 if (group == AUGROUP_ERROR)
8582 group = AUGROUP_ALL; /* no match, use all groups */
8583 else
8584 *argp = skipwhite(p); /* match, skip over group name */
8585 vim_free(group_name);
8586 }
8587 return group;
8588}
8589
8590/*
8591 * do_autocmd() for one event.
8592 * If *pat == NUL do for all patterns.
8593 * If *cmd == NUL show entries.
8594 * If forceit == TRUE delete entries.
8595 * If group is not AUGROUP_ALL, only use this group.
8596 */
8597 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008598do_autocmd_event(
8599 event_T event,
8600 char_u *pat,
8601 int nested,
8602 char_u *cmd,
8603 int forceit,
8604 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008605{
8606 AutoPat *ap;
8607 AutoPat **prev_ap;
8608 AutoCmd *ac;
8609 AutoCmd **prev_ac;
8610 int brace_level;
8611 char_u *endpat;
8612 int findgroup;
8613 int allgroups;
8614 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008615 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008616 int buflocal_nr;
8617 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008618
8619 if (group == AUGROUP_ALL)
8620 findgroup = current_augroup;
8621 else
8622 findgroup = group;
8623 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8624
8625 /*
8626 * Show or delete all patterns for an event.
8627 */
8628 if (*pat == NUL)
8629 {
8630 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8631 {
8632 if (forceit) /* delete the AutoPat, if it's in the current group */
8633 {
8634 if (ap->group == findgroup)
8635 au_remove_pat(ap);
8636 }
8637 else if (group == AUGROUP_ALL || ap->group == group)
8638 show_autocmd(ap, event);
8639 }
8640 }
8641
8642 /*
8643 * Loop through all the specified patterns.
8644 */
8645 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8646 {
8647 /*
8648 * Find end of the pattern.
8649 * Watch out for a comma in braces, like "*.\{obj,o\}".
8650 */
8651 brace_level = 0;
8652 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008653 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008654 {
8655 if (*endpat == '{')
8656 brace_level++;
8657 else if (*endpat == '}')
8658 brace_level--;
8659 }
8660 if (pat == endpat) /* ignore single comma */
8661 continue;
8662 patlen = (int)(endpat - pat);
8663
8664 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008665 * detect special <buflocal[=X]> buffer-local patterns
8666 */
8667 is_buflocal = FALSE;
8668 buflocal_nr = 0;
8669
Bram Moolenaar1e997822015-02-17 16:04:57 +01008670 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008671 && pat[patlen - 1] == '>')
8672 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008673 /* "<buffer...>": Error will be printed only for addition.
8674 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008675 is_buflocal = TRUE;
8676 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008677 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008678 buflocal_nr = curbuf->b_fnum;
8679 else if (patlen > 9 && pat[7] == '=')
8680 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008681 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8682 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008683 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008684 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008685 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008686 buflocal_nr = atoi((char *)pat + 8);
8687 }
8688 }
8689
8690 if (is_buflocal)
8691 {
8692 /* normalize pat into standard "<buffer>#N" form */
8693 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8694 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008695 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008696 }
8697
8698 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008699 * Find AutoPat entries with this pattern. When adding a command it
8700 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008701 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008702 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8703 prev_ap = &last_autopat[(int)event];
8704 else
8705 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008706 while ((ap = *prev_ap) != NULL)
8707 {
8708 if (ap->pat != NULL)
8709 {
8710 /* Accept a pattern when:
8711 * - a group was specified and it's that group, or a group was
8712 * not specified and it's the current group, or a group was
8713 * not specified and we are listing
8714 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008715 * - the pattern matches.
8716 * For <buffer[=X]>, this condition works because we normalize
8717 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008718 */
8719 if ((allgroups || ap->group == findgroup)
8720 && ap->patlen == patlen
8721 && STRNCMP(pat, ap->pat, patlen) == 0)
8722 {
8723 /*
8724 * Remove existing autocommands.
8725 * If adding any new autocmd's for this AutoPat, don't
8726 * delete the pattern from the autopat list, append to
8727 * this list.
8728 */
8729 if (forceit)
8730 {
8731 if (*cmd != NUL && ap->next == NULL)
8732 {
8733 au_remove_cmds(ap);
8734 break;
8735 }
8736 au_remove_pat(ap);
8737 }
8738
8739 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008740 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008741 */
8742 else if (*cmd == NUL)
8743 show_autocmd(ap, event);
8744
8745 /*
8746 * Add autocmd to this autopat, if it's the last one.
8747 */
8748 else if (ap->next == NULL)
8749 break;
8750 }
8751 }
8752 prev_ap = &ap->next;
8753 }
8754
8755 /*
8756 * Add a new command.
8757 */
8758 if (*cmd != NUL)
8759 {
8760 /*
8761 * If the pattern we want to add a command to does appear at the
8762 * end of the list (or not is not in the list at all), add the
8763 * pattern at the end of the list.
8764 */
8765 if (ap == NULL)
8766 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008767 /* refuse to add buffer-local ap if buffer number is invalid */
8768 if (is_buflocal && (buflocal_nr == 0
8769 || buflist_findnr(buflocal_nr) == NULL))
8770 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008771 semsg(_("E680: <buffer=%d>: invalid buffer number "),
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008772 buflocal_nr);
8773 return FAIL;
8774 }
8775
Bram Moolenaar071d4272004-06-13 20:20:40 +00008776 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8777 if (ap == NULL)
8778 return FAIL;
8779 ap->pat = vim_strnsave(pat, patlen);
8780 ap->patlen = patlen;
8781 if (ap->pat == NULL)
8782 {
8783 vim_free(ap);
8784 return FAIL;
8785 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008786
8787 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008788 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008789 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008790 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008791 }
8792 else
8793 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008794 char_u *reg_pat;
8795
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008796 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008797 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008798 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008799 if (reg_pat != NULL)
8800 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008801 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008802 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008803 {
8804 vim_free(ap->pat);
8805 vim_free(ap);
8806 return FAIL;
8807 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008808 }
8809 ap->cmds = NULL;
8810 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008811 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812 ap->next = NULL;
8813 if (group == AUGROUP_ALL)
8814 ap->group = current_augroup;
8815 else
8816 ap->group = group;
8817 }
8818
8819 /*
8820 * Add the autocmd at the end of the AutoCmd list.
8821 */
8822 prev_ac = &(ap->cmds);
8823 while ((ac = *prev_ac) != NULL)
8824 prev_ac = &ac->next;
8825 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8826 if (ac == NULL)
8827 return FAIL;
8828 ac->cmd = vim_strsave(cmd);
8829#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02008830 ac->script_ctx = current_sctx;
8831 ac->script_ctx.sc_lnum += sourcing_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832#endif
8833 if (ac->cmd == NULL)
8834 {
8835 vim_free(ac);
8836 return FAIL;
8837 }
8838 ac->next = NULL;
8839 *prev_ac = ac;
8840 ac->nested = nested;
8841 }
8842 }
8843
8844 au_cleanup(); /* may really delete removed patterns/commands now */
8845 return OK;
8846}
8847
8848/*
8849 * Implementation of ":doautocmd [group] event [fname]".
8850 * Return OK for success, FAIL for failure;
8851 */
8852 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008853do_doautocmd(
8854 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008855 int do_msg, /* give message for no matching autocmds? */
8856 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008857{
8858 char_u *fname;
8859 int nothing_done = TRUE;
8860 int group;
8861
Bram Moolenaar1610d052016-06-09 22:53:01 +02008862 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008863 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008864
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865 /*
8866 * Check for a legal group name. If not, use AUGROUP_ALL.
8867 */
8868 group = au_get_grouparg(&arg);
8869 if (arg == NULL) /* out of memory */
8870 return FAIL;
8871
8872 if (*arg == '*')
8873 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008874 emsg(_("E217: Can't execute autocommands for ALL events"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008875 return FAIL;
8876 }
8877
8878 /*
8879 * Scan over the events.
8880 * If we find an illegal name, return here, don't do anything.
8881 */
8882 fname = find_end_event(arg, group != AUGROUP_ALL);
8883 if (fname == NULL)
8884 return FAIL;
8885
8886 fname = skipwhite(fname);
8887
8888 /*
8889 * Loop over the events.
8890 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008891 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008892 if (apply_autocmds_group(event_name2nr(arg, &arg),
8893 fname, NULL, TRUE, group, curbuf, NULL))
8894 nothing_done = FALSE;
8895
8896 if (nothing_done && do_msg)
8897 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008898 if (did_something != NULL)
8899 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008900
8901#ifdef FEAT_EVAL
8902 return aborting() ? FAIL : OK;
8903#else
8904 return OK;
8905#endif
8906}
8907
8908/*
8909 * ":doautoall": execute autocommands for each loaded buffer.
8910 */
8911 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008912ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008913{
8914 int retval;
8915 aco_save_T aco;
8916 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008917 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008918 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008919 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008920 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008921
8922 /*
8923 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8924 * equal to curbuf, but for some buffers there may not be a window.
8925 * So we change the buffer for the current window for a moment. This
8926 * gives problems when the autocommands make changes to the list of
8927 * buffers or windows...
8928 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008929 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008930 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008931 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008932 {
8933 /* find a window for this buffer and save some values */
8934 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008935 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008936
8937 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008938 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008939
Bram Moolenaar1610d052016-06-09 22:53:01 +02008940 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008941 {
8942 /* Execute the modeline settings, but don't set window-local
8943 * options if we are using the current window for another
8944 * buffer. */
8945 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8946 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008947
8948 /* restore the current window */
8949 aucmd_restbuf(&aco);
8950
8951 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008952 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008953 break;
8954 }
8955 }
8956
8957 check_cursor(); /* just in case lines got deleted */
8958}
8959
8960/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008961 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8962 * return TRUE and advance *argp to after it.
8963 * Thus return TRUE when do_modelines() should be called.
8964 */
8965 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008966check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008967{
8968 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8969 {
8970 *argp = skipwhite(*argp + 12);
8971 return FALSE;
8972 }
8973 return TRUE;
8974}
8975
8976/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008977 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008978 * Search for a visible window containing the current buffer. If there isn't
8979 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008980 * Set "curbuf" and "curwin" to match "buf".
8981 */
8982 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008983aucmd_prepbuf(
8984 aco_save_T *aco, /* structure to save values in */
8985 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986{
8987 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008988 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008989#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008990 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008991#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992
8993 /* Find a window that is for the new buffer */
8994 if (buf == curbuf) /* be quick when buf is curbuf */
8995 win = curwin;
8996 else
Bram Moolenaar29323592016-07-24 22:04:11 +02008997 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008998 if (win->w_buffer == buf)
8999 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009000
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009001 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9002 * back to using the current window. */
9003 if (win == NULL && aucmd_win == NULL)
9004 {
9005 win_alloc_aucmd_win();
9006 if (aucmd_win == NULL)
9007 win = curwin;
9008 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009009 if (win == NULL && aucmd_win_used)
9010 /* Strange recursive autocommand, fall back to using the current
9011 * window. Expect a few side effects... */
9012 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009013
9014 aco->save_curwin = curwin;
9015 aco->save_curbuf = curbuf;
Bram Moolenaara42df592018-12-24 00:22:39 +01009016 aco->save_prevwin = prevwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017 if (win != NULL)
9018 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009019 /* There is a window for "buf" in the current tab page, make it the
9020 * curwin. This is preferred, it has the least side effects (esp. if
9021 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009022 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009023 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009024 }
9025 else
9026 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009027 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009028 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009029 * Anything related to a window (e.g., setting folds) may have
9030 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009031 aco->use_aucmd_win = TRUE;
9032 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009033 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009034#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009035 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009036#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009038 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009039
9040 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9041 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009042 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009043 aco->globaldir = globaldir;
9044 globaldir = NULL;
9045
Bram Moolenaar071d4272004-06-13 20:20:40 +00009046
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009047 /* Split the current window, put the aucmd_win in the upper half.
9048 * We don't want the BufEnter or WinEnter autocommands. */
9049 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009050 make_snapshot(SNAP_AUCMD_IDX);
9051 save_ea = p_ea;
9052 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009053
Bram Moolenaar4033c552017-09-16 20:54:51 +02009054#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009055 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9056 save_acd = p_acd;
9057 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009058#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009059
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009060 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9061 (void)win_comp_pos(); /* recompute window positions */
9062 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009063#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009064 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009065#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009066 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009067 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009069 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009070 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009071 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009072}
9073
9074/*
9075 * Cleanup after executing autocommands for a (hidden) buffer.
9076 * Restore the window as it was (if possible).
9077 */
9078 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009079aucmd_restbuf(
9080 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009081{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009082 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009083
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009084 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009085 {
9086 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009087 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009088 * page. Do not trigger autocommands here. */
9089 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009090 if (curwin != aucmd_win)
9091 {
9092 tabpage_T *tp;
9093 win_T *wp;
9094
9095 FOR_ALL_TAB_WINDOWS(tp, wp)
9096 {
9097 if (wp == aucmd_win)
9098 {
9099 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009100 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009101 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009102 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009103 }
9104 }
9105 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009106win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009107
9108 /* Remove the window and frame from the tree of frames. */
9109 (void)winframe_remove(curwin, &dummy, NULL);
9110 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009111 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009112 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009113
9114 if (!valid_tabpage_win(curtab))
9115 /* no valid window in current tabpage */
9116 close_tabpage(curtab);
9117
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009118 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9119 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009120 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009121
9122 if (win_valid(aco->save_curwin))
9123 curwin = aco->save_curwin;
9124 else
9125 /* Hmm, original window disappeared. Just use the first one. */
9126 curwin = firstwin;
Bram Moolenaara42df592018-12-24 00:22:39 +01009127 if (win_valid(aco->save_prevwin))
9128 prevwin = aco->save_prevwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009129#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009130 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9131 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009132#endif
9133 curbuf = curwin->w_buffer;
9134
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009135 vim_free(globaldir);
9136 globaldir = aco->globaldir;
9137
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009138 /* the buffer contents may have changed */
9139 check_cursor();
9140 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9141 {
9142 curwin->w_topline = curbuf->b_ml.ml_line_count;
9143#ifdef FEAT_DIFF
9144 curwin->w_topfill = 0;
9145#endif
9146 }
9147#if defined(FEAT_GUI)
9148 /* Hide the scrollbars from the aucmd_win and update. */
9149 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9150 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9151 gui_may_update_scrollbars();
9152#endif
9153 }
9154 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009155 {
9156 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009157 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009158 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009159 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009160 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009161 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009163 && curbuf != aco->new_curbuf.br_buf
9164 && bufref_valid(&aco->new_curbuf)
9165 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009166 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009167# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9168 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009169 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009170# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009171 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009172 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173 curwin->w_buffer = curbuf;
9174 ++curbuf->b_nwindows;
9175 }
9176
9177 curwin = aco->save_curwin;
9178 curbuf = curwin->w_buffer;
Bram Moolenaara42df592018-12-24 00:22:39 +01009179 if (win_valid(aco->save_prevwin))
9180 prevwin = aco->save_prevwin;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009181 /* In case the autocommand move the cursor to a position that that
9182 * not exist in curbuf. */
9183 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184 }
9185 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009186}
9187
9188static int autocmd_nested = FALSE;
9189
9190/*
9191 * Execute autocommands for "event" and file name "fname".
9192 * Return TRUE if some commands were executed.
9193 */
9194 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009195apply_autocmds(
9196 event_T event,
9197 char_u *fname, /* NULL or empty means use actual file name */
9198 char_u *fname_io, /* fname to use for <afile> on cmdline */
9199 int force, /* when TRUE, ignore autocmd_busy */
9200 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009201{
9202 return apply_autocmds_group(event, fname, fname_io, force,
9203 AUGROUP_ALL, buf, NULL);
9204}
9205
9206/*
9207 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9208 * setting v:filearg.
9209 */
9210 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009211apply_autocmds_exarg(
9212 event_T event,
9213 char_u *fname,
9214 char_u *fname_io,
9215 int force,
9216 buf_T *buf,
9217 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009218{
9219 return apply_autocmds_group(event, fname, fname_io, force,
9220 AUGROUP_ALL, buf, eap);
9221}
9222
9223/*
9224 * Like apply_autocmds(), but handles the caller's retval. If the script
9225 * processing is being aborted or if retval is FAIL when inside a try
9226 * conditional, no autocommands are executed. If otherwise the autocommands
9227 * cause the script to be aborted, retval is set to FAIL.
9228 */
9229 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009230apply_autocmds_retval(
9231 event_T event,
9232 char_u *fname, /* NULL or empty means use actual file name */
9233 char_u *fname_io, /* fname to use for <afile> on cmdline */
9234 int force, /* when TRUE, ignore autocmd_busy */
9235 buf_T *buf, /* buffer for <abuf> */
9236 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237{
9238 int did_cmd;
9239
Bram Moolenaar1e015462005-09-25 22:16:38 +00009240#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009241 if (should_abort(*retval))
9242 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009243#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009244
9245 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9246 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009247 if (did_cmd
9248#ifdef FEAT_EVAL
9249 && aborting()
9250#endif
9251 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009252 *retval = FAIL;
9253 return did_cmd;
9254}
9255
Bram Moolenaard35f9712005-12-18 22:02:33 +00009256/*
9257 * Return TRUE when there is a CursorHold autocommand defined.
9258 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009260has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009261{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009262 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9263 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009264}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009265
9266/*
9267 * Return TRUE if the CursorHold event can be triggered.
9268 */
9269 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009270trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009271{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009272 int state;
9273
Bram Moolenaar05334432011-07-20 18:29:39 +02009274 if (!did_cursorhold
9275 && has_cursorhold()
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02009276 && reg_recording == 0
Bram Moolenaar05334432011-07-20 18:29:39 +02009277 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009278#ifdef FEAT_INS_EXPAND
9279 && !ins_compl_active()
9280#endif
9281 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009282 {
9283 state = get_real_state();
9284 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9285 return TRUE;
9286 }
9287 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009288}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009289
9290/*
9291 * Return TRUE when there is a CursorMoved autocommand defined.
9292 */
9293 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009294has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009295{
9296 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9297}
9298
9299/*
9300 * Return TRUE when there is a CursorMovedI autocommand defined.
9301 */
9302 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009303has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009304{
9305 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9306}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009307
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009308/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009309 * Return TRUE when there is a TextChanged autocommand defined.
9310 */
9311 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009312has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009313{
9314 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9315}
9316
9317/*
9318 * Return TRUE when there is a TextChangedI autocommand defined.
9319 */
9320 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009321has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009322{
9323 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9324}
9325
9326/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009327 * Return TRUE when there is a TextChangedP autocommand defined.
9328 */
9329 int
9330has_textchangedP(void)
9331{
9332 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9333}
9334
9335/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009336 * Return TRUE when there is an InsertCharPre autocommand defined.
9337 */
9338 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009339has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009340{
9341 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9342}
9343
Bram Moolenaard5005162014-08-22 23:05:54 +02009344/*
9345 * Return TRUE when there is an CmdUndefined autocommand defined.
9346 */
9347 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009348has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009349{
9350 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9351}
9352
9353/*
9354 * Return TRUE when there is an FuncUndefined autocommand defined.
9355 */
9356 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009357has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009358{
9359 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9360}
9361
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009362/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009363 * Return TRUE when there is a TextYankPost autocommand defined.
9364 */
9365 int
9366has_textyankpost(void)
9367{
9368 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9369}
9370
9371/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009372 * Execute autocommands for "event" and file name "fname".
9373 * Return TRUE if some commands were executed.
9374 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009375 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009376apply_autocmds_group(
9377 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009378 char_u *fname, /* NULL or empty means use actual file name */
9379 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009380 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009381 int force, /* when TRUE, ignore autocmd_busy */
9382 int group, /* group ID, or AUGROUP_ALL */
9383 buf_T *buf, /* buffer for <abuf> */
9384 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009385{
9386 char_u *sfname = NULL; /* short file name */
9387 char_u *tail;
9388 int save_changed;
9389 buf_T *old_curbuf;
9390 int retval = FALSE;
9391 char_u *save_sourcing_name;
9392 linenr_T save_sourcing_lnum;
9393 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009394 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009395 int save_autocmd_bufnr;
9396 char_u *save_autocmd_match;
9397 int save_autocmd_busy;
9398 int save_autocmd_nested;
9399 static int nesting = 0;
9400 AutoPatCmd patcmd;
9401 AutoPat *ap;
9402#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009403 sctx_T save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009404 funccal_entry_T funccal_entry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009405 char_u *save_cmdarg;
9406 long save_cmdbang;
9407#endif
9408 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009409#ifdef FEAT_PROFILE
9410 proftime_T wait_time;
9411#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009412 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009413 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009414 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009415
9416 /*
9417 * Quickly return if there are no autocommands for this event or
9418 * autocommands are blocked.
9419 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009420 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9421 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009422 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009423
9424 /*
9425 * When autocommands are busy, new autocommands are only executed when
9426 * explicitly enabled with the "nested" flag.
9427 */
9428 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009429 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009430
9431#ifdef FEAT_EVAL
9432 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009433 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 * occurred or an exception was thrown but not caught.
9435 */
9436 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009437 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009438#endif
9439
9440 /*
9441 * FileChangedShell never nests, because it can create an endless loop.
9442 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009443 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9444 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009445 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009446
9447 /*
9448 * Ignore events in 'eventignore'.
9449 */
9450 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009451 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009452
9453 /*
9454 * Allow nesting of autocommands, but restrict the depth, because it's
9455 * possible to create an endless loop.
9456 */
9457 if (nesting == 10)
9458 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009459 emsg(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009460 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009461 }
9462
9463 /*
9464 * Check if these autocommands are disabled. Used when doing ":all" or
9465 * ":ball".
9466 */
9467 if ( (autocmd_no_enter
9468 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9469 || (autocmd_no_leave
9470 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009471 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009472
9473 /*
9474 * Save the autocmd_* variables and info about the current buffer.
9475 */
9476 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009477 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478 save_autocmd_bufnr = autocmd_bufnr;
9479 save_autocmd_match = autocmd_match;
9480 save_autocmd_busy = autocmd_busy;
9481 save_autocmd_nested = autocmd_nested;
9482 save_changed = curbuf->b_changed;
9483 old_curbuf = curbuf;
9484
9485 /*
9486 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009487 * Make a copy to avoid that changing a buffer name or directory makes it
9488 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009489 */
9490 if (fname_io == NULL)
9491 {
Bram Moolenaar60a68362018-04-30 15:40:48 +02009492 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
9493 || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009494 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009495 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009496 autocmd_fname = fname;
9497 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009498 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009499 else
9500 autocmd_fname = NULL;
9501 }
9502 else
9503 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009504 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009505 autocmd_fname = vim_strsave(autocmd_fname);
9506 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009507
9508 /*
9509 * Set the buffer number to be used for <abuf>.
9510 */
9511 if (buf == NULL)
9512 autocmd_bufnr = 0;
9513 else
9514 autocmd_bufnr = buf->b_fnum;
9515
9516 /*
9517 * When the file name is NULL or empty, use the file name of buffer "buf".
9518 * Always use the full path of the file name to match with, in case
9519 * "allow_dirs" is set.
9520 */
9521 if (fname == NULL || *fname == NUL)
9522 {
9523 if (buf == NULL)
9524 fname = NULL;
9525 else
9526 {
9527#ifdef FEAT_SYN_HL
9528 if (event == EVENT_SYNTAX)
9529 fname = buf->b_p_syn;
9530 else
9531#endif
9532 if (event == EVENT_FILETYPE)
9533 fname = buf->b_p_ft;
9534 else
9535 {
9536 if (buf->b_sfname != NULL)
9537 sfname = vim_strsave(buf->b_sfname);
9538 fname = buf->b_ffname;
9539 }
9540 }
9541 if (fname == NULL)
9542 fname = (char_u *)"";
9543 fname = vim_strsave(fname); /* make a copy, so we can change it */
9544 }
9545 else
9546 {
9547 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009548 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009549 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009550 if (event == EVENT_FILETYPE
9551 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009552 || event == EVENT_CMDLINECHANGED
9553 || event == EVENT_CMDLINEENTER
9554 || event == EVENT_CMDLINELEAVE
9555 || event == EVENT_CMDWINENTER
9556 || event == EVENT_CMDWINLEAVE
9557 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009558 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009559 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009560 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009561 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009562 || event == EVENT_COLORSCHEME
Bram Moolenaar60a68362018-04-30 15:40:48 +02009563 || event == EVENT_COLORSCHEMEPRE
Bram Moolenaar53744302015-07-17 17:38:22 +02009564 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009565 || event == EVENT_QUICKFIXCMDPOST
9566 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009567 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009568 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009569 autocmd_fname_full = TRUE; /* don't expand it later */
9570 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009571 else
9572 fname = FullName_save(fname, FALSE);
9573 }
9574 if (fname == NULL) /* out of memory */
9575 {
9576 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009577 retval = FALSE;
9578 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009579 }
9580
9581#ifdef BACKSLASH_IN_FILENAME
9582 /*
9583 * Replace all backslashes with forward slashes. This makes the
9584 * autocommand patterns portable between Unix and MS-DOS.
9585 */
9586 if (sfname != NULL)
9587 forward_slash(sfname);
9588 forward_slash(fname);
9589#endif
9590
9591#ifdef VMS
9592 /* remove version for correct match */
9593 if (sfname != NULL)
9594 vms_remove_version(sfname);
9595 vms_remove_version(fname);
9596#endif
9597
9598 /*
9599 * Set the name to be used for <amatch>.
9600 */
9601 autocmd_match = fname;
9602
9603
Bram Moolenaar8c555332018-06-22 21:30:31 +02009604 /* Don't redraw while doing autocommands. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009605 ++RedrawingDisabled;
9606 save_sourcing_name = sourcing_name;
9607 sourcing_name = NULL; /* don't free this one */
9608 save_sourcing_lnum = sourcing_lnum;
9609 sourcing_lnum = 0; /* no line number here */
9610
9611#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009612 save_current_sctx = current_sctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009613
Bram Moolenaar05159a02005-02-26 23:04:13 +00009614# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009615 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009616 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9617# endif
9618
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009619 // Don't use local function variables, if called from a function.
9620 save_funccal(&funccal_entry);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009621#endif
9622
9623 /*
9624 * When starting to execute autocommands, save the search patterns.
9625 */
9626 if (!autocmd_busy)
9627 {
9628 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009629#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009630 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009631#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009632 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009633 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009634 did_save_redobuff = TRUE;
9635 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009636 did_filetype = keep_filetype;
9637 }
9638
9639 /*
9640 * Note that we are applying autocmds. Some commands need to know.
9641 */
9642 autocmd_busy = TRUE;
9643 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9644 ++nesting; /* see matching decrement below */
9645
9646 /* Remember that FileType was triggered. Used for did_filetype(). */
9647 if (event == EVENT_FILETYPE)
9648 did_filetype = TRUE;
9649
9650 tail = gettail(fname);
9651
9652 /* Find first autocommand that matches */
9653 patcmd.curpat = first_autopat[(int)event];
9654 patcmd.nextcmd = NULL;
9655 patcmd.group = group;
9656 patcmd.fname = fname;
9657 patcmd.sfname = sfname;
9658 patcmd.tail = tail;
9659 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009660 patcmd.arg_bufnr = autocmd_bufnr;
9661 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009662 auto_next_pat(&patcmd, FALSE);
9663
9664 /* found one, start executing the autocommands */
9665 if (patcmd.curpat != NULL)
9666 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009667 /* add to active_apc_list */
9668 patcmd.next = active_apc_list;
9669 active_apc_list = &patcmd;
9670
Bram Moolenaar071d4272004-06-13 20:20:40 +00009671#ifdef FEAT_EVAL
9672 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009673 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009674 if (eap != NULL)
9675 {
9676 save_cmdarg = set_cmdarg(eap, NULL);
9677 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9678 }
9679 else
9680 save_cmdarg = NULL; /* avoid gcc warning */
9681#endif
9682 retval = TRUE;
9683 /* mark the last pattern, to avoid an endless loop when more patterns
9684 * are added when executing autocommands */
9685 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9686 ap->last = FALSE;
9687 ap->last = TRUE;
9688 check_lnums(TRUE); /* make sure cursor and topline are valid */
9689 do_cmdline(NULL, getnextac, (void *)&patcmd,
9690 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9691#ifdef FEAT_EVAL
9692 if (eap != NULL)
9693 {
9694 (void)set_cmdarg(NULL, save_cmdarg);
9695 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9696 }
9697#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009698 /* delete from active_apc_list */
9699 if (active_apc_list == &patcmd) /* just in case */
9700 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009701 }
9702
9703 --RedrawingDisabled;
9704 autocmd_busy = save_autocmd_busy;
9705 filechangeshell_busy = FALSE;
9706 autocmd_nested = save_autocmd_nested;
9707 vim_free(sourcing_name);
9708 sourcing_name = save_sourcing_name;
9709 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009710 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009711 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009712 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009713 autocmd_bufnr = save_autocmd_bufnr;
9714 autocmd_match = save_autocmd_match;
9715#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009716 current_sctx = save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009717 restore_funccal();
Bram Moolenaar05159a02005-02-26 23:04:13 +00009718# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009719 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009720 prof_child_exit(&wait_time);
9721# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009722#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009723 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009724 vim_free(fname);
9725 vim_free(sfname);
9726 --nesting; /* see matching increment above */
9727
9728 /*
9729 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009730 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9731 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009732 */
9733 if (!autocmd_busy)
9734 {
9735 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009736 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009737 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009738 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009739 while (au_pending_free_buf != NULL)
9740 {
9741 buf_T *b = au_pending_free_buf->b_next;
9742 vim_free(au_pending_free_buf);
9743 au_pending_free_buf = b;
9744 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009745 while (au_pending_free_win != NULL)
9746 {
9747 win_T *w = au_pending_free_win->w_next;
9748 vim_free(au_pending_free_win);
9749 au_pending_free_win = w;
9750 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009751 }
9752
9753 /*
9754 * Some events don't set or reset the Changed flag.
9755 * Check if still in the same buffer!
9756 */
9757 if (curbuf == old_curbuf
9758 && (event == EVENT_BUFREADPOST
9759 || event == EVENT_BUFWRITEPOST
9760 || event == EVENT_FILEAPPENDPOST
9761 || event == EVENT_VIMLEAVE
9762 || event == EVENT_VIMLEAVEPRE))
9763 {
9764#ifdef FEAT_TITLE
9765 if (curbuf->b_changed != save_changed)
9766 need_maketitle = TRUE;
9767#endif
9768 curbuf->b_changed = save_changed;
9769 }
9770
9771 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009772
9773BYPASS_AU:
9774 /* When wiping out a buffer make sure all its buffer-local autocommands
9775 * are deleted. */
9776 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9777 aubuflocal_remove(buf);
9778
Bram Moolenaarc3691332016-04-20 12:49:49 +02009779 if (retval == OK && event == EVENT_FILETYPE)
9780 au_did_filetype = TRUE;
9781
Bram Moolenaar071d4272004-06-13 20:20:40 +00009782 return retval;
9783}
9784
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009785# ifdef FEAT_EVAL
9786static char_u *old_termresponse = NULL;
9787# endif
9788
9789/*
9790 * Block triggering autocommands until unblock_autocmd() is called.
9791 * Can be used recursively, so long as it's symmetric.
9792 */
9793 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009794block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009795{
9796# ifdef FEAT_EVAL
9797 /* Remember the value of v:termresponse. */
9798 if (autocmd_blocked == 0)
9799 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9800# endif
9801 ++autocmd_blocked;
9802}
9803
9804 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009805unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009806{
9807 --autocmd_blocked;
9808
9809# ifdef FEAT_EVAL
9810 /* When v:termresponse was set while autocommands were blocked, trigger
9811 * the autocommands now. Esp. useful when executing a shell command
9812 * during startup (vimdiff). */
9813 if (autocmd_blocked == 0
9814 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9815 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9816# endif
9817}
9818
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009819 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009820is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009821{
9822 return autocmd_blocked != 0;
9823}
9824
Bram Moolenaar071d4272004-06-13 20:20:40 +00009825/*
9826 * Find next autocommand pattern that matches.
9827 */
9828 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009829auto_next_pat(
9830 AutoPatCmd *apc,
9831 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009832{
9833 AutoPat *ap;
9834 AutoCmd *cp;
9835 char_u *name;
9836 char *s;
9837
Bram Moolenaard23a8232018-02-10 18:45:26 +01009838 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009839
9840 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9841 {
9842 apc->curpat = NULL;
9843
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009844 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009845 * the group matches. For buffer-local autocommands only check the
9846 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009847 if (ap->pat != NULL && ap->cmds != NULL
9848 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9849 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009850 /* execution-condition */
9851 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009852 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009853 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009854 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009855 {
9856 name = event_nr2name(apc->event);
Bram Moolenaar8c555332018-06-22 21:30:31 +02009857 s = _("%s Autocommands for \"%s\"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009858 sourcing_name = alloc((unsigned)(STRLEN(s)
9859 + STRLEN(name) + ap->patlen + 1));
9860 if (sourcing_name != NULL)
9861 {
9862 sprintf((char *)sourcing_name, s,
9863 (char *)name, (char *)ap->pat);
9864 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009865 {
9866 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009867 smsg(_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009868 verbose_leave();
9869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009870 }
9871
9872 apc->curpat = ap;
9873 apc->nextcmd = ap->cmds;
9874 /* mark last command */
9875 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9876 cp->last = FALSE;
9877 cp->last = TRUE;
9878 }
9879 line_breakcheck();
9880 if (apc->curpat != NULL) /* found a match */
9881 break;
9882 }
9883 if (stop_at_last && ap->last)
9884 break;
9885 }
9886}
9887
9888/*
9889 * Get next autocommand command.
9890 * Called by do_cmdline() to get the next line for ":if".
9891 * Returns allocated string, or NULL for end of autocommands.
9892 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009893 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009894getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009895{
9896 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9897 char_u *retval;
9898 AutoCmd *ac;
9899
9900 /* Can be called again after returning the last line. */
9901 if (acp->curpat == NULL)
9902 return NULL;
9903
9904 /* repeat until we find an autocommand to execute */
9905 for (;;)
9906 {
9907 /* skip removed commands */
9908 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9909 if (acp->nextcmd->last)
9910 acp->nextcmd = NULL;
9911 else
9912 acp->nextcmd = acp->nextcmd->next;
9913
9914 if (acp->nextcmd != NULL)
9915 break;
9916
9917 /* at end of commands, find next pattern that matches */
9918 if (acp->curpat->last)
9919 acp->curpat = NULL;
9920 else
9921 acp->curpat = acp->curpat->next;
9922 if (acp->curpat != NULL)
9923 auto_next_pat(acp, TRUE);
9924 if (acp->curpat == NULL)
9925 return NULL;
9926 }
9927
9928 ac = acp->nextcmd;
9929
9930 if (p_verbose >= 9)
9931 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009932 verbose_enter_scroll();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009933 smsg(_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009934 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009935 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009936 }
9937 retval = vim_strsave(ac->cmd);
9938 autocmd_nested = ac->nested;
9939#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009940 current_sctx = ac->script_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009941#endif
9942 if (ac->last)
9943 acp->nextcmd = NULL;
9944 else
9945 acp->nextcmd = ac->next;
9946 return retval;
9947}
9948
9949/*
9950 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009951 * To account for buffer-local autocommands, function needs to know
9952 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009953 */
9954 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009955has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956{
9957 AutoPat *ap;
9958 char_u *fname;
9959 char_u *tail = gettail(sfname);
9960 int retval = FALSE;
9961
9962 fname = FullName_save(sfname, FALSE);
9963 if (fname == NULL)
9964 return FALSE;
9965
9966#ifdef BACKSLASH_IN_FILENAME
9967 /*
9968 * Replace all backslashes with forward slashes. This makes the
9969 * autocommand patterns portable between Unix and MS-DOS.
9970 */
9971 sfname = vim_strsave(sfname);
9972 if (sfname != NULL)
9973 forward_slash(sfname);
9974 forward_slash(fname);
9975#endif
9976
9977 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9978 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009979 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009980 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009981 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009982 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009983 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009984 {
9985 retval = TRUE;
9986 break;
9987 }
9988
9989 vim_free(fname);
9990#ifdef BACKSLASH_IN_FILENAME
9991 vim_free(sfname);
9992#endif
9993
9994 return retval;
9995}
9996
9997#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9998/*
9999 * Function given to ExpandGeneric() to obtain the list of autocommand group
10000 * names.
10001 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010002 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010003get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010004{
10005 if (idx == augroups.ga_len) /* add "END" add the end */
10006 return (char_u *)"END";
10007 if (idx >= augroups.ga_len) /* end of list */
10008 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010009 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010010 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010011 return (char_u *)"";
10012 return AUGROUP_NAME(idx); /* return a name */
10013}
10014
10015static int include_groups = FALSE;
10016
10017 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010018set_context_in_autocmd(
10019 expand_T *xp,
10020 char_u *arg,
10021 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010022{
10023 char_u *p;
10024 int group;
10025
10026 /* check for a group name, skip it if present */
10027 include_groups = FALSE;
10028 p = arg;
10029 group = au_get_grouparg(&arg);
10030 if (group == AUGROUP_ERROR)
10031 return NULL;
10032 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010033 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010034 {
10035 arg = p;
10036 group = AUGROUP_ALL;
10037 }
10038
10039 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010040 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041 if (*p == ',')
10042 arg = p + 1;
10043 if (*p == NUL)
10044 {
10045 if (group == AUGROUP_ALL)
10046 include_groups = TRUE;
10047 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10048 xp->xp_pattern = arg;
10049 return NULL;
10050 }
10051
10052 /* skip over pattern */
10053 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010054 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010055 arg++;
10056 if (*arg)
10057 return arg; /* expand (next) command */
10058
10059 if (doautocmd)
10060 xp->xp_context = EXPAND_FILES; /* expand file names */
10061 else
10062 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10063 return NULL;
10064}
10065
10066/*
10067 * Function given to ExpandGeneric() to obtain the list of event names.
10068 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010069 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010070get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010071{
10072 if (idx < augroups.ga_len) /* First list group names, if wanted */
10073 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010074 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010075 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010076 return (char_u *)""; /* skip deleted entries */
10077 return AUGROUP_NAME(idx); /* return a name */
10078 }
10079 return (char_u *)event_names[idx - augroups.ga_len].name;
10080}
10081
10082#endif /* FEAT_CMDL_COMPL */
10083
10084/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010085 * Return TRUE if autocmd is supported.
10086 */
10087 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010088autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010089{
10090 char_u *p;
10091
10092 return (event_name2nr(name, &p) != NUM_EVENTS);
10093}
10094
10095/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010096 * Return TRUE if an autocommand is defined for a group, event and
10097 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10098 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10099 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10100 * Used for:
10101 * exists("#Group") or
10102 * exists("#Group#Event") or
10103 * exists("#Group#Event#pat") or
10104 * exists("#Event") or
10105 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010106 */
10107 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010108au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010109{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010110 char_u *arg_save;
10111 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010112 char_u *event_name;
10113 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010114 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010115 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010116 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010117 int group;
10118 int retval = FALSE;
10119
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010120 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010121 arg_save = vim_strsave(arg);
10122 if (arg_save == NULL)
10123 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010124 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010125 if (p != NULL)
10126 *p++ = NUL;
10127
10128 /* First, look for an autocmd group name */
10129 group = au_find_group(arg_save);
10130 if (group == AUGROUP_ERROR)
10131 {
10132 /* Didn't match a group name, assume the first argument is an event. */
10133 group = AUGROUP_ALL;
10134 event_name = arg_save;
10135 }
10136 else
10137 {
10138 if (p == NULL)
10139 {
10140 /* "Group": group name is present and it's recognized */
10141 retval = TRUE;
10142 goto theend;
10143 }
10144
10145 /* Must be "Group#Event" or "Group#Event#pat". */
10146 event_name = p;
10147 p = vim_strchr(event_name, '#');
10148 if (p != NULL)
10149 *p++ = NUL; /* "Group#Event#pat" */
10150 }
10151
10152 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010153
10154 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010155 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010156
10157 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010158 if (event == NUM_EVENTS)
10159 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010160
10161 /* Find the first autocommand for this event.
10162 * If there isn't any, return FALSE;
10163 * If there is one and no pattern given, return TRUE; */
10164 ap = first_autopat[(int)event];
10165 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010166 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010167
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010168 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10169 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010170 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010171 buflocal_buf = curbuf;
10172
Bram Moolenaar071d4272004-06-13 20:20:40 +000010173 /* Check if there is an autocommand with the given pattern. */
10174 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010175 /* only use a pattern when it has not been removed and has commands. */
10176 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010177 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010178 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010179 && (pattern == NULL
10180 || (buflocal_buf == NULL
10181 ? fnamecmp(ap->pat, pattern) == 0
10182 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010183 {
10184 retval = TRUE;
10185 break;
10186 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010187
Bram Moolenaar195d6352005-12-19 22:08:24 +000010188theend:
10189 vim_free(arg_save);
10190 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010192
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010193
10194/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010195 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10196 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10197 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010198 * Used for autocommands and 'wildignore'.
10199 * Returns TRUE if there is a match, FALSE otherwise.
10200 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010201 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010202match_file_pat(
10203 char_u *pattern, /* pattern to match with */
10204 regprog_T **prog, /* pre-compiled regprog or NULL */
10205 char_u *fname, /* full path of file name */
10206 char_u *sfname, /* short file name or NULL */
10207 char_u *tail, /* tail of path */
10208 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010209{
10210 regmatch_T regmatch;
10211 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010212
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010213 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010214 if (prog != NULL)
10215 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010216 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010217 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010218
10219 /*
10220 * Try for a match with the pattern with:
10221 * 1. the full file name, when the pattern has a '/'.
10222 * 2. the short file name, when the pattern has a '/'.
10223 * 3. the tail of the file name, when the pattern has no '/'.
10224 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010225 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010226 && ((allow_dirs
10227 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10228 || (sfname != NULL
10229 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010230 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010231 result = TRUE;
10232
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010233 if (prog != NULL)
10234 *prog = regmatch.regprog;
10235 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010236 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010237 return result;
10238}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010239
10240#if defined(FEAT_WILDIGN) || defined(PROTO)
10241/*
10242 * Return TRUE if a file matches with a pattern in "list".
10243 * "list" is a comma-separated list of patterns, like 'wildignore'.
10244 * "sfname" is the short file name or NULL, "ffname" the long file name.
10245 */
10246 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010247match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010248{
10249 char_u buf[100];
10250 char_u *tail;
10251 char_u *regpat;
10252 char allow_dirs;
10253 int match;
10254 char_u *p;
10255
10256 tail = gettail(sfname);
10257
10258 /* try all patterns in 'wildignore' */
10259 p = list;
10260 while (*p)
10261 {
10262 copy_option_part(&p, buf, 100, ",");
10263 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10264 if (regpat == NULL)
10265 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010266 match = match_file_pat(regpat, NULL, ffname, sfname,
10267 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010268 vim_free(regpat);
10269 if (match)
10270 return TRUE;
10271 }
10272 return FALSE;
10273}
10274#endif
10275
10276/*
10277 * Convert the given pattern "pat" which has shell style wildcards in it, into
10278 * a regular expression, and return the result in allocated memory. If there
10279 * is a directory path separator to be matched, then TRUE is put in
10280 * allow_dirs, otherwise FALSE is put there -- webb.
10281 * Handle backslashes before special characters, like "\*" and "\ ".
10282 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010283 * Returns NULL when out of memory.
10284 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010285 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010286file_pat_to_reg_pat(
10287 char_u *pat,
10288 char_u *pat_end, /* first char after pattern or NULL */
10289 char *allow_dirs, /* Result passed back out in here */
10290 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010291{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010292 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010293 char_u *endp;
10294 char_u *reg_pat;
10295 char_u *p;
10296 int i;
10297 int nested = 0;
10298 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010299
10300 if (allow_dirs != NULL)
10301 *allow_dirs = FALSE;
10302 if (pat_end == NULL)
10303 pat_end = pat + STRLEN(pat);
10304
Bram Moolenaar071d4272004-06-13 20:20:40 +000010305 for (p = pat; p < pat_end; p++)
10306 {
10307 switch (*p)
10308 {
10309 case '*':
10310 case '.':
10311 case ',':
10312 case '{':
10313 case '}':
10314 case '~':
10315 size += 2; /* extra backslash */
10316 break;
10317#ifdef BACKSLASH_IN_FILENAME
10318 case '\\':
10319 case '/':
10320 size += 4; /* could become "[\/]" */
10321 break;
10322#endif
10323 default:
10324 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010325# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010326 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010327 {
10328 ++p;
10329 ++size;
10330 }
10331# endif
10332 break;
10333 }
10334 }
10335 reg_pat = alloc(size + 1);
10336 if (reg_pat == NULL)
10337 return NULL;
10338
Bram Moolenaar071d4272004-06-13 20:20:40 +000010339 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010340
10341 if (pat[0] == '*')
10342 while (pat[0] == '*' && pat < pat_end - 1)
10343 pat++;
10344 else
10345 reg_pat[i++] = '^';
10346 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010347 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010348 {
10349 while (endp - pat > 0 && *endp == '*')
10350 endp--;
10351 add_dollar = FALSE;
10352 }
10353 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10354 {
10355 switch (*p)
10356 {
10357 case '*':
10358 reg_pat[i++] = '.';
10359 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010360 while (p[1] == '*') /* "**" matches like "*" */
10361 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010362 break;
10363 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010364 case '~':
10365 reg_pat[i++] = '\\';
10366 reg_pat[i++] = *p;
10367 break;
10368 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010369 reg_pat[i++] = '.';
10370 break;
10371 case '\\':
10372 if (p[1] == NUL)
10373 break;
10374#ifdef BACKSLASH_IN_FILENAME
10375 if (!no_bslash)
10376 {
10377 /* translate:
10378 * "\x" to "\\x" e.g., "dir\file"
10379 * "\*" to "\\.*" e.g., "dir\*.c"
10380 * "\?" to "\\." e.g., "dir\??.c"
10381 * "\+" to "\+" e.g., "fileX\+.c"
10382 */
10383 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10384 && p[1] != '+')
10385 {
10386 reg_pat[i++] = '[';
10387 reg_pat[i++] = '\\';
10388 reg_pat[i++] = '/';
10389 reg_pat[i++] = ']';
10390 if (allow_dirs != NULL)
10391 *allow_dirs = TRUE;
10392 break;
10393 }
10394 }
10395#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010396 /* Undo escaping from ExpandEscape():
10397 * foo\?bar -> foo?bar
10398 * foo\%bar -> foo%bar
10399 * foo\,bar -> foo,bar
10400 * foo\ bar -> foo bar
10401 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010402 * regexp.
10403 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010404 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010405 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010406 if (*++p == '?'
10407#ifdef BACKSLASH_IN_FILENAME
10408 && no_bslash
10409#endif
10410 )
10411 reg_pat[i++] = '?';
10412 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010413 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010414 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010415 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010416 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10417 {
10418 reg_pat[i++] = '\\';
10419 reg_pat[i++] = '{';
10420 p += 2;
10421 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010422 else
10423 {
10424 if (allow_dirs != NULL && vim_ispathsep(*p)
10425#ifdef BACKSLASH_IN_FILENAME
10426 && (!no_bslash || *p != '\\')
10427#endif
10428 )
10429 *allow_dirs = TRUE;
10430 reg_pat[i++] = '\\';
10431 reg_pat[i++] = *p;
10432 }
10433 break;
10434#ifdef BACKSLASH_IN_FILENAME
10435 case '/':
10436 reg_pat[i++] = '[';
10437 reg_pat[i++] = '\\';
10438 reg_pat[i++] = '/';
10439 reg_pat[i++] = ']';
10440 if (allow_dirs != NULL)
10441 *allow_dirs = TRUE;
10442 break;
10443#endif
10444 case '{':
10445 reg_pat[i++] = '\\';
10446 reg_pat[i++] = '(';
10447 nested++;
10448 break;
10449 case '}':
10450 reg_pat[i++] = '\\';
10451 reg_pat[i++] = ')';
10452 --nested;
10453 break;
10454 case ',':
10455 if (nested)
10456 {
10457 reg_pat[i++] = '\\';
10458 reg_pat[i++] = '|';
10459 }
10460 else
10461 reg_pat[i++] = ',';
10462 break;
10463 default:
10464# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010465 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010466 reg_pat[i++] = *p++;
10467 else
10468# endif
10469 if (allow_dirs != NULL && vim_ispathsep(*p))
10470 *allow_dirs = TRUE;
10471 reg_pat[i++] = *p;
10472 break;
10473 }
10474 }
10475 if (add_dollar)
10476 reg_pat[i++] = '$';
10477 reg_pat[i] = NUL;
10478 if (nested != 0)
10479 {
10480 if (nested < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +010010481 emsg(_("E219: Missing {."));
Bram Moolenaar071d4272004-06-13 20:20:40 +000010482 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +010010483 emsg(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010484 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010485 }
10486 return reg_pat;
10487}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010488
10489#if defined(EINTR) || defined(PROTO)
10490/*
10491 * Version of read() that retries when interrupted by EINTR (possibly
10492 * by a SIGWINCH).
10493 */
10494 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010495read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010496{
10497 long ret;
10498
10499 for (;;)
10500 {
10501 ret = vim_read(fd, buf, bufsize);
10502 if (ret >= 0 || errno != EINTR)
10503 break;
10504 }
10505 return ret;
10506}
10507
10508/*
10509 * Version of write() that retries when interrupted by EINTR (possibly
10510 * by a SIGWINCH).
10511 */
10512 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010513write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010514{
10515 long ret = 0;
10516 long wlen;
10517
10518 /* Repeat the write() so long it didn't fail, other than being interrupted
10519 * by a signal. */
10520 while (ret < (long)bufsize)
10521 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010522 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010523 if (wlen < 0)
10524 {
10525 if (errno != EINTR)
10526 break;
10527 }
10528 else
10529 ret += wlen;
10530 }
10531 return ret;
10532}
10533#endif