blob: 4cb13f27a5e904733ab8fa67d47b8e703f8bf10b [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
Bram Moolenaard25c16e2016-01-29 22:13:30 +010030static char_u *next_fenc(char_u **pp);
Bram Moolenaar13505972019-01-24 15:04:48 +010031#ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010032static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000033#endif
34#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010035static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000036#endif
37#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020038static 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 +000039#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010040static int set_rw_fname(char_u *fname, char_u *sfname);
41static int msg_add_fileformat(int eol_type);
42static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020043static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010044static int time_differs(long t1, long t2);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010045static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
46static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000047
Bram Moolenaar13505972019-01-24 15:04:48 +010048#define AUGROUP_DEFAULT -1 /* default autocmd group */
49#define AUGROUP_ERROR -2 /* erroneous autocmd group */
50#define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000051
Bram Moolenaar13505972019-01-24 15:04:48 +010052#define HAS_BW_FLAGS
53#define FIO_LATIN1 0x01 /* convert Latin1 */
54#define FIO_UTF8 0x02 /* convert UTF-8 */
55#define FIO_UCS2 0x04 /* convert UCS-2 */
56#define FIO_UCS4 0x08 /* convert UCS-4 */
57#define FIO_UTF16 0x10 /* convert UTF-16 */
58#ifdef WIN3264
59# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
60# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
61# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
Bram Moolenaar071d4272004-06-13 20:20:40 +000062#endif
Bram Moolenaar13505972019-01-24 15:04:48 +010063#ifdef MACOS_CONVERT
64# define FIO_MACROMAN 0x20 /* convert MacRoman */
65#endif
66#define FIO_ENDIAN_L 0x80 /* little endian */
67#define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
68#define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
69#define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
70#define FIO_ALL -1 /* allow all formats */
Bram Moolenaar071d4272004-06-13 20:20:40 +000071
72/* When converting, a read() or write() may leave some bytes to be converted
73 * for the next call. The value is guessed... */
74#define CONV_RESTLEN 30
75
76/* We have to guess how much a sequence of bytes may expand when converting
77 * with iconv() to be able to allocate a buffer. */
78#define ICONV_MULT 8
79
80/*
81 * Structure to pass arguments from buf_write() to buf_write_bytes().
82 */
83struct bw_info
84{
85 int bw_fd; /* file descriptor */
86 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000087 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000088#ifdef HAS_BW_FLAGS
89 int bw_flags; /* FIO_ flags */
90#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020091#ifdef FEAT_CRYPT
92 buf_T *bw_buffer; /* buffer being written */
93#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000094 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
95 int bw_restlen; /* nr of bytes in bw_rest[] */
96 int bw_first; /* first write call */
97 char_u *bw_conv_buf; /* buffer for writing converted chars */
98 int bw_conv_buflen; /* size of bw_conv_buf */
99 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000100 linenr_T bw_conv_error_lnum; /* first line with error or zero */
101 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar13505972019-01-24 15:04:48 +0100102#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000103 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104#endif
105};
106
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100107static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100109static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
110static int ucs2bytes(unsigned c, char_u **pp, int flags);
111static int need_conversion(char_u *fenc);
112static int get_fio_flags(char_u *ptr);
113static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
114static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar13505972019-01-24 15:04:48 +0100115#ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100116static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar13505972019-01-24 15:04:48 +0100117#endif
118#ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100119static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000120#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000121static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000122
Bram Moolenaarc3691332016-04-20 12:49:49 +0200123/*
124 * Set by the apply_autocmds_group function if the given event is equal to
125 * EVENT_FILETYPE. Used by the readfile function in order to determine if
126 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
127 *
128 * Relying on this value requires one to reset it prior calling
129 * apply_autocmds_group.
130 */
131static int au_did_filetype INIT(= FALSE);
Bram Moolenaarc3691332016-04-20 12:49:49 +0200132
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100134filemess(
135 buf_T *buf,
136 char_u *name,
137 char_u *s,
138 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000139{
140 int msg_scroll_save;
141
142 if (msg_silent != 0)
143 return;
144 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
145 /* If it's extremely long, truncate it. */
146 if (STRLEN(IObuff) > IOSIZE - 80)
147 IObuff[IOSIZE - 80] = NUL;
148 STRCAT(IObuff, s);
149 /*
150 * For the first message may have to start a new line.
151 * For further ones overwrite the previous one, reset msg_scroll before
152 * calling filemess().
153 */
154 msg_scroll_save = msg_scroll;
155 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
156 msg_scroll = FALSE;
157 if (!msg_scroll) /* wait a bit when overwriting an error msg */
158 check_for_delay(FALSE);
159 msg_start();
160 msg_scroll = msg_scroll_save;
161 msg_scrolled_ign = TRUE;
162 /* may truncate the message to avoid a hit-return prompt */
163 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
164 msg_clr_eos();
165 out_flush();
166 msg_scrolled_ign = FALSE;
167}
168
169/*
170 * Read lines from file "fname" into the buffer after line "from".
171 *
172 * 1. We allocate blocks with lalloc, as big as possible.
173 * 2. Each block is filled with characters from the file with a single read().
174 * 3. The lines are inserted in the buffer with ml_append().
175 *
176 * (caller must check that fname != NULL, unless READ_STDIN is used)
177 *
178 * "lines_to_skip" is the number of lines that must be skipped
179 * "lines_to_read" is the number of lines that are appended
180 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
181 *
182 * flags:
183 * READ_NEW starting to edit a new buffer
184 * READ_FILTER reading filter output
185 * READ_STDIN read from stdin instead of a file
186 * READ_BUFFER read from curbuf instead of a file (converting after reading
187 * stdin)
188 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200189 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200190 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100192 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193 */
194 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100195readfile(
196 char_u *fname,
197 char_u *sfname,
198 linenr_T from,
199 linenr_T lines_to_skip,
200 linenr_T lines_to_read,
201 exarg_T *eap, /* can be NULL! */
202 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203{
204 int fd = 0;
205 int newfile = (flags & READ_NEW);
206 int check_readonly;
207 int filtering = (flags & READ_FILTER);
208 int read_stdin = (flags & READ_STDIN);
209 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200210 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000211 int set_options = newfile || read_buffer
212 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000213 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
214 colnr_T read_buf_col = 0; /* next char to read from this line */
215 char_u c;
216 linenr_T lnum = from;
217 char_u *ptr = NULL; /* pointer into read buffer */
218 char_u *buffer = NULL; /* read buffer */
219 char_u *new_buffer = NULL; /* init to shut up gcc */
220 char_u *line_start = NULL; /* init to shut up gcc */
221 int wasempty; /* buffer was empty before reading */
222 colnr_T len;
223 long size = 0;
224 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200225 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000226 int skip_read = FALSE;
227#ifdef FEAT_CRYPT
228 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200229 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200231#ifdef FEAT_PERSISTENT_UNDO
232 context_sha256_T sha_ctx;
233 int read_undo_file = FALSE;
234#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000235 int split = 0; /* number of split lines */
236#define UNKNOWN 0x0fffffff /* file size is unknown */
237 linenr_T linecnt;
238 int error = FALSE; /* errors encountered */
239 int ff_error = EOL_UNKNOWN; /* file format with errors */
240 long linerest = 0; /* remaining chars in line */
241#ifdef UNIX
242 int perm = 0;
243 int swap_mode = -1; /* protection bits for swap file */
244#else
245 int perm;
246#endif
247 int fileformat = 0; /* end-of-line format */
248 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200249 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250 int file_readonly;
251 linenr_T skip_count = 0;
252 linenr_T read_count = 0;
253 int msg_save = msg_scroll;
254 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
255 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100256 int try_mac;
257 int try_dos;
258 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000259 int file_rewind = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000261 linenr_T conv_error = 0; /* line nr with conversion error */
262 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000263 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
264 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000265 int bad_char_behavior = BAD_REPLACE;
266 /* BAD_KEEP, BAD_DROP or character to
267 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268 char_u *tmpname = NULL; /* name of 'charconvert' output file */
269 int fio_flags = 0;
270 char_u *fenc; /* fileencoding to use */
271 int fenc_alloced; /* fenc_next is in allocated memory */
272 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
273 int advance_fenc = FALSE;
274 long real_size = 0;
Bram Moolenaar13505972019-01-24 15:04:48 +0100275#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
Bram Moolenaar13505972019-01-24 15:04:48 +0100277# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000278 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
279 'charconvert' next */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280# endif
Bram Moolenaar13505972019-01-24 15:04:48 +0100281#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000282 int converted = FALSE; /* TRUE if conversion done */
283 int notconverted = FALSE; /* TRUE if conversion wanted but it
284 wasn't possible */
285 char_u conv_rest[CONV_RESTLEN];
286 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200287 buf_T *old_curbuf;
288 char_u *old_b_ffname;
289 char_u *old_b_fname;
290 int using_b_ffname;
291 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200292
Bram Moolenaarc3691332016-04-20 12:49:49 +0200293 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200294
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100295 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000296
297 /*
298 * If there is no file name yet, use the one for the read file.
299 * BF_NOTEDITED is set to reflect this.
300 * Don't do this for a read from a filter.
301 * Only do this when 'cpoptions' contains the 'f' flag.
302 */
303 if (curbuf->b_ffname == NULL
304 && !filtering
305 && fname != NULL
306 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
307 && !(flags & READ_DUMMY))
308 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000309 if (set_rw_fname(fname, sfname) == FAIL)
310 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311 }
312
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200313 /* Remember the initial values of curbuf, curbuf->b_ffname and
314 * curbuf->b_fname to detect whether they are altered as a result of
315 * executing nasty autocommands. Also check if "fname" and "sfname"
316 * point to one of these values. */
317 old_curbuf = curbuf;
318 old_b_ffname = curbuf->b_ffname;
319 old_b_fname = curbuf->b_fname;
320 using_b_ffname = (fname == curbuf->b_ffname)
321 || (sfname == curbuf->b_ffname);
322 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200323
Bram Moolenaardf177f62005-02-22 08:39:57 +0000324 /* After reading a file the cursor line changes but we don't want to
325 * display the line. */
326 ex_no_reprint = TRUE;
327
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000328 /* don't display the file info for another buffer now */
329 need_fileinfo = FALSE;
330
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 /*
332 * For Unix: Use the short file name whenever possible.
333 * Avoids problems with networks and when directory names are changed.
334 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
335 * another directory, which we don't detect.
336 */
337 if (sfname == NULL)
338 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200339#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 fname = sfname;
341#endif
342
Bram Moolenaar071d4272004-06-13 20:20:40 +0000343 /*
344 * The BufReadCmd and FileReadCmd events intercept the reading process by
345 * executing the associated commands instead.
346 */
347 if (!filtering && !read_stdin && !read_buffer)
348 {
349 pos_T pos;
350
351 pos = curbuf->b_op_start;
352
353 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
354 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
355 curbuf->b_op_start.col = 0;
356
357 if (newfile)
358 {
359 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
360 FALSE, curbuf, eap))
361#ifdef FEAT_EVAL
362 return aborting() ? FAIL : OK;
363#else
364 return OK;
365#endif
366 }
367 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
368 FALSE, NULL, eap))
369#ifdef FEAT_EVAL
370 return aborting() ? FAIL : OK;
371#else
372 return OK;
373#endif
374
375 curbuf->b_op_start = pos;
376 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000377
378 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
379 msg_scroll = FALSE; /* overwrite previous file message */
380 else
381 msg_scroll = TRUE; /* don't overwrite previous file message */
382
383 /*
384 * If the name ends in a path separator, we can't open it. Check here,
385 * because reading the file may actually work, but then creating the swap
386 * file may destroy it! Reported on MS-DOS and Win 95.
387 * If the name is too long we might crash further on, quit here.
388 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000389 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000391 p = fname + STRLEN(fname);
392 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000393 {
394 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
395 msg_end();
396 msg_scroll = msg_save;
397 return FAIL;
398 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399 }
400
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200401 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200403#ifdef UNIX
404 /*
405 * On Unix it is possible to read a directory, so we have to
406 * check for it before the mch_open().
407 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000408 perm = mch_getperm(fname);
409 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410 && !S_ISFIFO(perm) /* ... or fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 && !S_ISSOCK(perm) /* ... or socket */
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000412# ifdef OPEN_CHR_FILES
413 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
414 /* ... or a character special file named /dev/fd/<n> */
415# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 )
417 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100418 int retval = FAIL;
419
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100421 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000422 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100423 retval = NOTDONE;
424 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 else
426 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
427 msg_end();
428 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100429 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200431#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100432#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000433 /*
434 * MS-Windows allows opening a device, but we will probably get stuck
435 * trying to read it.
436 */
437 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
438 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000439 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000440 msg_end();
441 msg_scroll = msg_save;
442 return FAIL;
443 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000444#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200445 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000446
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200447 /* Set default or forced 'fileformat' and 'binary'. */
448 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449
450 /*
451 * When opening a new file we take the readonly flag from the file.
452 * Default is r/w, can be set to r/o below.
453 * Don't reset it when in readonly mode
454 * Only set/reset b_p_ro when BF_CHECK_RO is set.
455 */
456 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000457 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 curbuf->b_p_ro = FALSE;
459
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200460 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200462 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463 if (mch_stat((char *)fname, &st) >= 0)
464 {
465 buf_store_time(curbuf, &st, fname);
466 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467#ifdef UNIX
468 /*
469 * Use the protection bits of the original file for the swap file.
470 * This makes it possible for others to read the name of the
471 * edited file from the swapfile, but only if they can read the
472 * edited file.
473 * Remove the "write" and "execute" bits for group and others
474 * (they must not write the swapfile).
475 * Add the "read" and "write" bits for the user, otherwise we may
476 * not be able to write to the file ourselves.
477 * Setting the bits is done below, after creating the swap file.
478 */
479 swap_mode = (st.st_mode & 0644) | 0600;
480#endif
481#ifdef FEAT_CW_EDITOR
482 /* Get the FSSpec on MacOS
483 * TODO: Update it properly when the buffer name changes
484 */
485 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
486#endif
487#ifdef VMS
488 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000489 curbuf->b_fab_rat = st.st_fab_rat;
490 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491#endif
492 }
493 else
494 {
495 curbuf->b_mtime = 0;
496 curbuf->b_mtime_read = 0;
497 curbuf->b_orig_size = 0;
498 curbuf->b_orig_mode = 0;
499 }
500
501 /* Reset the "new file" flag. It will be set again below when the
502 * file doesn't exist. */
503 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
504 }
505
506/*
507 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100508 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 */
510 file_readonly = FALSE;
511 if (read_stdin)
512 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100513#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
515 setmode(0, O_BINARY);
516#endif
517 }
518 else if (!read_buffer)
519 {
520#ifdef USE_MCH_ACCESS
521 if (
522# ifdef UNIX
523 !(perm & 0222) ||
524# endif
525 mch_access((char *)fname, W_OK))
526 file_readonly = TRUE;
527 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
528#else
529 if (!newfile
530 || readonlymode
531 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
532 {
533 file_readonly = TRUE;
534 /* try to open ro */
535 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
536 }
537#endif
538 }
539
540 if (fd < 0) /* cannot open at all */
541 {
542#ifndef UNIX
543 int isdir_f;
544#endif
545 msg_scroll = msg_save;
546#ifndef UNIX
547 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100548 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 */
550 isdir_f = (mch_isdir(fname));
551 perm = mch_getperm(fname); /* check if the file exists */
552 if (isdir_f)
553 {
554 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
555 curbuf->b_p_ro = TRUE; /* must use "w!" now */
556 }
557 else
558#endif
559 if (newfile)
560 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200561 if (perm < 0
562#ifdef ENOENT
563 && errno == ENOENT
564#endif
565 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 {
567 /*
568 * Set the 'new-file' flag, so that when the file has
569 * been created by someone else, a ":w" will complain.
570 */
571 curbuf->b_flags |= BF_NEW;
572
573 /* Create a swap file now, so that other Vims are warned
574 * that we are editing this file. Don't do this for a
575 * "nofile" or "nowrite" buffer type. */
576#ifdef FEAT_QUICKFIX
577 if (!bt_dontwrite(curbuf))
578#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000579 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000581 /* SwapExists autocommand may mess things up */
582 if (curbuf != old_curbuf
583 || (using_b_ffname
584 && (old_b_ffname != curbuf->b_ffname))
585 || (using_b_fname
586 && (old_b_fname != curbuf->b_fname)))
587 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100588 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000589 return FAIL;
590 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000591 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000592 if (dir_of_file_exists(fname))
593 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
594 else
595 filemess(curbuf, sfname,
596 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597#ifdef FEAT_VIMINFO
598 /* Even though this is a new file, it might have been
599 * edited before and deleted. Get the old marks. */
600 check_marks_read();
601#endif
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200602 /* Set forced 'fileencoding'. */
603 if (eap != NULL)
604 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
606 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 /* remember the current fileformat */
608 save_file_ff(curbuf);
609
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100610#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 if (aborting()) /* autocmds may abort script processing */
612 return FAIL;
613#endif
614 return OK; /* a new file is not an error */
615 }
616 else
617 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000618 filemess(curbuf, sfname, (char_u *)(
619# ifdef EFBIG
620 (errno == EFBIG) ? _("[File too big]") :
621# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200622# ifdef EOVERFLOW
623 (errno == EOVERFLOW) ? _("[File too big]") :
624# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000625 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 curbuf->b_p_ro = TRUE; /* must use "w!" now */
627 }
628 }
629
630 return FAIL;
631 }
632
633 /*
634 * Only set the 'ro' flag for readonly files the first time they are
635 * loaded. Help files always get readonly mode
636 */
637 if ((check_readonly && file_readonly) || curbuf->b_help)
638 curbuf->b_p_ro = TRUE;
639
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000640 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000642 /* Don't change 'eol' if reading from buffer as it will already be
643 * correctly set when reading stdin. */
644 if (!read_buffer)
645 {
646 curbuf->b_p_eol = TRUE;
647 curbuf->b_start_eol = TRUE;
648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000650 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 }
652
653 /* Create a swap file now, so that other Vims are warned that we are
654 * editing this file.
655 * Don't do this for a "nofile" or "nowrite" buffer type. */
656#ifdef FEAT_QUICKFIX
657 if (!bt_dontwrite(curbuf))
658#endif
659 {
660 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000661 if (!read_stdin && (curbuf != old_curbuf
662 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
663 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
664 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100665 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000666 if (!read_buffer)
667 close(fd);
668 return FAIL;
669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670#ifdef UNIX
671 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000672 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
673 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100674 {
675 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
676
677 /*
678 * If the group-read bit is set but not the world-read bit, then
679 * the group must be equal to the group of the original file. If
680 * we can't make that happen then reset the group-read bit. This
681 * avoids making the swap file readable to more users when the
682 * primary group of the user is too permissive.
683 */
684 if ((swap_mode & 044) == 040)
685 {
686 stat_T swap_st;
687
688 if (mch_stat((char *)swap_fname, &swap_st) >= 0
689 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200690# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100691 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200692 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200693# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200694 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100695 swap_mode &= 0600;
696 }
697
698 (void)mch_setperm(swap_fname, (long)swap_mode);
699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700#endif
701 }
702
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000703#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704 /* If "Quit" selected at ATTENTION dialog, don't load the file */
705 if (swap_exists_action == SEA_QUIT)
706 {
707 if (!read_buffer && !read_stdin)
708 close(fd);
709 return FAIL;
710 }
711#endif
712
713 ++no_wait_return; /* don't wait for return yet */
714
715 /*
716 * Set '[ mark to the line above where the lines go (line 1 if zero).
717 */
718 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
719 curbuf->b_op_start.col = 0;
720
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100721 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
722 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
723 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
724
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 if (!read_buffer)
726 {
727 int m = msg_scroll;
728 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729
730 /*
731 * The file must be closed again, the autocommands may want to change
732 * the file before reading it.
733 */
734 if (!read_stdin)
735 close(fd); /* ignore errors */
736
737 /*
738 * The output from the autocommands should not overwrite anything and
739 * should not be overwritten: Set msg_scroll, restore its value if no
740 * output was done.
741 */
742 msg_scroll = TRUE;
743 if (filtering)
744 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
745 FALSE, curbuf, eap);
746 else if (read_stdin)
747 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
748 FALSE, curbuf, eap);
749 else if (newfile)
750 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
751 FALSE, curbuf, eap);
752 else
753 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
754 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100755 /* autocommands may have changed it */
756 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
757 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
758 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
759
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 if (msg_scrolled == n)
761 msg_scroll = m;
762
763#ifdef FEAT_EVAL
764 if (aborting()) /* autocmds may abort script processing */
765 {
766 --no_wait_return;
767 msg_scroll = msg_save;
768 curbuf->b_p_ro = TRUE; /* must use "w!" now */
769 return FAIL;
770 }
771#endif
772 /*
773 * Don't allow the autocommands to change the current buffer.
774 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000775 *
776 * Don't allow the autocommands to change the buffer name either
777 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 */
779 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000780 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
781 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
783 {
784 --no_wait_return;
785 msg_scroll = msg_save;
786 if (fd < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100787 emsg(_("E200: *ReadPre autocommands made the file unreadable"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000788 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100789 emsg(_("E201: *ReadPre autocommands must not change current buffer"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 curbuf->b_p_ro = TRUE; /* must use "w!" now */
791 return FAIL;
792 }
793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794
795 /* Autocommands may add lines to the file, need to check if it is empty */
796 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
797
798 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
799 {
800 /*
801 * Show the user that we are busy reading the input. Sometimes this
802 * may take a while. When reading from stdin another program may
803 * still be running, don't move the cursor to the last line, unless
804 * always using the GUI.
805 */
806 if (read_stdin)
807 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100808 if (!is_not_a_term())
809 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100811 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000812#endif
813#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100814 /* Also write a message in the GUI window, if there is one. */
815 if (gui.in_use && !gui.dying && !gui.starting)
816 {
817 p = (char_u *)_("Reading from stdin...");
818 gui_write(p, (int)STRLEN(p));
819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100821 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000822 }
823 else if (!read_buffer)
824 filemess(curbuf, sfname, (char_u *)"", 0);
825 }
826
827 msg_scroll = FALSE; /* overwrite the file message */
828
829 /*
830 * Set linecnt now, before the "retry" caused by a wrong guess for
831 * fileformat, and after the autocommands, which may change them.
832 */
833 linecnt = curbuf->b_ml.ml_line_count;
834
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000835 /* "++bad=" argument. */
836 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000837 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000838 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000839 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000840 curbuf->b_bad_char = eap->bad_char;
841 }
842 else
843 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000844
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000846 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 */
848 if (eap != NULL && eap->force_enc != 0)
849 {
850 fenc = enc_canonize(eap->cmd + eap->force_enc);
851 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000852 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 }
854 else if (curbuf->b_p_bin)
855 {
856 fenc = (char_u *)""; /* binary: don't convert */
857 fenc_alloced = FALSE;
858 }
859 else if (curbuf->b_help)
860 {
861 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000862 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000863
864 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
865 * fails it must be latin1.
866 * Always do this when 'encoding' is "utf-8". Otherwise only do
867 * this when needed to avoid [converted] remarks all the time.
868 * It is needed when the first line contains non-ASCII characters.
869 * That is only in *.??x files. */
870 fenc = (char_u *)"latin1";
871 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000872 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000874 fc = fname[STRLEN(fname) - 1];
875 if (TOLOWER_ASC(fc) == 'x')
876 {
877 /* Read the first line (and a bit more). Immediately rewind to
878 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100879 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200880 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000881 for (p = firstline; p < firstline + len; ++p)
882 if (*p >= 0x80)
883 {
884 c = TRUE;
885 break;
886 }
887 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 }
889
890 if (c)
891 {
892 fenc_next = fenc;
893 fenc = (char_u *)"utf-8";
894
895 /* When the file is utf-8 but a character doesn't fit in
896 * 'encoding' don't retry. In help text editing utf-8 bytes
897 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000898 if (!enc_utf8)
899 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 }
901 fenc_alloced = FALSE;
902 }
903 else if (*p_fencs == NUL)
904 {
905 fenc = curbuf->b_p_fenc; /* use format from buffer */
906 fenc_alloced = FALSE;
907 }
908 else
909 {
910 fenc_next = p_fencs; /* try items in 'fileencodings' */
911 fenc = next_fenc(&fenc_next);
912 fenc_alloced = TRUE;
913 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914
915 /*
916 * Jump back here to retry reading the file in different ways.
917 * Reasons to retry:
918 * - encoding conversion failed: try another one from "fenc_next"
919 * - BOM detected and fenc was set, need to setup conversion
920 * - "fileformat" check failed: try another
921 *
922 * Variables set for special retry actions:
923 * "file_rewind" Rewind the file to start reading it again.
924 * "advance_fenc" Advance "fenc" using "fenc_next".
925 * "skip_read" Re-use already read bytes (BOM detected).
926 * "did_iconv" iconv() conversion failed, try 'charconvert'.
927 * "keep_fileformat" Don't reset "fileformat".
928 *
929 * Other status indicators:
930 * "tmpname" When != NULL did conversion with 'charconvert'.
931 * Output file has to be deleted afterwards.
932 * "iconv_fd" When != -1 did conversion with iconv().
933 */
934retry:
935
936 if (file_rewind)
937 {
938 if (read_buffer)
939 {
940 read_buf_lnum = 1;
941 read_buf_col = 0;
942 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200943 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944 {
945 /* Can't rewind the file, give up. */
946 error = TRUE;
947 goto failed;
948 }
949 /* Delete the previously read lines. */
950 while (lnum > from)
951 ml_delete(lnum--, FALSE);
952 file_rewind = FALSE;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000953 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000954 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000956 curbuf->b_start_bomb = FALSE;
957 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000958 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 }
960
961 /*
962 * When retrying with another "fenc" and the first time "fileformat"
963 * will be reset.
964 */
965 if (keep_fileformat)
966 keep_fileformat = FALSE;
967 else
968 {
969 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000970 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000972 try_unix = try_dos = try_mac = FALSE;
973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974 else if (curbuf->b_p_bin)
975 fileformat = EOL_UNIX; /* binary: use Unix format */
976 else if (*p_ffs == NUL)
977 fileformat = get_fileformat(curbuf);/* use format from buffer */
978 else
979 fileformat = EOL_UNKNOWN; /* detect from file */
980 }
981
Bram Moolenaar13505972019-01-24 15:04:48 +0100982#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 if (iconv_fd != (iconv_t)-1)
984 {
985 /* aborted conversion with iconv(), close the descriptor */
986 iconv_close(iconv_fd);
987 iconv_fd = (iconv_t)-1;
988 }
Bram Moolenaar13505972019-01-24 15:04:48 +0100989#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990
991 if (advance_fenc)
992 {
993 /*
994 * Try the next entry in 'fileencodings'.
995 */
996 advance_fenc = FALSE;
997
998 if (eap != NULL && eap->force_enc != 0)
999 {
1000 /* Conversion given with "++cc=" wasn't possible, read
1001 * without conversion. */
1002 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001003 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001004 if (fenc_alloced)
1005 vim_free(fenc);
1006 fenc = (char_u *)"";
1007 fenc_alloced = FALSE;
1008 }
1009 else
1010 {
1011 if (fenc_alloced)
1012 vim_free(fenc);
1013 if (fenc_next != NULL)
1014 {
1015 fenc = next_fenc(&fenc_next);
1016 fenc_alloced = (fenc_next != NULL);
1017 }
1018 else
1019 {
1020 fenc = (char_u *)"";
1021 fenc_alloced = FALSE;
1022 }
1023 }
1024 if (tmpname != NULL)
1025 {
1026 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001027 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 }
1029 }
1030
1031 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001032 * Conversion may be required when the encoding of the file is different
1033 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 */
1035 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001036 converted = need_conversion(fenc);
1037 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 {
1039
1040 /* "ucs-bom" means we need to check the first bytes of the file
1041 * for a BOM. */
1042 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1043 fio_flags = FIO_UCSBOM;
1044
1045 /*
1046 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1047 * done. This is handled below after read(). Prepare the
1048 * fio_flags to avoid having to parse the string each time.
1049 * Also check for Unicode to Latin1 conversion, because iconv()
1050 * appears not to handle this correctly. This works just like
1051 * conversion to UTF-8 except how the resulting character is put in
1052 * the buffer.
1053 */
1054 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1055 fio_flags = get_fio_flags(fenc);
1056
Bram Moolenaar13505972019-01-24 15:04:48 +01001057#ifdef WIN3264
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 /*
1059 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1060 * is handled with MultiByteToWideChar().
1061 */
1062 if (fio_flags == 0)
1063 fio_flags = get_win_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001064#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065
Bram Moolenaar13505972019-01-24 15:04:48 +01001066#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1068 if (fio_flags == 0)
1069 fio_flags = get_mac_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001070#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071
Bram Moolenaar13505972019-01-24 15:04:48 +01001072#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 /*
1074 * Try using iconv() if we can't convert internally.
1075 */
1076 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001077# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078 && !did_iconv
Bram Moolenaar13505972019-01-24 15:04:48 +01001079# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 )
1081 iconv_fd = (iconv_t)my_iconv_open(
1082 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001083#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084
Bram Moolenaar13505972019-01-24 15:04:48 +01001085#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 /*
1087 * Use the 'charconvert' expression when conversion is required
1088 * and we can't do it internally or with iconv().
1089 */
1090 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001091 && !read_fifo
Bram Moolenaar13505972019-01-24 15:04:48 +01001092# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001094# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 )
1096 {
Bram Moolenaar13505972019-01-24 15:04:48 +01001097# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 did_iconv = FALSE;
Bram Moolenaar13505972019-01-24 15:04:48 +01001099# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 /* Skip conversion when it's already done (retry for wrong
1101 * "fileformat"). */
1102 if (tmpname == NULL)
1103 {
1104 tmpname = readfile_charconvert(fname, fenc, &fd);
1105 if (tmpname == NULL)
1106 {
1107 /* Conversion failed. Try another one. */
1108 advance_fenc = TRUE;
1109 if (fd < 0)
1110 {
1111 /* Re-opening the original file failed! */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001112 emsg(_("E202: Conversion made file unreadable!"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 error = TRUE;
1114 goto failed;
1115 }
1116 goto retry;
1117 }
1118 }
1119 }
1120 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001121#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 {
1123 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001124#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001126#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127 )
1128 {
1129 /* Conversion wanted but we can't.
1130 * Try the next conversion in 'fileencodings' */
1131 advance_fenc = TRUE;
1132 goto retry;
1133 }
1134 }
1135 }
1136
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001137 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001139 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001140 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141
1142 if (!skip_read)
1143 {
1144 linerest = 0;
1145 filesize = 0;
1146 skip_count = lines_to_skip;
1147 read_count = lines_to_read;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148 conv_restlen = 0;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001149#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001150 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1151 && curbuf->b_ffname != NULL
1152 && curbuf->b_p_udf
1153 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001154 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001155 && !read_stdin
1156 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001157 if (read_undo_file)
1158 sha256_start(&sha_ctx);
1159#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001160#ifdef FEAT_CRYPT
1161 if (curbuf->b_cryptstate != NULL)
1162 {
1163 /* Need to free the state, but keep the key, don't want to ask for
1164 * it again. */
1165 crypt_free_state(curbuf->b_cryptstate);
1166 curbuf->b_cryptstate = NULL;
1167 }
1168#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169 }
1170
1171 while (!error && !got_int)
1172 {
1173 /*
1174 * We allocate as much space for the file as we can get, plus
1175 * space for the old line plus room for one terminating NUL.
1176 * The amount is limited by the fact that read() only can read
1177 * upto max_unsigned characters (and other things).
1178 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001179 if (!skip_read)
1180 {
Bram Moolenaar30276f22019-01-24 17:59:39 +01001181#if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001182 size = SSIZE_MAX; /* use max I/O size, 52K */
Bram Moolenaar30276f22019-01-24 17:59:39 +01001183#else
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001184 /* Use buffer >= 64K. Add linerest to double the size if the
1185 * line gets very long, to avoid a lot of copying. But don't
1186 * read more than 1 Mbyte at a time, so we can be interrupted.
1187 */
1188 size = 0x10000L + linerest;
1189 if (size > 0x100000L)
1190 size = 0x100000L;
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001191#endif
1192 }
1193
1194 /* Protect against the argument of lalloc() going negative. */
Bram Moolenaar30276f22019-01-24 17:59:39 +01001195 if (size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196 {
1197 ++split;
1198 *ptr = NL; /* split line by inserting a NL */
1199 size = 1;
1200 }
1201 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 {
1203 if (!skip_read)
1204 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001205 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206 {
1207 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1208 FALSE)) != NULL)
1209 break;
1210 }
1211 if (new_buffer == NULL)
1212 {
1213 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1214 error = TRUE;
1215 break;
1216 }
1217 if (linerest) /* copy characters from the previous buffer */
1218 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1219 vim_free(buffer);
1220 buffer = new_buffer;
1221 ptr = buffer + linerest;
1222 line_start = buffer;
1223
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224 /* May need room to translate into.
1225 * For iconv() we don't really know the required space, use a
1226 * factor ICONV_MULT.
1227 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1228 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1229 * become up to 4 bytes, size must be multiple of 2
1230 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1231 * multiple of 2
1232 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1233 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001234 real_size = (int)size;
Bram Moolenaar13505972019-01-24 15:04:48 +01001235#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 if (iconv_fd != (iconv_t)-1)
1237 size = size / ICONV_MULT;
1238 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240 if (fio_flags & FIO_LATIN1)
1241 size = size / 2;
1242 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1243 size = (size * 2 / 3) & ~1;
1244 else if (fio_flags & FIO_UCS4)
1245 size = (size * 2 / 3) & ~3;
1246 else if (fio_flags == FIO_UCSBOM)
1247 size = size / ICONV_MULT; /* worst case */
Bram Moolenaar13505972019-01-24 15:04:48 +01001248#ifdef WIN3264
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249 else if (fio_flags & FIO_CODEPAGE)
1250 size = size / ICONV_MULT; /* also worst case */
Bram Moolenaar13505972019-01-24 15:04:48 +01001251#endif
1252#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253 else if (fio_flags & FIO_MACROMAN)
1254 size = size / ICONV_MULT; /* also worst case */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255#endif
1256
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257 if (conv_restlen > 0)
1258 {
1259 /* Insert unconverted bytes from previous line. */
1260 mch_memmove(ptr, conv_rest, conv_restlen);
1261 ptr += conv_restlen;
1262 size -= conv_restlen;
1263 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264
1265 if (read_buffer)
1266 {
1267 /*
1268 * Read bytes from curbuf. Used for converting text read
1269 * from stdin.
1270 */
1271 if (read_buf_lnum > from)
1272 size = 0;
1273 else
1274 {
1275 int n, ni;
1276 long tlen;
1277
1278 tlen = 0;
1279 for (;;)
1280 {
1281 p = ml_get(read_buf_lnum) + read_buf_col;
1282 n = (int)STRLEN(p);
1283 if ((int)tlen + n + 1 > size)
1284 {
1285 /* Filled up to "size", append partial line.
1286 * Change NL to NUL to reverse the effect done
1287 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001288 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 for (ni = 0; ni < n; ++ni)
1290 {
1291 if (p[ni] == NL)
1292 ptr[tlen++] = NUL;
1293 else
1294 ptr[tlen++] = p[ni];
1295 }
1296 read_buf_col += n;
1297 break;
1298 }
1299 else
1300 {
1301 /* Append whole line and new-line. Change NL
1302 * to NUL to reverse the effect done below. */
1303 for (ni = 0; ni < n; ++ni)
1304 {
1305 if (p[ni] == NL)
1306 ptr[tlen++] = NUL;
1307 else
1308 ptr[tlen++] = p[ni];
1309 }
1310 ptr[tlen++] = NL;
1311 read_buf_col = 0;
1312 if (++read_buf_lnum > from)
1313 {
1314 /* When the last line didn't have an
1315 * end-of-line don't add it now either. */
1316 if (!curbuf->b_p_eol)
1317 --tlen;
1318 size = tlen;
1319 break;
1320 }
1321 }
1322 }
1323 }
1324 }
1325 else
1326 {
1327 /*
1328 * Read bytes from the file.
1329 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001330 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 }
1332
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001333#ifdef FEAT_CRYPT
1334 /*
1335 * At start of file: Check for magic number of encryption.
1336 */
1337 if (filesize == 0 && size > 0)
1338 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1339 &filesize, newfile, sfname,
1340 &did_ask_for_key);
1341 /*
1342 * Decrypt the read bytes. This is done before checking for
1343 * EOF because the crypt layer may be buffering.
1344 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001345 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1346 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001347 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001348# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001349 if (crypt_works_inplace(curbuf->b_cryptstate))
1350 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001351# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001352 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
Bram Moolenaar987411d2019-01-18 22:48:34 +01001353# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001354 }
1355 else
1356 {
1357 char_u *newptr = NULL;
1358 int decrypted_size;
1359
1360 decrypted_size = crypt_decode_alloc(
1361 curbuf->b_cryptstate, ptr, size, &newptr);
1362
1363 /* If the crypt layer is buffering, not producing
1364 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001365 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001366 continue;
1367
1368 if (linerest == 0)
1369 {
1370 /* Simple case: reuse returned buffer (may be
1371 * NULL, checked later). */
1372 new_buffer = newptr;
1373 }
1374 else
1375 {
1376 long_u new_size;
1377
1378 /* Need new buffer to add bytes carried over. */
1379 new_size = (long_u)(decrypted_size + linerest + 1);
1380 new_buffer = lalloc(new_size, FALSE);
1381 if (new_buffer == NULL)
1382 {
1383 do_outofmem_msg(new_size);
1384 error = TRUE;
1385 break;
1386 }
1387
1388 mch_memmove(new_buffer, buffer, linerest);
1389 if (newptr != NULL)
1390 mch_memmove(new_buffer + linerest, newptr,
1391 decrypted_size);
1392 }
1393
1394 if (new_buffer != NULL)
1395 {
1396 vim_free(buffer);
1397 buffer = new_buffer;
1398 new_buffer = NULL;
1399 line_start = buffer;
1400 ptr = buffer + linerest;
1401 }
1402 size = decrypted_size;
1403 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01001404# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001405 }
1406#endif
1407
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 if (size <= 0)
1409 {
1410 if (size < 0) /* read error */
1411 error = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001413 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001414 /*
1415 * Reached end-of-file but some trailing bytes could
1416 * not be converted. Truncated file?
1417 */
1418
1419 /* When we did a conversion report an error. */
1420 if (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001421#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001422 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001423#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001424 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001425 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001426 if (can_retry)
1427 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001428 if (conv_error == 0)
1429 conv_error = curbuf->b_ml.ml_line_count
1430 - linecnt + 1;
1431 }
1432 /* Remember the first linenr with an illegal byte */
1433 else if (illegal_byte == 0)
1434 illegal_byte = curbuf->b_ml.ml_line_count
1435 - linecnt + 1;
1436 if (bad_char_behavior == BAD_DROP)
1437 {
1438 *(ptr - conv_restlen) = NUL;
1439 conv_restlen = 0;
1440 }
1441 else
1442 {
1443 /* Replace the trailing bytes with the replacement
1444 * character if we were converting; if we weren't,
1445 * leave the UTF8 checking code to do it, as it
1446 * works slightly differently. */
1447 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001448#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001449 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001450#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001451 ))
1452 {
1453 while (conv_restlen > 0)
1454 {
1455 *(--ptr) = bad_char_behavior;
1456 --conv_restlen;
1457 }
1458 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001459 fio_flags = 0; /* don't convert this */
Bram Moolenaar13505972019-01-24 15:04:48 +01001460#ifdef USE_ICONV
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001461 if (iconv_fd != (iconv_t)-1)
1462 {
1463 iconv_close(iconv_fd);
1464 iconv_fd = (iconv_t)-1;
1465 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001466#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001467 }
1468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 }
1471 skip_read = FALSE;
1472
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 /*
1474 * At start of file (or after crypt magic number): Check for BOM.
1475 * Also check for a BOM for other Unicode encodings, but not after
1476 * converting with 'charconvert' or when a BOM has already been
1477 * found.
1478 */
1479 if ((filesize == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001480#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001481 || (cryptkey != NULL
1482 && filesize == crypt_get_header_len(
1483 crypt_get_method_nr(curbuf)))
Bram Moolenaar13505972019-01-24 15:04:48 +01001484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485 )
1486 && (fio_flags == FIO_UCSBOM
1487 || (!curbuf->b_p_bomb
1488 && tmpname == NULL
1489 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1490 {
1491 char_u *ccname;
1492 int blen;
1493
1494 /* no BOM detection in a short file or in binary mode */
1495 if (size < 2 || curbuf->b_p_bin)
1496 ccname = NULL;
1497 else
1498 ccname = check_for_bom(ptr, size, &blen,
1499 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1500 if (ccname != NULL)
1501 {
1502 /* Remove BOM from the text */
1503 filesize += blen;
1504 size -= blen;
1505 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001506 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001507 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001509 curbuf->b_start_bomb = TRUE;
1510 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 }
1512
1513 if (fio_flags == FIO_UCSBOM)
1514 {
1515 if (ccname == NULL)
1516 {
1517 /* No BOM detected: retry with next encoding. */
1518 advance_fenc = TRUE;
1519 }
1520 else
1521 {
1522 /* BOM detected: set "fenc" and jump back */
1523 if (fenc_alloced)
1524 vim_free(fenc);
1525 fenc = ccname;
1526 fenc_alloced = FALSE;
1527 }
1528 /* retry reading without getting new bytes or rewinding */
1529 skip_read = TRUE;
1530 goto retry;
1531 }
1532 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001533
1534 /* Include not converted bytes. */
1535 ptr -= conv_restlen;
1536 size += conv_restlen;
1537 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 /*
1539 * Break here for a read error or end-of-file.
1540 */
1541 if (size <= 0)
1542 break;
1543
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544
Bram Moolenaar13505972019-01-24 15:04:48 +01001545#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 if (iconv_fd != (iconv_t)-1)
1547 {
1548 /*
1549 * Attempt conversion of the read bytes to 'encoding' using
1550 * iconv().
1551 */
1552 const char *fromp;
1553 char *top;
1554 size_t from_size;
1555 size_t to_size;
1556
1557 fromp = (char *)ptr;
1558 from_size = size;
1559 ptr += size;
1560 top = (char *)ptr;
1561 to_size = real_size - size;
1562
1563 /*
1564 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001565 * another conversion. Except for when there is no
1566 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001568 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1569 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1571 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001572 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001573 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001574 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001575 if (conv_error == 0)
1576 conv_error = readfile_linenr(linecnt,
1577 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001578
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001579 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001580 ++fromp;
1581 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001582 if (bad_char_behavior == BAD_KEEP)
1583 {
1584 *top++ = *(fromp - 1);
1585 --to_size;
1586 }
1587 else if (bad_char_behavior != BAD_DROP)
1588 {
1589 *top++ = bad_char_behavior;
1590 --to_size;
1591 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
1594 if (from_size > 0)
1595 {
1596 /* Some remaining characters, keep them for the next
1597 * round. */
1598 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1599 conv_restlen = (int)from_size;
1600 }
1601
1602 /* move the linerest to before the converted characters */
1603 line_start = ptr - linerest;
1604 mch_memmove(line_start, buffer, (size_t)linerest);
1605 size = (long)((char_u *)top - ptr);
1606 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
Bram Moolenaar13505972019-01-24 15:04:48 +01001609#ifdef WIN3264
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 if (fio_flags & FIO_CODEPAGE)
1611 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001613 WCHAR ucs2buf[3];
1614 int ucs2len;
1615 int codepage = FIO_GET_CP(fio_flags);
1616 int bytelen;
1617 int found_bad;
1618 char replstr[2];
1619
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 /*
1621 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001622 * a codepage, using standard MS-Windows functions. This
1623 * requires two steps:
1624 * 1. convert from 'fileencoding' to ucs-2
1625 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001627 * Because there may be illegal bytes AND an incomplete byte
1628 * sequence at the end, we may have to do the conversion one
1629 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001632 /* Replacement string for WideCharToMultiByte(). */
1633 if (bad_char_behavior > 0)
1634 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 replstr[0] = '?';
1637 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638
1639 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001640 * Move the bytes to the end of the buffer, so that we have
1641 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001643 src = ptr + real_size - size;
1644 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001646 /*
1647 * Do the conversion.
1648 */
1649 dst = ptr;
1650 size = size;
1651 while (size > 0)
1652 {
1653 found_bad = FALSE;
1654
1655# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1656 if (codepage == CP_UTF8)
1657 {
1658 /* Handle CP_UTF8 input ourselves to be able to handle
1659 * trailing bytes properly.
1660 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001661 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001662 if (bytelen > size)
1663 {
1664 /* Only got some bytes of a character. Normally
1665 * it's put in "conv_rest", but if it's too long
1666 * deal with it as if they were illegal bytes. */
1667 if (bytelen <= CONV_RESTLEN)
1668 break;
1669
1670 /* weird overlong byte sequence */
1671 bytelen = size;
1672 found_bad = TRUE;
1673 }
1674 else
1675 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001676 int u8c = utf_ptr2char(src);
1677
Bram Moolenaar86e01082005-12-29 22:45:34 +00001678 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001679 found_bad = TRUE;
1680 ucs2buf[0] = u8c;
1681 ucs2len = 1;
1682 }
1683 }
1684 else
1685# endif
1686 {
1687 /* We don't know how long the byte sequence is, try
1688 * from one to three bytes. */
1689 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1690 ++bytelen)
1691 {
1692 ucs2len = MultiByteToWideChar(codepage,
1693 MB_ERR_INVALID_CHARS,
1694 (LPCSTR)src, bytelen,
1695 ucs2buf, 3);
1696 if (ucs2len > 0)
1697 break;
1698 }
1699 if (ucs2len == 0)
1700 {
1701 /* If we have only one byte then it's probably an
1702 * incomplete byte sequence. Otherwise discard
1703 * one byte as a bad character. */
1704 if (size == 1)
1705 break;
1706 found_bad = TRUE;
1707 bytelen = 1;
1708 }
1709 }
1710
1711 if (!found_bad)
1712 {
1713 int i;
1714
1715 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1716 if (enc_utf8)
1717 {
1718 /* From UCS-2 to UTF-8. Cannot fail. */
1719 for (i = 0; i < ucs2len; ++i)
1720 dst += utf_char2bytes(ucs2buf[i], dst);
1721 }
1722 else
1723 {
1724 BOOL bad = FALSE;
1725 int dstlen;
1726
1727 /* From UCS-2 to "enc_codepage". If the
1728 * conversion uses the default character "?",
1729 * the data doesn't fit in this encoding. */
1730 dstlen = WideCharToMultiByte(enc_codepage, 0,
1731 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001732 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001733 replstr, &bad);
1734 if (bad)
1735 found_bad = TRUE;
1736 else
1737 dst += dstlen;
1738 }
1739 }
1740
1741 if (found_bad)
1742 {
1743 /* Deal with bytes we can't convert. */
1744 if (can_retry)
1745 goto rewind_retry;
1746 if (conv_error == 0)
1747 conv_error = readfile_linenr(linecnt, ptr, dst);
1748 if (bad_char_behavior != BAD_DROP)
1749 {
1750 if (bad_char_behavior == BAD_KEEP)
1751 {
1752 mch_memmove(dst, src, bytelen);
1753 dst += bytelen;
1754 }
1755 else
1756 *dst++ = bad_char_behavior;
1757 }
1758 }
1759
1760 src += bytelen;
1761 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001763
1764 if (size > 0)
1765 {
1766 /* An incomplete byte sequence remaining. */
1767 mch_memmove(conv_rest, src, size);
1768 conv_restlen = size;
1769 }
1770
1771 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001772 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 }
1774 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001775#endif
1776#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 if (fio_flags & FIO_MACROMAN)
1778 {
1779 /*
1780 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001781 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001783 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785 }
1786 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001787#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 if (fio_flags != 0)
1789 {
1790 int u8c;
1791 char_u *dest;
1792 char_u *tail = NULL;
1793
1794 /*
1795 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1796 * "enc_utf8" not set: Convert Unicode to Latin1.
1797 * Go from end to start through the buffer, because the number
1798 * of bytes may increase.
1799 * "dest" points to after where the UTF-8 bytes go, "p" points
1800 * to after the next character to convert.
1801 */
1802 dest = ptr + real_size;
1803 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1804 {
1805 p = ptr + size;
1806 if (fio_flags == FIO_UTF8)
1807 {
1808 /* Check for a trailing incomplete UTF-8 sequence */
1809 tail = ptr + size - 1;
1810 while (tail > ptr && (*tail & 0xc0) == 0x80)
1811 --tail;
1812 if (tail + utf_byte2len(*tail) <= ptr + size)
1813 tail = NULL;
1814 else
1815 p = tail;
1816 }
1817 }
1818 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1819 {
1820 /* Check for a trailing byte */
1821 p = ptr + (size & ~1);
1822 if (size & 1)
1823 tail = p;
1824 if ((fio_flags & FIO_UTF16) && p > ptr)
1825 {
1826 /* Check for a trailing leading word */
1827 if (fio_flags & FIO_ENDIAN_L)
1828 {
1829 u8c = (*--p << 8);
1830 u8c += *--p;
1831 }
1832 else
1833 {
1834 u8c = *--p;
1835 u8c += (*--p << 8);
1836 }
1837 if (u8c >= 0xd800 && u8c <= 0xdbff)
1838 tail = p;
1839 else
1840 p += 2;
1841 }
1842 }
1843 else /* FIO_UCS4 */
1844 {
1845 /* Check for trailing 1, 2 or 3 bytes */
1846 p = ptr + (size & ~3);
1847 if (size & 3)
1848 tail = p;
1849 }
1850
1851 /* If there is a trailing incomplete sequence move it to
1852 * conv_rest[]. */
1853 if (tail != NULL)
1854 {
1855 conv_restlen = (int)((ptr + size) - tail);
1856 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1857 size -= conv_restlen;
1858 }
1859
1860
1861 while (p > ptr)
1862 {
1863 if (fio_flags & FIO_LATIN1)
1864 u8c = *--p;
1865 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1866 {
1867 if (fio_flags & FIO_ENDIAN_L)
1868 {
1869 u8c = (*--p << 8);
1870 u8c += *--p;
1871 }
1872 else
1873 {
1874 u8c = *--p;
1875 u8c += (*--p << 8);
1876 }
1877 if ((fio_flags & FIO_UTF16)
1878 && u8c >= 0xdc00 && u8c <= 0xdfff)
1879 {
1880 int u16c;
1881
1882 if (p == ptr)
1883 {
1884 /* Missing leading word. */
1885 if (can_retry)
1886 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001887 if (conv_error == 0)
1888 conv_error = readfile_linenr(linecnt,
1889 ptr, p);
1890 if (bad_char_behavior == BAD_DROP)
1891 continue;
1892 if (bad_char_behavior != BAD_KEEP)
1893 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 }
1895
1896 /* found second word of double-word, get the first
1897 * word and compute the resulting character */
1898 if (fio_flags & FIO_ENDIAN_L)
1899 {
1900 u16c = (*--p << 8);
1901 u16c += *--p;
1902 }
1903 else
1904 {
1905 u16c = *--p;
1906 u16c += (*--p << 8);
1907 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001908 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1909 + (u8c & 0x3ff);
1910
Bram Moolenaar071d4272004-06-13 20:20:40 +00001911 /* Check if the word is indeed a leading word. */
1912 if (u16c < 0xd800 || u16c > 0xdbff)
1913 {
1914 if (can_retry)
1915 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001916 if (conv_error == 0)
1917 conv_error = readfile_linenr(linecnt,
1918 ptr, p);
1919 if (bad_char_behavior == BAD_DROP)
1920 continue;
1921 if (bad_char_behavior != BAD_KEEP)
1922 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 }
1925 }
1926 else if (fio_flags & FIO_UCS4)
1927 {
1928 if (fio_flags & FIO_ENDIAN_L)
1929 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001930 u8c = (unsigned)*--p << 24;
1931 u8c += (unsigned)*--p << 16;
1932 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 u8c += *--p;
1934 }
1935 else /* big endian */
1936 {
1937 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001938 u8c += (unsigned)*--p << 8;
1939 u8c += (unsigned)*--p << 16;
1940 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 }
1942 }
1943 else /* UTF-8 */
1944 {
1945 if (*--p < 0x80)
1946 u8c = *p;
1947 else
1948 {
1949 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001950 p -= len;
1951 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 if (len == 0)
1953 {
1954 /* Not a valid UTF-8 character, retry with
1955 * another fenc when possible, otherwise just
1956 * report the error. */
1957 if (can_retry)
1958 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001959 if (conv_error == 0)
1960 conv_error = readfile_linenr(linecnt,
1961 ptr, p);
1962 if (bad_char_behavior == BAD_DROP)
1963 continue;
1964 if (bad_char_behavior != BAD_KEEP)
1965 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 }
1968 }
1969 if (enc_utf8) /* produce UTF-8 */
1970 {
1971 dest -= utf_char2len(u8c);
1972 (void)utf_char2bytes(u8c, dest);
1973 }
1974 else /* produce Latin1 */
1975 {
1976 --dest;
1977 if (u8c >= 0x100)
1978 {
1979 /* character doesn't fit in latin1, retry with
1980 * another fenc when possible, otherwise just
1981 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001982 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001983 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001984 if (conv_error == 0)
1985 conv_error = readfile_linenr(linecnt, ptr, p);
1986 if (bad_char_behavior == BAD_DROP)
1987 ++dest;
1988 else if (bad_char_behavior == BAD_KEEP)
1989 *dest = u8c;
1990 else if (eap != NULL && eap->bad_char != 0)
1991 *dest = bad_char_behavior;
1992 else
1993 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 }
1995 else
1996 *dest = u8c;
1997 }
1998 }
1999
2000 /* move the linerest to before the converted characters */
2001 line_start = dest - linerest;
2002 mch_memmove(line_start, buffer, (size_t)linerest);
2003 size = (long)((ptr + real_size) - dest);
2004 ptr = dest;
2005 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002006 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002008 int incomplete_tail = FALSE;
2009
2010 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2011 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002013 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002014 int l;
2015
2016 if (todo <= 0)
2017 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 if (*p >= 0x80)
2019 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 /* A length of 1 means it's an illegal byte. Accept
2021 * an incomplete character at the end though, the next
2022 * read() will get the next bytes, we'll check it
2023 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002024 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002025 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002027 /* Avoid retrying with a different encoding when
2028 * a truncated file is more likely, or attempting
2029 * to read the rest of an incomplete sequence when
2030 * we have already done so. */
2031 if (p > ptr || filesize > 0)
2032 incomplete_tail = TRUE;
2033 /* Incomplete byte sequence, move it to conv_rest[]
2034 * and try to read the rest of it, unless we've
2035 * already done so. */
2036 if (p > ptr)
2037 {
2038 conv_restlen = todo;
2039 mch_memmove(conv_rest, p, conv_restlen);
2040 size -= conv_restlen;
2041 break;
2042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002044 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002045 {
2046 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002047 * do that, unless at EOF where a truncated
2048 * file is more likely than a conversion error. */
2049 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002050 break;
Bram Moolenaar13505972019-01-24 15:04:48 +01002051#ifdef USE_ICONV
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002052 /* When we did a conversion report an error. */
2053 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2054 conv_error = readfile_linenr(linecnt, ptr, p);
Bram Moolenaar13505972019-01-24 15:04:48 +01002055#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002056 /* Remember the first linenr with an illegal byte */
2057 if (conv_error == 0 && illegal_byte == 0)
2058 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002059
2060 /* Drop, keep or replace the bad byte. */
2061 if (bad_char_behavior == BAD_DROP)
2062 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002063 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002064 --p;
2065 --size;
2066 }
2067 else if (bad_char_behavior != BAD_KEEP)
2068 *p = bad_char_behavior;
2069 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002070 else
2071 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 }
2073 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002074 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 {
2076 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 /* Retry reading with another conversion. */
Bram Moolenaar13505972019-01-24 15:04:48 +01002079#if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002080 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2081 /* iconv() failed, try 'charconvert' */
2082 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 else
Bram Moolenaar13505972019-01-24 15:04:48 +01002084#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002085 /* use next item from 'fileencodings' */
2086 advance_fenc = TRUE;
2087 file_rewind = TRUE;
2088 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 }
2090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091
2092 /* count the number of characters (after conversion!) */
2093 filesize += size;
2094
2095 /*
2096 * when reading the first part of a file: guess EOL type
2097 */
2098 if (fileformat == EOL_UNKNOWN)
2099 {
2100 /* First try finding a NL, for Dos and Unix */
2101 if (try_dos || try_unix)
2102 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002103 /* Reset the carriage return counter. */
2104 if (try_mac)
2105 try_mac = 1;
2106
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107 for (p = ptr; p < ptr + size; ++p)
2108 {
2109 if (*p == NL)
2110 {
2111 if (!try_unix
2112 || (try_dos && p > ptr && p[-1] == CAR))
2113 fileformat = EOL_DOS;
2114 else
2115 fileformat = EOL_UNIX;
2116 break;
2117 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002118 else if (*p == CAR && try_mac)
2119 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 }
2121
2122 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2123 if (fileformat == EOL_UNIX && try_mac)
2124 {
2125 /* Need to reset the counters when retrying fenc. */
2126 try_mac = 1;
2127 try_unix = 1;
2128 for (; p >= ptr && *p != CAR; p--)
2129 ;
2130 if (p >= ptr)
2131 {
2132 for (p = ptr; p < ptr + size; ++p)
2133 {
2134 if (*p == NL)
2135 try_unix++;
2136 else if (*p == CAR)
2137 try_mac++;
2138 }
2139 if (try_mac > try_unix)
2140 fileformat = EOL_MAC;
2141 }
2142 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002143 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2144 /* Looking for CR but found no end-of-line markers at
2145 * all: use the default format. */
2146 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147 }
2148
2149 /* No NL found: may use Mac format */
2150 if (fileformat == EOL_UNKNOWN && try_mac)
2151 fileformat = EOL_MAC;
2152
2153 /* Still nothing found? Use first format in 'ffs' */
2154 if (fileformat == EOL_UNKNOWN)
2155 fileformat = default_fileformat();
2156
2157 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002158 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159 set_fileformat(fileformat, OPT_LOCAL);
2160 }
2161 }
2162
2163 /*
2164 * This loop is executed once for every character read.
2165 * Keep it fast!
2166 */
2167 if (fileformat == EOL_MAC)
2168 {
2169 --ptr;
2170 while (++ptr, --size >= 0)
2171 {
2172 /* catch most common case first */
2173 if ((c = *ptr) != NUL && c != CAR && c != NL)
2174 continue;
2175 if (c == NUL)
2176 *ptr = NL; /* NULs are replaced by newlines! */
2177 else if (c == NL)
2178 *ptr = CAR; /* NLs are replaced by CRs! */
2179 else
2180 {
2181 if (skip_count == 0)
2182 {
2183 *ptr = NUL; /* end of line */
2184 len = (colnr_T) (ptr - line_start + 1);
2185 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2186 {
2187 error = TRUE;
2188 break;
2189 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002190#ifdef FEAT_PERSISTENT_UNDO
2191 if (read_undo_file)
2192 sha256_update(&sha_ctx, line_start, len);
2193#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 ++lnum;
2195 if (--read_count == 0)
2196 {
2197 error = TRUE; /* break loop */
2198 line_start = ptr; /* nothing left to write */
2199 break;
2200 }
2201 }
2202 else
2203 --skip_count;
2204 line_start = ptr + 1;
2205 }
2206 }
2207 }
2208 else
2209 {
2210 --ptr;
2211 while (++ptr, --size >= 0)
2212 {
2213 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2214 continue;
2215 if (c == NUL)
2216 *ptr = NL; /* NULs are replaced by newlines! */
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 (fileformat == EOL_DOS)
2224 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002225 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002227 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 ptr[-1] = NUL;
2229 --len;
2230 }
2231 /*
2232 * Reading in Dos format, but no CR-LF found!
2233 * When 'fileformats' includes "unix", delete all
2234 * the lines read so far and start all over again.
2235 * Otherwise give an error message later.
2236 */
2237 else if (ff_error != EOL_DOS)
2238 {
2239 if ( try_unix
2240 && !read_stdin
2241 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002242 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2243 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 {
2245 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002246 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 set_fileformat(EOL_UNIX, OPT_LOCAL);
2248 file_rewind = TRUE;
2249 keep_fileformat = TRUE;
2250 goto retry;
2251 }
2252 ff_error = EOL_DOS;
2253 }
2254 }
2255 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2256 {
2257 error = TRUE;
2258 break;
2259 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002260#ifdef FEAT_PERSISTENT_UNDO
2261 if (read_undo_file)
2262 sha256_update(&sha_ctx, line_start, len);
2263#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 ++lnum;
2265 if (--read_count == 0)
2266 {
2267 error = TRUE; /* break loop */
2268 line_start = ptr; /* nothing left to write */
2269 break;
2270 }
2271 }
2272 else
2273 --skip_count;
2274 line_start = ptr + 1;
2275 }
2276 }
2277 }
2278 linerest = (long)(ptr - line_start);
2279 ui_breakcheck();
2280 }
2281
2282failed:
2283 /* not an error, max. number of lines reached */
2284 if (error && read_count == 0)
2285 error = FALSE;
2286
2287 /*
2288 * If we get EOF in the middle of a line, note the fact and
2289 * complete the line ourselves.
2290 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2291 */
2292 if (!error
2293 && !got_int
2294 && linerest != 0
2295 && !(!curbuf->b_p_bin
2296 && fileformat == EOL_DOS
2297 && *line_start == Ctrl_Z
2298 && ptr == line_start + 1))
2299 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002300 /* remember for when writing */
2301 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 curbuf->b_p_eol = FALSE;
2303 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002304 len = (colnr_T)(ptr - line_start + 1);
2305 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 error = TRUE;
2307 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002308 {
2309#ifdef FEAT_PERSISTENT_UNDO
2310 if (read_undo_file)
2311 sha256_update(&sha_ctx, line_start, len);
2312#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002314 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 }
2316
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002317 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 save_file_ff(curbuf); /* remember the current file format */
2319
2320#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002321 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002322 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002323 crypt_free_state(curbuf->b_cryptstate);
2324 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002325 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002326 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2327 crypt_free_key(cryptkey);
2328 /* Don't set cryptkey to NULL, it's used below as a flag that
2329 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330#endif
2331
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002332 /* If editing a new file: set 'fenc' for the current buffer.
2333 * Also for ":read ++edit file". */
2334 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002336 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 if (fenc_alloced)
2338 vim_free(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01002339#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 if (iconv_fd != (iconv_t)-1)
2341 {
2342 iconv_close(iconv_fd);
2343 iconv_fd = (iconv_t)-1;
2344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345#endif
2346
2347 if (!read_buffer && !read_stdin)
2348 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002349#ifdef HAVE_FD_CLOEXEC
2350 else
2351 {
2352 int fdflags = fcntl(fd, F_GETFD);
2353 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002354 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002355 }
2356#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 vim_free(buffer);
2358
2359#ifdef HAVE_DUP
2360 if (read_stdin)
2361 {
2362 /* Use stderr for stdin, makes shell commands work. */
2363 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002364 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 }
2366#endif
2367
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 if (tmpname != NULL)
2369 {
2370 mch_remove(tmpname); /* delete converted file */
2371 vim_free(tmpname);
2372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 --no_wait_return; /* may wait for return now */
2374
2375 /*
2376 * In recovery mode everything but autocommands is skipped.
2377 */
2378 if (!recoverymode)
2379 {
2380 /* need to delete the last line, which comes from the empty buffer */
2381 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2382 {
2383#ifdef FEAT_NETBEANS_INTG
2384 netbeansFireChanges = 0;
2385#endif
2386 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2387#ifdef FEAT_NETBEANS_INTG
2388 netbeansFireChanges = 1;
2389#endif
2390 --linecnt;
2391 }
2392 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2393 if (filesize == 0)
2394 linecnt = 0;
2395 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002396 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002398#ifdef FEAT_DIFF
2399 /* After reading the text into the buffer the diff info needs to
2400 * be updated. */
2401 diff_invalidate(curbuf);
2402#endif
2403#ifdef FEAT_FOLDING
2404 /* All folds in the window are invalid now. Mark them for update
2405 * before triggering autocommands. */
2406 foldUpdateAll(curwin);
2407#endif
2408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 else if (linecnt) /* appended at least one line */
2410 appended_lines_mark(from, linecnt);
2411
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412#ifndef ALWAYS_USE_GUI
2413 /*
2414 * If we were reading from the same terminal as where messages go,
2415 * the screen will have been messed up.
2416 * Switch on raw mode now and clear the screen.
2417 */
2418 if (read_stdin)
2419 {
2420 settmode(TMODE_RAW); /* set to raw mode */
2421 starttermcap();
2422 screenclear();
2423 }
2424#endif
2425
2426 if (got_int)
2427 {
2428 if (!(flags & READ_DUMMY))
2429 {
2430 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2431 if (newfile)
2432 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2433 }
2434 msg_scroll = msg_save;
2435#ifdef FEAT_VIMINFO
2436 check_marks_read();
2437#endif
2438 return OK; /* an interrupt isn't really an error */
2439 }
2440
2441 if (!filtering && !(flags & READ_DUMMY))
2442 {
2443 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2444 c = FALSE;
2445
2446#ifdef UNIX
Bram Moolenaard569bb02018-08-11 13:57:20 +02002447 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 {
2449 STRCAT(IObuff, _("[fifo]"));
2450 c = TRUE;
2451 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002452 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 {
2454 STRCAT(IObuff, _("[socket]"));
2455 c = TRUE;
2456 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002457# ifdef OPEN_CHR_FILES
2458 if (S_ISCHR(perm)) /* or character special */
2459 {
2460 STRCAT(IObuff, _("[character special]"));
2461 c = TRUE;
2462 }
2463# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464#endif
2465 if (curbuf->b_p_ro)
2466 {
2467 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2468 c = TRUE;
2469 }
2470 if (read_no_eol_lnum)
2471 {
2472 msg_add_eol();
2473 c = TRUE;
2474 }
2475 if (ff_error == EOL_DOS)
2476 {
2477 STRCAT(IObuff, _("[CR missing]"));
2478 c = TRUE;
2479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 if (split)
2481 {
2482 STRCAT(IObuff, _("[long lines split]"));
2483 c = TRUE;
2484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 if (notconverted)
2486 {
2487 STRCAT(IObuff, _("[NOT converted]"));
2488 c = TRUE;
2489 }
2490 else if (converted)
2491 {
2492 STRCAT(IObuff, _("[converted]"));
2493 c = TRUE;
2494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495#ifdef FEAT_CRYPT
2496 if (cryptkey != NULL)
2497 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002498 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 c = TRUE;
2500 }
2501#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002502 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002504 sprintf((char *)IObuff + STRLEN(IObuff),
2505 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506 c = TRUE;
2507 }
2508 else if (illegal_byte > 0)
2509 {
2510 sprintf((char *)IObuff + STRLEN(IObuff),
2511 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2512 c = TRUE;
2513 }
Bram Moolenaar13505972019-01-24 15:04:48 +01002514 else if (error)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 {
2516 STRCAT(IObuff, _("[READ ERRORS]"));
2517 c = TRUE;
2518 }
2519 if (msg_add_fileformat(fileformat))
2520 c = TRUE;
2521#ifdef FEAT_CRYPT
2522 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002523 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002524 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 else
2526#endif
2527 msg_add_lines(c, (long)linecnt, filesize);
2528
Bram Moolenaard23a8232018-02-10 18:45:26 +01002529 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 msg_scrolled_ign = TRUE;
2531#ifdef ALWAYS_USE_GUI
2532 /* Don't show the message when reading stdin, it would end up in a
2533 * message box (which might be shown when exiting!) */
2534 if (read_stdin || read_buffer)
2535 p = msg_may_trunc(FALSE, IObuff);
2536 else
2537#endif
Bram Moolenaar32526b32019-01-19 17:43:09 +01002538 p = (char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002540 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 /* Need to repeat the message after redrawing when:
2542 * - When reading from stdin (the screen will be cleared next).
2543 * - When restart_edit is set (otherwise there will be a delay
2544 * before redrawing).
2545 * - When the screen was scrolled but there is no wait-return
2546 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002547 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 msg_scrolled_ign = FALSE;
2549 }
2550
2551 /* with errors writing the file requires ":w!" */
2552 if (newfile && (error
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002553 || conv_error != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01002554 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 curbuf->b_p_ro = TRUE;
2556
2557 u_clearline(); /* cannot use "U" command after adding lines */
2558
2559 /*
2560 * In Ex mode: cursor at last new line.
2561 * Otherwise: cursor at first new line.
2562 */
2563 if (exmode_active)
2564 curwin->w_cursor.lnum = from + linecnt;
2565 else
2566 curwin->w_cursor.lnum = from + 1;
2567 check_cursor_lnum();
2568 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2569
2570 /*
2571 * Set '[ and '] marks to the newly read lines.
2572 */
2573 curbuf->b_op_start.lnum = from + 1;
2574 curbuf->b_op_start.col = 0;
2575 curbuf->b_op_end.lnum = from + linecnt;
2576 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002577
2578#ifdef WIN32
2579 /*
2580 * Work around a weird problem: When a file has two links (only
2581 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002582 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002583 * It's correct again after reading the file, thus reset the timestamp
2584 * here.
2585 */
2586 if (newfile && !read_stdin && !read_buffer
2587 && mch_stat((char *)fname, &st) >= 0)
2588 {
2589 buf_store_time(curbuf, &st, fname);
2590 curbuf->b_mtime_read = curbuf->b_mtime;
2591 }
2592#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 }
2594 msg_scroll = msg_save;
2595
2596#ifdef FEAT_VIMINFO
2597 /*
2598 * Get the marks before executing autocommands, so they can be used there.
2599 */
2600 check_marks_read();
2601#endif
2602
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002604 * We remember if the last line of the read didn't have
2605 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2606 * or writing the read again with 'binary' on. The latter is required
2607 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002609 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002611 /* When reloading a buffer put the cursor at the first line that is
2612 * different. */
2613 if (flags & READ_KEEP_UNDO)
2614 u_find_first_changed();
2615
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002616#ifdef FEAT_PERSISTENT_UNDO
2617 /*
2618 * When opening a new file locate undo info and read it.
2619 */
2620 if (read_undo_file)
2621 {
2622 char_u hash[UNDO_HASH_SIZE];
2623
2624 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002625 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002626 }
2627#endif
2628
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002629 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 {
2631 int m = msg_scroll;
2632 int n = msg_scrolled;
2633
2634 /* Save the fileformat now, otherwise the buffer will be considered
2635 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002636 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 save_file_ff(curbuf);
2638
2639 /*
2640 * The output from the autocommands should not overwrite anything and
2641 * should not be overwritten: Set msg_scroll, restore its value if no
2642 * output was done.
2643 */
2644 msg_scroll = TRUE;
2645 if (filtering)
2646 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2647 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002648 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002649 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2651 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002652 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2653 /*
2654 * EVENT_FILETYPE was not triggered but the buffer already has a
2655 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2656 */
2657 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2658 TRUE, curbuf);
2659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 else
2661 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2662 FALSE, NULL, eap);
2663 if (msg_scrolled == n)
2664 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002665# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 if (aborting()) /* autocmds may abort script processing */
2667 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002668# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670
2671 if (recoverymode && error)
2672 return FAIL;
2673 return OK;
2674}
2675
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002676#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002677/*
2678 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2679 * which is the name of files used for process substitution output by
2680 * some shells on some operating systems, e.g., bash on SunOS.
2681 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2682 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002683 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002684is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002685{
2686 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2687 && VIM_ISDIGIT(fname[8])
2688 && *skipdigits(fname + 9) == NUL
2689 && (fname[9] != NUL
2690 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2691}
2692#endif
2693
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002694/*
2695 * From the current line count and characters read after that, estimate the
2696 * line number where we are now.
2697 * Used for error messages that include a line number.
2698 */
2699 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002700readfile_linenr(
2701 linenr_T linecnt, /* line count before reading more bytes */
2702 char_u *p, /* start of more bytes read */
2703 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002704{
2705 char_u *s;
2706 linenr_T lnum;
2707
2708 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2709 for (s = p; s < endp; ++s)
2710 if (*s == '\n')
2711 ++lnum;
2712 return lnum;
2713}
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002714
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002716 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2717 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 * Returns OK or FAIL.
2719 */
2720 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002721prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722{
Bram Moolenaar13505972019-01-24 15:04:48 +01002723 eap->cmd = alloc(15 + (unsigned)STRLEN(buf->b_p_fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 if (eap->cmd == NULL)
2725 return FAIL;
2726
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002727 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2728 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002729 eap->bad_char = buf->b_bad_char;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002730 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002731
2732 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002733 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002734 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735 return OK;
2736}
2737
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002738/*
2739 * Set default or forced 'fileformat' and 'binary'.
2740 */
2741 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002742set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002743{
2744 /* set default 'fileformat' */
2745 if (set_options)
2746 {
2747 if (eap != NULL && eap->force_ff != 0)
2748 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2749 else if (*p_ffs != NUL)
2750 set_fileformat(default_fileformat(), OPT_LOCAL);
2751 }
2752
2753 /* set or reset 'binary' */
2754 if (eap != NULL && eap->force_bin != 0)
2755 {
2756 int oldval = curbuf->b_p_bin;
2757
2758 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2759 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2760 }
2761}
2762
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002763/*
2764 * Set forced 'fileencoding'.
2765 */
2766 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002767set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002768{
2769 if (eap->force_enc != 0)
2770 {
2771 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2772
2773 if (fenc != NULL)
2774 set_string_option_direct((char_u *)"fenc", -1,
2775 fenc, OPT_FREE|OPT_LOCAL, 0);
2776 vim_free(fenc);
2777 }
2778}
2779
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780/*
2781 * Find next fileencoding to use from 'fileencodings'.
2782 * "pp" points to fenc_next. It's advanced to the next item.
2783 * When there are no more items, an empty string is returned and *pp is set to
2784 * NULL.
2785 * When *pp is not set to NULL, the result is in allocated memory.
2786 */
2787 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002788next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789{
2790 char_u *p;
2791 char_u *r;
2792
2793 if (**pp == NUL)
2794 {
2795 *pp = NULL;
2796 return (char_u *)"";
2797 }
2798 p = vim_strchr(*pp, ',');
2799 if (p == NULL)
2800 {
2801 r = enc_canonize(*pp);
2802 *pp += STRLEN(*pp);
2803 }
2804 else
2805 {
2806 r = vim_strnsave(*pp, (int)(p - *pp));
2807 *pp = p + 1;
2808 if (r != NULL)
2809 {
2810 p = enc_canonize(r);
2811 vim_free(r);
2812 r = p;
2813 }
2814 }
2815 if (r == NULL) /* out of memory */
2816 {
2817 r = (char_u *)"";
2818 *pp = NULL;
2819 }
2820 return r;
2821}
2822
Bram Moolenaar13505972019-01-24 15:04:48 +01002823#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824/*
2825 * Convert a file with the 'charconvert' expression.
2826 * This closes the file which is to be read, converts it and opens the
2827 * resulting file for reading.
2828 * Returns name of the resulting converted file (the caller should delete it
2829 * after reading it).
2830 * Returns NULL if the conversion failed ("*fdp" is not set) .
2831 */
2832 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002833readfile_charconvert(
2834 char_u *fname, /* name of input file */
2835 char_u *fenc, /* converted from */
2836 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837{
2838 char_u *tmpname;
Bram Moolenaar32526b32019-01-19 17:43:09 +01002839 char *errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002841 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842 if (tmpname == NULL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002843 errmsg = _("Can't find temp file for conversion");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844 else
2845 {
2846 close(*fdp); /* close the input file, ignore errors */
2847 *fdp = -1;
2848 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2849 fname, tmpname) == FAIL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002850 errmsg = _("Conversion with 'charconvert' failed");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2852 O_RDONLY | O_EXTRA, 0)) < 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002853 errmsg = _("can't read output of 'charconvert'");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 }
2855
2856 if (errmsg != NULL)
2857 {
2858 /* Don't use emsg(), it breaks mappings, the retry with
2859 * another type of conversion might still work. */
Bram Moolenaar32526b32019-01-19 17:43:09 +01002860 msg(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 if (tmpname != NULL)
2862 {
2863 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002864 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 }
2866 }
2867
2868 /* If the input file is closed, open it (caller should check for error). */
2869 if (*fdp < 0)
2870 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2871
2872 return tmpname;
2873}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874#endif
2875
Bram Moolenaar13505972019-01-24 15:04:48 +01002876
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877#ifdef FEAT_VIMINFO
2878/*
2879 * Read marks for the current buffer from the viminfo file, when we support
2880 * buffer marks and the buffer has a name.
2881 */
2882 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002883check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884{
2885 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2886 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002887 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888
2889 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2890 * the ' parameter after opening a buffer. */
2891 curbuf->b_marks_read = TRUE;
2892}
2893#endif
2894
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002895#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002897 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2899 * *filesizep are updated.
2900 * Return the (new) encryption key, NULL for no encryption.
2901 */
2902 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002903check_for_cryptkey(
2904 char_u *cryptkey, /* previous encryption key or NULL */
2905 char_u *ptr, /* pointer to read bytes */
2906 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002907 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002908 int newfile, /* editing a new buffer */
2909 char_u *fname, /* file name to display */
2910 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002912 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002913 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002914
2915 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002917 /* Mark the buffer as read-only until the decryption has taken place.
2918 * Avoids accidentally overwriting the file with garbage. */
2919 curbuf->b_p_ro = TRUE;
2920
Bram Moolenaar2be79502014-08-13 21:58:28 +02002921 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002922 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002923 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 {
2925 if (*curbuf->b_p_key)
2926 cryptkey = curbuf->b_p_key;
2927 else
2928 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002929 /* When newfile is TRUE, store the typed key in the 'key'
2930 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002931 * Don't ask for the key again when first time Enter was hit.
2932 * Happens when retrying to detect encoding. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002933 smsg(_(need_key_msg), fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002934 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002935 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002936 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002937 *did_ask = TRUE;
2938
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 /* check if empty key entered */
2940 if (cryptkey != NULL && *cryptkey == NUL)
2941 {
2942 if (cryptkey != curbuf->b_p_key)
2943 vim_free(cryptkey);
2944 cryptkey = NULL;
2945 }
2946 }
2947 }
2948
2949 if (cryptkey != NULL)
2950 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002951 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002952
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002953 curbuf->b_cryptstate = crypt_create_from_header(
2954 method, cryptkey, ptr);
2955 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002957 /* Remove cryptmethod specific header from the text. */
2958 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02002959 if (*sizep <= header_len)
2960 /* invalid header, buffer can't be encrypted */
2961 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002962 *filesizep += header_len;
2963 *sizep -= header_len;
2964 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
2965
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002966 /* Restore the read-only flag. */
2967 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 }
2969 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002970 /* When starting to edit a new file which does not have encryption, clear
2971 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002972 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2974
2975 return cryptkey;
2976}
Bram Moolenaar80794b12010-06-13 05:20:42 +02002977#endif /* FEAT_CRYPT */
2978
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979#ifdef UNIX
2980 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002981set_file_time(
2982 char_u *fname,
2983 time_t atime, /* access time */
2984 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985{
2986# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2987 struct utimbuf buf;
2988
2989 buf.actime = atime;
2990 buf.modtime = mtime;
2991 (void)utime((char *)fname, &buf);
2992# else
2993# if defined(HAVE_UTIMES)
2994 struct timeval tvp[2];
2995
2996 tvp[0].tv_sec = atime;
2997 tvp[0].tv_usec = 0;
2998 tvp[1].tv_sec = mtime;
2999 tvp[1].tv_usec = 0;
3000# ifdef NeXT
3001 (void)utimes((char *)fname, tvp);
3002# else
3003 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3004# endif
3005# endif
3006# endif
3007}
3008#endif /* UNIX */
3009
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003010#if defined(VMS) && !defined(MIN)
3011/* Older DECC compiler for VAX doesn't define MIN() */
3012# define MIN(a, b) ((a) < (b) ? (a) : (b))
3013#endif
3014
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003016 * Return TRUE if a file appears to be read-only from the file permissions.
3017 */
3018 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003019check_file_readonly(
3020 char_u *fname, /* full path to file */
3021 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003022{
3023#ifndef USE_MCH_ACCESS
3024 int fd = 0;
3025#endif
3026
3027 return (
3028#ifdef USE_MCH_ACCESS
3029# ifdef UNIX
3030 (perm & 0222) == 0 ||
3031# endif
3032 mch_access((char *)fname, W_OK)
3033#else
3034 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3035 ? TRUE : (close(fd), FALSE)
3036#endif
3037 );
3038}
3039
3040
3041/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003042 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 *
3044 * We do our own buffering here because fwrite() is so slow.
3045 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003046 * If "forceit" is true, we don't care for errors when attempting backups.
3047 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003048 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003049 *
3050 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3051 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 *
3053 * This function must NOT use NameBuff (because it's called by autowrite()).
3054 *
3055 * return FAIL for failure, OK otherwise
3056 */
3057 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003058buf_write(
3059 buf_T *buf,
3060 char_u *fname,
3061 char_u *sfname,
3062 linenr_T start,
3063 linenr_T end,
3064 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003066 int append, /* append to the file */
3067 int forceit,
3068 int reset_changed,
3069 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070{
3071 int fd;
3072 char_u *backup = NULL;
3073 int backup_copy = FALSE; /* copy the original file? */
3074 int dobackup;
3075 char_u *ffname;
3076 char_u *wfname = NULL; /* name of file to write to */
3077 char_u *s;
3078 char_u *ptr;
3079 char_u c;
3080 int len;
3081 linenr_T lnum;
3082 long nchars;
3083 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003084 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 char_u *errnum = NULL;
3086 char_u *buffer;
3087 char_u smallbuf[SMBUFSIZE];
3088 char_u *backup_ext;
3089 int bufsize;
3090 long perm; /* file permissions */
3091 int retval = OK;
3092 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3093 int msg_save = msg_scroll;
3094 int overwriting; /* TRUE if writing over original */
3095 int no_eol = FALSE; /* no end-of-line written */
3096 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003097 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003099 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100 int file_readonly = FALSE; /* overwritten file is read-only */
3101 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003102#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003103 int made_writable = FALSE; /* 'w' bit has been set */
3104#endif
3105 /* writing everything */
3106 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 int attr;
3109 int fileformat;
3110 int write_bin;
3111 struct bw_info write_info; /* info for buf_write_bytes() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112 int converted = FALSE;
3113 int notconverted = FALSE;
3114 char_u *fenc; /* effective 'fileencoding' */
3115 char_u *fenc_tofree = NULL; /* allocated "fenc" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116#ifdef HAS_BW_FLAGS
3117 int wb_flags = 0;
3118#endif
3119#ifdef HAVE_ACL
3120 vim_acl_T acl = NULL; /* ACL copied from original file to
3121 backup or new file */
3122#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003123#ifdef FEAT_PERSISTENT_UNDO
3124 int write_undo_file = FALSE;
3125 context_sha256_T sha_ctx;
3126#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003127 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128
3129 if (fname == NULL || *fname == NUL) /* safety check */
3130 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003131 if (buf->b_ml.ml_mfp == NULL)
3132 {
3133 /* This can happen during startup when there is a stray "w" in the
3134 * vimrc file. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003135 emsg(_(e_emptybuf));
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003136 return FAIL;
3137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138
3139 /*
3140 * Disallow writing from .exrc and .vimrc in current directory for
3141 * security reasons.
3142 */
3143 if (check_secure())
3144 return FAIL;
3145
3146 /* Avoid a crash for a long name. */
3147 if (STRLEN(fname) >= MAXPATHL)
3148 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003149 emsg(_(e_longname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150 return FAIL;
3151 }
3152
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3154 write_info.bw_conv_buf = NULL;
3155 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003156 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 write_info.bw_restlen = 0;
Bram Moolenaar13505972019-01-24 15:04:48 +01003158#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 write_info.bw_iconv_fd = (iconv_t)-1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003161#ifdef FEAT_CRYPT
3162 write_info.bw_buffer = buf;
3163#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164
Bram Moolenaardf177f62005-02-22 08:39:57 +00003165 /* After writing a file changedtick changes but we don't want to display
3166 * the line. */
3167 ex_no_reprint = TRUE;
3168
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169 /*
3170 * If there is no file name yet, use the one for the written file.
3171 * BF_NOTEDITED is set to reflect this (in case the write fails).
3172 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003173 * Don't do this when appending.
3174 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003176 if (buf->b_ffname == NULL
3177 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 && whole
3179 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003180#ifdef FEAT_QUICKFIX
3181 && !bt_nofile(buf)
3182#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003184 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3186 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003187 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003189 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190 }
3191
3192 if (sfname == NULL)
3193 sfname = fname;
3194 /*
3195 * For Unix: Use the short file name whenever possible.
3196 * Avoids problems with networks and when directory names are changed.
3197 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3198 * another directory, which we don't detect
3199 */
3200 ffname = fname; /* remember full fname */
3201#ifdef UNIX
3202 fname = sfname;
3203#endif
3204
3205 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3206 overwriting = TRUE;
3207 else
3208 overwriting = FALSE;
3209
3210 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003211 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212
3213 ++no_wait_return; /* don't wait for return yet */
3214
3215 /*
3216 * Set '[ and '] marks to the lines to be written.
3217 */
3218 buf->b_op_start.lnum = start;
3219 buf->b_op_start.col = 0;
3220 buf->b_op_end.lnum = end;
3221 buf->b_op_end.col = 0;
3222
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 {
3224 aco_save_T aco;
3225 int buf_ffname = FALSE;
3226 int buf_sfname = FALSE;
3227 int buf_fname_f = FALSE;
3228 int buf_fname_s = FALSE;
3229 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003230 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003231 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003232 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233
3234 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003235 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 * Set curbuf to the buffer to be written.
3237 * Careful: The autocommands may call buf_write() recursively!
3238 */
3239 if (ffname == buf->b_ffname)
3240 buf_ffname = TRUE;
3241 if (sfname == buf->b_sfname)
3242 buf_sfname = TRUE;
3243 if (fname == buf->b_ffname)
3244 buf_fname_f = TRUE;
3245 if (fname == buf->b_sfname)
3246 buf_fname_s = TRUE;
3247
3248 /* set curwin/curbuf to buf and save a few things */
3249 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003250 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251
3252 if (append)
3253 {
3254 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3255 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003256 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003257#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003258 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003259 nofile_err = TRUE;
3260 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003261#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003262 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 }
3266 else if (filtering)
3267 {
3268 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3269 NULL, sfname, FALSE, curbuf, eap);
3270 }
3271 else if (reset_changed && whole)
3272 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003273 int was_changed = curbufIsChanged();
3274
3275 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3276 sfname, sfname, FALSE, curbuf, eap);
3277 if (did_cmd)
3278 {
3279 if (was_changed && !curbufIsChanged())
3280 {
3281 /* Written everything correctly and BufWriteCmd has reset
3282 * 'modified': Correct the undo information so that an
3283 * undo now sets 'modified'. */
3284 u_unchanged(curbuf);
3285 u_update_save_nr(curbuf);
3286 }
3287 }
3288 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003289 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003290#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003291 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003292 nofile_err = TRUE;
3293 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003294#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003295 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003297 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 }
3299 else
3300 {
3301 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3302 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003303 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003304#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003305 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003306 nofile_err = TRUE;
3307 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003308#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003309 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312 }
3313
3314 /* restore curwin/curbuf and a few other things */
3315 aucmd_restbuf(&aco);
3316
3317 /*
3318 * In three situations we return here and don't write the file:
3319 * 1. the autocommands deleted or unloaded the buffer.
3320 * 2. The autocommands abort script processing.
3321 * 3. If one of the "Cmd" autocommands was executed.
3322 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003323 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003325 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003326 || did_cmd || nofile_err
3327#ifdef FEAT_EVAL
3328 || aborting()
3329#endif
3330 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331 {
3332 --no_wait_return;
3333 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003334 if (nofile_err)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003335 emsg(_("E676: No matching autocommands for acwrite buffer"));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003336
Bram Moolenaar1e015462005-09-25 22:16:38 +00003337 if (nofile_err
3338#ifdef FEAT_EVAL
3339 || aborting()
3340#endif
3341 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342 /* An aborting error, interrupt or exception in the
3343 * autocommands. */
3344 return FAIL;
3345 if (did_cmd)
3346 {
3347 if (buf == NULL)
3348 /* The buffer was deleted. We assume it was written
3349 * (can't retry anyway). */
3350 return OK;
3351 if (overwriting)
3352 {
3353 /* Assume the buffer was written, update the timestamp. */
3354 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003355 if (append)
3356 buf->b_flags &= ~BF_NEW;
3357 else
3358 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003360 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003361 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 /* Buffer still changed, the autocommands didn't work
3363 * properly. */
3364 return FAIL;
3365 return OK;
3366 }
3367#ifdef FEAT_EVAL
3368 if (!aborting())
3369#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003370 emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 return FAIL;
3372 }
3373
3374 /*
3375 * The autocommands may have changed the number of lines in the file.
3376 * When writing the whole file, adjust the end.
3377 * When writing part of the file, assume that the autocommands only
3378 * changed the number of lines that are to be written (tricky!).
3379 */
3380 if (buf->b_ml.ml_line_count != old_line_count)
3381 {
3382 if (whole) /* write all */
3383 end = buf->b_ml.ml_line_count;
3384 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3385 end += buf->b_ml.ml_line_count - old_line_count;
3386 else /* less lines */
3387 {
3388 end -= old_line_count - buf->b_ml.ml_line_count;
3389 if (end < start)
3390 {
3391 --no_wait_return;
3392 msg_scroll = msg_save;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003393 emsg(_("E204: Autocommand changed number of lines in unexpected way"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394 return FAIL;
3395 }
3396 }
3397 }
3398
3399 /*
3400 * The autocommands may have changed the name of the buffer, which may
3401 * be kept in fname, ffname and sfname.
3402 */
3403 if (buf_ffname)
3404 ffname = buf->b_ffname;
3405 if (buf_sfname)
3406 sfname = buf->b_sfname;
3407 if (buf_fname_f)
3408 fname = buf->b_ffname;
3409 if (buf_fname_s)
3410 fname = buf->b_sfname;
3411 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412
3413#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003414 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 {
3416 if (whole)
3417 {
3418 /*
3419 * b_changed can be 0 after an undo, but we still need to write
3420 * the buffer to NetBeans.
3421 */
3422 if (buf->b_changed || isNetbeansModified(buf))
3423 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003424 --no_wait_return; /* may wait for return now */
3425 msg_scroll = msg_save;
3426 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 return retval;
3428 }
3429 else
3430 {
3431 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003432 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 buffer = NULL;
3434 goto fail;
3435 }
3436 }
3437 else
3438 {
3439 errnum = (char_u *)"E657: ";
3440 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3441 buffer = NULL;
3442 goto fail;
3443 }
3444 }
3445#endif
3446
3447 if (shortmess(SHM_OVER) && !exiting)
3448 msg_scroll = FALSE; /* overwrite previous file message */
3449 else
3450 msg_scroll = TRUE; /* don't overwrite previous file message */
3451 if (!filtering)
3452 filemess(buf,
3453#ifndef UNIX
3454 sfname,
3455#else
3456 fname,
3457#endif
3458 (char_u *)"", 0); /* show that we are busy */
3459 msg_scroll = FALSE; /* always overwrite the file message now */
3460
3461 buffer = alloc(BUFSIZE);
3462 if (buffer == NULL) /* can't allocate big buffer, use small
3463 * one (to be able to write when out of
3464 * memory) */
3465 {
3466 buffer = smallbuf;
3467 bufsize = SMBUFSIZE;
3468 }
3469 else
3470 bufsize = BUFSIZE;
3471
3472 /*
3473 * Get information about original file (if there is one).
3474 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003475#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003476 st_old.st_dev = 0;
3477 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478 perm = -1;
3479 if (mch_stat((char *)fname, &st_old) < 0)
3480 newfile = TRUE;
3481 else
3482 {
3483 perm = st_old.st_mode;
3484 if (!S_ISREG(st_old.st_mode)) /* not a file */
3485 {
3486 if (S_ISDIR(st_old.st_mode))
3487 {
3488 errnum = (char_u *)"E502: ";
3489 errmsg = (char_u *)_("is a directory");
3490 goto fail;
3491 }
3492 if (mch_nodetype(fname) != NODE_WRITABLE)
3493 {
3494 errnum = (char_u *)"E503: ";
3495 errmsg = (char_u *)_("is not a file or writable device");
3496 goto fail;
3497 }
3498 /* It's a device of some kind (or a fifo) which we can write to
3499 * but for which we can't make a backup. */
3500 device = TRUE;
3501 newfile = TRUE;
3502 perm = -1;
3503 }
3504 }
3505#else /* !UNIX */
3506 /*
3507 * Check for a writable device name.
3508 */
3509 c = mch_nodetype(fname);
3510 if (c == NODE_OTHER)
3511 {
3512 errnum = (char_u *)"E503: ";
3513 errmsg = (char_u *)_("is not a file or writable device");
3514 goto fail;
3515 }
3516 if (c == NODE_WRITABLE)
3517 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003518# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003519 /* MS-Windows allows opening a device, but we will probably get stuck
3520 * trying to write to it. */
3521 if (!p_odev)
3522 {
3523 errnum = (char_u *)"E796: ";
3524 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3525 goto fail;
3526 }
3527# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528 device = TRUE;
3529 newfile = TRUE;
3530 perm = -1;
3531 }
3532 else
3533 {
3534 perm = mch_getperm(fname);
3535 if (perm < 0)
3536 newfile = TRUE;
3537 else if (mch_isdir(fname))
3538 {
3539 errnum = (char_u *)"E502: ";
3540 errmsg = (char_u *)_("is a directory");
3541 goto fail;
3542 }
3543 if (overwriting)
3544 (void)mch_stat((char *)fname, &st_old);
3545 }
3546#endif /* !UNIX */
3547
3548 if (!device && !newfile)
3549 {
3550 /*
3551 * Check if the file is really writable (when renaming the file to
3552 * make a backup we won't discover it later).
3553 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003554 file_readonly = check_file_readonly(fname, (int)perm);
3555
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556 if (!forceit && file_readonly)
3557 {
3558 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3559 {
3560 errnum = (char_u *)"E504: ";
3561 errmsg = (char_u *)_(err_readonly);
3562 }
3563 else
3564 {
3565 errnum = (char_u *)"E505: ";
3566 errmsg = (char_u *)_("is read-only (add ! to override)");
3567 }
3568 goto fail;
3569 }
3570
3571 /*
3572 * Check if the timestamp hasn't changed since reading the file.
3573 */
3574 if (overwriting)
3575 {
3576 retval = check_mtime(buf, &st_old);
3577 if (retval == FAIL)
3578 goto fail;
3579 }
3580 }
3581
3582#ifdef HAVE_ACL
3583 /*
3584 * For systems that support ACL: get the ACL from the original file.
3585 */
3586 if (!newfile)
3587 acl = mch_get_acl(fname);
3588#endif
3589
3590 /*
3591 * If 'backupskip' is not empty, don't make a backup for some files.
3592 */
3593 dobackup = (p_wb || p_bk || *p_pm != NUL);
3594#ifdef FEAT_WILDIGN
3595 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3596 dobackup = FALSE;
3597#endif
3598
3599 /*
3600 * Save the value of got_int and reset it. We don't want a previous
3601 * interruption cancel writing, only hitting CTRL-C while writing should
3602 * abort it.
3603 */
3604 prev_got_int = got_int;
3605 got_int = FALSE;
3606
3607 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3608 buf->b_saving = TRUE;
3609
3610 /*
3611 * If we are not appending or filtering, the file exists, and the
3612 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3613 * When 'patchmode' is set also make a backup when appending.
3614 *
3615 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3616 * off. This helps when editing large files on almost-full disks.
3617 */
3618 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3619 {
3620#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003621 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622#endif
3623
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003624 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 backup_copy = TRUE;
3626#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003627 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 {
3629 int i;
3630
3631# ifdef UNIX
3632 /*
3633 * Don't rename the file when:
3634 * - it's a hard link
3635 * - it's a symbolic link
3636 * - we don't have write permission in the directory
3637 * - we can't set the owner/group of the new file
3638 */
3639 if (st_old.st_nlink > 1
3640 || mch_lstat((char *)fname, &st) < 0
3641 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003642 || st.st_ino != st_old.st_ino
3643# ifndef HAVE_FCHOWN
3644 || st.st_uid != st_old.st_uid
3645 || st.st_gid != st_old.st_gid
3646# endif
3647 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003648 backup_copy = TRUE;
3649 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003650# else
3651# ifdef WIN32
3652 /* On NTFS file systems hard links are possible. */
3653 if (mch_is_linked(fname))
3654 backup_copy = TRUE;
3655 else
3656# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657# endif
3658 {
3659 /*
3660 * Check if we can create a file and set the owner/group to
3661 * the ones from the original file.
3662 * First find a file name that doesn't exist yet (use some
3663 * arbitrary numbers).
3664 */
3665 STRCPY(IObuff, fname);
3666 for (i = 4913; ; i += 123)
3667 {
3668 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003669 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 break;
3671 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003672 fd = mch_open((char *)IObuff,
3673 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 if (fd < 0) /* can't write in directory */
3675 backup_copy = TRUE;
3676 else
3677 {
3678# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003679# ifdef HAVE_FCHOWN
Bram Moolenaar42335f52018-09-13 15:33:43 +02003680 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003681# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 if (mch_stat((char *)IObuff, &st) < 0
3683 || st.st_uid != st_old.st_uid
3684 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003685 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686 backup_copy = TRUE;
3687# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003688 /* Close the file before removing it, on MS-Windows we
3689 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003690 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003691 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003692# ifdef MSWIN
3693 /* MS-Windows may trigger a virus scanner to open the
3694 * file, we can't delete it then. Keep trying for half a
3695 * second. */
3696 {
3697 int try;
3698
3699 for (try = 0; try < 10; ++try)
3700 {
3701 if (mch_lstat((char *)IObuff, &st) < 0)
3702 break;
3703 ui_delay(50L, TRUE); /* wait 50 msec */
3704 mch_remove(IObuff);
3705 }
3706 }
3707# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 }
3709 }
3710 }
3711
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712 /*
3713 * Break symlinks and/or hardlinks if we've been asked to.
3714 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003715 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003717# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 int lstat_res;
3719
3720 lstat_res = mch_lstat((char *)fname, &st);
3721
3722 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003723 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724 && lstat_res == 0
3725 && st.st_ino != st_old.st_ino)
3726 backup_copy = FALSE;
3727
3728 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003729 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 && st_old.st_nlink > 1
3731 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3732 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003733# else
3734# if defined(WIN32)
3735 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003736 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003737 backup_copy = FALSE;
3738
3739 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003740 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003741 backup_copy = FALSE;
3742# endif
3743# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745
3746#endif
3747
3748 /* make sure we have a valid backup extension to use */
3749 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751 else
3752 backup_ext = p_bex;
3753
3754 if (backup_copy
3755 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3756 {
3757 int bfd;
3758 char_u *copybuf, *wp;
3759 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003760 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 char_u *dirp;
3762 char_u *rootname;
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003763#if defined(UNIX) || defined(WIN3264)
3764 char_u *p;
3765#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003766#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003768 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769#endif
3770
3771 copybuf = alloc(BUFSIZE + 1);
3772 if (copybuf == NULL)
3773 {
3774 some_error = TRUE; /* out of memory */
3775 goto nobackup;
3776 }
3777
3778 /*
3779 * Try to make the backup in each directory in the 'bdir' option.
3780 *
3781 * Unix semantics has it, that we may have a writable file,
3782 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3783 * - the directory is not writable,
3784 * - the file may be a symbolic link,
3785 * - the file may belong to another user/group, etc.
3786 *
3787 * For these reasons, the existing writable file must be truncated
3788 * and reused. Creation of a backup COPY will be attempted.
3789 */
3790 dirp = p_bdir;
3791 while (*dirp)
3792 {
3793#ifdef UNIX
3794 st_new.st_ino = 0;
3795 st_new.st_dev = 0;
3796 st_new.st_gid = 0;
3797#endif
3798
3799 /*
3800 * Isolate one directory name, using an entry in 'bdir'.
3801 */
3802 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003803
3804#if defined(UNIX) || defined(WIN3264)
3805 p = copybuf + STRLEN(copybuf);
3806 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
3807 // Ends with '//', use full path
3808 if ((p = make_percent_swname(copybuf, fname)) != NULL)
3809 {
3810 backup = modname(p, backup_ext, FALSE);
3811 vim_free(p);
3812 }
3813#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 rootname = get_file_in_dir(fname, copybuf);
3815 if (rootname == NULL)
3816 {
3817 some_error = TRUE; /* out of memory */
3818 goto nobackup;
3819 }
3820
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003821#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 did_set_shortname = FALSE;
3823#endif
3824
3825 /*
3826 * May try twice if 'shortname' not set.
3827 */
3828 for (;;)
3829 {
3830 /*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003831 * Make the backup file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003833 if (backup == NULL)
3834 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835 rootname, backup_ext, FALSE);
3836 if (backup == NULL)
3837 {
3838 vim_free(rootname);
3839 some_error = TRUE; /* out of memory */
3840 goto nobackup;
3841 }
3842
3843 /*
3844 * Check if backup file already exists.
3845 */
3846 if (mch_stat((char *)backup, &st_new) >= 0)
3847 {
3848#ifdef UNIX
3849 /*
3850 * Check if backup file is same as original file.
3851 * May happen when modname() gave the same file back.
3852 * E.g. silly link, or file name-length reached.
3853 * If we don't check here, we either ruin the file
3854 * when copying or erase it after writing. jw.
3855 */
3856 if (st_new.st_dev == st_old.st_dev
3857 && st_new.st_ino == st_old.st_ino)
3858 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003859 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 /*
3861 * may try again with 'shortname' set
3862 */
3863 if (!(buf->b_shortname || buf->b_p_sn))
3864 {
3865 buf->b_shortname = TRUE;
3866 did_set_shortname = TRUE;
3867 continue;
3868 }
3869 /* setting shortname didn't help */
3870 if (did_set_shortname)
3871 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 break;
3873 }
3874#endif
3875
3876 /*
3877 * If we are not going to keep the backup file, don't
3878 * delete an existing one, try to use another name.
3879 * Change one character, just before the extension.
3880 */
3881 if (!p_bk)
3882 {
3883 wp = backup + STRLEN(backup) - 1
3884 - STRLEN(backup_ext);
3885 if (wp < backup) /* empty file name ??? */
3886 wp = backup;
3887 *wp = 'z';
3888 while (*wp > 'a'
3889 && mch_stat((char *)backup, &st_new) >= 0)
3890 --*wp;
3891 /* They all exist??? Must be something wrong. */
3892 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003893 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894 }
3895 }
3896 break;
3897 }
3898 vim_free(rootname);
3899
3900 /*
3901 * Try to create the backup file
3902 */
3903 if (backup != NULL)
3904 {
3905 /* remove old backup, if present */
3906 mch_remove(backup);
3907 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003908 * we were sleeping (symlink hacker attack?). Reset umask
3909 * if possible to avoid mch_setperm() below. */
3910#ifdef UNIX
3911 umask_save = umask(0);
3912#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003914 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3915 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003916#ifdef UNIX
3917 (void)umask(umask_save);
3918#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003920 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 else
3922 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003923 /* Set file protection same as original file, but
3924 * strip s-bit. Only needed if umask() wasn't used
3925 * above. */
3926#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003928#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 /*
3930 * Try to set the group of the backup same as the
3931 * original file. If this fails, set the protection
3932 * bits for the group same as the protection bits for
3933 * others.
3934 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003935 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003937 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938# endif
3939 )
3940 mch_setperm(backup,
3941 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003942# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003943 mch_copy_sec(fname, backup);
3944# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945#endif
3946
3947 /*
3948 * copy the file.
3949 */
3950 write_info.bw_fd = bfd;
3951 write_info.bw_buf = copybuf;
3952#ifdef HAS_BW_FLAGS
3953 write_info.bw_flags = FIO_NOCONVERT;
3954#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003955 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 BUFSIZE)) > 0)
3957 {
3958 if (buf_write_bytes(&write_info) == FAIL)
3959 {
3960 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3961 break;
3962 }
3963 ui_breakcheck();
3964 if (got_int)
3965 {
3966 errmsg = (char_u *)_(e_interr);
3967 break;
3968 }
3969 }
3970
3971 if (close(bfd) < 0 && errmsg == NULL)
3972 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3973 if (write_info.bw_len < 0)
3974 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3975#ifdef UNIX
3976 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3977#endif
3978#ifdef HAVE_ACL
3979 mch_set_acl(backup, acl);
3980#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003981#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003982 mch_copy_sec(fname, backup);
3983#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984 break;
3985 }
3986 }
3987 }
3988 nobackup:
3989 close(fd); /* ignore errors for closing read file */
3990 vim_free(copybuf);
3991
3992 if (backup == NULL && errmsg == NULL)
3993 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3994 /* ignore errors when forceit is TRUE */
3995 if ((some_error || errmsg != NULL) && !forceit)
3996 {
3997 retval = FAIL;
3998 goto fail;
3999 }
4000 errmsg = NULL;
4001 }
4002 else
4003 {
4004 char_u *dirp;
4005 char_u *p;
4006 char_u *rootname;
4007
4008 /*
4009 * Make a backup by renaming the original file.
4010 */
4011 /*
4012 * If 'cpoptions' includes the "W" flag, we don't want to
4013 * overwrite a read-only file. But rename may be possible
4014 * anyway, thus we need an extra check here.
4015 */
4016 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4017 {
4018 errnum = (char_u *)"E504: ";
4019 errmsg = (char_u *)_(err_readonly);
4020 goto fail;
4021 }
4022
4023 /*
4024 *
4025 * Form the backup file name - change path/fo.o.h to
4026 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4027 * that works is used.
4028 */
4029 dirp = p_bdir;
4030 while (*dirp)
4031 {
4032 /*
4033 * Isolate one directory name and make the backup file name.
4034 */
4035 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004036
4037#if defined(UNIX) || defined(WIN3264)
4038 p = IObuff + STRLEN(IObuff);
4039 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
4040 // path ends with '//', use full path
4041 if ((p = make_percent_swname(IObuff, fname)) != NULL)
4042 {
4043 backup = modname(p, backup_ext, FALSE);
4044 vim_free(p);
4045 }
4046#endif
4047 if (backup == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048 {
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004049 rootname = get_file_in_dir(fname, IObuff);
4050 if (rootname == NULL)
4051 backup = NULL;
4052 else
4053 {
4054 backup = buf_modname(
4055 (buf->b_p_sn || buf->b_shortname),
4056 rootname, backup_ext, FALSE);
4057 vim_free(rootname);
4058 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059 }
4060
4061 if (backup != NULL)
4062 {
4063 /*
4064 * If we are not going to keep the backup file, don't
4065 * delete an existing one, try to use another name.
4066 * Change one character, just before the extension.
4067 */
4068 if (!p_bk && mch_getperm(backup) >= 0)
4069 {
4070 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4071 if (p < backup) /* empty file name ??? */
4072 p = backup;
4073 *p = 'z';
4074 while (*p > 'a' && mch_getperm(backup) >= 0)
4075 --*p;
4076 /* They all exist??? Must be something wrong! */
4077 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004078 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 }
4080 }
4081 if (backup != NULL)
4082 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004084 * Delete any existing backup and move the current version
4085 * to the backup. For safety, we don't remove the backup
4086 * until the write has finished successfully. And if the
4087 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 */
4089 /*
4090 * If the renaming of the original file to the backup file
4091 * works, quit here.
4092 */
4093 if (vim_rename(fname, backup) == 0)
4094 break;
4095
Bram Moolenaard23a8232018-02-10 18:45:26 +01004096 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 }
4098 }
4099 if (backup == NULL && !forceit)
4100 {
4101 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4102 goto fail;
4103 }
4104 }
4105 }
4106
Bram Moolenaar53076832015-12-31 19:53:21 +01004107#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 /* When using ":w!" and the file was read-only: make it writable */
4109 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4110 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4111 {
4112 perm |= 0200;
4113 (void)mch_setperm(fname, perm);
4114 made_writable = TRUE;
4115 }
4116#endif
4117
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004118 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004119 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4120 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 {
4122 buf->b_p_ro = FALSE;
4123#ifdef FEAT_TITLE
4124 need_maketitle = TRUE; /* set window title later */
4125#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 }
4128
4129 if (end > buf->b_ml.ml_line_count)
4130 end = buf->b_ml.ml_line_count;
4131 if (buf->b_ml.ml_flags & ML_EMPTY)
4132 start = end + 1;
4133
4134 /*
4135 * If the original file is being overwritten, there is a small chance that
4136 * we crash in the middle of writing. Therefore the file is preserved now.
4137 * This makes all block numbers positive so that recovery does not need
4138 * the original file.
4139 * Don't do this if there is a backup file and we are exiting.
4140 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004141 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 && !(exiting && backup != NULL))
4143 {
4144 ml_preserve(buf, FALSE);
4145 if (got_int)
4146 {
4147 errmsg = (char_u *)_(e_interr);
4148 goto restore_backup;
4149 }
4150 }
4151
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152#ifdef VMS
4153 vms_remove_version(fname); /* remove version */
4154#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004155 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 * multi-byte conversion. */
4157 wfname = fname;
4158
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4160 if (eap != NULL && eap->force_enc != 0)
4161 {
4162 fenc = eap->cmd + eap->force_enc;
4163 fenc = enc_canonize(fenc);
4164 fenc_tofree = fenc;
4165 }
4166 else
4167 fenc = buf->b_p_fenc;
4168
4169 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004170 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004172 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173
4174 /*
4175 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4176 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4177 * Prepare the flags for it and allocate bw_conv_buf when needed.
4178 */
4179 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4180 {
4181 wb_flags = get_fio_flags(fenc);
4182 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4183 {
4184 /* Need to allocate a buffer to translate into. */
4185 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4186 write_info.bw_conv_buflen = bufsize * 2;
4187 else /* FIO_UCS4 */
4188 write_info.bw_conv_buflen = bufsize * 4;
4189 write_info.bw_conv_buf
4190 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4191 if (write_info.bw_conv_buf == NULL)
4192 end = 0;
4193 }
4194 }
4195
Bram Moolenaar13505972019-01-24 15:04:48 +01004196#ifdef WIN3264
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4198 {
4199 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4200 write_info.bw_conv_buflen = bufsize * 4;
4201 write_info.bw_conv_buf
4202 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4203 if (write_info.bw_conv_buf == NULL)
4204 end = 0;
4205 }
Bram Moolenaar13505972019-01-24 15:04:48 +01004206#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207
Bram Moolenaar13505972019-01-24 15:04:48 +01004208#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4210 {
4211 write_info.bw_conv_buflen = bufsize * 3;
4212 write_info.bw_conv_buf
4213 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4214 if (write_info.bw_conv_buf == NULL)
4215 end = 0;
4216 }
Bram Moolenaar13505972019-01-24 15:04:48 +01004217#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218
Bram Moolenaar13505972019-01-24 15:04:48 +01004219#if defined(FEAT_EVAL) || defined(USE_ICONV)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 if (converted && wb_flags == 0)
4221 {
Bram Moolenaar13505972019-01-24 15:04:48 +01004222# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 /*
4224 * Use iconv() conversion when conversion is needed and it's not done
4225 * internally.
4226 */
4227 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4228 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4229 if (write_info.bw_iconv_fd != (iconv_t)-1)
4230 {
4231 /* We're going to use iconv(), allocate a buffer to convert in. */
4232 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4233 write_info.bw_conv_buf
4234 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4235 if (write_info.bw_conv_buf == NULL)
4236 end = 0;
4237 write_info.bw_first = TRUE;
4238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239# ifdef FEAT_EVAL
Bram Moolenaar13505972019-01-24 15:04:48 +01004240 else
4241# endif
4242# endif
4243
4244# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 /*
4246 * When the file needs to be converted with 'charconvert' after
4247 * writing, write to a temp file instead and let the conversion
4248 * overwrite the original file.
4249 */
4250 if (*p_ccv != NUL)
4251 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004252 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253 if (wfname == NULL) /* Can't write without a tempfile! */
4254 {
4255 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4256 goto restore_backup;
4257 }
4258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259# endif
Bram Moolenaar13505972019-01-24 15:04:48 +01004260 }
4261#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004262 if (converted && wb_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01004263#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264 && write_info.bw_iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01004265# endif
4266# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267 && wfname == fname
Bram Moolenaar13505972019-01-24 15:04:48 +01004268# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 )
4270 {
4271 if (!forceit)
4272 {
4273 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4274 goto restore_backup;
4275 }
4276 notconverted = TRUE;
4277 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004278
4279 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004280 * If conversion is taking place, we may first pretend to write and check
4281 * for conversion errors. Then loop again to write for real.
4282 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004284 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285 {
4286 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004287 * There is no need to check conversion when:
4288 * - there is no conversion
4289 * - we make a backup file, that can be restored in case of conversion
4290 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004292 if (!converted || dobackup)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004293 checking_conversion = FALSE;
4294
4295 if (checking_conversion)
4296 {
4297 /* Make sure we don't write anything. */
4298 fd = -1;
4299 write_info.bw_fd = fd;
4300 }
4301 else
4302 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004303#ifdef HAVE_FTRUNCATE
4304# define TRUNC_ON_OPEN 0
4305#else
4306# define TRUNC_ON_OPEN O_TRUNC
4307#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004308 /*
4309 * Open the file "wfname" for writing.
4310 * We may try to open the file twice: If we can't write to the file
4311 * and forceit is TRUE we delete the existing file and try to
4312 * create a new one. If this still fails we may have lost the
4313 * original file! (this may happen when the user reached his
4314 * quotum for number of files).
4315 * Appending will fail if the file does not exist and forceit is
4316 * FALSE.
4317 */
4318 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4319 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004320 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004321 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004323 /*
4324 * A forced write will try to create a new file if the old one
4325 * is still readonly. This may also happen when the directory
4326 * is read-only. In that case the mch_remove() will fail.
4327 */
4328 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004329 {
4330#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004331 stat_T st;
4332
4333 /* Don't delete the file when it's a hard or symbolic link.
4334 */
4335 if ((!newfile && st_old.st_nlink > 1)
4336 || (mch_lstat((char *)fname, &st) == 0
4337 && (st.st_dev != st_old.st_dev
4338 || st.st_ino != st_old.st_ino)))
4339 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4340 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004341#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004342 {
4343 errmsg = (char_u *)_("E212: Can't open file for writing");
4344 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4345 && perm >= 0)
4346 {
4347#ifdef UNIX
4348 /* we write to the file, thus it should be marked
4349 writable after all */
4350 if (!(perm & 0200))
4351 made_writable = TRUE;
4352 perm |= 0200;
4353 if (st_old.st_uid != getuid()
4354 || st_old.st_gid != getgid())
4355 perm &= 0777;
4356#endif
4357 if (!append) /* don't remove when appending */
4358 mch_remove(wfname);
4359 continue;
4360 }
4361 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363
4364restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004366 stat_T st;
4367
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004369 * If we failed to open the file, we don't need a backup.
4370 * Throw it away. If we moved or removed the original file
4371 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004373 if (backup != NULL && wfname == fname)
4374 {
4375 if (backup_copy)
4376 {
4377 /*
4378 * There is a small chance that we removed the
4379 * original, try to move the copy in its place.
4380 * This may not work if the vim_rename() fails.
4381 * In that case we leave the copy around.
4382 */
4383 /* If file does not exist, put the copy in its
4384 * place */
4385 if (mch_stat((char *)fname, &st) < 0)
4386 vim_rename(backup, fname);
4387 /* if original file does exist throw away the copy
4388 */
4389 if (mch_stat((char *)fname, &st) >= 0)
4390 mch_remove(backup);
4391 }
4392 else
4393 {
4394 /* try to put the original file back */
4395 vim_rename(backup, fname);
4396 }
4397 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004399 /* if original file no longer exists give an extra warning
4400 */
4401 if (!newfile && mch_stat((char *)fname, &st) < 0)
4402 end = 0;
4403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004404
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004405 if (wfname != fname)
4406 vim_free(wfname);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004407 goto fail;
4408 }
4409 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004411#if defined(UNIX)
4412 {
4413 stat_T st;
4414
4415 /* Double check we are writing the intended file before making
4416 * any changes. */
4417 if (overwriting
4418 && (!dobackup || backup_copy)
4419 && fname == wfname
4420 && perm >= 0
4421 && mch_fstat(fd, &st) == 0
4422 && st.st_ino != st_old.st_ino)
4423 {
4424 close(fd);
4425 errmsg = (char_u *)_("E949: File changed while writing");
4426 goto fail;
4427 }
4428 }
4429#endif
4430#ifdef HAVE_FTRUNCATE
4431 if (!append)
Bram Moolenaar42335f52018-09-13 15:33:43 +02004432 vim_ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004433#endif
4434
Bram Moolenaard0573012017-10-28 21:11:06 +02004435#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004436 if (backup != NULL && overwriting && !append)
4437 {
4438 if (backup_copy)
4439 (void)mch_copy_file_attribute(wfname, backup);
4440 else
4441 (void)mch_copy_file_attribute(backup, wfname);
4442 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004444 if (!overwriting && !append)
4445 {
4446 if (buf->b_ffname != NULL)
4447 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4448 /* Should copy resource fork */
4449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450#endif
4451
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004453 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004455 char_u *header;
4456 int header_len;
4457
4458 buf->b_cryptstate = crypt_create_for_writing(
4459 crypt_get_method_nr(buf),
4460 buf->b_p_key, &header, &header_len);
4461 if (buf->b_cryptstate == NULL || header == NULL)
4462 end = 0;
4463 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004465 /* Write magic number, so that Vim knows how this file is
4466 * encrypted when reading it back. */
4467 write_info.bw_buf = header;
4468 write_info.bw_len = header_len;
4469 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004471 end = 0;
4472 wb_flags |= FIO_ENCRYPTED;
4473 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004478 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004480 write_info.bw_buf = buffer;
4481 nchars = 0;
4482
4483 /* use "++bin", "++nobin" or 'binary' */
4484 if (eap != NULL && eap->force_bin != 0)
4485 write_bin = (eap->force_bin == FORCE_BIN);
4486 else
4487 write_bin = buf->b_p_bin;
4488
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004490 * The BOM is written just after the encryption magic number.
4491 * Skip it when appending and the file already existed, the BOM only
4492 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004494 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004496 write_info.bw_len = make_bom(buffer, fenc);
4497 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004499 /* don't convert, do encryption */
4500 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4501 if (buf_write_bytes(&write_info) == FAIL)
4502 end = 0;
4503 else
4504 nchars += write_info.bw_len;
4505 }
4506 }
4507 write_info.bw_start_lnum = start;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004508
4509#ifdef FEAT_PERSISTENT_UNDO
4510 write_undo_file = (buf->b_p_udf
4511 && overwriting
4512 && !append
4513 && !filtering
4514 && reset_changed
4515 && !checking_conversion);
4516 if (write_undo_file)
4517 /* Prepare for computing the hash value of the text. */
4518 sha256_start(&sha_ctx);
4519#endif
4520
4521 write_info.bw_len = bufsize;
4522#ifdef HAS_BW_FLAGS
4523 write_info.bw_flags = wb_flags;
4524#endif
4525 fileformat = get_fileformat_force(buf, eap);
4526 s = buffer;
4527 len = 0;
4528 for (lnum = start; lnum <= end; ++lnum)
4529 {
4530 /*
4531 * The next while loop is done once for each character written.
4532 * Keep it fast!
4533 */
4534 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4535#ifdef FEAT_PERSISTENT_UNDO
4536 if (write_undo_file)
4537 sha256_update(&sha_ctx, ptr + 1,
4538 (UINT32_T)(STRLEN(ptr + 1) + 1));
4539#endif
4540 while ((c = *++ptr) != NUL)
4541 {
4542 if (c == NL)
4543 *s = NUL; /* replace newlines with NULs */
4544 else if (c == CAR && fileformat == EOL_MAC)
4545 *s = NL; /* Mac: replace CRs with NLs */
4546 else
4547 *s = c;
4548 ++s;
4549 if (++len != bufsize)
4550 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004551 if (buf_write_bytes(&write_info) == FAIL)
4552 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004553 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004554 break;
4555 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004556 nchars += bufsize;
4557 s = buffer;
4558 len = 0;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004559 write_info.bw_start_lnum = lnum;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004560 }
4561 /* write failed or last line has no EOL: stop here */
4562 if (end == 0
4563 || (lnum == end
4564 && (write_bin || !buf->b_p_fixeol)
4565 && (lnum == buf->b_no_eol_lnum
4566 || (lnum == buf->b_ml.ml_line_count
4567 && !buf->b_p_eol))))
4568 {
4569 ++lnum; /* written the line, count it */
4570 no_eol = TRUE;
4571 break;
4572 }
4573 if (fileformat == EOL_UNIX)
4574 *s++ = NL;
4575 else
4576 {
4577 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4578 if (fileformat == EOL_DOS) /* write CR-NL */
4579 {
4580 if (++len == bufsize)
4581 {
4582 if (buf_write_bytes(&write_info) == FAIL)
4583 {
4584 end = 0; /* write error: break loop */
4585 break;
4586 }
4587 nchars += bufsize;
4588 s = buffer;
4589 len = 0;
4590 }
4591 *s++ = NL;
4592 }
4593 }
4594 if (++len == bufsize && end)
4595 {
4596 if (buf_write_bytes(&write_info) == FAIL)
4597 {
4598 end = 0; /* write error: break loop */
4599 break;
4600 }
4601 nchars += bufsize;
4602 s = buffer;
4603 len = 0;
4604
4605 ui_breakcheck();
4606 if (got_int)
4607 {
4608 end = 0; /* Interrupted, break loop */
4609 break;
4610 }
4611 }
4612#ifdef VMS
4613 /*
4614 * On VMS there is a problem: newlines get added when writing
4615 * blocks at a time. Fix it by writing a line at a time.
4616 * This is much slower!
4617 * Explanation: VAX/DECC RTL insists that records in some RMS
4618 * structures end with a newline (carriage return) character, and
4619 * if they don't it adds one.
4620 * With other RMS structures it works perfect without this fix.
4621 */
4622 if (buf->b_fab_rfm == FAB$C_VFC
4623 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4624 {
4625 int b2write;
4626
4627 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4628 ? MIN(4096, bufsize)
4629 : MIN(buf->b_fab_mrs, bufsize));
4630
4631 b2write = len;
4632 while (b2write > 0)
4633 {
4634 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4635 if (buf_write_bytes(&write_info) == FAIL)
4636 {
4637 end = 0;
4638 break;
4639 }
4640 b2write -= MIN(b2write, buf->b_fab_mrs);
4641 }
4642 write_info.bw_len = bufsize;
4643 nchars += len;
4644 s = buffer;
4645 len = 0;
4646 }
4647#endif
4648 }
4649 if (len > 0 && end > 0)
4650 {
4651 write_info.bw_len = len;
4652 if (buf_write_bytes(&write_info) == FAIL)
4653 end = 0; /* write error */
4654 nchars += len;
4655 }
4656
4657 /* Stop when writing done or an error was encountered. */
4658 if (!checking_conversion || end == 0)
4659 break;
4660
4661 /* If no error happened until now, writing should be ok, so loop to
4662 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004663 }
4664
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004665 /* If we started writing, finish writing. Also when an error was
4666 * encountered. */
4667 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004669#if defined(UNIX) && defined(HAVE_FSYNC)
4670 /*
4671 * On many journalling file systems there is a bug that causes both the
4672 * original and the backup file to be lost when halting the system
4673 * right after writing the file. That's because only the meta-data is
4674 * journalled. Syncing the file slows down the system, but assures it
4675 * has been written to disk and we don't lose it.
4676 * For a device do try the fsync() but don't complain if it does not
4677 * work (could be a pipe).
4678 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4679 */
4680 if (p_fs && fsync(fd) != 0 && !device)
4681 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004682 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004683 end = 0;
4684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685#endif
4686
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004687#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004688 /* Probably need to set the security context. */
4689 if (!backup_copy)
4690 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004691#endif
4692
Bram Moolenaara5792f52005-11-23 21:25:05 +00004693#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004694 /* When creating a new file, set its owner/group to that of the
4695 * original file. Get the new device and inode number. */
4696 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004697 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004698# ifdef HAVE_FCHOWN
4699 stat_T st;
4700
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004701 /* Don't change the owner when it's already OK, some systems remove
4702 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004703 if (mch_stat((char *)wfname, &st) < 0
4704 || st.st_uid != st_old.st_uid
4705 || st.st_gid != st_old.st_gid)
4706 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004707 /* changing owner might not be possible */
Bram Moolenaar42335f52018-09-13 15:33:43 +02004708 vim_ignored = fchown(fd, st_old.st_uid, -1);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004709 /* if changing group fails clear the group permissions */
4710 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4711 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004712 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004713# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004714 buf_setino(buf);
4715 }
4716 else if (!buf->b_dev_valid)
4717 /* Set the inode when creating a new file. */
4718 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004719#endif
4720
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004721#ifdef UNIX
4722 if (made_writable)
4723 perm &= ~0200; /* reset 'w' bit for security reasons */
4724#endif
4725#ifdef HAVE_FCHMOD
4726 /* set permission of new file same as old file */
4727 if (perm >= 0)
4728 (void)mch_fsetperm(fd, perm);
4729#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004730 if (close(fd) != 0)
4731 {
4732 errmsg = (char_u *)_("E512: Close failed");
4733 end = 0;
4734 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004736#ifndef HAVE_FCHMOD
4737 /* set permission of new file same as old file */
4738 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004739 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004740#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004742 /*
4743 * Probably need to set the ACL before changing the user (can't set the
4744 * ACL on a file the user doesn't own).
4745 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4746 * default), chmod() discards all part of a file's ACL that don't
4747 * represent the mode of the file. It's non-trivial for us to discover
4748 * whether we're in that situation, so we simply always re-set the ACL.
4749 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004750# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004751 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004752# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004753 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004755#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004756 if (buf->b_cryptstate != NULL)
4757 {
4758 crypt_free_state(buf->b_cryptstate);
4759 buf->b_cryptstate = NULL;
4760 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004761#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762
Bram Moolenaar13505972019-01-24 15:04:48 +01004763#if defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004766 /*
4767 * The file was written to a temp file, now it needs to be
4768 * converted with 'charconvert' to (overwrite) the output file.
4769 */
4770 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004772 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4773 fenc, wfname, fname) == FAIL)
4774 {
4775 write_info.bw_conv_error = TRUE;
4776 end = 0;
4777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004779 mch_remove(wfname);
4780 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784
4785 if (end == 0)
4786 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004787 /*
4788 * Error encountered.
4789 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 if (errmsg == NULL)
4791 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004793 {
4794 if (write_info.bw_conv_error_lnum == 0)
4795 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4796 else
4797 {
4798 errmsg_allocated = TRUE;
4799 errmsg = alloc(300);
4800 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4801 (long)write_info.bw_conv_error_lnum);
4802 }
4803 }
Bram Moolenaar13505972019-01-24 15:04:48 +01004804 else if (got_int)
4805 errmsg = (char_u *)_(e_interr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 else
Bram Moolenaar13505972019-01-24 15:04:48 +01004807 errmsg = (char_u *)_("E514: write error (file system full?)");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808 }
4809
4810 /*
4811 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004812 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 * original file when trying to make a backup when writing the file a
4814 * second time.
4815 * When "backup_copy" is set we need to copy the backup over the new
4816 * file. Otherwise rename the backup file.
4817 * If this is OK, don't give the extra warning message.
4818 */
4819 if (backup != NULL)
4820 {
4821 if (backup_copy)
4822 {
4823 /* This may take a while, if we were interrupted let the user
4824 * know we got the message. */
4825 if (got_int)
4826 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01004827 msg(_(e_interr));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 out_flush();
4829 }
4830 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4831 {
4832 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004833 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4834 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 {
4836 /* copy the file. */
4837 write_info.bw_buf = smallbuf;
4838#ifdef HAS_BW_FLAGS
4839 write_info.bw_flags = FIO_NOCONVERT;
4840#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004841 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 SMBUFSIZE)) > 0)
4843 if (buf_write_bytes(&write_info) == FAIL)
4844 break;
4845
4846 if (close(write_info.bw_fd) >= 0
4847 && write_info.bw_len == 0)
4848 end = 1; /* success */
4849 }
4850 close(fd); /* ignore errors for closing read file */
4851 }
4852 }
4853 else
4854 {
4855 if (vim_rename(backup, fname) == 0)
4856 end = 1;
4857 }
4858 }
4859 goto fail;
4860 }
4861
4862 lnum -= start; /* compute number of written lines */
4863 --no_wait_return; /* may wait for return now */
4864
4865#if !(defined(UNIX) || defined(VMS))
4866 fname = sfname; /* use shortname now, for the messages */
4867#endif
4868 if (!filtering)
4869 {
4870 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4871 c = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 if (write_info.bw_conv_error)
4873 {
4874 STRCAT(IObuff, _(" CONVERSION ERROR"));
4875 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004876 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004877 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004878 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 }
4880 else if (notconverted)
4881 {
4882 STRCAT(IObuff, _("[NOT converted]"));
4883 c = TRUE;
4884 }
4885 else if (converted)
4886 {
4887 STRCAT(IObuff, _("[converted]"));
4888 c = TRUE;
4889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 if (device)
4891 {
4892 STRCAT(IObuff, _("[Device]"));
4893 c = TRUE;
4894 }
4895 else if (newfile)
4896 {
4897 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4898 c = TRUE;
4899 }
4900 if (no_eol)
4901 {
4902 msg_add_eol();
4903 c = TRUE;
4904 }
4905 /* may add [unix/dos/mac] */
4906 if (msg_add_fileformat(fileformat))
4907 c = TRUE;
4908#ifdef FEAT_CRYPT
4909 if (wb_flags & FIO_ENCRYPTED)
4910 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004911 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 c = TRUE;
4913 }
4914#endif
4915 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4916 if (!shortmess(SHM_WRITE))
4917 {
4918 if (append)
4919 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4920 else
4921 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4922 }
4923
Bram Moolenaar32526b32019-01-19 17:43:09 +01004924 set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 }
4926
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004927 /* When written everything correctly: reset 'modified'. Unless not
4928 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004929 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 && !write_info.bw_conv_error
Bram Moolenaar13505972019-01-24 15:04:48 +01004931 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 {
4933 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004934 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004935 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01004936 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
4937 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004939 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 }
4941
4942 /*
4943 * If written to the current file, update the timestamp of the swap file
4944 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4945 */
4946 if (overwriting)
4947 {
4948 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004949 if (append)
4950 buf->b_flags &= ~BF_NEW;
4951 else
4952 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 }
4954
4955 /*
4956 * If we kept a backup until now, and we are in patch mode, then we make
4957 * the backup file our 'original' file.
4958 */
4959 if (*p_pm && dobackup)
4960 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004961 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 fname, p_pm, FALSE);
4963
4964 if (backup != NULL)
4965 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004966 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967
4968 /*
4969 * If the original file does not exist yet
4970 * the current backup file becomes the original file
4971 */
4972 if (org == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004973 emsg(_("E205: Patchmode: can't save original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 else if (mch_stat(org, &st) < 0)
4975 {
4976 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01004977 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978#ifdef UNIX
4979 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4980#endif
4981 }
4982 }
4983 /*
4984 * If there is no backup file, remember that a (new) file was
4985 * created.
4986 */
4987 else
4988 {
4989 int empty_fd;
4990
4991 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004992 || (empty_fd = mch_open(org,
4993 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004994 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004995 emsg(_("E206: patchmode: can't touch empty original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996 else
4997 close(empty_fd);
4998 }
4999 if (org != NULL)
5000 {
5001 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5002 vim_free(org);
5003 }
5004 }
5005
5006 /*
5007 * Remove the backup unless 'backup' option is set
5008 */
5009 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005010 emsg(_("E207: Can't delete backup file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012 goto nofail;
5013
5014 /*
5015 * Finish up. We get here either after failure or success.
5016 */
5017fail:
5018 --no_wait_return; /* may wait for return now */
5019nofail:
5020
5021 /* Done saving, we accept changed buffer warnings again */
5022 buf->b_saving = FALSE;
5023
5024 vim_free(backup);
5025 if (buffer != smallbuf)
5026 vim_free(buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 vim_free(fenc_tofree);
5028 vim_free(write_info.bw_conv_buf);
Bram Moolenaar13505972019-01-24 15:04:48 +01005029#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 if (write_info.bw_iconv_fd != (iconv_t)-1)
5031 {
5032 iconv_close(write_info.bw_iconv_fd);
5033 write_info.bw_iconv_fd = (iconv_t)-1;
5034 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035#endif
5036#ifdef HAVE_ACL
5037 mch_free_acl(acl);
5038#endif
5039
5040 if (errmsg != NULL)
5041 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005042 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043
Bram Moolenaar8820b482017-03-16 17:23:31 +01005044 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 msg_add_fname(buf,
5046#ifndef UNIX
5047 sfname
5048#else
5049 fname
5050#endif
5051 ); /* put file name in IObuff with quotes */
5052 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5053 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5054 /* If the error message has the form "is ...", put the error number in
5055 * front of the file name. */
5056 if (errnum != NULL)
5057 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005058 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 mch_memmove(IObuff, errnum, (size_t)numlen);
5060 }
5061 STRCAT(IObuff, errmsg);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005062 emsg((char *)IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005063 if (errmsg_allocated)
5064 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065
5066 retval = FAIL;
5067 if (end == 0)
5068 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01005069 msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070 attr | MSG_HIST);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005071 msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005072 attr | MSG_HIST);
5073
5074 /* Update the timestamp to avoid an "overwrite changed file"
5075 * prompt when writing again. */
5076 if (mch_stat((char *)fname, &st_old) >= 0)
5077 {
5078 buf_store_time(buf, &st_old, fname);
5079 buf->b_mtime_read = buf->b_mtime;
5080 }
5081 }
5082 }
5083 msg_scroll = msg_save;
5084
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005085#ifdef FEAT_PERSISTENT_UNDO
5086 /*
5087 * When writing the whole file and 'undofile' is set, also write the undo
5088 * file.
5089 */
5090 if (retval == OK && write_undo_file)
5091 {
5092 char_u hash[UNDO_HASH_SIZE];
5093
5094 sha256_finish(&sha_ctx, hash);
5095 u_write_undo(NULL, FALSE, buf, hash);
5096 }
5097#endif
5098
Bram Moolenaar071d4272004-06-13 20:20:40 +00005099#ifdef FEAT_EVAL
5100 if (!should_abort(retval))
5101#else
5102 if (!got_int)
5103#endif
5104 {
5105 aco_save_T aco;
5106
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005107 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5108
Bram Moolenaar071d4272004-06-13 20:20:40 +00005109 /*
5110 * Apply POST autocommands.
5111 * Careful: The autocommands may call buf_write() recursively!
5112 */
5113 aucmd_prepbuf(&aco, buf);
5114
5115 if (append)
5116 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5117 FALSE, curbuf, eap);
5118 else if (filtering)
5119 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5120 FALSE, curbuf, eap);
5121 else if (reset_changed && whole)
5122 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5123 FALSE, curbuf, eap);
5124 else
5125 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5126 FALSE, curbuf, eap);
5127
5128 /* restore curwin/curbuf and a few other things */
5129 aucmd_restbuf(&aco);
5130
5131#ifdef FEAT_EVAL
5132 if (aborting()) /* autocmds may abort script processing */
5133 retval = FALSE;
5134#endif
5135 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136
5137 got_int |= prev_got_int;
5138
Bram Moolenaar071d4272004-06-13 20:20:40 +00005139 return retval;
5140}
5141
5142/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005143 * Set the name of the current buffer. Use when the buffer doesn't have a
5144 * name and a ":r" or ":w" command with a file name is used.
5145 */
5146 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005147set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005148{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005149 buf_T *buf = curbuf;
5150
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005151 /* It's like the unnamed buffer is deleted.... */
5152 if (curbuf->b_p_bl)
5153 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5154 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005155#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005156 if (aborting()) /* autocmds may abort script processing */
5157 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005158#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005159 if (curbuf != buf)
5160 {
5161 /* We are in another buffer now, don't do the renaming. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005162 emsg(_(e_auchangedbuf));
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005163 return FAIL;
5164 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005165
5166 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5167 curbuf->b_flags |= BF_NOTEDITED;
5168
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005169 /* ....and a new named one is created */
5170 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5171 if (curbuf->b_p_bl)
5172 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005173#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005174 if (aborting()) /* autocmds may abort script processing */
5175 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005176#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005177
5178 /* Do filetype detection now if 'filetype' is empty. */
5179 if (*curbuf->b_p_ft == NUL)
5180 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005181 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005182 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005183 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005184 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005185
5186 return OK;
5187}
5188
5189/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190 * Put file name into IObuff with quotes.
5191 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005192 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005193msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194{
5195 if (fname == NULL)
5196 fname = (char_u *)"-stdin-";
5197 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5198 IObuff[0] = '"';
5199 STRCAT(IObuff, "\" ");
5200}
5201
5202/*
5203 * Append message for text mode to IObuff.
5204 * Return TRUE if something appended.
5205 */
5206 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005207msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208{
5209#ifndef USE_CRNL
5210 if (eol_type == EOL_DOS)
5211 {
5212 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5213 return TRUE;
5214 }
5215#endif
5216#ifndef USE_CR
5217 if (eol_type == EOL_MAC)
5218 {
5219 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5220 return TRUE;
5221 }
5222#endif
5223#if defined(USE_CRNL) || defined(USE_CR)
5224 if (eol_type == EOL_UNIX)
5225 {
5226 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5227 return TRUE;
5228 }
5229#endif
5230 return FALSE;
5231}
5232
5233/*
5234 * Append line and character count to IObuff.
5235 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005236 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005237msg_add_lines(
5238 int insert_space,
5239 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005240 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241{
5242 char_u *p;
5243
5244 p = IObuff + STRLEN(IObuff);
5245
5246 if (insert_space)
5247 *p++ = ' ';
5248 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005249 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01005250 "%ldL, %lldC", lnum, (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005251 else
5252 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005253 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005255 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5256 NGETTEXT("%lld character", "%lld characters", nchars),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01005257 (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258 }
5259}
5260
5261/*
5262 * Append message for missing line separator to IObuff.
5263 */
5264 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005265msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266{
5267 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5268}
5269
5270/*
5271 * Check modification time of file, before writing to it.
5272 * The size isn't checked, because using a tool like "gzip" takes care of
5273 * using the same timestamp but can't set the size.
5274 */
5275 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005276check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005277{
5278 if (buf->b_mtime_read != 0
5279 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5280 {
5281 msg_scroll = TRUE; /* don't overwrite messages here */
5282 msg_silent = 0; /* must give this prompt */
5283 /* don't use emsg() here, don't want to flush the buffers */
Bram Moolenaar32526b32019-01-19 17:43:09 +01005284 msg_attr(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005285 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5287 TRUE) == 'n')
5288 return FAIL;
5289 msg_scroll = FALSE; /* always overwrite the file message now */
5290 }
5291 return OK;
5292}
5293
5294 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005295time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005297#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005298 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5299 * the seconds. Since the roundoff is done when flushing the inode, the
5300 * time may change unexpectedly by one second!!! */
5301 return (t1 - t2 > 1 || t2 - t1 > 1);
5302#else
5303 return (t1 != t2);
5304#endif
5305}
5306
5307/*
5308 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005309 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310 *
5311 * Return FAIL for failure, OK otherwise.
5312 */
5313 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005314buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315{
5316 int wlen;
5317 char_u *buf = ip->bw_buf; /* data to write */
5318 int len = ip->bw_len; /* length of data */
5319#ifdef HAS_BW_FLAGS
5320 int flags = ip->bw_flags; /* extra flags */
5321#endif
5322
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323 /*
5324 * Skip conversion when writing the crypt magic number or the BOM.
5325 */
5326 if (!(flags & FIO_NOCONVERT))
5327 {
5328 char_u *p;
5329 unsigned c;
5330 int n;
5331
5332 if (flags & FIO_UTF8)
5333 {
5334 /*
5335 * Convert latin1 in the buffer to UTF-8 in the file.
5336 */
5337 p = ip->bw_conv_buf; /* translate to buffer */
5338 for (wlen = 0; wlen < len; ++wlen)
5339 p += utf_char2bytes(buf[wlen], p);
5340 buf = ip->bw_conv_buf;
5341 len = (int)(p - ip->bw_conv_buf);
5342 }
5343 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5344 {
5345 /*
5346 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5347 * Latin1 chars in the file.
5348 */
5349 if (flags & FIO_LATIN1)
5350 p = buf; /* translate in-place (can only get shorter) */
5351 else
5352 p = ip->bw_conv_buf; /* translate to buffer */
5353 for (wlen = 0; wlen < len; wlen += n)
5354 {
5355 if (wlen == 0 && ip->bw_restlen != 0)
5356 {
5357 int l;
5358
5359 /* Use remainder of previous call. Append the start of
5360 * buf[] to get a full sequence. Might still be too
5361 * short! */
5362 l = CONV_RESTLEN - ip->bw_restlen;
5363 if (l > len)
5364 l = len;
5365 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005366 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367 if (n > ip->bw_restlen + len)
5368 {
5369 /* We have an incomplete byte sequence at the end to
5370 * be written. We can't convert it without the
5371 * remaining bytes. Keep them for the next call. */
5372 if (ip->bw_restlen + len > CONV_RESTLEN)
5373 return FAIL;
5374 ip->bw_restlen += len;
5375 break;
5376 }
5377 if (n > 1)
5378 c = utf_ptr2char(ip->bw_rest);
5379 else
5380 c = ip->bw_rest[0];
5381 if (n >= ip->bw_restlen)
5382 {
5383 n -= ip->bw_restlen;
5384 ip->bw_restlen = 0;
5385 }
5386 else
5387 {
5388 ip->bw_restlen -= n;
5389 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5390 (size_t)ip->bw_restlen);
5391 n = 0;
5392 }
5393 }
5394 else
5395 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005396 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397 if (n > len - wlen)
5398 {
5399 /* We have an incomplete byte sequence at the end to
5400 * be written. We can't convert it without the
5401 * remaining bytes. Keep them for the next call. */
5402 if (len - wlen > CONV_RESTLEN)
5403 return FAIL;
5404 ip->bw_restlen = len - wlen;
5405 mch_memmove(ip->bw_rest, buf + wlen,
5406 (size_t)ip->bw_restlen);
5407 break;
5408 }
5409 if (n > 1)
5410 c = utf_ptr2char(buf + wlen);
5411 else
5412 c = buf[wlen];
5413 }
5414
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005415 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5416 {
5417 ip->bw_conv_error = TRUE;
5418 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5419 }
5420 if (c == NL)
5421 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005422 }
5423 if (flags & FIO_LATIN1)
5424 len = (int)(p - buf);
5425 else
5426 {
5427 buf = ip->bw_conv_buf;
5428 len = (int)(p - ip->bw_conv_buf);
5429 }
5430 }
5431
Bram Moolenaar13505972019-01-24 15:04:48 +01005432#ifdef WIN3264
Bram Moolenaar071d4272004-06-13 20:20:40 +00005433 else if (flags & FIO_CODEPAGE)
5434 {
5435 /*
5436 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5437 * codepage.
5438 */
5439 char_u *from;
5440 size_t fromlen;
5441 char_u *to;
5442 int u8c;
5443 BOOL bad = FALSE;
5444 int needed;
5445
5446 if (ip->bw_restlen > 0)
5447 {
5448 /* Need to concatenate the remainder of the previous call and
5449 * the bytes of the current call. Use the end of the
5450 * conversion buffer for this. */
5451 fromlen = len + ip->bw_restlen;
5452 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5453 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5454 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5455 }
5456 else
5457 {
5458 from = buf;
5459 fromlen = len;
5460 }
5461
5462 to = ip->bw_conv_buf;
5463 if (enc_utf8)
5464 {
5465 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5466 * The buffer has been allocated to be big enough. */
5467 while (fromlen > 0)
5468 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005469 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005470 if (n > (int)fromlen) /* incomplete byte sequence */
5471 break;
5472 u8c = utf_ptr2char(from);
5473 *to++ = (u8c & 0xff);
5474 *to++ = (u8c >> 8);
5475 fromlen -= n;
5476 from += n;
5477 }
5478
5479 /* Copy remainder to ip->bw_rest[] to be used for the next
5480 * call. */
5481 if (fromlen > CONV_RESTLEN)
5482 {
5483 /* weird overlong sequence */
5484 ip->bw_conv_error = TRUE;
5485 return FAIL;
5486 }
5487 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005488 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489 }
5490 else
5491 {
5492 /* Convert from enc_codepage to UCS-2, to the start of the
5493 * buffer. The buffer has been allocated to be big enough. */
5494 ip->bw_restlen = 0;
5495 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005496 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497 NULL, 0);
5498 if (needed == 0)
5499 {
5500 /* When conversion fails there may be a trailing byte. */
5501 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005502 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503 NULL, 0);
5504 if (needed == 0)
5505 {
5506 /* Conversion doesn't work. */
5507 ip->bw_conv_error = TRUE;
5508 return FAIL;
5509 }
5510 /* Save the trailing byte for the next call. */
5511 ip->bw_rest[0] = from[fromlen - 1];
5512 ip->bw_restlen = 1;
5513 }
5514 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005515 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516 (LPWSTR)to, needed);
5517 if (needed == 0)
5518 {
5519 /* Safety check: Conversion doesn't work. */
5520 ip->bw_conv_error = TRUE;
5521 return FAIL;
5522 }
5523 to += needed * 2;
5524 }
5525
5526 fromlen = to - ip->bw_conv_buf;
5527 buf = to;
Bram Moolenaar13505972019-01-24 15:04:48 +01005528# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 if (FIO_GET_CP(flags) == CP_UTF8)
5530 {
5531 /* Convert from UCS-2 to UTF-8, using the remainder of the
5532 * conversion buffer. Fails when out of space. */
5533 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5534 {
5535 u8c = *from++;
5536 u8c += (*from++ << 8);
5537 to += utf_char2bytes(u8c, to);
5538 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5539 {
5540 ip->bw_conv_error = TRUE;
5541 return FAIL;
5542 }
5543 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005544 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 }
5546 else
Bram Moolenaar13505972019-01-24 15:04:48 +01005547# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 {
5549 /* Convert from UCS-2 to the codepage, using the remainder of
5550 * the conversion buffer. If the conversion uses the default
5551 * character "0", the data doesn't fit in this encoding, so
5552 * fail. */
5553 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5554 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005555 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5556 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557 if (bad)
5558 {
5559 ip->bw_conv_error = TRUE;
5560 return FAIL;
5561 }
5562 }
5563 }
Bram Moolenaar13505972019-01-24 15:04:48 +01005564#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565
Bram Moolenaar13505972019-01-24 15:04:48 +01005566#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 else if (flags & FIO_MACROMAN)
5568 {
5569 /*
5570 * Convert UTF-8 or latin1 to Apple MacRoman.
5571 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005572 char_u *from;
5573 size_t fromlen;
5574
5575 if (ip->bw_restlen > 0)
5576 {
5577 /* Need to concatenate the remainder of the previous call and
5578 * the bytes of the current call. Use the end of the
5579 * conversion buffer for this. */
5580 fromlen = len + ip->bw_restlen;
5581 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5582 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5583 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5584 }
5585 else
5586 {
5587 from = buf;
5588 fromlen = len;
5589 }
5590
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005591 if (enc2macroman(from, fromlen,
5592 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5593 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 {
5595 ip->bw_conv_error = TRUE;
5596 return FAIL;
5597 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599 }
Bram Moolenaar13505972019-01-24 15:04:48 +01005600#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601
Bram Moolenaar13505972019-01-24 15:04:48 +01005602#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603 if (ip->bw_iconv_fd != (iconv_t)-1)
5604 {
5605 const char *from;
5606 size_t fromlen;
5607 char *to;
5608 size_t tolen;
5609
5610 /* Convert with iconv(). */
5611 if (ip->bw_restlen > 0)
5612 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005613 char *fp;
5614
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 /* Need to concatenate the remainder of the previous call and
5616 * the bytes of the current call. Use the end of the
5617 * conversion buffer for this. */
5618 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005619 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5620 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5621 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5622 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 tolen = ip->bw_conv_buflen - fromlen;
5624 }
5625 else
5626 {
5627 from = (const char *)buf;
5628 fromlen = len;
5629 tolen = ip->bw_conv_buflen;
5630 }
5631 to = (char *)ip->bw_conv_buf;
5632
5633 if (ip->bw_first)
5634 {
5635 size_t save_len = tolen;
5636
5637 /* output the initial shift state sequence */
5638 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5639
5640 /* There is a bug in iconv() on Linux (which appears to be
5641 * wide-spread) which sets "to" to NULL and messes up "tolen".
5642 */
5643 if (to == NULL)
5644 {
5645 to = (char *)ip->bw_conv_buf;
5646 tolen = save_len;
5647 }
5648 ip->bw_first = FALSE;
5649 }
5650
5651 /*
5652 * If iconv() has an error or there is not enough room, fail.
5653 */
5654 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5655 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5656 || fromlen > CONV_RESTLEN)
5657 {
5658 ip->bw_conv_error = TRUE;
5659 return FAIL;
5660 }
5661
5662 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5663 if (fromlen > 0)
5664 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5665 ip->bw_restlen = (int)fromlen;
5666
5667 buf = ip->bw_conv_buf;
5668 len = (int)((char_u *)to - ip->bw_conv_buf);
5669 }
Bram Moolenaar13505972019-01-24 15:04:48 +01005670#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005673 if (ip->bw_fd < 0)
5674 /* Only checking conversion, which is OK if we get here. */
5675 return OK;
5676
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005678 if (flags & FIO_ENCRYPTED)
5679 {
5680 /* Encrypt the data. Do it in-place if possible, otherwise use an
5681 * allocated buffer. */
Bram Moolenaar987411d2019-01-18 22:48:34 +01005682# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005683 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5684 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01005685# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005686 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
Bram Moolenaar987411d2019-01-18 22:48:34 +01005687# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005688 }
5689 else
5690 {
5691 char_u *outbuf;
5692
5693 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5694 if (len == 0)
5695 return OK; /* Crypt layer is buffering, will flush later. */
5696 wlen = write_eintr(ip->bw_fd, outbuf, len);
5697 vim_free(outbuf);
5698 return (wlen < len) ? FAIL : OK;
5699 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01005700# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005701 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702#endif
5703
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005704 wlen = write_eintr(ip->bw_fd, buf, len);
5705 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706}
5707
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708/*
5709 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005710 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 */
5712 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005713ucs2bytes(
5714 unsigned c, /* in: character */
5715 char_u **pp, /* in/out: pointer to result */
5716 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717{
5718 char_u *p = *pp;
5719 int error = FALSE;
5720 int cc;
5721
5722
5723 if (flags & FIO_UCS4)
5724 {
5725 if (flags & FIO_ENDIAN_L)
5726 {
5727 *p++ = c;
5728 *p++ = (c >> 8);
5729 *p++ = (c >> 16);
5730 *p++ = (c >> 24);
5731 }
5732 else
5733 {
5734 *p++ = (c >> 24);
5735 *p++ = (c >> 16);
5736 *p++ = (c >> 8);
5737 *p++ = c;
5738 }
5739 }
5740 else if (flags & (FIO_UCS2 | FIO_UTF16))
5741 {
5742 if (c >= 0x10000)
5743 {
5744 if (flags & FIO_UTF16)
5745 {
5746 /* Make two words, ten bits of the character in each. First
5747 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5748 c -= 0x10000;
5749 if (c >= 0x100000)
5750 error = TRUE;
5751 cc = ((c >> 10) & 0x3ff) + 0xd800;
5752 if (flags & FIO_ENDIAN_L)
5753 {
5754 *p++ = cc;
5755 *p++ = ((unsigned)cc >> 8);
5756 }
5757 else
5758 {
5759 *p++ = ((unsigned)cc >> 8);
5760 *p++ = cc;
5761 }
5762 c = (c & 0x3ff) + 0xdc00;
5763 }
5764 else
5765 error = TRUE;
5766 }
5767 if (flags & FIO_ENDIAN_L)
5768 {
5769 *p++ = c;
5770 *p++ = (c >> 8);
5771 }
5772 else
5773 {
5774 *p++ = (c >> 8);
5775 *p++ = c;
5776 }
5777 }
5778 else /* Latin1 */
5779 {
5780 if (c >= 0x100)
5781 {
5782 error = TRUE;
5783 *p++ = 0xBF;
5784 }
5785 else
5786 *p++ = c;
5787 }
5788
5789 *pp = p;
5790 return error;
5791}
5792
5793/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005794 * Return TRUE if file encoding "fenc" requires conversion from or to
5795 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796 */
5797 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005798need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005800 int same_encoding;
5801 int enc_flags;
5802 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005804 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005805 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005806 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005807 fenc_flags = 0;
5808 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005809 else
5810 {
5811 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5812 * "ucs-4be", etc. */
5813 enc_flags = get_fio_flags(p_enc);
5814 fenc_flags = get_fio_flags(fenc);
5815 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5816 }
5817 if (same_encoding)
5818 {
5819 /* Specified encoding matches with 'encoding'. This requires
5820 * conversion when 'encoding' is Unicode but not UTF-8. */
5821 return enc_unicode != 0;
5822 }
5823
5824 /* Encodings differ. However, conversion is not needed when 'enc' is any
5825 * Unicode encoding and the file is UTF-8. */
5826 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005827}
5828
5829/*
5830 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5831 * internal conversion.
5832 * if "ptr" is an empty string, use 'encoding'.
5833 */
5834 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005835get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005836{
5837 int prop;
5838
5839 if (*ptr == NUL)
5840 ptr = p_enc;
5841
5842 prop = enc_canon_props(ptr);
5843 if (prop & ENC_UNICODE)
5844 {
5845 if (prop & ENC_2BYTE)
5846 {
5847 if (prop & ENC_ENDIAN_L)
5848 return FIO_UCS2 | FIO_ENDIAN_L;
5849 return FIO_UCS2;
5850 }
5851 if (prop & ENC_4BYTE)
5852 {
5853 if (prop & ENC_ENDIAN_L)
5854 return FIO_UCS4 | FIO_ENDIAN_L;
5855 return FIO_UCS4;
5856 }
5857 if (prop & ENC_2WORD)
5858 {
5859 if (prop & ENC_ENDIAN_L)
5860 return FIO_UTF16 | FIO_ENDIAN_L;
5861 return FIO_UTF16;
5862 }
5863 return FIO_UTF8;
5864 }
5865 if (prop & ENC_LATIN1)
5866 return FIO_LATIN1;
5867 /* must be ENC_DBCS, requires iconv() */
5868 return 0;
5869}
5870
5871#ifdef WIN3264
5872/*
5873 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5874 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5875 * Used for conversion between 'encoding' and 'fileencoding'.
5876 */
5877 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005878get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879{
5880 int cp;
5881
5882 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5883 if (!enc_utf8 && enc_codepage <= 0)
5884 return 0;
5885
5886 cp = encname2codepage(ptr);
5887 if (cp == 0)
5888 {
5889# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5890 if (STRCMP(ptr, "utf-8") == 0)
5891 cp = CP_UTF8;
5892 else
5893# endif
5894 return 0;
5895 }
5896 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5897}
5898#endif
5899
Bram Moolenaard0573012017-10-28 21:11:06 +02005900#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901/*
5902 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5903 * needed for the internal conversion to/from utf-8 or latin1.
5904 */
5905 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005906get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907{
5908 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5909 && (enc_canon_props(ptr) & ENC_MACROMAN))
5910 return FIO_MACROMAN;
5911 return 0;
5912}
5913#endif
5914
5915/*
5916 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5917 * "size" must be at least 2.
5918 * Return the name of the encoding and set "*lenp" to the length.
5919 * Returns NULL when no BOM found.
5920 */
5921 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005922check_for_bom(
5923 char_u *p,
5924 long size,
5925 int *lenp,
5926 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927{
5928 char *name = NULL;
5929 int len = 2;
5930
5931 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005932 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 {
5934 name = "utf-8"; /* EF BB BF */
5935 len = 3;
5936 }
5937 else if (p[0] == 0xff && p[1] == 0xfe)
5938 {
5939 if (size >= 4 && p[2] == 0 && p[3] == 0
5940 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5941 {
5942 name = "ucs-4le"; /* FF FE 00 00 */
5943 len = 4;
5944 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005945 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005947 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5948 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949 name = "utf-16le"; /* FF FE */
5950 }
5951 else if (p[0] == 0xfe && p[1] == 0xff
5952 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5953 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005954 /* Default to utf-16, it works also for ucs-2 text. */
5955 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005957 else
5958 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959 }
5960 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5961 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5962 {
5963 name = "ucs-4"; /* 00 00 FE FF */
5964 len = 4;
5965 }
5966
5967 *lenp = len;
5968 return (char_u *)name;
5969}
5970
5971/*
5972 * Generate a BOM in "buf[4]" for encoding "name".
5973 * Return the length of the BOM (zero when no BOM).
5974 */
5975 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005976make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977{
5978 int flags;
5979 char_u *p;
5980
5981 flags = get_fio_flags(name);
5982
5983 /* Can't put a BOM in a non-Unicode file. */
5984 if (flags == FIO_LATIN1 || flags == 0)
5985 return 0;
5986
5987 if (flags == FIO_UTF8) /* UTF-8 */
5988 {
5989 buf[0] = 0xef;
5990 buf[1] = 0xbb;
5991 buf[2] = 0xbf;
5992 return 3;
5993 }
5994 p = buf;
5995 (void)ucs2bytes(0xfeff, &p, flags);
5996 return (int)(p - buf);
5997}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998
5999/*
6000 * Try to find a shortname by comparing the fullname with the current
6001 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006002 * Returns "full_path" or pointer into "full_path" if shortened.
6003 */
6004 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006005shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006006{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006007 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006008 char_u *p = full_path;
6009
Bram Moolenaard9462e32011-04-11 21:35:11 +02006010 dirname = alloc(MAXPATHL);
6011 if (dirname == NULL)
6012 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006013 if (mch_dirname(dirname, MAXPATHL) == OK)
6014 {
6015 p = shorten_fname(full_path, dirname);
6016 if (p == NULL || *p == NUL)
6017 p = full_path;
6018 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006019 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006020 return p;
6021}
6022
6023/*
6024 * Try to find a shortname by comparing the fullname with the current
6025 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 * Returns NULL if not shorter name possible, pointer into "full_path"
6027 * otherwise.
6028 */
6029 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006030shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031{
6032 int len;
6033 char_u *p;
6034
6035 if (full_path == NULL)
6036 return NULL;
6037 len = (int)STRLEN(dir_name);
6038 if (fnamencmp(dir_name, full_path, len) == 0)
6039 {
6040 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006041#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006043 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 * slash, since C: by itself does not define a specific dir. In this
6045 * case p may already be correct. <negri>
6046 */
6047 if (!((len > 2) && (*(p - 2) == ':')))
6048#endif
6049 {
6050 if (vim_ispathsep(*p))
6051 ++p;
6052#ifndef VMS /* the path separator is always part of the path */
6053 else
6054 p = NULL;
6055#endif
6056 }
6057 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006058#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059 /*
6060 * When using a file in the current drive, remove the drive name:
6061 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6062 * a floppy from "A:\dir" to "B:\dir".
6063 */
6064 else if (len > 3
6065 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6066 && full_path[1] == ':'
6067 && vim_ispathsep(full_path[2]))
6068 p = full_path + 2;
6069#endif
6070 else
6071 p = NULL;
6072 return p;
6073}
6074
6075/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006076 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077 * When "force" is TRUE: Use full path from now on for files currently being
6078 * edited, both for file name and swap file name. Try to shorten the file
6079 * names a bit, if safe to do so.
6080 * When "force" is FALSE: Only try to shorten absolute file names.
6081 * For buffers that have buftype "nofile" or "scratch": never change the file
6082 * name.
6083 */
6084 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006085shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6086{
6087 char_u *p;
6088
6089 if (buf->b_fname != NULL
6090#ifdef FEAT_QUICKFIX
6091 && !bt_nofile(buf)
6092#endif
6093 && !path_with_url(buf->b_fname)
6094 && (force
6095 || buf->b_sfname == NULL
6096 || mch_isFullName(buf->b_sfname)))
6097 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02006098 if (buf->b_sfname != buf->b_ffname)
6099 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02006100 p = shorten_fname(buf->b_ffname, dirname);
6101 if (p != NULL)
6102 {
6103 buf->b_sfname = vim_strsave(p);
6104 buf->b_fname = buf->b_sfname;
6105 }
6106 if (p == NULL || buf->b_fname == NULL)
6107 buf->b_fname = buf->b_ffname;
6108 }
6109}
6110
6111/*
6112 * Shorten filenames for all buffers.
6113 */
6114 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006115shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116{
6117 char_u dirname[MAXPATHL];
6118 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119
6120 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006121 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006123 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006124
6125 /* Always make the swap file name a full path, a "nofile" buffer may
6126 * also have a swap file. */
6127 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006130 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131}
6132
6133#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6134 || defined(FEAT_GUI_MSWIN) \
6135 || defined(FEAT_GUI_MAC) \
6136 || defined(PROTO)
6137/*
6138 * Shorten all filenames in "fnames[count]" by current directory.
6139 */
6140 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006141shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142{
6143 int i;
6144 char_u dirname[MAXPATHL];
6145 char_u *p;
6146
6147 if (fnames == NULL || count < 1)
6148 return;
6149 mch_dirname(dirname, sizeof(dirname));
6150 for (i = 0; i < count; ++i)
6151 {
6152 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6153 {
6154 /* shorten_fname() returns pointer in given "fnames[i]". If free
6155 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6156 * "p" first then free fnames[i]. */
6157 p = vim_strsave(p);
6158 vim_free(fnames[i]);
6159 fnames[i] = p;
6160 }
6161 }
6162}
6163#endif
6164
6165/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02006166 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 * fo_o_h.ext for MSDOS or when shortname option set.
6168 *
6169 * Assumed that fname is a valid name found in the filesystem we assure that
6170 * the return value is a different name and ends in 'ext'.
6171 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6172 * characters otherwise.
6173 * Space for the returned name is allocated, must be freed later.
6174 * Returns NULL when out of memory.
6175 */
6176 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006177modname(
6178 char_u *fname,
6179 char_u *ext,
6180 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006182 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 fname, ext, prepend_dot);
6184}
6185
6186 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006187buf_modname(
6188 int shortname, /* use 8.3 file name */
6189 char_u *fname,
6190 char_u *ext,
6191 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192{
6193 char_u *retval;
6194 char_u *s;
6195 char_u *e;
6196 char_u *ptr;
6197 int fnamelen, extlen;
6198
6199 extlen = (int)STRLEN(ext);
6200
6201 /*
6202 * If there is no file name we must get the name of the current directory
6203 * (we need the full path in case :cd is used).
6204 */
6205 if (fname == NULL || *fname == NUL)
6206 {
6207 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6208 if (retval == NULL)
6209 return NULL;
6210 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6211 (fnamelen = (int)STRLEN(retval)) == 0)
6212 {
6213 vim_free(retval);
6214 return NULL;
6215 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006216 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 {
6218 retval[fnamelen++] = PATHSEP;
6219 retval[fnamelen] = NUL;
6220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 }
6223 else
6224 {
6225 fnamelen = (int)STRLEN(fname);
6226 retval = alloc((unsigned)(fnamelen + extlen + 3));
6227 if (retval == NULL)
6228 return NULL;
6229 STRCPY(retval, fname);
6230#ifdef VMS
6231 vms_remove_version(retval); /* we do not need versions here */
6232#endif
6233 }
6234
6235 /*
6236 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6237 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6238 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6239 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6240 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006241 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006244#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006246#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006248#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 )
6250 if (*ptr == '.') /* replace '.' by '_' */
6251 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006253 {
6254 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006256 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258
6259 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6261 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262
6263 s = ptr + STRLEN(ptr);
6264
6265 /*
6266 * For 8.3 file names we may have to reduce the length.
6267 */
6268#ifdef USE_LONG_FNAME
6269 if (!USE_LONG_FNAME || shortname)
6270#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272#endif
6273 {
6274 /*
6275 * If there is no file name, or the file name ends in '/', and the
6276 * extension starts with '.', put a '_' before the dot, because just
6277 * ".ext" is invalid.
6278 */
6279 if (fname == NULL || *fname == NUL
6280 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6281 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 *s++ = '_';
6284 }
6285 /*
6286 * If the extension starts with '.', truncate the base name at 8
6287 * characters
6288 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006291 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 {
6293 s = ptr + 8;
6294 *s = '\0';
6295 }
6296 }
6297 /*
6298 * If the extension doesn't start with '.', and the file name
6299 * doesn't have an extension yet, append a '.'
6300 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 else if ((e = vim_strchr(ptr, '.')) == NULL)
6302 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 /*
6304 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006305 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 */
6307 else if ((int)STRLEN(e) + extlen > 4)
6308 s = e + 4 - extlen;
6309 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006310#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 /*
6312 * If there is no file name, and the extension starts with '.', put a
6313 * '_' before the dot, because just ".ext" may be invalid if it's on a
6314 * FAT partition, and on HPFS it doesn't matter.
6315 */
6316 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6317 *s++ = '_';
6318#endif
6319
6320 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006321 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 * ext can start with '.' and cannot exceed 3 more characters.
6323 */
6324 STRCPY(s, ext);
6325
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 /*
6327 * Prepend the dot.
6328 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006329 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330#ifdef USE_LONG_FNAME
6331 && USE_LONG_FNAME
6332#endif
6333 )
6334 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006335 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338
6339 /*
6340 * Check that, after appending the extension, the file name is really
6341 * different.
6342 */
6343 if (fname != NULL && STRCMP(fname, retval) == 0)
6344 {
6345 /* we search for a character that can be replaced by '_' */
6346 while (--s >= ptr)
6347 {
6348 if (*s != '_')
6349 {
6350 *s = '_';
6351 break;
6352 }
6353 }
6354 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6355 *ptr = 'v';
6356 }
6357 return retval;
6358}
6359
6360/*
6361 * Like fgets(), but if the file line is too long, it is truncated and the
6362 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006363 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 */
6365 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006366vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367{
6368 char *eof;
6369#define FGETS_SIZE 200
6370 char tbuf[FGETS_SIZE];
6371
6372 buf[size - 2] = NUL;
6373#ifdef USE_CR
6374 eof = fgets_cr((char *)buf, size, fp);
6375#else
6376 eof = fgets((char *)buf, size, fp);
6377#endif
6378 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6379 {
6380 buf[size - 1] = NUL; /* Truncate the line */
6381
6382 /* Now throw away the rest of the line: */
6383 do
6384 {
6385 tbuf[FGETS_SIZE - 2] = NUL;
6386#ifdef USE_CR
Bram Moolenaar42335f52018-09-13 15:33:43 +02006387 vim_ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388#else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006389 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390#endif
6391 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6392 }
6393 return (eof == NULL);
6394}
6395
6396#if defined(USE_CR) || defined(PROTO)
6397/*
6398 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6399 * Returns TRUE for end-of-file.
6400 * Only used for the Mac, because it's much slower than vim_fgets().
6401 */
6402 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006403tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404{
6405 int i = 0;
6406 int c;
6407 int eof = FALSE;
6408
6409 for (;;)
6410 {
6411 c = fgetc(fp);
6412 if (c == EOF)
6413 {
6414 eof = TRUE;
6415 break;
6416 }
6417 if (c == '\r')
6418 {
6419 /* Always store a NL for end-of-line. */
6420 if (i < size - 1)
6421 buf[i++] = '\n';
6422 c = fgetc(fp);
6423 if (c != '\n') /* Macintosh format: single CR. */
6424 ungetc(c, fp);
6425 break;
6426 }
6427 if (i < size - 1)
6428 buf[i++] = c;
6429 if (c == '\n')
6430 break;
6431 }
6432 buf[i] = NUL;
6433 return eof;
6434}
6435#endif
6436
6437/*
6438 * rename() only works if both files are on the same file system, this
6439 * function will (attempts to?) copy the file across if rename fails -- webb
6440 * Return -1 for failure, 0 for success.
6441 */
6442 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006443vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444{
6445 int fd_in;
6446 int fd_out;
6447 int n;
6448 char *errmsg = NULL;
6449 char *buffer;
6450#ifdef AMIGA
6451 BPTR flock;
6452#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006453 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006454 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006455#ifdef HAVE_ACL
6456 vim_acl_T acl; /* ACL from original file */
6457#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006458 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459
6460 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006461 * When the names are identical, there is nothing to do. When they refer
6462 * to the same file (ignoring case and slash/backslash differences) but
6463 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464 */
6465 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006466 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006467 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006468 use_tmp_file = TRUE;
6469 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006470 return 0;
6471 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472
6473 /*
6474 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6475 */
6476 if (mch_stat((char *)from, &st) < 0)
6477 return -1;
6478
Bram Moolenaar3576da72008-12-30 15:15:57 +00006479#ifdef UNIX
6480 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006481 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006482
6483 /* It's possible for the source and destination to be the same file.
6484 * This happens when "from" and "to" differ in case and are on a FAT32
6485 * filesystem. In that case go through a temp file name. */
6486 if (mch_stat((char *)to, &st_to) >= 0
6487 && st.st_dev == st_to.st_dev
6488 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006489 use_tmp_file = TRUE;
6490 }
6491#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006492#ifdef WIN3264
6493 {
6494 BY_HANDLE_FILE_INFORMATION info1, info2;
6495
6496 /* It's possible for the source and destination to be the same file.
6497 * In that case go through a temp file name. This makes rename("foo",
6498 * "./foo") a no-op (in a complicated way). */
6499 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6500 && win32_fileinfo(to, &info2) == FILEINFO_OK
6501 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6502 && info1.nFileIndexHigh == info2.nFileIndexHigh
6503 && info1.nFileIndexLow == info2.nFileIndexLow)
6504 use_tmp_file = TRUE;
6505 }
6506#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006507
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006508 if (use_tmp_file)
6509 {
6510 char tempname[MAXPATHL + 1];
6511
6512 /*
6513 * Find a name that doesn't exist and is in the same directory.
6514 * Rename "from" to "tempname" and then rename "tempname" to "to".
6515 */
6516 if (STRLEN(from) >= MAXPATHL - 5)
6517 return -1;
6518 STRCPY(tempname, from);
6519 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006520 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006521 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6522 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006523 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006524 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006525 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006526 if (mch_rename(tempname, (char *)to) == 0)
6527 return 0;
6528 /* Strange, the second step failed. Try moving the
6529 * file back and return failure. */
6530 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006531 return -1;
6532 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006533 /* If it fails for one temp name it will most likely fail
6534 * for any temp name, give up. */
6535 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006536 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006537 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006538 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006539 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006540
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 /*
6542 * Delete the "to" file, this is required on some systems to make the
6543 * mch_rename() work, on other systems it makes sure that we don't have
6544 * two files when the mch_rename() fails.
6545 */
6546
6547#ifdef AMIGA
6548 /*
6549 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6550 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006551 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 * deleting the "from" file (horror!) we lock it during the remove.
6553 *
6554 * When used for making a backup before writing the file: This should not
6555 * happen with ":w", because startscript() should detect this problem and
6556 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6557 * name. This problem does exist with ":w filename", but then the
6558 * original file will be somewhere else so the backup isn't really
6559 * important. If autoscripting is off the rename may fail.
6560 */
6561 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6562#endif
6563 mch_remove(to);
6564#ifdef AMIGA
6565 if (flock)
6566 UnLock(flock);
6567#endif
6568
6569 /*
6570 * First try a normal rename, return if it works.
6571 */
6572 if (mch_rename((char *)from, (char *)to) == 0)
6573 return 0;
6574
6575 /*
6576 * Rename() failed, try copying the file.
6577 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006578 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006579#ifdef HAVE_ACL
6580 /* For systems that support ACL: get the ACL from the original file. */
6581 acl = mch_get_acl(from);
6582#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6584 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006585 {
6586#ifdef HAVE_ACL
6587 mch_free_acl(acl);
6588#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006590 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006591
6592 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006593 fd_out = mch_open((char *)to,
6594 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 if (fd_out == -1)
6596 {
6597 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006598#ifdef HAVE_ACL
6599 mch_free_acl(acl);
6600#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601 return -1;
6602 }
6603
6604 buffer = (char *)alloc(BUFSIZE);
6605 if (buffer == NULL)
6606 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006608 close(fd_in);
6609#ifdef HAVE_ACL
6610 mch_free_acl(acl);
6611#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 return -1;
6613 }
6614
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006615 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6616 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 {
6618 errmsg = _("E208: Error writing to \"%s\"");
6619 break;
6620 }
6621
6622 vim_free(buffer);
6623 close(fd_in);
6624 if (close(fd_out) < 0)
6625 errmsg = _("E209: Error closing \"%s\"");
6626 if (n < 0)
6627 {
6628 errmsg = _("E210: Error reading \"%s\"");
6629 to = from;
6630 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006631#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006632 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006633#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006634#ifdef HAVE_ACL
6635 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006636 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006637#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006638#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006639 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006640#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 if (errmsg != NULL)
6642 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006643 semsg(errmsg, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 return -1;
6645 }
6646 mch_remove(from);
6647 return 0;
6648}
6649
6650static int already_warned = FALSE;
6651
6652/*
6653 * Check if any not hidden buffer has been changed.
6654 * Postpone the check if there are characters in the stuff buffer, a global
6655 * command is being executed, a mapping is being executed or an autocommand is
6656 * busy.
6657 * Returns TRUE if some message was written (screen should be redrawn and
6658 * cursor positioned).
6659 */
6660 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006661check_timestamps(
6662 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663{
6664 buf_T *buf;
6665 int didit = 0;
6666 int n;
6667
6668 /* Don't check timestamps while system() or another low-level function may
6669 * cause us to lose and gain focus. */
6670 if (no_check_timestamps > 0)
6671 return FALSE;
6672
6673 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6674 * event and we would keep on checking if the file is steadily growing.
6675 * Do check again after typing something. */
6676 if (focus && did_check_timestamps)
6677 {
6678 need_check_timestamps = TRUE;
6679 return FALSE;
6680 }
6681
6682 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006683 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 need_check_timestamps = TRUE; /* check later */
6685 else
6686 {
6687 ++no_wait_return;
6688 did_check_timestamps = TRUE;
6689 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006690 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 {
6692 /* Only check buffers in a window. */
6693 if (buf->b_nwindows > 0)
6694 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006695 bufref_T bufref;
6696
6697 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 n = buf_check_timestamp(buf, focus);
6699 if (didit < n)
6700 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006701 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 {
6703 /* Autocommands have removed the buffer, start at the
6704 * first one again. */
6705 buf = firstbuf;
6706 continue;
6707 }
6708 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 }
6710 --no_wait_return;
6711 need_check_timestamps = FALSE;
6712 if (need_wait_return && didit == 2)
6713 {
6714 /* make sure msg isn't overwritten */
Bram Moolenaar32526b32019-01-19 17:43:09 +01006715 msg_puts("\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 out_flush();
6717 }
6718 }
6719 return didit;
6720}
6721
6722/*
6723 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6724 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6725 * empty.
6726 */
6727 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006728move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729{
6730 buf_T *tbuf = curbuf;
6731 int retval = OK;
6732 linenr_T lnum;
6733 char_u *p;
6734
6735 /* Copy the lines in "frombuf" to "tobuf". */
6736 curbuf = tobuf;
6737 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6738 {
6739 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6740 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6741 {
6742 vim_free(p);
6743 retval = FAIL;
6744 break;
6745 }
6746 vim_free(p);
6747 }
6748
6749 /* Delete all the lines in "frombuf". */
6750 if (retval != FAIL)
6751 {
6752 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006753 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6754 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 {
6756 /* Oops! We could try putting back the saved lines, but that
6757 * might fail again... */
6758 retval = FAIL;
6759 break;
6760 }
6761 }
6762
6763 curbuf = tbuf;
6764 return retval;
6765}
6766
6767/*
6768 * Check if buffer "buf" has been changed.
6769 * Also check if the file for a new buffer unexpectedly appeared.
6770 * return 1 if a changed buffer was found.
6771 * return 2 if a message has been displayed.
6772 * return 0 otherwise.
6773 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006775buf_check_timestamp(
6776 buf_T *buf,
6777 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006779 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 int stat_res;
6781 int retval = 0;
6782 char_u *path;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006783 char *tbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006785 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 int helpmesg = FALSE;
6787 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006788 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6790 int can_reload = FALSE;
6791#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006792 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793 int orig_mode = buf->b_orig_mode;
6794#ifdef FEAT_GUI
6795 int save_mouse_correct = need_mouse_correct;
6796#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006798 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006799#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006800 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006801#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006802 bufref_T bufref;
6803
6804 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805
6806 /* If there is no file name, the buffer is not loaded, 'buftype' is
6807 * set, we are in the middle of a save or being called recursively: ignore
6808 * this buffer. */
6809 if (buf->b_ffname == NULL
6810 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02006811 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006814#ifdef FEAT_NETBEANS_INTG
6815 || isNetbeansBuffer(buf)
6816#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006817#ifdef FEAT_TERMINAL
6818 || buf->b_term != NULL
6819#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 )
6821 return 0;
6822
6823 if ( !(buf->b_flags & BF_NOTEDITED)
6824 && buf->b_mtime != 0
6825 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6826 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006827 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828#ifdef HAVE_ST_MODE
6829 || (int)st.st_mode != buf->b_orig_mode
6830#else
6831 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6832#endif
6833 ))
6834 {
6835 retval = 1;
6836
Bram Moolenaar386bc822018-07-07 18:34:12 +02006837 // set b_mtime to stop further warnings (e.g., when executing
6838 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839 if (stat_res < 0)
6840 {
Bram Moolenaar386bc822018-07-07 18:34:12 +02006841 // When 'autoread' is set we'll check the file again to see if it
6842 // re-appears.
6843 buf->b_mtime = buf->b_p_ar;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 buf->b_orig_size = 0;
6845 buf->b_orig_mode = 0;
6846 }
6847 else
6848 buf_store_time(buf, &st, buf->b_ffname);
6849
6850 /* Don't do anything for a directory. Might contain the file
6851 * explorer. */
6852 if (mch_isdir(buf->b_fname))
6853 ;
6854
6855 /*
6856 * If 'autoread' is set, the buffer has no changes and the file still
6857 * exists, reload the buffer. Use the buffer-local option value if it
6858 * was set, the global option value otherwise.
6859 */
6860 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6861 && !bufIsChanged(buf) && stat_res >= 0)
6862 reload = TRUE;
6863 else
6864 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006865 if (stat_res < 0)
6866 reason = "deleted";
6867 else if (bufIsChanged(buf))
6868 reason = "conflict";
6869 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6870 reason = "changed";
6871 else if (orig_mode != buf->b_orig_mode)
6872 reason = "mode";
6873 else
6874 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875
6876 /*
6877 * Only give the warning if there are no FileChangedShell
6878 * autocommands.
6879 * Avoid being called recursively by setting "busy".
6880 */
6881 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006882#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006883 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6884 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006885#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006886 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6888 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006889 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890 busy = FALSE;
6891 if (n)
6892 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006893 if (!bufref_valid(&bufref))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006894 emsg(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006895#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006896 s = get_vim_var_str(VV_FCS_CHOICE);
6897 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6898 reload = TRUE;
6899 else if (STRCMP(s, "ask") == 0)
6900 n = FALSE;
6901 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006902#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006903 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006905 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006907 if (*reason == 'd')
6908 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 else
6910 {
6911 helpmesg = TRUE;
6912#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6913 can_reload = TRUE;
6914#endif
6915 /*
6916 * Check if the file contents really changed to avoid
6917 * giving a warning when only the timestamp was set (e.g.,
6918 * checked out of CVS). Always warn when the buffer was
6919 * changed.
6920 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921 if (reason[2] == 'n')
6922 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006924 mesg2 = _("See \":help W12\" for more info.");
6925 }
6926 else if (reason[1] == 'h')
6927 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006929 mesg2 = _("See \":help W11\" for more info.");
6930 }
6931 else if (*reason == 'm')
6932 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006934 mesg2 = _("See \":help W16\" for more info.");
6935 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006936 else
6937 /* Only timestamp changed, store it to avoid a warning
6938 * in check_mtime() later. */
6939 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 }
6941 }
6942 }
6943
6944 }
6945 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6946 && vim_fexists(buf->b_ffname))
6947 {
6948 retval = 1;
6949 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6950 buf->b_flags |= BF_NEW_W;
6951#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6952 can_reload = TRUE;
6953#endif
6954 }
6955
6956 if (mesg != NULL)
6957 {
6958 path = home_replace_save(buf, buf->b_fname);
6959 if (path != NULL)
6960 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006961 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 mesg2 = "";
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006963 tbuf = (char *)alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 + STRLEN(mesg2) + 2));
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006965 sprintf(tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006966#ifdef FEAT_EVAL
6967 /* Set warningmsg here, before the unimportant and output-specific
6968 * mesg2 has been appended. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006969 set_vim_var_string(VV_WARNINGMSG, (char_u *)tbuf, -1);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006970#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6972 if (can_reload)
6973 {
6974 if (*mesg2 != NUL)
6975 {
6976 STRCAT(tbuf, "\n");
6977 STRCAT(tbuf, mesg2);
6978 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006979 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"),
6980 (char_u *)tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006981 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 reload = TRUE;
6983 }
6984 else
6985#endif
6986 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6987 {
6988 if (*mesg2 != NUL)
6989 {
6990 STRCAT(tbuf, "; ");
6991 STRCAT(tbuf, mesg2);
6992 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006993 emsg(tbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 retval = 2;
6995 }
6996 else
6997 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 {
7000 msg_start();
Bram Moolenaar32526b32019-01-19 17:43:09 +01007001 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 if (*mesg2 != NUL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01007003 msg_puts_attr(mesg2, HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 msg_clr_eos();
7005 (void)msg_end();
7006 if (emsg_silent == 0)
7007 {
7008 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007009#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 /* give the user some time to think about it */
7013 ui_delay(1000L, TRUE);
7014
7015 /* don't redraw and erase the message */
7016 redraw_cmdline = FALSE;
7017 }
7018 }
7019 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 }
7021
7022 vim_free(path);
7023 vim_free(tbuf);
7024 }
7025 }
7026
7027 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007028 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007029 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007030 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007031#ifdef FEAT_PERSISTENT_UNDO
7032 if (buf->b_p_udf && buf->b_ffname != NULL)
7033 {
7034 char_u hash[UNDO_HASH_SIZE];
7035 buf_T *save_curbuf = curbuf;
7036
7037 /* Any existing undo file is unusable, write it now. */
7038 curbuf = buf;
7039 u_compute_hash(hash);
7040 u_write_undo(NULL, FALSE, buf, hash);
7041 curbuf = save_curbuf;
7042 }
7043#endif
7044 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007046 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007047 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007048 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7049 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007050#ifdef FEAT_GUI
7051 /* restore this in case an autocommand has set it; it would break
7052 * 'mousefocus' */
7053 need_mouse_correct = save_mouse_correct;
7054#endif
7055
7056 return retval;
7057}
7058
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007059/*
7060 * Reload a buffer that is already loaded.
7061 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007062 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7063 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007064 */
7065 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007066buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007067{
7068 exarg_T ea;
7069 pos_T old_cursor;
7070 linenr_T old_topline;
7071 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007072 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007073 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007074 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007075 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007076 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007077
7078 /* set curwin/curbuf for "buf" and save some things */
7079 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007080
7081 /* We only want to read the text from the file, not reset the syntax
7082 * highlighting, clear marks, diff status, etc. Force the fileformat
7083 * and encoding to be the same. */
7084 if (prep_exarg(&ea, buf) == OK)
7085 {
7086 old_cursor = curwin->w_cursor;
7087 old_topline = curwin->w_topline;
7088
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007089 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007090 {
7091 /* Save all the text, so that the reload can be undone.
7092 * Sync first so that this is a separate undo-able action. */
7093 u_sync(FALSE);
7094 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7095 flags |= READ_KEEP_UNDO;
7096 }
7097
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007098 /*
7099 * To behave like when a new file is edited (matters for
7100 * BufReadPost autocommands) we first need to delete the current
7101 * buffer contents. But if reading the file fails we should keep
7102 * the old contents. Can't use memory only, the file might be
7103 * too big. Use a hidden buffer to move the buffer contents to.
7104 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007105 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007106 savebuf = NULL;
7107 else
7108 {
7109 /* Allocate a buffer without putting it in the buffer list. */
7110 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007111 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007112 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007113 {
7114 /* Open the memline. */
7115 curbuf = savebuf;
7116 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007117 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007118 curbuf = buf;
7119 curwin->w_buffer = buf;
7120 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007121 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007122 || move_lines(buf, savebuf) == FAIL)
7123 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007124 semsg(_("E462: Could not prepare for reloading \"%s\""),
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007125 buf->b_fname);
7126 saved = FAIL;
7127 }
7128 }
7129
7130 if (saved == OK)
7131 {
7132 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007134 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7135 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007136 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007138#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007139 if (!aborting())
7140#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007141 semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007142 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143 {
7144 /* Put the text back from the save buffer. First
7145 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007146 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007147 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007148 break;
7149 (void)move_lines(savebuf, buf);
7150 }
7151 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007152 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007153 {
7154 /* Mark the buffer as unmodified and free undo info. */
7155 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007156 if ((flags & READ_KEEP_UNDO) == 0)
7157 {
7158 u_blockfree(buf);
7159 u_clearall(buf);
7160 }
7161 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007162 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007163 /* Mark all undo states as changed. */
7164 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007165 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007166 }
7167 }
7168 vim_free(ea.cmd);
7169
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007170 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007171 wipe_buffer(savebuf, FALSE);
7172
7173#ifdef FEAT_DIFF
7174 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007175 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007176#endif
7177
7178 /* Restore the topline and cursor position and check it (lines may
7179 * have been removed). */
7180 if (old_topline > curbuf->b_ml.ml_line_count)
7181 curwin->w_topline = curbuf->b_ml.ml_line_count;
7182 else
7183 curwin->w_topline = old_topline;
7184 curwin->w_cursor = old_cursor;
7185 check_cursor();
7186 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007187 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007188#ifdef FEAT_FOLDING
7189 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007190 win_T *wp;
7191 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007192
7193 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007194 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195 if (wp->w_buffer == curwin->w_buffer
7196 && !foldmethodIsManual(wp))
7197 foldUpdateAll(wp);
7198 }
7199#endif
7200 /* If the mode didn't change and 'readonly' was set, keep the old
7201 * value; the user probably used the ":view" command. But don't
7202 * reset it, might have had a read error. */
7203 if (orig_mode == curbuf->b_orig_mode)
7204 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007205
7206 /* Modelines must override settings done by autocommands. */
7207 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007208 }
7209
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007210 /* restore curwin/curbuf and a few other things */
7211 aucmd_restbuf(&aco);
7212 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213}
7214
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007216buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217{
7218 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007219 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220#ifdef HAVE_ST_MODE
7221 buf->b_orig_mode = (int)st->st_mode;
7222#else
7223 buf->b_orig_mode = mch_getperm(fname);
7224#endif
7225}
7226
7227/*
7228 * Adjust the line with missing eol, used for the next write.
7229 * Used for do_filter(), when the input lines for the filter are deleted.
7230 */
7231 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007232write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007234 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7235 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236}
7237
Bram Moolenaarda440d22016-01-16 21:27:23 +01007238#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7239/*
7240 * Delete "name" and everything in it, recursively.
7241 * return 0 for succes, -1 if some file was not deleted.
7242 */
7243 int
7244delete_recursive(char_u *name)
7245{
7246 int result = 0;
7247 char_u **files;
7248 int file_count;
7249 int i;
7250 char_u *exp;
7251
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007252 /* A symbolic link to a directory itself is deleted, not the directory it
7253 * points to. */
7254 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007255# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007256 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007257# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007258 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007259# endif
7260 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007261 {
7262 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7263 exp = vim_strsave(NameBuff);
7264 if (exp == NULL)
7265 return -1;
7266 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007267 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007268 {
7269 for (i = 0; i < file_count; ++i)
7270 if (delete_recursive(files[i]) != 0)
7271 result = -1;
7272 FreeWild(file_count, files);
7273 }
7274 else
7275 result = -1;
7276 vim_free(exp);
7277 (void)mch_rmdir(name);
7278 }
7279 else
7280 result = mch_remove(name) == 0 ? 0 : -1;
7281
7282 return result;
7283}
7284#endif
7285
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286#if defined(TEMPDIRNAMES) || defined(PROTO)
7287static long temp_count = 0; /* Temp filename counter. */
7288
7289/*
7290 * Delete the temp directory and all files it contains.
7291 */
7292 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007293vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 if (vim_tempdir != NULL)
7296 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007297 /* remove the trailing path separator */
7298 gettail(vim_tempdir)[-1] = NUL;
7299 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007300 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301 }
7302}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303
7304/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007305 * Directory "tempdir" was created. Expand this name to a full path and put
7306 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7307 * "tempdir" must be no longer than MAXPATHL.
7308 */
7309 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007310vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007311{
7312 char_u *buf;
7313
7314 buf = alloc((unsigned)MAXPATHL + 2);
7315 if (buf != NULL)
7316 {
7317 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7318 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007319 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007320 vim_tempdir = vim_strsave(buf);
7321 vim_free(buf);
7322 }
7323}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007324#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007325
7326/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327 * vim_tempname(): Return a unique name that can be used for a temp file.
7328 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007329 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7330 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007331 *
7332 * The returned pointer is to allocated memory.
7333 * The returned pointer is NULL if no valid name was found.
7334 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007336vim_tempname(
7337 int extra_char UNUSED, /* char to use in the name instead of '?' */
7338 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007339{
7340#ifdef USE_TMPNAM
7341 char_u itmp[L_tmpnam]; /* use tmpnam() */
7342#else
7343 char_u itmp[TEMPNAMELEN];
7344#endif
7345
7346#ifdef TEMPDIRNAMES
7347 static char *(tempdirs[]) = {TEMPDIRNAMES};
7348 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007350 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351# endif
7352
7353 /*
7354 * This will create a directory for private use by this instance of Vim.
7355 * This is done once, and the same directory is used for all temp files.
7356 * This method avoids security problems because of symlink attacks et al.
7357 * It's also a bit faster, because we only need to check for an existing
7358 * file when creating the directory and not for each temp file.
7359 */
7360 if (vim_tempdir == NULL)
7361 {
7362 /*
7363 * Try the entries in TEMPDIRNAMES to create the temp directory.
7364 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007365 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007367# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007368 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007369 long nr;
7370 long off;
7371# endif
7372
Bram Moolenaare1a61992015-12-03 21:02:27 +01007373 /* Expand $TMP, leave room for "/v1100000/999999999".
7374 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007376 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007378 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007379 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380
Bram Moolenaareaf03392009-11-17 11:08:52 +00007381# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007382 {
7383# if defined(UNIX) || defined(VMS)
7384 /* Make sure the umask doesn't remove the executable bit.
7385 * "repl" has been reported to use "177". */
7386 mode_t umask_save = umask(077);
7387# endif
7388 /* Leave room for filename */
7389 STRCAT(itmp, "vXXXXXX");
7390 if (mkdtemp((char *)itmp) != NULL)
7391 vim_settempdir(itmp);
7392# if defined(UNIX) || defined(VMS)
7393 (void)umask(umask_save);
7394# endif
7395 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007396# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 /* Get an arbitrary number of up to 6 digits. When it's
7398 * unlikely that it already exists it will be faster,
7399 * otherwise it doesn't matter. The use of mkdir() avoids any
7400 * security problems because of the predictable number. */
7401 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007402 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403
7404 /* Try up to 10000 different values until we find a name that
7405 * doesn't exist. */
7406 for (off = 0; off < 10000L; ++off)
7407 {
7408 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007409# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412
Bram Moolenaareaf03392009-11-17 11:08:52 +00007413 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7414# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 /* If mkdir() does not set errno to EEXIST, check for
7416 * existing file here. There is a race condition then,
7417 * although it's fail-safe. */
7418 if (mch_stat((char *)itmp, &st) >= 0)
7419 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# endif
7421# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 /* Make sure the umask doesn't remove the executable bit.
7423 * "repl" has been reported to use "177". */
7424 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007425# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 if (r == 0)
7431 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 break;
7434 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 /* If the mkdir() didn't fail because the file/dir exists,
7437 * we probably can't create any dir here, try another
7438 * place. */
7439 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 break;
7442 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 if (vim_tempdir != NULL)
7445 break;
7446 }
7447 }
7448 }
7449
7450 if (vim_tempdir != NULL)
7451 {
7452 /* There is no need to check if the file exists, because we own the
7453 * directory and nobody else creates a file in it. */
7454 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7455 return vim_strsave(itmp);
7456 }
7457
7458 return NULL;
7459
7460#else /* TEMPDIRNAMES */
7461
7462# ifdef WIN3264
7463 char szTempFile[_MAX_PATH + 1];
7464 char buf4[4];
7465 char_u *retval;
7466 char_u *p;
7467
7468 STRCPY(itmp, "");
7469 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007470 {
7471 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7472 szTempFile[1] = NUL;
7473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007474 strcpy(buf4, "VIM");
7475 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007476 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007478 if (!keep)
7479 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007480 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481
7482 /* Backslashes in a temp file name cause problems when filtering with
7483 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7484 * didn't set 'shellslash'. */
7485 retval = vim_strsave(itmp);
7486 if (*p_shcf == '-' || p_ssl)
7487 for (p = retval; *p; ++p)
7488 if (*p == '\\')
7489 *p = '/';
7490 return retval;
7491
7492# else /* WIN3264 */
7493
7494# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007495 char_u *p;
7496
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007498 p = tmpnam((char *)itmp);
7499 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 return NULL;
7501# else
7502 char_u *p;
7503
7504# ifdef VMS_TEMPNAM
7505 /* mktemp() is not working on VMS. It seems to be
7506 * a do-nothing function. Therefore we use tempnam().
7507 */
7508 sprintf((char *)itmp, "VIM%c", extra_char);
7509 p = (char_u *)tempnam("tmp:", (char *)itmp);
7510 if (p != NULL)
7511 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007512 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 * and VIM will then be unable to find the file later */
7514 STRCPY(itmp, p);
7515 STRCAT(itmp, ".txt");
7516 free(p);
7517 }
7518 else
7519 return NULL;
7520# else
7521 STRCPY(itmp, TEMPNAME);
7522 if ((p = vim_strchr(itmp, '?')) != NULL)
7523 *p = extra_char;
7524 if (mktemp((char *)itmp) == NULL)
7525 return NULL;
7526# endif
7527# endif
7528
7529 return vim_strsave(itmp);
7530# endif /* WIN3264 */
7531#endif /* TEMPDIRNAMES */
7532}
7533
7534#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7535/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007536 * Convert all backslashes in fname to forward slashes in-place, unless when
7537 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007538 */
7539 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007540forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541{
7542 char_u *p;
7543
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007544 if (path_with_url(fname))
7545 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007546 for (p = fname; *p != NUL; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007548 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 ++p;
Bram Moolenaar13505972019-01-24 15:04:48 +01007550 else if (*p == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 *p = '/';
7552}
7553#endif
7554
7555
7556/*
7557 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 */
7559
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560/*
7561 * The autocommands are stored in a list for each event.
7562 * Autocommands for the same pattern, that are consecutive, are joined
7563 * together, to avoid having to match the pattern too often.
7564 * The result is an array of Autopat lists, which point to AutoCmd lists:
7565 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007566 * last_autopat[0] -----------------------------+
7567 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7569 * Autopat.cmds Autopat.cmds
7570 * | |
7571 * V V
7572 * AutoCmd.next AutoCmd.next
7573 * | |
7574 * V V
7575 * AutoCmd.next NULL
7576 * |
7577 * V
7578 * NULL
7579 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007580 * last_autopat[1] --------+
7581 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582 * first_autopat[1] --> Autopat.next --> NULL
7583 * Autopat.cmds
7584 * |
7585 * V
7586 * AutoCmd.next
7587 * |
7588 * V
7589 * NULL
7590 * etc.
7591 *
7592 * The order of AutoCmds is important, this is the order in which they were
7593 * defined and will have to be executed.
7594 */
7595typedef struct AutoCmd
7596{
7597 char_u *cmd; /* The command to be executed (NULL
7598 when command has been removed) */
7599 char nested; /* If autocommands nest here */
7600 char last; /* last command in list */
7601#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007602 sctx_T script_ctx; /* script context where defined */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603#endif
7604 struct AutoCmd *next; /* Next AutoCmd in list */
7605} AutoCmd;
7606
7607typedef struct AutoPat
7608{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007609 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7610 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611 char_u *pat; /* pattern as typed (NULL when pattern
7612 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007613 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007615 int group; /* group ID */
7616 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007617 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007618 char allow_dirs; /* Pattern may match whole path */
7619 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620} AutoPat;
7621
7622static struct event_name
7623{
7624 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007625 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626} event_names[] =
7627{
7628 {"BufAdd", EVENT_BUFADD},
7629 {"BufCreate", EVENT_BUFADD},
7630 {"BufDelete", EVENT_BUFDELETE},
7631 {"BufEnter", EVENT_BUFENTER},
7632 {"BufFilePost", EVENT_BUFFILEPOST},
7633 {"BufFilePre", EVENT_BUFFILEPRE},
7634 {"BufHidden", EVENT_BUFHIDDEN},
7635 {"BufLeave", EVENT_BUFLEAVE},
7636 {"BufNew", EVENT_BUFNEW},
7637 {"BufNewFile", EVENT_BUFNEWFILE},
7638 {"BufRead", EVENT_BUFREADPOST},
7639 {"BufReadCmd", EVENT_BUFREADCMD},
7640 {"BufReadPost", EVENT_BUFREADPOST},
7641 {"BufReadPre", EVENT_BUFREADPRE},
7642 {"BufUnload", EVENT_BUFUNLOAD},
7643 {"BufWinEnter", EVENT_BUFWINENTER},
7644 {"BufWinLeave", EVENT_BUFWINLEAVE},
7645 {"BufWipeout", EVENT_BUFWIPEOUT},
7646 {"BufWrite", EVENT_BUFWRITEPRE},
7647 {"BufWritePost", EVENT_BUFWRITEPOST},
7648 {"BufWritePre", EVENT_BUFWRITEPRE},
7649 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007650 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007651 {"CmdlineEnter", EVENT_CMDLINEENTER},
7652 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653 {"CmdwinEnter", EVENT_CMDWINENTER},
7654 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007655 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007656 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar60a68362018-04-30 15:40:48 +02007657 {"ColorSchemePre", EVENT_COLORSCHEMEPRE},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007658 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007659 {"CursorHold", EVENT_CURSORHOLD},
7660 {"CursorHoldI", EVENT_CURSORHOLDI},
7661 {"CursorMoved", EVENT_CURSORMOVED},
7662 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaare8fa05b2018-09-16 15:48:06 +02007663 {"DiffUpdated", EVENT_DIFFUPDATED},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007664 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007666 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7669 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7670 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7671 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007672 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673 {"FileChangedRO", EVENT_FILECHANGEDRO},
7674 {"FileReadPost", EVENT_FILEREADPOST},
7675 {"FileReadPre", EVENT_FILEREADPRE},
7676 {"FileReadCmd", EVENT_FILEREADCMD},
7677 {"FileType", EVENT_FILETYPE},
7678 {"FileWritePost", EVENT_FILEWRITEPOST},
7679 {"FileWritePre", EVENT_FILEWRITEPRE},
7680 {"FileWriteCmd", EVENT_FILEWRITECMD},
7681 {"FilterReadPost", EVENT_FILTERREADPOST},
7682 {"FilterReadPre", EVENT_FILTERREADPRE},
7683 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7684 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7685 {"FocusGained", EVENT_FOCUSGAINED},
7686 {"FocusLost", EVENT_FOCUSLOST},
7687 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7688 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007689 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007690 {"InsertChange", EVENT_INSERTCHANGE},
7691 {"InsertEnter", EVENT_INSERTENTER},
7692 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007693 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007694 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007695 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007696 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7697 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007698 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007700 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007701 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7702 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007703 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaar2b618522019-01-12 13:26:03 +01007704 {"SourcePre", EVENT_SOURCEPRE},
7705 {"SourcePost", EVENT_SOURCEPOST},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007706 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 {"StdinReadPost", EVENT_STDINREADPOST},
7708 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007709 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007710 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007711 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007712 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007713 {"TabEnter", EVENT_TABENTER},
7714 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007716 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007718 {"TextChanged", EVENT_TEXTCHANGED},
7719 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007720 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 {"User", EVENT_USER},
7722 {"VimEnter", EVENT_VIMENTER},
7723 {"VimLeave", EVENT_VIMLEAVE},
7724 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007725 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726 {"WinEnter", EVENT_WINENTER},
7727 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007728 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007729 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007730 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007731};
7732
7733static AutoPat *first_autopat[NUM_EVENTS] =
7734{
7735 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7736 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7737 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7738 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007739 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007740 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007741};
7742
Bram Moolenaar462455e2017-11-10 21:53:11 +01007743static AutoPat *last_autopat[NUM_EVENTS] =
7744{
7745 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7746 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7747 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7748 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7749 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7750 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7751};
7752
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753/*
7754 * struct used to keep status while executing autocommands for an event.
7755 */
7756typedef struct AutoPatCmd
7757{
7758 AutoPat *curpat; /* next AutoPat to examine */
7759 AutoCmd *nextcmd; /* next AutoCmd to execute */
7760 int group; /* group being used */
7761 char_u *fname; /* fname to match with */
7762 char_u *sfname; /* sfname to match with */
7763 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007764 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007765 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7766 buf is deleted */
7767 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768} AutoPatCmd;
7769
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007770static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007771
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772/*
7773 * augroups stores a list of autocmd group names.
7774 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007775static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007777/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007778static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779
7780/*
7781 * The ID of the current group. Group 0 is the default one.
7782 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783static int current_augroup = AUGROUP_DEFAULT;
7784
7785static int au_need_clean = FALSE; /* need to delete marked patterns */
7786
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007787static char_u *event_nr2name(event_T event);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007788static int au_get_grouparg(char_u **argp);
7789static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7790static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7791static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007792static 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 +00007793
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007794
Bram Moolenaar754b5602006-02-09 23:53:20 +00007795static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007797static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007799 static char_u *
7800get_deleted_augroup(void)
7801{
7802 if (deleted_augroup == NULL)
7803 deleted_augroup = (char_u *)_("--Deleted--");
7804 return deleted_augroup;
7805}
7806
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807/*
7808 * Show the autocommands for one AutoPat.
7809 */
7810 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007811show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812{
7813 AutoCmd *ac;
7814
7815 /* Check for "got_int" (here and at various places below), which is set
7816 * when "q" has been hit for the "--more--" prompt */
7817 if (got_int)
7818 return;
7819 if (ap->pat == NULL) /* pattern has been removed */
7820 return;
7821
7822 msg_putchar('\n');
7823 if (got_int)
7824 return;
7825 if (event != last_event || ap->group != last_group)
7826 {
7827 if (ap->group != AUGROUP_DEFAULT)
7828 {
7829 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01007830 msg_puts_attr((char *)get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007831 else
Bram Moolenaar32526b32019-01-19 17:43:09 +01007832 msg_puts_attr((char *)AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
7833 msg_puts(" ");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834 }
Bram Moolenaar32526b32019-01-19 17:43:09 +01007835 msg_puts_attr((char *)event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836 last_event = event;
7837 last_group = ap->group;
7838 msg_putchar('\n');
7839 if (got_int)
7840 return;
7841 }
7842 msg_col = 4;
7843 msg_outtrans(ap->pat);
7844
7845 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7846 {
7847 if (ac->cmd != NULL) /* skip removed commands */
7848 {
7849 if (msg_col >= 14)
7850 msg_putchar('\n');
7851 msg_col = 14;
7852 if (got_int)
7853 return;
7854 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007855#ifdef FEAT_EVAL
7856 if (p_verbose > 0)
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007857 last_set_msg(ac->script_ctx);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007858#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 if (got_int)
7860 return;
7861 if (ac->next != NULL)
7862 {
7863 msg_putchar('\n');
7864 if (got_int)
7865 return;
7866 }
7867 }
7868 }
7869}
7870
7871/*
7872 * Mark an autocommand pattern for deletion.
7873 */
7874 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007875au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007876{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007877 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007878 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879 au_need_clean = TRUE;
7880}
7881
7882/*
7883 * Mark all commands for a pattern for deletion.
7884 */
7885 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007886au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887{
7888 AutoCmd *ac;
7889
7890 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007891 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 au_need_clean = TRUE;
7893}
7894
7895/*
7896 * Cleanup autocommands and patterns that have been deleted.
7897 * This is only done when not executing autocommands.
7898 */
7899 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007900au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901{
7902 AutoPat *ap, **prev_ap;
7903 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007904 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905
7906 if (autocmd_busy || !au_need_clean)
7907 return;
7908
7909 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007910 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7911 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912 {
7913 /* loop over all autocommand patterns */
7914 prev_ap = &(first_autopat[(int)event]);
7915 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7916 {
7917 /* loop over all commands for this pattern */
7918 prev_ac = &(ap->cmds);
7919 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7920 {
7921 /* remove the command if the pattern is to be deleted or when
7922 * the command has been marked for deletion */
7923 if (ap->pat == NULL || ac->cmd == NULL)
7924 {
7925 *prev_ac = ac->next;
7926 vim_free(ac->cmd);
7927 vim_free(ac);
7928 }
7929 else
7930 prev_ac = &(ac->next);
7931 }
7932
7933 /* remove the pattern if it has been marked for deletion */
7934 if (ap->pat == NULL)
7935 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01007936 if (ap->next == NULL)
7937 {
7938 if (prev_ap == &(first_autopat[(int)event]))
7939 last_autopat[(int)event] = NULL;
7940 else
7941 /* this depends on the "next" field being the first in
7942 * the struct */
7943 last_autopat[(int)event] = (AutoPat *)prev_ap;
7944 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007945 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007946 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947 vim_free(ap);
7948 }
7949 else
7950 prev_ap = &(ap->next);
7951 }
7952 }
7953
7954 au_need_clean = FALSE;
7955}
7956
7957/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007958 * Called when buffer is freed, to remove/invalidate related buffer-local
7959 * autocmds.
7960 */
7961 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007962aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007963{
7964 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007965 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007966 AutoPatCmd *apc;
7967
7968 /* invalidate currently executing autocommands */
7969 for (apc = active_apc_list; apc; apc = apc->next)
7970 if (buf->b_fnum == apc->arg_bufnr)
7971 apc->arg_bufnr = 0;
7972
7973 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007974 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7975 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007976 /* loop over all autocommand patterns */
7977 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7978 if (ap->buflocal_nr == buf->b_fnum)
7979 {
7980 au_remove_pat(ap);
7981 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007982 {
7983 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007984 smsg(_("auto-removing autocommand: %s <buffer=%d>"),
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007985 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007986 verbose_leave();
7987 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007988 }
7989 au_cleanup();
7990}
7991
7992/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007993 * Add an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007994 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007995 */
7996 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007997au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998{
7999 int i;
8000
8001 i = au_find_group(name);
8002 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8003 {
8004 /* First try using a free entry. */
8005 for (i = 0; i < augroups.ga_len; ++i)
8006 if (AUGROUP_NAME(i) == NULL)
8007 break;
8008 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8009 return AUGROUP_ERROR;
8010
8011 AUGROUP_NAME(i) = vim_strsave(name);
8012 if (AUGROUP_NAME(i) == NULL)
8013 return AUGROUP_ERROR;
8014 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008015 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016 }
8017
8018 return i;
8019}
8020
8021 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008022au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008023{
8024 int i;
8025
8026 i = au_find_group(name);
8027 if (i == AUGROUP_ERROR) /* the group doesn't exist */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008028 semsg(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008029 else if (i == current_augroup)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008030 emsg(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008031 else
8032 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008033 event_T event;
8034 AutoPat *ap;
8035 int in_use = FALSE;
8036
8037 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8038 event = (event_T)((int)event + 1))
8039 {
8040 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008041 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008042 {
8043 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8044 in_use = TRUE;
8045 event = NUM_EVENTS;
8046 break;
8047 }
8048 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008049 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008050 if (in_use)
8051 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008052 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008053 }
8054 else
8055 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008056 }
8057}
8058
8059/*
8060 * Find the ID of an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008061 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008062 */
8063 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008064au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008065{
8066 int i;
8067
8068 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008069 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008070 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071 return i;
8072 return AUGROUP_ERROR;
8073}
8074
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008075/*
8076 * Return TRUE if augroup "name" exists.
8077 */
8078 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008079au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008080{
8081 return au_find_group(name) != AUGROUP_ERROR;
8082}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008083
Bram Moolenaar071d4272004-06-13 20:20:40 +00008084/*
8085 * ":augroup {name}".
8086 */
8087 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008088do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008089{
8090 int i;
8091
8092 if (del_group)
8093 {
8094 if (*arg == NUL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008095 emsg(_(e_argreq));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096 else
8097 au_del_group(arg);
8098 }
8099 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8100 current_augroup = AUGROUP_DEFAULT;
8101 else if (*arg) /* ":aug xxx": switch to group xxx */
8102 {
8103 i = au_new_group(arg);
8104 if (i != AUGROUP_ERROR)
8105 current_augroup = i;
8106 }
8107 else /* ":aug": list the group names */
8108 {
8109 msg_start();
8110 for (i = 0; i < augroups.ga_len; ++i)
8111 {
8112 if (AUGROUP_NAME(i) != NULL)
8113 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01008114 msg_puts((char *)AUGROUP_NAME(i));
8115 msg_puts(" ");
Bram Moolenaar071d4272004-06-13 20:20:40 +00008116 }
8117 }
8118 msg_clr_eos();
8119 msg_end();
8120 }
8121}
8122
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008123#if defined(EXITFREE) || defined(PROTO)
8124 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008125free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008126{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008127 int i;
8128 char_u *s;
8129
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008130 for (current_augroup = -1; current_augroup < augroups.ga_len;
8131 ++current_augroup)
8132 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008133
8134 for (i = 0; i < augroups.ga_len; ++i)
8135 {
8136 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008137 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008138 vim_free(s);
8139 }
8140 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008141}
8142#endif
8143
Bram Moolenaar071d4272004-06-13 20:20:40 +00008144/*
8145 * Return the event number for event name "start".
8146 * Return NUM_EVENTS if the event name was not found.
8147 * Return a pointer to the next event name in "end".
8148 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008149 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008150event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008151{
8152 char_u *p;
8153 int i;
8154 int len;
8155
Bram Moolenaare99e8442016-07-26 20:43:40 +02008156 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008157 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008158 ;
8159 for (i = 0; event_names[i].name != NULL; ++i)
8160 {
8161 len = (int)STRLEN(event_names[i].name);
8162 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8163 break;
8164 }
8165 if (*p == ',')
8166 ++p;
8167 *end = p;
8168 if (event_names[i].name == NULL)
8169 return NUM_EVENTS;
8170 return event_names[i].event;
8171}
8172
8173/*
8174 * Return the name for event "event".
8175 */
8176 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008177event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008178{
8179 int i;
8180
8181 for (i = 0; event_names[i].name != NULL; ++i)
8182 if (event_names[i].event == event)
8183 return (char_u *)event_names[i].name;
8184 return (char_u *)"Unknown";
8185}
8186
8187/*
8188 * Scan over the events. "*" stands for all events.
8189 */
8190 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008191find_end_event(
8192 char_u *arg,
8193 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008194{
8195 char_u *pat;
8196 char_u *p;
8197
8198 if (*arg == '*')
8199 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008200 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008202 semsg(_("E215: Illegal character after *: %s"), arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008203 return NULL;
8204 }
8205 pat = arg + 1;
8206 }
8207 else
8208 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008209 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008210 {
8211 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8212 {
8213 if (have_group)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008214 semsg(_("E216: No such event: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008215 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008216 semsg(_("E216: No such group or event: %s"), pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008217 return NULL;
8218 }
8219 }
8220 }
8221 return pat;
8222}
8223
8224/*
8225 * Return TRUE if "event" is included in 'eventignore'.
8226 */
8227 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008228event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008229{
8230 char_u *p = p_ei;
8231
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008232 while (*p != NUL)
8233 {
8234 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8235 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008236 if (event_name2nr(p, &p) == event)
8237 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239
8240 return FALSE;
8241}
8242
8243/*
8244 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8245 */
8246 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008247check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008248{
8249 char_u *p = p_ei;
8250
Bram Moolenaar071d4272004-06-13 20:20:40 +00008251 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008252 {
8253 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8254 {
8255 p += 3;
8256 if (*p == ',')
8257 ++p;
8258 }
8259 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008260 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008261 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008262
8263 return OK;
8264}
8265
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008266# if defined(FEAT_SYN_HL) || defined(PROTO)
8267
8268/*
8269 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8270 * buffer loaded into the window. "what" must start with a comma.
8271 * Returns the old value of 'eventignore' in allocated memory.
8272 */
8273 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008274au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008275{
8276 char_u *new_ei;
8277 char_u *save_ei;
8278
8279 save_ei = vim_strsave(p_ei);
8280 if (save_ei != NULL)
8281 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008282 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008283 if (new_ei != NULL)
8284 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008285 if (*what == ',' && *p_ei == NUL)
8286 STRCPY(new_ei, what + 1);
8287 else
8288 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008289 set_string_option_direct((char_u *)"ei", -1, new_ei,
8290 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008291 vim_free(new_ei);
8292 }
8293 }
8294 return save_ei;
8295}
8296
8297 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008298au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008299{
8300 if (old_ei != NULL)
8301 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008302 set_string_option_direct((char_u *)"ei", -1, old_ei,
8303 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008304 vim_free(old_ei);
8305 }
8306}
8307# endif /* FEAT_SYN_HL */
8308
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309/*
8310 * do_autocmd() -- implements the :autocmd command. Can be used in the
8311 * following ways:
8312 *
8313 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8314 * will be automatically executed for <event>
8315 * when editing a file matching <pat>, in
8316 * the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008317 * :autocmd <event> <pat> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008318 * <event> and <pat>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008319 * :autocmd <event> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008320 * <event>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008321 * :autocmd Show all autocommands.
8322 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323 * <event> and <pat>, and add the command
8324 * <cmd>, for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008325 * :autocmd! <event> <pat> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008326 * <event> and <pat> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008327 * :autocmd! <event> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328 * <event> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008329 * :autocmd! Remove ALL autocommands for the current
Bram Moolenaar071d4272004-06-13 20:20:40 +00008330 * group.
8331 *
8332 * Multiple events and patterns may be given separated by commas. Here are
8333 * some examples:
8334 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8335 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8336 *
8337 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008338 *
8339 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008340 */
8341 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008342do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008343{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008344 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008345 char_u *pat;
8346 char_u *envpat = NULL;
8347 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008348 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008349 int need_free = FALSE;
8350 int nested = FALSE;
8351 int group;
8352
Bram Moolenaare99e8442016-07-26 20:43:40 +02008353 if (*arg == '|')
8354 {
8355 arg = (char_u *)"";
8356 group = AUGROUP_ALL; /* no argument, use all groups */
8357 }
8358 else
8359 {
8360 /*
8361 * Check for a legal group name. If not, use AUGROUP_ALL.
8362 */
8363 group = au_get_grouparg(&arg);
8364 if (arg == NULL) /* out of memory */
8365 return;
8366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008367
8368 /*
8369 * Scan over the events.
8370 * If we find an illegal name, return here, don't do anything.
8371 */
8372 pat = find_end_event(arg, group != AUGROUP_ALL);
8373 if (pat == NULL)
8374 return;
8375
Bram Moolenaar071d4272004-06-13 20:20:40 +00008376 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008377 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008378 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008379 pat = (char_u *)"";
8380 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008381 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008382 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008383 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008384 /*
8385 * Scan over the pattern. Put a NUL at the end.
8386 */
8387 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008388 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008389 cmd++;
8390 if (*cmd)
8391 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008392
Bram Moolenaare99e8442016-07-26 20:43:40 +02008393 /* Expand environment variables in the pattern. Set 'shellslash', we want
8394 * forward slashes here. */
8395 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8396 {
8397#ifdef BACKSLASH_IN_FILENAME
8398 int p_ssl_save = p_ssl;
8399
8400 p_ssl = TRUE;
8401#endif
8402 envpat = expand_env_save(pat);
8403#ifdef BACKSLASH_IN_FILENAME
8404 p_ssl = p_ssl_save;
8405#endif
8406 if (envpat != NULL)
8407 pat = envpat;
8408 }
8409
8410 /*
8411 * Check for "nested" flag.
8412 */
8413 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008414 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008415 {
8416 nested = TRUE;
8417 cmd = skipwhite(cmd + 6);
8418 }
8419
8420 /*
8421 * Find the start of the commands.
8422 * Expand <sfile> in it.
8423 */
8424 if (*cmd != NUL)
8425 {
8426 cmd = expand_sfile(cmd);
8427 if (cmd == NULL) /* some error */
8428 return;
8429 need_free = TRUE;
8430 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008431 }
8432
8433 /*
8434 * Print header when showing autocommands.
8435 */
8436 if (!forceit && *cmd == NUL)
8437 {
8438 /* Highlight title */
Bram Moolenaar32526b32019-01-19 17:43:09 +01008439 msg_puts_title(_("\n--- Autocommands ---"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 }
8441
8442 /*
8443 * Loop over the events.
8444 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008445 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008446 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008447 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008448 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008449 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8450 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451 if (do_autocmd_event(event, pat,
8452 nested, cmd, forceit, group) == FAIL)
8453 break;
8454 }
8455 else
8456 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008457 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008458 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8459 nested, cmd, forceit, group) == FAIL)
8460 break;
8461 }
8462
8463 if (need_free)
8464 vim_free(cmd);
8465 vim_free(envpat);
8466}
8467
8468/*
8469 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8470 * The "argp" argument is advanced to the following argument.
8471 *
8472 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8473 */
8474 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008475au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008476{
8477 char_u *group_name;
8478 char_u *p;
8479 char_u *arg = *argp;
8480 int group = AUGROUP_ALL;
8481
Bram Moolenaar1c465442017-03-12 20:10:05 +01008482 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008483 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008484 if (p > arg)
8485 {
8486 group_name = vim_strnsave(arg, (int)(p - arg));
8487 if (group_name == NULL) /* out of memory */
8488 return AUGROUP_ERROR;
8489 group = au_find_group(group_name);
8490 if (group == AUGROUP_ERROR)
8491 group = AUGROUP_ALL; /* no match, use all groups */
8492 else
8493 *argp = skipwhite(p); /* match, skip over group name */
8494 vim_free(group_name);
8495 }
8496 return group;
8497}
8498
8499/*
8500 * do_autocmd() for one event.
8501 * If *pat == NUL do for all patterns.
8502 * If *cmd == NUL show entries.
8503 * If forceit == TRUE delete entries.
8504 * If group is not AUGROUP_ALL, only use this group.
8505 */
8506 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008507do_autocmd_event(
8508 event_T event,
8509 char_u *pat,
8510 int nested,
8511 char_u *cmd,
8512 int forceit,
8513 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008514{
8515 AutoPat *ap;
8516 AutoPat **prev_ap;
8517 AutoCmd *ac;
8518 AutoCmd **prev_ac;
8519 int brace_level;
8520 char_u *endpat;
8521 int findgroup;
8522 int allgroups;
8523 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008524 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008525 int buflocal_nr;
8526 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008527
8528 if (group == AUGROUP_ALL)
8529 findgroup = current_augroup;
8530 else
8531 findgroup = group;
8532 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8533
8534 /*
8535 * Show or delete all patterns for an event.
8536 */
8537 if (*pat == NUL)
8538 {
8539 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8540 {
8541 if (forceit) /* delete the AutoPat, if it's in the current group */
8542 {
8543 if (ap->group == findgroup)
8544 au_remove_pat(ap);
8545 }
8546 else if (group == AUGROUP_ALL || ap->group == group)
8547 show_autocmd(ap, event);
8548 }
8549 }
8550
8551 /*
8552 * Loop through all the specified patterns.
8553 */
8554 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8555 {
8556 /*
8557 * Find end of the pattern.
8558 * Watch out for a comma in braces, like "*.\{obj,o\}".
8559 */
8560 brace_level = 0;
8561 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008562 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008563 {
8564 if (*endpat == '{')
8565 brace_level++;
8566 else if (*endpat == '}')
8567 brace_level--;
8568 }
8569 if (pat == endpat) /* ignore single comma */
8570 continue;
8571 patlen = (int)(endpat - pat);
8572
8573 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008574 * detect special <buflocal[=X]> buffer-local patterns
8575 */
8576 is_buflocal = FALSE;
8577 buflocal_nr = 0;
8578
Bram Moolenaar1e997822015-02-17 16:04:57 +01008579 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008580 && pat[patlen - 1] == '>')
8581 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008582 /* "<buffer...>": Error will be printed only for addition.
8583 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008584 is_buflocal = TRUE;
8585 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008586 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008587 buflocal_nr = curbuf->b_fnum;
8588 else if (patlen > 9 && pat[7] == '=')
8589 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008590 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8591 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008592 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008593 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008594 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008595 buflocal_nr = atoi((char *)pat + 8);
8596 }
8597 }
8598
8599 if (is_buflocal)
8600 {
8601 /* normalize pat into standard "<buffer>#N" form */
8602 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8603 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008604 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008605 }
8606
8607 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008608 * Find AutoPat entries with this pattern. When adding a command it
8609 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008610 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008611 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8612 prev_ap = &last_autopat[(int)event];
8613 else
8614 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008615 while ((ap = *prev_ap) != NULL)
8616 {
8617 if (ap->pat != NULL)
8618 {
8619 /* Accept a pattern when:
8620 * - a group was specified and it's that group, or a group was
8621 * not specified and it's the current group, or a group was
8622 * not specified and we are listing
8623 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008624 * - the pattern matches.
8625 * For <buffer[=X]>, this condition works because we normalize
8626 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008627 */
8628 if ((allgroups || ap->group == findgroup)
8629 && ap->patlen == patlen
8630 && STRNCMP(pat, ap->pat, patlen) == 0)
8631 {
8632 /*
8633 * Remove existing autocommands.
8634 * If adding any new autocmd's for this AutoPat, don't
8635 * delete the pattern from the autopat list, append to
8636 * this list.
8637 */
8638 if (forceit)
8639 {
8640 if (*cmd != NUL && ap->next == NULL)
8641 {
8642 au_remove_cmds(ap);
8643 break;
8644 }
8645 au_remove_pat(ap);
8646 }
8647
8648 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008649 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008650 */
8651 else if (*cmd == NUL)
8652 show_autocmd(ap, event);
8653
8654 /*
8655 * Add autocmd to this autopat, if it's the last one.
8656 */
8657 else if (ap->next == NULL)
8658 break;
8659 }
8660 }
8661 prev_ap = &ap->next;
8662 }
8663
8664 /*
8665 * Add a new command.
8666 */
8667 if (*cmd != NUL)
8668 {
8669 /*
8670 * If the pattern we want to add a command to does appear at the
8671 * end of the list (or not is not in the list at all), add the
8672 * pattern at the end of the list.
8673 */
8674 if (ap == NULL)
8675 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008676 /* refuse to add buffer-local ap if buffer number is invalid */
8677 if (is_buflocal && (buflocal_nr == 0
8678 || buflist_findnr(buflocal_nr) == NULL))
8679 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008680 semsg(_("E680: <buffer=%d>: invalid buffer number "),
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008681 buflocal_nr);
8682 return FAIL;
8683 }
8684
Bram Moolenaar071d4272004-06-13 20:20:40 +00008685 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8686 if (ap == NULL)
8687 return FAIL;
8688 ap->pat = vim_strnsave(pat, patlen);
8689 ap->patlen = patlen;
8690 if (ap->pat == NULL)
8691 {
8692 vim_free(ap);
8693 return FAIL;
8694 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008695
8696 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008697 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008698 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008699 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008700 }
8701 else
8702 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008703 char_u *reg_pat;
8704
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008705 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008706 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008707 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008708 if (reg_pat != NULL)
8709 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008710 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008711 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008712 {
8713 vim_free(ap->pat);
8714 vim_free(ap);
8715 return FAIL;
8716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008717 }
8718 ap->cmds = NULL;
8719 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008720 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008721 ap->next = NULL;
8722 if (group == AUGROUP_ALL)
8723 ap->group = current_augroup;
8724 else
8725 ap->group = group;
8726 }
8727
8728 /*
8729 * Add the autocmd at the end of the AutoCmd list.
8730 */
8731 prev_ac = &(ap->cmds);
8732 while ((ac = *prev_ac) != NULL)
8733 prev_ac = &ac->next;
8734 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8735 if (ac == NULL)
8736 return FAIL;
8737 ac->cmd = vim_strsave(cmd);
8738#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02008739 ac->script_ctx = current_sctx;
8740 ac->script_ctx.sc_lnum += sourcing_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008741#endif
8742 if (ac->cmd == NULL)
8743 {
8744 vim_free(ac);
8745 return FAIL;
8746 }
8747 ac->next = NULL;
8748 *prev_ac = ac;
8749 ac->nested = nested;
8750 }
8751 }
8752
8753 au_cleanup(); /* may really delete removed patterns/commands now */
8754 return OK;
8755}
8756
8757/*
8758 * Implementation of ":doautocmd [group] event [fname]".
8759 * Return OK for success, FAIL for failure;
8760 */
8761 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008762do_doautocmd(
8763 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008764 int do_msg, /* give message for no matching autocmds? */
8765 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008766{
8767 char_u *fname;
8768 int nothing_done = TRUE;
8769 int group;
8770
Bram Moolenaar1610d052016-06-09 22:53:01 +02008771 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008772 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008773
Bram Moolenaar071d4272004-06-13 20:20:40 +00008774 /*
8775 * Check for a legal group name. If not, use AUGROUP_ALL.
8776 */
8777 group = au_get_grouparg(&arg);
8778 if (arg == NULL) /* out of memory */
8779 return FAIL;
8780
8781 if (*arg == '*')
8782 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008783 emsg(_("E217: Can't execute autocommands for ALL events"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008784 return FAIL;
8785 }
8786
8787 /*
8788 * Scan over the events.
8789 * If we find an illegal name, return here, don't do anything.
8790 */
8791 fname = find_end_event(arg, group != AUGROUP_ALL);
8792 if (fname == NULL)
8793 return FAIL;
8794
8795 fname = skipwhite(fname);
8796
8797 /*
8798 * Loop over the events.
8799 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008800 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008801 if (apply_autocmds_group(event_name2nr(arg, &arg),
8802 fname, NULL, TRUE, group, curbuf, NULL))
8803 nothing_done = FALSE;
8804
8805 if (nothing_done && do_msg)
Bram Moolenaar32526b32019-01-19 17:43:09 +01008806 msg(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008807 if (did_something != NULL)
8808 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008809
8810#ifdef FEAT_EVAL
8811 return aborting() ? FAIL : OK;
8812#else
8813 return OK;
8814#endif
8815}
8816
8817/*
8818 * ":doautoall": execute autocommands for each loaded buffer.
8819 */
8820 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008821ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008822{
8823 int retval;
8824 aco_save_T aco;
8825 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008826 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008827 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008828 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008829 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008830
8831 /*
8832 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8833 * equal to curbuf, but for some buffers there may not be a window.
8834 * So we change the buffer for the current window for a moment. This
8835 * gives problems when the autocommands make changes to the list of
8836 * buffers or windows...
8837 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008838 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008839 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008840 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008841 {
8842 /* find a window for this buffer and save some values */
8843 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008844 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008845
8846 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008847 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008848
Bram Moolenaar1610d052016-06-09 22:53:01 +02008849 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008850 {
8851 /* Execute the modeline settings, but don't set window-local
8852 * options if we are using the current window for another
8853 * buffer. */
8854 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8855 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008856
8857 /* restore the current window */
8858 aucmd_restbuf(&aco);
8859
8860 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008861 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008862 break;
8863 }
8864 }
8865
8866 check_cursor(); /* just in case lines got deleted */
8867}
8868
8869/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008870 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8871 * return TRUE and advance *argp to after it.
8872 * Thus return TRUE when do_modelines() should be called.
8873 */
8874 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008875check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008876{
8877 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8878 {
8879 *argp = skipwhite(*argp + 12);
8880 return FALSE;
8881 }
8882 return TRUE;
8883}
8884
8885/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008886 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008887 * Search for a visible window containing the current buffer. If there isn't
8888 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008889 * Set "curbuf" and "curwin" to match "buf".
8890 */
8891 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008892aucmd_prepbuf(
8893 aco_save_T *aco, /* structure to save values in */
8894 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008895{
8896 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008897 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008898#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008899 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008900#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008901
8902 /* Find a window that is for the new buffer */
8903 if (buf == curbuf) /* be quick when buf is curbuf */
8904 win = curwin;
8905 else
Bram Moolenaar29323592016-07-24 22:04:11 +02008906 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008907 if (win->w_buffer == buf)
8908 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008909
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008910 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8911 * back to using the current window. */
8912 if (win == NULL && aucmd_win == NULL)
8913 {
8914 win_alloc_aucmd_win();
8915 if (aucmd_win == NULL)
8916 win = curwin;
8917 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008918 if (win == NULL && aucmd_win_used)
8919 /* Strange recursive autocommand, fall back to using the current
8920 * window. Expect a few side effects... */
8921 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008922
8923 aco->save_curwin = curwin;
8924 aco->save_curbuf = curbuf;
Bram Moolenaara42df592018-12-24 00:22:39 +01008925 aco->save_prevwin = prevwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008926 if (win != NULL)
8927 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008928 /* There is a window for "buf" in the current tab page, make it the
8929 * curwin. This is preferred, it has the least side effects (esp. if
8930 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008931 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008932 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008933 }
8934 else
8935 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008936 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008937 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008938 * Anything related to a window (e.g., setting folds) may have
8939 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008940 aco->use_aucmd_win = TRUE;
8941 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008942 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01008943#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008944 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01008945#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008946 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008947 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008948
8949 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8950 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01008951 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008952 aco->globaldir = globaldir;
8953 globaldir = NULL;
8954
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008956 /* Split the current window, put the aucmd_win in the upper half.
8957 * We don't want the BufEnter or WinEnter autocommands. */
8958 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008959 make_snapshot(SNAP_AUCMD_IDX);
8960 save_ea = p_ea;
8961 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008962
Bram Moolenaar4033c552017-09-16 20:54:51 +02008963#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008964 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8965 save_acd = p_acd;
8966 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02008967#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008968
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008969 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8970 (void)win_comp_pos(); /* recompute window positions */
8971 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02008972#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008973 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008974#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02008975 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008976 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008979 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008980 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981}
8982
8983/*
8984 * Cleanup after executing autocommands for a (hidden) buffer.
8985 * Restore the window as it was (if possible).
8986 */
8987 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008988aucmd_restbuf(
8989 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008990{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008991 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008992
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008993 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008994 {
8995 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008996 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008997 * page. Do not trigger autocommands here. */
8998 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008999 if (curwin != aucmd_win)
9000 {
9001 tabpage_T *tp;
9002 win_T *wp;
9003
9004 FOR_ALL_TAB_WINDOWS(tp, wp)
9005 {
9006 if (wp == aucmd_win)
9007 {
9008 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009009 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009010 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009011 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009012 }
9013 }
9014 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009015win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009016
9017 /* Remove the window and frame from the tree of frames. */
9018 (void)winframe_remove(curwin, &dummy, NULL);
9019 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009020 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009021 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009022
9023 if (!valid_tabpage_win(curtab))
9024 /* no valid window in current tabpage */
9025 close_tabpage(curtab);
9026
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009027 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9028 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009029 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009030
9031 if (win_valid(aco->save_curwin))
9032 curwin = aco->save_curwin;
9033 else
9034 /* Hmm, original window disappeared. Just use the first one. */
9035 curwin = firstwin;
Bram Moolenaara42df592018-12-24 00:22:39 +01009036 if (win_valid(aco->save_prevwin))
9037 prevwin = aco->save_prevwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009038#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009039 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9040 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009041#endif
9042 curbuf = curwin->w_buffer;
9043
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009044 vim_free(globaldir);
9045 globaldir = aco->globaldir;
9046
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009047 /* the buffer contents may have changed */
9048 check_cursor();
9049 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9050 {
9051 curwin->w_topline = curbuf->b_ml.ml_line_count;
9052#ifdef FEAT_DIFF
9053 curwin->w_topfill = 0;
9054#endif
9055 }
9056#if defined(FEAT_GUI)
9057 /* Hide the scrollbars from the aucmd_win and update. */
9058 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9059 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9060 gui_may_update_scrollbars();
9061#endif
9062 }
9063 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009064 {
9065 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009066 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009067 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009068 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009069 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009070 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009071 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009072 && curbuf != aco->new_curbuf.br_buf
9073 && bufref_valid(&aco->new_curbuf)
9074 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009075 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009076# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9077 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009078 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009079# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009081 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009082 curwin->w_buffer = curbuf;
9083 ++curbuf->b_nwindows;
9084 }
9085
9086 curwin = aco->save_curwin;
9087 curbuf = curwin->w_buffer;
Bram Moolenaara42df592018-12-24 00:22:39 +01009088 if (win_valid(aco->save_prevwin))
9089 prevwin = aco->save_prevwin;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009090 /* In case the autocommand move the cursor to a position that that
9091 * not exist in curbuf. */
9092 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009093 }
9094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009095}
9096
9097static int autocmd_nested = FALSE;
9098
9099/*
9100 * Execute autocommands for "event" and file name "fname".
9101 * Return TRUE if some commands were executed.
9102 */
9103 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009104apply_autocmds(
9105 event_T event,
9106 char_u *fname, /* NULL or empty means use actual file name */
9107 char_u *fname_io, /* fname to use for <afile> on cmdline */
9108 int force, /* when TRUE, ignore autocmd_busy */
9109 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009110{
9111 return apply_autocmds_group(event, fname, fname_io, force,
9112 AUGROUP_ALL, buf, NULL);
9113}
9114
9115/*
9116 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9117 * setting v:filearg.
9118 */
9119 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009120apply_autocmds_exarg(
9121 event_T event,
9122 char_u *fname,
9123 char_u *fname_io,
9124 int force,
9125 buf_T *buf,
9126 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009127{
9128 return apply_autocmds_group(event, fname, fname_io, force,
9129 AUGROUP_ALL, buf, eap);
9130}
9131
9132/*
9133 * Like apply_autocmds(), but handles the caller's retval. If the script
9134 * processing is being aborted or if retval is FAIL when inside a try
9135 * conditional, no autocommands are executed. If otherwise the autocommands
9136 * cause the script to be aborted, retval is set to FAIL.
9137 */
9138 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009139apply_autocmds_retval(
9140 event_T event,
9141 char_u *fname, /* NULL or empty means use actual file name */
9142 char_u *fname_io, /* fname to use for <afile> on cmdline */
9143 int force, /* when TRUE, ignore autocmd_busy */
9144 buf_T *buf, /* buffer for <abuf> */
9145 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146{
9147 int did_cmd;
9148
Bram Moolenaar1e015462005-09-25 22:16:38 +00009149#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009150 if (should_abort(*retval))
9151 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009152#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009153
9154 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9155 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009156 if (did_cmd
9157#ifdef FEAT_EVAL
9158 && aborting()
9159#endif
9160 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009161 *retval = FAIL;
9162 return did_cmd;
9163}
9164
Bram Moolenaard35f9712005-12-18 22:02:33 +00009165/*
9166 * Return TRUE when there is a CursorHold autocommand defined.
9167 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009168 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009169has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009171 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9172 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009174
9175/*
9176 * Return TRUE if the CursorHold event can be triggered.
9177 */
9178 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009179trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009180{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009181 int state;
9182
Bram Moolenaar05334432011-07-20 18:29:39 +02009183 if (!did_cursorhold
9184 && has_cursorhold()
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02009185 && reg_recording == 0
Bram Moolenaar05334432011-07-20 18:29:39 +02009186 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009187#ifdef FEAT_INS_EXPAND
9188 && !ins_compl_active()
9189#endif
9190 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009191 {
9192 state = get_real_state();
9193 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9194 return TRUE;
9195 }
9196 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009197}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009198
9199/*
9200 * Return TRUE when there is a CursorMoved autocommand defined.
9201 */
9202 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009203has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009204{
9205 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9206}
9207
Bram Moolenaar113e1072019-01-20 15:30:40 +01009208#if defined(FEAT_CONCEAL) || defined(PROTO)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009209/*
9210 * Return TRUE when there is a CursorMovedI autocommand defined.
9211 */
9212 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009213has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009214{
9215 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9216}
Bram Moolenaar113e1072019-01-20 15:30:40 +01009217#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009218
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009219/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009220 * Return TRUE when there is a TextChanged autocommand defined.
9221 */
9222 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009223has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009224{
9225 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9226}
9227
9228/*
9229 * Return TRUE when there is a TextChangedI autocommand defined.
9230 */
9231 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009232has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009233{
9234 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9235}
9236
Bram Moolenaar113e1072019-01-20 15:30:40 +01009237#if defined(FEAT_INS_EXPAND) || defined(PROTO)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009238/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009239 * Return TRUE when there is a TextChangedP autocommand defined.
9240 */
9241 int
9242has_textchangedP(void)
9243{
9244 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9245}
Bram Moolenaar113e1072019-01-20 15:30:40 +01009246#endif
Bram Moolenaar5a093432018-02-10 18:15:19 +01009247
9248/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009249 * Return TRUE when there is an InsertCharPre autocommand defined.
9250 */
9251 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009252has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009253{
9254 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9255}
9256
Bram Moolenaard5005162014-08-22 23:05:54 +02009257/*
9258 * Return TRUE when there is an CmdUndefined autocommand defined.
9259 */
9260 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009261has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009262{
9263 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9264}
9265
9266/*
9267 * Return TRUE when there is an FuncUndefined autocommand defined.
9268 */
9269 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009270has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009271{
9272 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9273}
9274
Bram Moolenaar113e1072019-01-20 15:30:40 +01009275#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009276/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009277 * Return TRUE when there is a TextYankPost autocommand defined.
9278 */
9279 int
9280has_textyankpost(void)
9281{
9282 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9283}
Bram Moolenaar113e1072019-01-20 15:30:40 +01009284#endif
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009285
9286/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009287 * Execute autocommands for "event" and file name "fname".
9288 * Return TRUE if some commands were executed.
9289 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009290 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009291apply_autocmds_group(
9292 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009293 char_u *fname, /* NULL or empty means use actual file name */
9294 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009295 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009296 int force, /* when TRUE, ignore autocmd_busy */
9297 int group, /* group ID, or AUGROUP_ALL */
9298 buf_T *buf, /* buffer for <abuf> */
9299 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009300{
9301 char_u *sfname = NULL; /* short file name */
9302 char_u *tail;
9303 int save_changed;
9304 buf_T *old_curbuf;
9305 int retval = FALSE;
9306 char_u *save_sourcing_name;
9307 linenr_T save_sourcing_lnum;
9308 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009309 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009310 int save_autocmd_bufnr;
9311 char_u *save_autocmd_match;
9312 int save_autocmd_busy;
9313 int save_autocmd_nested;
9314 static int nesting = 0;
9315 AutoPatCmd patcmd;
9316 AutoPat *ap;
9317#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009318 sctx_T save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009319 funccal_entry_T funccal_entry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009320 char_u *save_cmdarg;
9321 long save_cmdbang;
9322#endif
9323 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009324#ifdef FEAT_PROFILE
9325 proftime_T wait_time;
9326#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009327 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009328 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009329 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009330
9331 /*
9332 * Quickly return if there are no autocommands for this event or
9333 * autocommands are blocked.
9334 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009335 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9336 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009337 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009338
9339 /*
9340 * When autocommands are busy, new autocommands are only executed when
9341 * explicitly enabled with the "nested" flag.
9342 */
9343 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009344 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009345
9346#ifdef FEAT_EVAL
9347 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009348 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009349 * occurred or an exception was thrown but not caught.
9350 */
9351 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009352 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009353#endif
9354
9355 /*
9356 * FileChangedShell never nests, because it can create an endless loop.
9357 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009358 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9359 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009360 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009361
9362 /*
9363 * Ignore events in 'eventignore'.
9364 */
9365 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009366 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009367
9368 /*
9369 * Allow nesting of autocommands, but restrict the depth, because it's
9370 * possible to create an endless loop.
9371 */
9372 if (nesting == 10)
9373 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009374 emsg(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009375 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009376 }
9377
9378 /*
9379 * Check if these autocommands are disabled. Used when doing ":all" or
9380 * ":ball".
9381 */
9382 if ( (autocmd_no_enter
9383 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9384 || (autocmd_no_leave
9385 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009386 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009387
9388 /*
9389 * Save the autocmd_* variables and info about the current buffer.
9390 */
9391 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009392 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009393 save_autocmd_bufnr = autocmd_bufnr;
9394 save_autocmd_match = autocmd_match;
9395 save_autocmd_busy = autocmd_busy;
9396 save_autocmd_nested = autocmd_nested;
9397 save_changed = curbuf->b_changed;
9398 old_curbuf = curbuf;
9399
9400 /*
9401 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009402 * Make a copy to avoid that changing a buffer name or directory makes it
9403 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009404 */
9405 if (fname_io == NULL)
9406 {
Bram Moolenaar60a68362018-04-30 15:40:48 +02009407 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
9408 || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009409 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009410 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009411 autocmd_fname = fname;
9412 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009413 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009414 else
9415 autocmd_fname = NULL;
9416 }
9417 else
9418 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009419 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009420 autocmd_fname = vim_strsave(autocmd_fname);
9421 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009422
9423 /*
9424 * Set the buffer number to be used for <abuf>.
9425 */
9426 if (buf == NULL)
9427 autocmd_bufnr = 0;
9428 else
9429 autocmd_bufnr = buf->b_fnum;
9430
9431 /*
9432 * When the file name is NULL or empty, use the file name of buffer "buf".
9433 * Always use the full path of the file name to match with, in case
9434 * "allow_dirs" is set.
9435 */
9436 if (fname == NULL || *fname == NUL)
9437 {
9438 if (buf == NULL)
9439 fname = NULL;
9440 else
9441 {
9442#ifdef FEAT_SYN_HL
9443 if (event == EVENT_SYNTAX)
9444 fname = buf->b_p_syn;
9445 else
9446#endif
9447 if (event == EVENT_FILETYPE)
9448 fname = buf->b_p_ft;
9449 else
9450 {
9451 if (buf->b_sfname != NULL)
9452 sfname = vim_strsave(buf->b_sfname);
9453 fname = buf->b_ffname;
9454 }
9455 }
9456 if (fname == NULL)
9457 fname = (char_u *)"";
9458 fname = vim_strsave(fname); /* make a copy, so we can change it */
9459 }
9460 else
9461 {
9462 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009463 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009464 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009465 if (event == EVENT_FILETYPE
9466 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009467 || event == EVENT_CMDLINECHANGED
9468 || event == EVENT_CMDLINEENTER
9469 || event == EVENT_CMDLINELEAVE
9470 || event == EVENT_CMDWINENTER
9471 || event == EVENT_CMDWINLEAVE
9472 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009473 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009474 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009475 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009476 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009477 || event == EVENT_COLORSCHEME
Bram Moolenaar60a68362018-04-30 15:40:48 +02009478 || event == EVENT_COLORSCHEMEPRE
Bram Moolenaar53744302015-07-17 17:38:22 +02009479 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009480 || event == EVENT_QUICKFIXCMDPOST
9481 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009482 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009483 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009484 autocmd_fname_full = TRUE; /* don't expand it later */
9485 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009486 else
9487 fname = FullName_save(fname, FALSE);
9488 }
9489 if (fname == NULL) /* out of memory */
9490 {
9491 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009492 retval = FALSE;
9493 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009494 }
9495
9496#ifdef BACKSLASH_IN_FILENAME
9497 /*
9498 * Replace all backslashes with forward slashes. This makes the
9499 * autocommand patterns portable between Unix and MS-DOS.
9500 */
9501 if (sfname != NULL)
9502 forward_slash(sfname);
9503 forward_slash(fname);
9504#endif
9505
9506#ifdef VMS
9507 /* remove version for correct match */
9508 if (sfname != NULL)
9509 vms_remove_version(sfname);
9510 vms_remove_version(fname);
9511#endif
9512
9513 /*
9514 * Set the name to be used for <amatch>.
9515 */
9516 autocmd_match = fname;
9517
9518
Bram Moolenaar8c555332018-06-22 21:30:31 +02009519 /* Don't redraw while doing autocommands. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 ++RedrawingDisabled;
9521 save_sourcing_name = sourcing_name;
9522 sourcing_name = NULL; /* don't free this one */
9523 save_sourcing_lnum = sourcing_lnum;
9524 sourcing_lnum = 0; /* no line number here */
9525
9526#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009527 save_current_sctx = current_sctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009528
Bram Moolenaar05159a02005-02-26 23:04:13 +00009529# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009530 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009531 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9532# endif
9533
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009534 // Don't use local function variables, if called from a function.
9535 save_funccal(&funccal_entry);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009536#endif
9537
9538 /*
9539 * When starting to execute autocommands, save the search patterns.
9540 */
9541 if (!autocmd_busy)
9542 {
9543 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009544#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009545 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009546#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009547 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009548 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009549 did_save_redobuff = TRUE;
9550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009551 did_filetype = keep_filetype;
9552 }
9553
9554 /*
9555 * Note that we are applying autocmds. Some commands need to know.
9556 */
9557 autocmd_busy = TRUE;
9558 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9559 ++nesting; /* see matching decrement below */
9560
9561 /* Remember that FileType was triggered. Used for did_filetype(). */
9562 if (event == EVENT_FILETYPE)
9563 did_filetype = TRUE;
9564
9565 tail = gettail(fname);
9566
9567 /* Find first autocommand that matches */
9568 patcmd.curpat = first_autopat[(int)event];
9569 patcmd.nextcmd = NULL;
9570 patcmd.group = group;
9571 patcmd.fname = fname;
9572 patcmd.sfname = sfname;
9573 patcmd.tail = tail;
9574 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009575 patcmd.arg_bufnr = autocmd_bufnr;
9576 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009577 auto_next_pat(&patcmd, FALSE);
9578
9579 /* found one, start executing the autocommands */
9580 if (patcmd.curpat != NULL)
9581 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009582 /* add to active_apc_list */
9583 patcmd.next = active_apc_list;
9584 active_apc_list = &patcmd;
9585
Bram Moolenaar071d4272004-06-13 20:20:40 +00009586#ifdef FEAT_EVAL
9587 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009588 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009589 if (eap != NULL)
9590 {
9591 save_cmdarg = set_cmdarg(eap, NULL);
9592 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9593 }
9594 else
9595 save_cmdarg = NULL; /* avoid gcc warning */
9596#endif
9597 retval = TRUE;
9598 /* mark the last pattern, to avoid an endless loop when more patterns
9599 * are added when executing autocommands */
9600 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9601 ap->last = FALSE;
9602 ap->last = TRUE;
9603 check_lnums(TRUE); /* make sure cursor and topline are valid */
9604 do_cmdline(NULL, getnextac, (void *)&patcmd,
9605 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9606#ifdef FEAT_EVAL
9607 if (eap != NULL)
9608 {
9609 (void)set_cmdarg(NULL, save_cmdarg);
9610 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9611 }
9612#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009613 /* delete from active_apc_list */
9614 if (active_apc_list == &patcmd) /* just in case */
9615 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009616 }
9617
9618 --RedrawingDisabled;
9619 autocmd_busy = save_autocmd_busy;
9620 filechangeshell_busy = FALSE;
9621 autocmd_nested = save_autocmd_nested;
9622 vim_free(sourcing_name);
9623 sourcing_name = save_sourcing_name;
9624 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009625 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009626 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009627 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009628 autocmd_bufnr = save_autocmd_bufnr;
9629 autocmd_match = save_autocmd_match;
9630#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009631 current_sctx = save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009632 restore_funccal();
Bram Moolenaar05159a02005-02-26 23:04:13 +00009633# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009634 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009635 prof_child_exit(&wait_time);
9636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009637#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009638 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009639 vim_free(fname);
9640 vim_free(sfname);
9641 --nesting; /* see matching increment above */
9642
9643 /*
9644 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009645 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9646 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009647 */
9648 if (!autocmd_busy)
9649 {
9650 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009651 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009652 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009653 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009654 while (au_pending_free_buf != NULL)
9655 {
9656 buf_T *b = au_pending_free_buf->b_next;
9657 vim_free(au_pending_free_buf);
9658 au_pending_free_buf = b;
9659 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009660 while (au_pending_free_win != NULL)
9661 {
9662 win_T *w = au_pending_free_win->w_next;
9663 vim_free(au_pending_free_win);
9664 au_pending_free_win = w;
9665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009666 }
9667
9668 /*
9669 * Some events don't set or reset the Changed flag.
9670 * Check if still in the same buffer!
9671 */
9672 if (curbuf == old_curbuf
9673 && (event == EVENT_BUFREADPOST
9674 || event == EVENT_BUFWRITEPOST
9675 || event == EVENT_FILEAPPENDPOST
9676 || event == EVENT_VIMLEAVE
9677 || event == EVENT_VIMLEAVEPRE))
9678 {
9679#ifdef FEAT_TITLE
9680 if (curbuf->b_changed != save_changed)
9681 need_maketitle = TRUE;
9682#endif
9683 curbuf->b_changed = save_changed;
9684 }
9685
9686 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009687
9688BYPASS_AU:
9689 /* When wiping out a buffer make sure all its buffer-local autocommands
9690 * are deleted. */
9691 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9692 aubuflocal_remove(buf);
9693
Bram Moolenaarc3691332016-04-20 12:49:49 +02009694 if (retval == OK && event == EVENT_FILETYPE)
9695 au_did_filetype = TRUE;
9696
Bram Moolenaar071d4272004-06-13 20:20:40 +00009697 return retval;
9698}
9699
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009700# ifdef FEAT_EVAL
9701static char_u *old_termresponse = NULL;
9702# endif
9703
9704/*
9705 * Block triggering autocommands until unblock_autocmd() is called.
9706 * Can be used recursively, so long as it's symmetric.
9707 */
9708 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009709block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009710{
9711# ifdef FEAT_EVAL
9712 /* Remember the value of v:termresponse. */
9713 if (autocmd_blocked == 0)
9714 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9715# endif
9716 ++autocmd_blocked;
9717}
9718
9719 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009720unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009721{
9722 --autocmd_blocked;
9723
9724# ifdef FEAT_EVAL
9725 /* When v:termresponse was set while autocommands were blocked, trigger
9726 * the autocommands now. Esp. useful when executing a shell command
9727 * during startup (vimdiff). */
9728 if (autocmd_blocked == 0
9729 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9730 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9731# endif
9732}
9733
Bram Moolenaar113e1072019-01-20 15:30:40 +01009734#if defined(FEAT_EVAL) && (defined(FEAT_XIM) || defined(IME_WITHOUT_XIM)) \
9735 || defined(PROTO)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009736 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009737is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009738{
9739 return autocmd_blocked != 0;
9740}
Bram Moolenaar113e1072019-01-20 15:30:40 +01009741#endif
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009742
Bram Moolenaar071d4272004-06-13 20:20:40 +00009743/*
9744 * Find next autocommand pattern that matches.
9745 */
9746 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009747auto_next_pat(
9748 AutoPatCmd *apc,
9749 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009750{
9751 AutoPat *ap;
9752 AutoCmd *cp;
9753 char_u *name;
9754 char *s;
9755
Bram Moolenaard23a8232018-02-10 18:45:26 +01009756 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009757
9758 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9759 {
9760 apc->curpat = NULL;
9761
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009762 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009763 * the group matches. For buffer-local autocommands only check the
9764 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009765 if (ap->pat != NULL && ap->cmds != NULL
9766 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9767 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009768 /* execution-condition */
9769 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009770 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009771 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009772 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009773 {
9774 name = event_nr2name(apc->event);
Bram Moolenaar8c555332018-06-22 21:30:31 +02009775 s = _("%s Autocommands for \"%s\"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009776 sourcing_name = alloc((unsigned)(STRLEN(s)
9777 + STRLEN(name) + ap->patlen + 1));
9778 if (sourcing_name != NULL)
9779 {
9780 sprintf((char *)sourcing_name, s,
9781 (char *)name, (char *)ap->pat);
9782 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009783 {
9784 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009785 smsg(_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009786 verbose_leave();
9787 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009788 }
9789
9790 apc->curpat = ap;
9791 apc->nextcmd = ap->cmds;
9792 /* mark last command */
9793 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9794 cp->last = FALSE;
9795 cp->last = TRUE;
9796 }
9797 line_breakcheck();
9798 if (apc->curpat != NULL) /* found a match */
9799 break;
9800 }
9801 if (stop_at_last && ap->last)
9802 break;
9803 }
9804}
9805
9806/*
9807 * Get next autocommand command.
9808 * Called by do_cmdline() to get the next line for ":if".
9809 * Returns allocated string, or NULL for end of autocommands.
9810 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009811 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009812getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009813{
9814 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9815 char_u *retval;
9816 AutoCmd *ac;
9817
9818 /* Can be called again after returning the last line. */
9819 if (acp->curpat == NULL)
9820 return NULL;
9821
9822 /* repeat until we find an autocommand to execute */
9823 for (;;)
9824 {
9825 /* skip removed commands */
9826 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9827 if (acp->nextcmd->last)
9828 acp->nextcmd = NULL;
9829 else
9830 acp->nextcmd = acp->nextcmd->next;
9831
9832 if (acp->nextcmd != NULL)
9833 break;
9834
9835 /* at end of commands, find next pattern that matches */
9836 if (acp->curpat->last)
9837 acp->curpat = NULL;
9838 else
9839 acp->curpat = acp->curpat->next;
9840 if (acp->curpat != NULL)
9841 auto_next_pat(acp, TRUE);
9842 if (acp->curpat == NULL)
9843 return NULL;
9844 }
9845
9846 ac = acp->nextcmd;
9847
9848 if (p_verbose >= 9)
9849 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009850 verbose_enter_scroll();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01009851 smsg(_("autocommand %s"), ac->cmd);
Bram Moolenaar32526b32019-01-19 17:43:09 +01009852 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009853 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009854 }
9855 retval = vim_strsave(ac->cmd);
9856 autocmd_nested = ac->nested;
9857#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009858 current_sctx = ac->script_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009859#endif
9860 if (ac->last)
9861 acp->nextcmd = NULL;
9862 else
9863 acp->nextcmd = ac->next;
9864 return retval;
9865}
9866
9867/*
9868 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009869 * To account for buffer-local autocommands, function needs to know
9870 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009871 */
9872 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009873has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009874{
9875 AutoPat *ap;
9876 char_u *fname;
9877 char_u *tail = gettail(sfname);
9878 int retval = FALSE;
9879
9880 fname = FullName_save(sfname, FALSE);
9881 if (fname == NULL)
9882 return FALSE;
9883
9884#ifdef BACKSLASH_IN_FILENAME
9885 /*
9886 * Replace all backslashes with forward slashes. This makes the
9887 * autocommand patterns portable between Unix and MS-DOS.
9888 */
9889 sfname = vim_strsave(sfname);
9890 if (sfname != NULL)
9891 forward_slash(sfname);
9892 forward_slash(fname);
9893#endif
9894
9895 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9896 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009897 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009898 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009899 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009900 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009901 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009902 {
9903 retval = TRUE;
9904 break;
9905 }
9906
9907 vim_free(fname);
9908#ifdef BACKSLASH_IN_FILENAME
9909 vim_free(sfname);
9910#endif
9911
9912 return retval;
9913}
9914
9915#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9916/*
9917 * Function given to ExpandGeneric() to obtain the list of autocommand group
9918 * names.
9919 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009920 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009921get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922{
9923 if (idx == augroups.ga_len) /* add "END" add the end */
9924 return (char_u *)"END";
9925 if (idx >= augroups.ga_len) /* end of list */
9926 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009927 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009928 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009929 return (char_u *)"";
9930 return AUGROUP_NAME(idx); /* return a name */
9931}
9932
9933static int include_groups = FALSE;
9934
9935 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009936set_context_in_autocmd(
9937 expand_T *xp,
9938 char_u *arg,
9939 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009940{
9941 char_u *p;
9942 int group;
9943
9944 /* check for a group name, skip it if present */
9945 include_groups = FALSE;
9946 p = arg;
9947 group = au_get_grouparg(&arg);
9948 if (group == AUGROUP_ERROR)
9949 return NULL;
9950 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009951 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009952 {
9953 arg = p;
9954 group = AUGROUP_ALL;
9955 }
9956
9957 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009958 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009959 if (*p == ',')
9960 arg = p + 1;
9961 if (*p == NUL)
9962 {
9963 if (group == AUGROUP_ALL)
9964 include_groups = TRUE;
9965 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9966 xp->xp_pattern = arg;
9967 return NULL;
9968 }
9969
9970 /* skip over pattern */
9971 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +01009972 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973 arg++;
9974 if (*arg)
9975 return arg; /* expand (next) command */
9976
9977 if (doautocmd)
9978 xp->xp_context = EXPAND_FILES; /* expand file names */
9979 else
9980 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9981 return NULL;
9982}
9983
9984/*
9985 * Function given to ExpandGeneric() to obtain the list of event names.
9986 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009988get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009989{
9990 if (idx < augroups.ga_len) /* First list group names, if wanted */
9991 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009992 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009993 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +00009994 return (char_u *)""; /* skip deleted entries */
9995 return AUGROUP_NAME(idx); /* return a name */
9996 }
9997 return (char_u *)event_names[idx - augroups.ga_len].name;
9998}
9999
10000#endif /* FEAT_CMDL_COMPL */
10001
Bram Moolenaar113e1072019-01-20 15:30:40 +010010002#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010003/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010004 * Return TRUE if autocmd is supported.
10005 */
10006 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010007autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010008{
10009 char_u *p;
10010
10011 return (event_name2nr(name, &p) != NUM_EVENTS);
10012}
10013
10014/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010015 * Return TRUE if an autocommand is defined for a group, event and
10016 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10017 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10018 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10019 * Used for:
10020 * exists("#Group") or
10021 * exists("#Group#Event") or
10022 * exists("#Group#Event#pat") or
10023 * exists("#Event") or
10024 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010025 */
10026 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010027au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010028{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010029 char_u *arg_save;
10030 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010031 char_u *event_name;
10032 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010033 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010034 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010035 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010036 int group;
10037 int retval = FALSE;
10038
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010039 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010040 arg_save = vim_strsave(arg);
10041 if (arg_save == NULL)
10042 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010043 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010044 if (p != NULL)
10045 *p++ = NUL;
10046
10047 /* First, look for an autocmd group name */
10048 group = au_find_group(arg_save);
10049 if (group == AUGROUP_ERROR)
10050 {
10051 /* Didn't match a group name, assume the first argument is an event. */
10052 group = AUGROUP_ALL;
10053 event_name = arg_save;
10054 }
10055 else
10056 {
10057 if (p == NULL)
10058 {
10059 /* "Group": group name is present and it's recognized */
10060 retval = TRUE;
10061 goto theend;
10062 }
10063
10064 /* Must be "Group#Event" or "Group#Event#pat". */
10065 event_name = p;
10066 p = vim_strchr(event_name, '#');
10067 if (p != NULL)
10068 *p++ = NUL; /* "Group#Event#pat" */
10069 }
10070
10071 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072
10073 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010074 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010075
10076 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010077 if (event == NUM_EVENTS)
10078 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010079
10080 /* Find the first autocommand for this event.
10081 * If there isn't any, return FALSE;
10082 * If there is one and no pattern given, return TRUE; */
10083 ap = first_autopat[(int)event];
10084 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010085 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010086
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010087 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10088 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010089 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010090 buflocal_buf = curbuf;
10091
Bram Moolenaar071d4272004-06-13 20:20:40 +000010092 /* Check if there is an autocommand with the given pattern. */
10093 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010094 /* only use a pattern when it has not been removed and has commands. */
10095 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010096 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010097 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010098 && (pattern == NULL
10099 || (buflocal_buf == NULL
10100 ? fnamecmp(ap->pat, pattern) == 0
10101 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010102 {
10103 retval = TRUE;
10104 break;
10105 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010106
Bram Moolenaar195d6352005-12-19 22:08:24 +000010107theend:
10108 vim_free(arg_save);
10109 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010110}
Bram Moolenaar113e1072019-01-20 15:30:40 +010010111#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010112
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010113
10114/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010115 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10116 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10117 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010118 * Used for autocommands and 'wildignore'.
10119 * Returns TRUE if there is a match, FALSE otherwise.
10120 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010121 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010122match_file_pat(
10123 char_u *pattern, /* pattern to match with */
10124 regprog_T **prog, /* pre-compiled regprog or NULL */
10125 char_u *fname, /* full path of file name */
10126 char_u *sfname, /* short file name or NULL */
10127 char_u *tail, /* tail of path */
10128 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129{
10130 regmatch_T regmatch;
10131 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010132
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010133 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010134 if (prog != NULL)
10135 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010136 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010137 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010138
10139 /*
10140 * Try for a match with the pattern with:
10141 * 1. the full file name, when the pattern has a '/'.
10142 * 2. the short file name, when the pattern has a '/'.
10143 * 3. the tail of the file name, when the pattern has no '/'.
10144 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010145 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010146 && ((allow_dirs
10147 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10148 || (sfname != NULL
10149 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010150 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010151 result = TRUE;
10152
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010153 if (prog != NULL)
10154 *prog = regmatch.regprog;
10155 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010156 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010157 return result;
10158}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010159
10160#if defined(FEAT_WILDIGN) || defined(PROTO)
10161/*
10162 * Return TRUE if a file matches with a pattern in "list".
10163 * "list" is a comma-separated list of patterns, like 'wildignore'.
10164 * "sfname" is the short file name or NULL, "ffname" the long file name.
10165 */
10166 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010167match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010168{
10169 char_u buf[100];
10170 char_u *tail;
10171 char_u *regpat;
10172 char allow_dirs;
10173 int match;
10174 char_u *p;
10175
10176 tail = gettail(sfname);
10177
10178 /* try all patterns in 'wildignore' */
10179 p = list;
10180 while (*p)
10181 {
10182 copy_option_part(&p, buf, 100, ",");
10183 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10184 if (regpat == NULL)
10185 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010186 match = match_file_pat(regpat, NULL, ffname, sfname,
10187 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010188 vim_free(regpat);
10189 if (match)
10190 return TRUE;
10191 }
10192 return FALSE;
10193}
10194#endif
10195
10196/*
10197 * Convert the given pattern "pat" which has shell style wildcards in it, into
10198 * a regular expression, and return the result in allocated memory. If there
10199 * is a directory path separator to be matched, then TRUE is put in
10200 * allow_dirs, otherwise FALSE is put there -- webb.
10201 * Handle backslashes before special characters, like "\*" and "\ ".
10202 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010203 * Returns NULL when out of memory.
10204 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010205 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010206file_pat_to_reg_pat(
10207 char_u *pat,
10208 char_u *pat_end, /* first char after pattern or NULL */
10209 char *allow_dirs, /* Result passed back out in here */
10210 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010211{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010212 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213 char_u *endp;
10214 char_u *reg_pat;
10215 char_u *p;
10216 int i;
10217 int nested = 0;
10218 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010219
10220 if (allow_dirs != NULL)
10221 *allow_dirs = FALSE;
10222 if (pat_end == NULL)
10223 pat_end = pat + STRLEN(pat);
10224
Bram Moolenaar071d4272004-06-13 20:20:40 +000010225 for (p = pat; p < pat_end; p++)
10226 {
10227 switch (*p)
10228 {
10229 case '*':
10230 case '.':
10231 case ',':
10232 case '{':
10233 case '}':
10234 case '~':
10235 size += 2; /* extra backslash */
10236 break;
10237#ifdef BACKSLASH_IN_FILENAME
10238 case '\\':
10239 case '/':
10240 size += 4; /* could become "[\/]" */
10241 break;
10242#endif
10243 default:
10244 size++;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010245 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010246 {
10247 ++p;
10248 ++size;
10249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010250 break;
10251 }
10252 }
10253 reg_pat = alloc(size + 1);
10254 if (reg_pat == NULL)
10255 return NULL;
10256
Bram Moolenaar071d4272004-06-13 20:20:40 +000010257 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010258
10259 if (pat[0] == '*')
10260 while (pat[0] == '*' && pat < pat_end - 1)
10261 pat++;
10262 else
10263 reg_pat[i++] = '^';
10264 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010265 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010266 {
10267 while (endp - pat > 0 && *endp == '*')
10268 endp--;
10269 add_dollar = FALSE;
10270 }
10271 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10272 {
10273 switch (*p)
10274 {
10275 case '*':
10276 reg_pat[i++] = '.';
10277 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010278 while (p[1] == '*') /* "**" matches like "*" */
10279 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010280 break;
10281 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010282 case '~':
10283 reg_pat[i++] = '\\';
10284 reg_pat[i++] = *p;
10285 break;
10286 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010287 reg_pat[i++] = '.';
10288 break;
10289 case '\\':
10290 if (p[1] == NUL)
10291 break;
10292#ifdef BACKSLASH_IN_FILENAME
10293 if (!no_bslash)
10294 {
10295 /* translate:
10296 * "\x" to "\\x" e.g., "dir\file"
10297 * "\*" to "\\.*" e.g., "dir\*.c"
10298 * "\?" to "\\." e.g., "dir\??.c"
10299 * "\+" to "\+" e.g., "fileX\+.c"
10300 */
10301 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10302 && p[1] != '+')
10303 {
10304 reg_pat[i++] = '[';
10305 reg_pat[i++] = '\\';
10306 reg_pat[i++] = '/';
10307 reg_pat[i++] = ']';
10308 if (allow_dirs != NULL)
10309 *allow_dirs = TRUE;
10310 break;
10311 }
10312 }
10313#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010314 /* Undo escaping from ExpandEscape():
10315 * foo\?bar -> foo?bar
10316 * foo\%bar -> foo%bar
10317 * foo\,bar -> foo,bar
10318 * foo\ bar -> foo bar
10319 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010320 * regexp.
10321 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010322 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010323 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010324 if (*++p == '?'
10325#ifdef BACKSLASH_IN_FILENAME
10326 && no_bslash
10327#endif
10328 )
10329 reg_pat[i++] = '?';
10330 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010331 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010332 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010333 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010334 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10335 {
10336 reg_pat[i++] = '\\';
10337 reg_pat[i++] = '{';
10338 p += 2;
10339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010340 else
10341 {
10342 if (allow_dirs != NULL && vim_ispathsep(*p)
10343#ifdef BACKSLASH_IN_FILENAME
10344 && (!no_bslash || *p != '\\')
10345#endif
10346 )
10347 *allow_dirs = TRUE;
10348 reg_pat[i++] = '\\';
10349 reg_pat[i++] = *p;
10350 }
10351 break;
10352#ifdef BACKSLASH_IN_FILENAME
10353 case '/':
10354 reg_pat[i++] = '[';
10355 reg_pat[i++] = '\\';
10356 reg_pat[i++] = '/';
10357 reg_pat[i++] = ']';
10358 if (allow_dirs != NULL)
10359 *allow_dirs = TRUE;
10360 break;
10361#endif
10362 case '{':
10363 reg_pat[i++] = '\\';
10364 reg_pat[i++] = '(';
10365 nested++;
10366 break;
10367 case '}':
10368 reg_pat[i++] = '\\';
10369 reg_pat[i++] = ')';
10370 --nested;
10371 break;
10372 case ',':
10373 if (nested)
10374 {
10375 reg_pat[i++] = '\\';
10376 reg_pat[i++] = '|';
10377 }
10378 else
10379 reg_pat[i++] = ',';
10380 break;
10381 default:
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010382 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010383 reg_pat[i++] = *p++;
Bram Moolenaar13505972019-01-24 15:04:48 +010010384 else if (allow_dirs != NULL && vim_ispathsep(*p))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010385 *allow_dirs = TRUE;
10386 reg_pat[i++] = *p;
10387 break;
10388 }
10389 }
10390 if (add_dollar)
10391 reg_pat[i++] = '$';
10392 reg_pat[i] = NUL;
10393 if (nested != 0)
10394 {
10395 if (nested < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +010010396 emsg(_("E219: Missing {."));
Bram Moolenaar071d4272004-06-13 20:20:40 +000010397 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +010010398 emsg(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010399 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010400 }
10401 return reg_pat;
10402}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010403
10404#if defined(EINTR) || defined(PROTO)
10405/*
10406 * Version of read() that retries when interrupted by EINTR (possibly
10407 * by a SIGWINCH).
10408 */
10409 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010410read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010411{
10412 long ret;
10413
10414 for (;;)
10415 {
10416 ret = vim_read(fd, buf, bufsize);
10417 if (ret >= 0 || errno != EINTR)
10418 break;
10419 }
10420 return ret;
10421}
10422
10423/*
10424 * Version of write() that retries when interrupted by EINTR (possibly
10425 * by a SIGWINCH).
10426 */
10427 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010428write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010429{
10430 long ret = 0;
10431 long wlen;
10432
10433 /* Repeat the write() so long it didn't fail, other than being interrupted
10434 * by a signal. */
10435 while (ret < (long)bufsize)
10436 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010437 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010438 if (wlen < 0)
10439 {
10440 if (errno != EINTR)
10441 break;
10442 }
10443 else
10444 ret += wlen;
10445 }
10446 return ret;
10447}
10448#endif