blob: 7bceb75fd71facd14856f1d806fdff6230be8ed9 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
30#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000032# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010033static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000034# endif
35#endif
36#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#endif
39#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020040static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
Bram Moolenaar071d4272004-06-13 20:20:40 +000041#endif
42#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010043static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000044#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010045static int set_rw_fname(char_u *fname, char_u *sfname);
46static int msg_add_fileformat(int eol_type);
47static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020048static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int time_differs(long t1, long t2);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010050static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
51static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000052
53# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000054# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000055# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000056
57#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
58# define HAS_BW_FLAGS
59# define FIO_LATIN1 0x01 /* convert Latin1 */
60# define FIO_UTF8 0x02 /* convert UTF-8 */
61# define FIO_UCS2 0x04 /* convert UCS-2 */
62# define FIO_UCS4 0x08 /* convert UCS-4 */
63# define FIO_UTF16 0x10 /* convert UTF-16 */
64# ifdef WIN3264
65# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
66# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
67# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
68# endif
Bram Moolenaard0573012017-10-28 21:11:06 +020069# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000070# define FIO_MACROMAN 0x20 /* convert MacRoman */
71# endif
72# define FIO_ENDIAN_L 0x80 /* little endian */
73# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
74# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
75# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
76# define FIO_ALL -1 /* allow all formats */
77#endif
78
79/* When converting, a read() or write() may leave some bytes to be converted
80 * for the next call. The value is guessed... */
81#define CONV_RESTLEN 30
82
83/* We have to guess how much a sequence of bytes may expand when converting
84 * with iconv() to be able to allocate a buffer. */
85#define ICONV_MULT 8
86
87/*
88 * Structure to pass arguments from buf_write() to buf_write_bytes().
89 */
90struct bw_info
91{
92 int bw_fd; /* file descriptor */
93 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000094 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000095#ifdef HAS_BW_FLAGS
96 int bw_flags; /* FIO_ flags */
97#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020098#ifdef FEAT_CRYPT
99 buf_T *bw_buffer; /* buffer being written */
100#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101#ifdef FEAT_MBYTE
102 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
103 int bw_restlen; /* nr of bytes in bw_rest[] */
104 int bw_first; /* first write call */
105 char_u *bw_conv_buf; /* buffer for writing converted chars */
106 int bw_conv_buflen; /* size of bw_conv_buf */
107 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000108 linenr_T bw_conv_error_lnum; /* first line with error or zero */
109 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000110# ifdef USE_ICONV
111 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
112# endif
113#endif
114};
115
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100116static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000117
118#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100119static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
120static int ucs2bytes(unsigned c, char_u **pp, int flags);
121static int need_conversion(char_u *fenc);
122static int get_fio_flags(char_u *ptr);
123static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
124static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100126static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# endif
Bram Moolenaard0573012017-10-28 21:11:06 +0200128# ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100129static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000130# endif
131#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100132static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000133#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100134static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000135#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000136static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000137
Bram Moolenaarc3691332016-04-20 12:49:49 +0200138/*
139 * Set by the apply_autocmds_group function if the given event is equal to
140 * EVENT_FILETYPE. Used by the readfile function in order to determine if
141 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
142 *
143 * Relying on this value requires one to reset it prior calling
144 * apply_autocmds_group.
145 */
146static int au_did_filetype INIT(= FALSE);
Bram Moolenaarc3691332016-04-20 12:49:49 +0200147
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100149filemess(
150 buf_T *buf,
151 char_u *name,
152 char_u *s,
153 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154{
155 int msg_scroll_save;
156
157 if (msg_silent != 0)
158 return;
159 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
160 /* If it's extremely long, truncate it. */
161 if (STRLEN(IObuff) > IOSIZE - 80)
162 IObuff[IOSIZE - 80] = NUL;
163 STRCAT(IObuff, s);
164 /*
165 * For the first message may have to start a new line.
166 * For further ones overwrite the previous one, reset msg_scroll before
167 * calling filemess().
168 */
169 msg_scroll_save = msg_scroll;
170 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
171 msg_scroll = FALSE;
172 if (!msg_scroll) /* wait a bit when overwriting an error msg */
173 check_for_delay(FALSE);
174 msg_start();
175 msg_scroll = msg_scroll_save;
176 msg_scrolled_ign = TRUE;
177 /* may truncate the message to avoid a hit-return prompt */
178 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
179 msg_clr_eos();
180 out_flush();
181 msg_scrolled_ign = FALSE;
182}
183
184/*
185 * Read lines from file "fname" into the buffer after line "from".
186 *
187 * 1. We allocate blocks with lalloc, as big as possible.
188 * 2. Each block is filled with characters from the file with a single read().
189 * 3. The lines are inserted in the buffer with ml_append().
190 *
191 * (caller must check that fname != NULL, unless READ_STDIN is used)
192 *
193 * "lines_to_skip" is the number of lines that must be skipped
194 * "lines_to_read" is the number of lines that are appended
195 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
196 *
197 * flags:
198 * READ_NEW starting to edit a new buffer
199 * READ_FILTER reading filter output
200 * READ_STDIN read from stdin instead of a file
201 * READ_BUFFER read from curbuf instead of a file (converting after reading
202 * stdin)
203 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200204 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200205 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000206 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100207 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208 */
209 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100210readfile(
211 char_u *fname,
212 char_u *sfname,
213 linenr_T from,
214 linenr_T lines_to_skip,
215 linenr_T lines_to_read,
216 exarg_T *eap, /* can be NULL! */
217 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218{
219 int fd = 0;
220 int newfile = (flags & READ_NEW);
221 int check_readonly;
222 int filtering = (flags & READ_FILTER);
223 int read_stdin = (flags & READ_STDIN);
224 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200225 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000226 int set_options = newfile || read_buffer
227 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
229 colnr_T read_buf_col = 0; /* next char to read from this line */
230 char_u c;
231 linenr_T lnum = from;
232 char_u *ptr = NULL; /* pointer into read buffer */
233 char_u *buffer = NULL; /* read buffer */
234 char_u *new_buffer = NULL; /* init to shut up gcc */
235 char_u *line_start = NULL; /* init to shut up gcc */
236 int wasempty; /* buffer was empty before reading */
237 colnr_T len;
238 long size = 0;
239 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200240 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241 int skip_read = FALSE;
242#ifdef FEAT_CRYPT
243 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200244 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200246#ifdef FEAT_PERSISTENT_UNDO
247 context_sha256_T sha_ctx;
248 int read_undo_file = FALSE;
249#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250 int split = 0; /* number of split lines */
251#define UNKNOWN 0x0fffffff /* file size is unknown */
252 linenr_T linecnt;
253 int error = FALSE; /* errors encountered */
254 int ff_error = EOL_UNKNOWN; /* file format with errors */
255 long linerest = 0; /* remaining chars in line */
256#ifdef UNIX
257 int perm = 0;
258 int swap_mode = -1; /* protection bits for swap file */
259#else
260 int perm;
261#endif
262 int fileformat = 0; /* end-of-line format */
263 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200264 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265 int file_readonly;
266 linenr_T skip_count = 0;
267 linenr_T read_count = 0;
268 int msg_save = msg_scroll;
269 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
270 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100271 int try_mac;
272 int try_dos;
273 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274 int file_rewind = FALSE;
275#ifdef FEAT_MBYTE
276 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000277 linenr_T conv_error = 0; /* line nr with conversion error */
278 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
280 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000281 int bad_char_behavior = BAD_REPLACE;
282 /* BAD_KEEP, BAD_DROP or character to
283 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284 char_u *tmpname = NULL; /* name of 'charconvert' output file */
285 int fio_flags = 0;
286 char_u *fenc; /* fileencoding to use */
287 int fenc_alloced; /* fenc_next is in allocated memory */
288 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
289 int advance_fenc = FALSE;
290 long real_size = 0;
291# ifdef USE_ICONV
292 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
293# ifdef FEAT_EVAL
294 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
295 'charconvert' next */
296# endif
297# endif
298 int converted = FALSE; /* TRUE if conversion done */
299 int notconverted = FALSE; /* TRUE if conversion wanted but it
300 wasn't possible */
301 char_u conv_rest[CONV_RESTLEN];
302 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
303#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200304 buf_T *old_curbuf;
305 char_u *old_b_ffname;
306 char_u *old_b_fname;
307 int using_b_ffname;
308 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200309
Bram Moolenaarc3691332016-04-20 12:49:49 +0200310 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200311
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100312 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000313
314 /*
315 * If there is no file name yet, use the one for the read file.
316 * BF_NOTEDITED is set to reflect this.
317 * Don't do this for a read from a filter.
318 * Only do this when 'cpoptions' contains the 'f' flag.
319 */
320 if (curbuf->b_ffname == NULL
321 && !filtering
322 && fname != NULL
323 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
324 && !(flags & READ_DUMMY))
325 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000326 if (set_rw_fname(fname, sfname) == FAIL)
327 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328 }
329
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200330 /* Remember the initial values of curbuf, curbuf->b_ffname and
331 * curbuf->b_fname to detect whether they are altered as a result of
332 * executing nasty autocommands. Also check if "fname" and "sfname"
333 * point to one of these values. */
334 old_curbuf = curbuf;
335 old_b_ffname = curbuf->b_ffname;
336 old_b_fname = curbuf->b_fname;
337 using_b_ffname = (fname == curbuf->b_ffname)
338 || (sfname == curbuf->b_ffname);
339 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200340
Bram Moolenaardf177f62005-02-22 08:39:57 +0000341 /* After reading a file the cursor line changes but we don't want to
342 * display the line. */
343 ex_no_reprint = TRUE;
344
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000345 /* don't display the file info for another buffer now */
346 need_fileinfo = FALSE;
347
Bram Moolenaar071d4272004-06-13 20:20:40 +0000348 /*
349 * For Unix: Use the short file name whenever possible.
350 * Avoids problems with networks and when directory names are changed.
351 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
352 * another directory, which we don't detect.
353 */
354 if (sfname == NULL)
355 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200356#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000357 fname = sfname;
358#endif
359
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 /*
361 * The BufReadCmd and FileReadCmd events intercept the reading process by
362 * executing the associated commands instead.
363 */
364 if (!filtering && !read_stdin && !read_buffer)
365 {
366 pos_T pos;
367
368 pos = curbuf->b_op_start;
369
370 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
371 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
372 curbuf->b_op_start.col = 0;
373
374 if (newfile)
375 {
376 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
377 FALSE, curbuf, eap))
378#ifdef FEAT_EVAL
379 return aborting() ? FAIL : OK;
380#else
381 return OK;
382#endif
383 }
384 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
385 FALSE, NULL, eap))
386#ifdef FEAT_EVAL
387 return aborting() ? FAIL : OK;
388#else
389 return OK;
390#endif
391
392 curbuf->b_op_start = pos;
393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394
395 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
396 msg_scroll = FALSE; /* overwrite previous file message */
397 else
398 msg_scroll = TRUE; /* don't overwrite previous file message */
399
400 /*
401 * If the name ends in a path separator, we can't open it. Check here,
402 * because reading the file may actually work, but then creating the swap
403 * file may destroy it! Reported on MS-DOS and Win 95.
404 * If the name is too long we might crash further on, quit here.
405 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000406 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000408 p = fname + STRLEN(fname);
409 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000410 {
411 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
412 msg_end();
413 msg_scroll = msg_save;
414 return FAIL;
415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 }
417
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200418 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200420#ifdef UNIX
421 /*
422 * On Unix it is possible to read a directory, so we have to
423 * check for it before the mch_open().
424 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 perm = mch_getperm(fname);
426 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 && !S_ISFIFO(perm) /* ... or fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 && !S_ISSOCK(perm) /* ... or socket */
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000429# ifdef OPEN_CHR_FILES
430 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
431 /* ... or a character special file named /dev/fd/<n> */
432# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 )
434 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100435 int retval = FAIL;
436
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100438 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100440 retval = NOTDONE;
441 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 else
443 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
444 msg_end();
445 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100446 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200448#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100449#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000450 /*
451 * MS-Windows allows opening a device, but we will probably get stuck
452 * trying to read it.
453 */
454 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
455 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000456 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000457 msg_end();
458 msg_scroll = msg_save;
459 return FAIL;
460 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000461#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200462 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000463
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200464 /* Set default or forced 'fileformat' and 'binary'. */
465 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000466
467 /*
468 * When opening a new file we take the readonly flag from the file.
469 * Default is r/w, can be set to r/o below.
470 * Don't reset it when in readonly mode
471 * Only set/reset b_p_ro when BF_CHECK_RO is set.
472 */
473 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000474 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 curbuf->b_p_ro = FALSE;
476
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200477 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200479 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480 if (mch_stat((char *)fname, &st) >= 0)
481 {
482 buf_store_time(curbuf, &st, fname);
483 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484#ifdef UNIX
485 /*
486 * Use the protection bits of the original file for the swap file.
487 * This makes it possible for others to read the name of the
488 * edited file from the swapfile, but only if they can read the
489 * edited file.
490 * Remove the "write" and "execute" bits for group and others
491 * (they must not write the swapfile).
492 * Add the "read" and "write" bits for the user, otherwise we may
493 * not be able to write to the file ourselves.
494 * Setting the bits is done below, after creating the swap file.
495 */
496 swap_mode = (st.st_mode & 0644) | 0600;
497#endif
498#ifdef FEAT_CW_EDITOR
499 /* Get the FSSpec on MacOS
500 * TODO: Update it properly when the buffer name changes
501 */
502 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
503#endif
504#ifdef VMS
505 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000506 curbuf->b_fab_rat = st.st_fab_rat;
507 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508#endif
509 }
510 else
511 {
512 curbuf->b_mtime = 0;
513 curbuf->b_mtime_read = 0;
514 curbuf->b_orig_size = 0;
515 curbuf->b_orig_mode = 0;
516 }
517
518 /* Reset the "new file" flag. It will be set again below when the
519 * file doesn't exist. */
520 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
521 }
522
523/*
524 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100525 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526 */
527 file_readonly = FALSE;
528 if (read_stdin)
529 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100530#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
532 setmode(0, O_BINARY);
533#endif
534 }
535 else if (!read_buffer)
536 {
537#ifdef USE_MCH_ACCESS
538 if (
539# ifdef UNIX
540 !(perm & 0222) ||
541# endif
542 mch_access((char *)fname, W_OK))
543 file_readonly = TRUE;
544 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
545#else
546 if (!newfile
547 || readonlymode
548 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
549 {
550 file_readonly = TRUE;
551 /* try to open ro */
552 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
553 }
554#endif
555 }
556
557 if (fd < 0) /* cannot open at all */
558 {
559#ifndef UNIX
560 int isdir_f;
561#endif
562 msg_scroll = msg_save;
563#ifndef UNIX
564 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100565 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 */
567 isdir_f = (mch_isdir(fname));
568 perm = mch_getperm(fname); /* check if the file exists */
569 if (isdir_f)
570 {
571 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
572 curbuf->b_p_ro = TRUE; /* must use "w!" now */
573 }
574 else
575#endif
576 if (newfile)
577 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200578 if (perm < 0
579#ifdef ENOENT
580 && errno == ENOENT
581#endif
582 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583 {
584 /*
585 * Set the 'new-file' flag, so that when the file has
586 * been created by someone else, a ":w" will complain.
587 */
588 curbuf->b_flags |= BF_NEW;
589
590 /* Create a swap file now, so that other Vims are warned
591 * that we are editing this file. Don't do this for a
592 * "nofile" or "nowrite" buffer type. */
593#ifdef FEAT_QUICKFIX
594 if (!bt_dontwrite(curbuf))
595#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000596 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000598 /* SwapExists autocommand may mess things up */
599 if (curbuf != old_curbuf
600 || (using_b_ffname
601 && (old_b_ffname != curbuf->b_ffname))
602 || (using_b_fname
603 && (old_b_fname != curbuf->b_fname)))
604 {
605 EMSG(_(e_auchangedbuf));
606 return FAIL;
607 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000608 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000609 if (dir_of_file_exists(fname))
610 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
611 else
612 filemess(curbuf, sfname,
613 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614#ifdef FEAT_VIMINFO
615 /* Even though this is a new file, it might have been
616 * edited before and deleted. Get the old marks. */
617 check_marks_read();
618#endif
619#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200620 /* Set forced 'fileencoding'. */
621 if (eap != NULL)
622 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
625 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 /* remember the current fileformat */
627 save_file_ff(curbuf);
628
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100629#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 if (aborting()) /* autocmds may abort script processing */
631 return FAIL;
632#endif
633 return OK; /* a new file is not an error */
634 }
635 else
636 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000637 filemess(curbuf, sfname, (char_u *)(
638# ifdef EFBIG
639 (errno == EFBIG) ? _("[File too big]") :
640# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200641# ifdef EOVERFLOW
642 (errno == EOVERFLOW) ? _("[File too big]") :
643# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000644 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645 curbuf->b_p_ro = TRUE; /* must use "w!" now */
646 }
647 }
648
649 return FAIL;
650 }
651
652 /*
653 * Only set the 'ro' flag for readonly files the first time they are
654 * loaded. Help files always get readonly mode
655 */
656 if ((check_readonly && file_readonly) || curbuf->b_help)
657 curbuf->b_p_ro = TRUE;
658
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000659 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000661 /* Don't change 'eol' if reading from buffer as it will already be
662 * correctly set when reading stdin. */
663 if (!read_buffer)
664 {
665 curbuf->b_p_eol = TRUE;
666 curbuf->b_start_eol = TRUE;
667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668#ifdef FEAT_MBYTE
669 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000670 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671#endif
672 }
673
674 /* Create a swap file now, so that other Vims are warned that we are
675 * editing this file.
676 * Don't do this for a "nofile" or "nowrite" buffer type. */
677#ifdef FEAT_QUICKFIX
678 if (!bt_dontwrite(curbuf))
679#endif
680 {
681 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000682 if (!read_stdin && (curbuf != old_curbuf
683 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
684 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
685 {
686 EMSG(_(e_auchangedbuf));
687 if (!read_buffer)
688 close(fd);
689 return FAIL;
690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691#ifdef UNIX
692 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000693 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
694 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100695 {
696 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
697
698 /*
699 * If the group-read bit is set but not the world-read bit, then
700 * the group must be equal to the group of the original file. If
701 * we can't make that happen then reset the group-read bit. This
702 * avoids making the swap file readable to more users when the
703 * primary group of the user is too permissive.
704 */
705 if ((swap_mode & 044) == 040)
706 {
707 stat_T swap_st;
708
709 if (mch_stat((char *)swap_fname, &swap_st) >= 0
710 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200711# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100712 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200713 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200714# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200715 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100716 swap_mode &= 0600;
717 }
718
719 (void)mch_setperm(swap_fname, (long)swap_mode);
720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721#endif
722 }
723
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000724#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 /* If "Quit" selected at ATTENTION dialog, don't load the file */
726 if (swap_exists_action == SEA_QUIT)
727 {
728 if (!read_buffer && !read_stdin)
729 close(fd);
730 return FAIL;
731 }
732#endif
733
734 ++no_wait_return; /* don't wait for return yet */
735
736 /*
737 * Set '[ mark to the line above where the lines go (line 1 if zero).
738 */
739 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
740 curbuf->b_op_start.col = 0;
741
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100742 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
743 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
744 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
745
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 if (!read_buffer)
747 {
748 int m = msg_scroll;
749 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750
751 /*
752 * The file must be closed again, the autocommands may want to change
753 * the file before reading it.
754 */
755 if (!read_stdin)
756 close(fd); /* ignore errors */
757
758 /*
759 * The output from the autocommands should not overwrite anything and
760 * should not be overwritten: Set msg_scroll, restore its value if no
761 * output was done.
762 */
763 msg_scroll = TRUE;
764 if (filtering)
765 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
766 FALSE, curbuf, eap);
767 else if (read_stdin)
768 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
769 FALSE, curbuf, eap);
770 else if (newfile)
771 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
772 FALSE, curbuf, eap);
773 else
774 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
775 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100776 /* autocommands may have changed it */
777 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
778 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
779 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
780
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781 if (msg_scrolled == n)
782 msg_scroll = m;
783
784#ifdef FEAT_EVAL
785 if (aborting()) /* autocmds may abort script processing */
786 {
787 --no_wait_return;
788 msg_scroll = msg_save;
789 curbuf->b_p_ro = TRUE; /* must use "w!" now */
790 return FAIL;
791 }
792#endif
793 /*
794 * Don't allow the autocommands to change the current buffer.
795 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000796 *
797 * Don't allow the autocommands to change the buffer name either
798 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 */
800 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000801 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
802 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
804 {
805 --no_wait_return;
806 msg_scroll = msg_save;
807 if (fd < 0)
808 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
809 else
810 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815
816 /* Autocommands may add lines to the file, need to check if it is empty */
817 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
818
819 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
820 {
821 /*
822 * Show the user that we are busy reading the input. Sometimes this
823 * may take a while. When reading from stdin another program may
824 * still be running, don't move the cursor to the last line, unless
825 * always using the GUI.
826 */
827 if (read_stdin)
828 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100829 if (!is_not_a_term())
830 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000831#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100832 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100835 /* Also write a message in the GUI window, if there is one. */
836 if (gui.in_use && !gui.dying && !gui.starting)
837 {
838 p = (char_u *)_("Reading from stdin...");
839 gui_write(p, (int)STRLEN(p));
840 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000841#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843 }
844 else if (!read_buffer)
845 filemess(curbuf, sfname, (char_u *)"", 0);
846 }
847
848 msg_scroll = FALSE; /* overwrite the file message */
849
850 /*
851 * Set linecnt now, before the "retry" caused by a wrong guess for
852 * fileformat, and after the autocommands, which may change them.
853 */
854 linecnt = curbuf->b_ml.ml_line_count;
855
856#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000857 /* "++bad=" argument. */
858 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000859 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000860 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000861 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000862 curbuf->b_bad_char = eap->bad_char;
863 }
864 else
865 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000866
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000868 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869 */
870 if (eap != NULL && eap->force_enc != 0)
871 {
872 fenc = enc_canonize(eap->cmd + eap->force_enc);
873 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000874 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875 }
876 else if (curbuf->b_p_bin)
877 {
878 fenc = (char_u *)""; /* binary: don't convert */
879 fenc_alloced = FALSE;
880 }
881 else if (curbuf->b_help)
882 {
883 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000884 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885
886 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
887 * fails it must be latin1.
888 * Always do this when 'encoding' is "utf-8". Otherwise only do
889 * this when needed to avoid [converted] remarks all the time.
890 * It is needed when the first line contains non-ASCII characters.
891 * That is only in *.??x files. */
892 fenc = (char_u *)"latin1";
893 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000894 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000896 fc = fname[STRLEN(fname) - 1];
897 if (TOLOWER_ASC(fc) == 'x')
898 {
899 /* Read the first line (and a bit more). Immediately rewind to
900 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100901 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200902 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000903 for (p = firstline; p < firstline + len; ++p)
904 if (*p >= 0x80)
905 {
906 c = TRUE;
907 break;
908 }
909 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910 }
911
912 if (c)
913 {
914 fenc_next = fenc;
915 fenc = (char_u *)"utf-8";
916
917 /* When the file is utf-8 but a character doesn't fit in
918 * 'encoding' don't retry. In help text editing utf-8 bytes
919 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000920 if (!enc_utf8)
921 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 }
923 fenc_alloced = FALSE;
924 }
925 else if (*p_fencs == NUL)
926 {
927 fenc = curbuf->b_p_fenc; /* use format from buffer */
928 fenc_alloced = FALSE;
929 }
930 else
931 {
932 fenc_next = p_fencs; /* try items in 'fileencodings' */
933 fenc = next_fenc(&fenc_next);
934 fenc_alloced = TRUE;
935 }
936#endif
937
938 /*
939 * Jump back here to retry reading the file in different ways.
940 * Reasons to retry:
941 * - encoding conversion failed: try another one from "fenc_next"
942 * - BOM detected and fenc was set, need to setup conversion
943 * - "fileformat" check failed: try another
944 *
945 * Variables set for special retry actions:
946 * "file_rewind" Rewind the file to start reading it again.
947 * "advance_fenc" Advance "fenc" using "fenc_next".
948 * "skip_read" Re-use already read bytes (BOM detected).
949 * "did_iconv" iconv() conversion failed, try 'charconvert'.
950 * "keep_fileformat" Don't reset "fileformat".
951 *
952 * Other status indicators:
953 * "tmpname" When != NULL did conversion with 'charconvert'.
954 * Output file has to be deleted afterwards.
955 * "iconv_fd" When != -1 did conversion with iconv().
956 */
957retry:
958
959 if (file_rewind)
960 {
961 if (read_buffer)
962 {
963 read_buf_lnum = 1;
964 read_buf_col = 0;
965 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200966 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 {
968 /* Can't rewind the file, give up. */
969 error = TRUE;
970 goto failed;
971 }
972 /* Delete the previously read lines. */
973 while (lnum > from)
974 ml_delete(lnum--, FALSE);
975 file_rewind = FALSE;
976#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000977 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000978 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000980 curbuf->b_start_bomb = FALSE;
981 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000982 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983#endif
984 }
985
986 /*
987 * When retrying with another "fenc" and the first time "fileformat"
988 * will be reset.
989 */
990 if (keep_fileformat)
991 keep_fileformat = FALSE;
992 else
993 {
994 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000995 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000997 try_unix = try_dos = try_mac = FALSE;
998 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 else if (curbuf->b_p_bin)
1000 fileformat = EOL_UNIX; /* binary: use Unix format */
1001 else if (*p_ffs == NUL)
1002 fileformat = get_fileformat(curbuf);/* use format from buffer */
1003 else
1004 fileformat = EOL_UNKNOWN; /* detect from file */
1005 }
1006
1007#ifdef FEAT_MBYTE
1008# ifdef USE_ICONV
1009 if (iconv_fd != (iconv_t)-1)
1010 {
1011 /* aborted conversion with iconv(), close the descriptor */
1012 iconv_close(iconv_fd);
1013 iconv_fd = (iconv_t)-1;
1014 }
1015# endif
1016
1017 if (advance_fenc)
1018 {
1019 /*
1020 * Try the next entry in 'fileencodings'.
1021 */
1022 advance_fenc = FALSE;
1023
1024 if (eap != NULL && eap->force_enc != 0)
1025 {
1026 /* Conversion given with "++cc=" wasn't possible, read
1027 * without conversion. */
1028 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001029 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 if (fenc_alloced)
1031 vim_free(fenc);
1032 fenc = (char_u *)"";
1033 fenc_alloced = FALSE;
1034 }
1035 else
1036 {
1037 if (fenc_alloced)
1038 vim_free(fenc);
1039 if (fenc_next != NULL)
1040 {
1041 fenc = next_fenc(&fenc_next);
1042 fenc_alloced = (fenc_next != NULL);
1043 }
1044 else
1045 {
1046 fenc = (char_u *)"";
1047 fenc_alloced = FALSE;
1048 }
1049 }
1050 if (tmpname != NULL)
1051 {
1052 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001053 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054 }
1055 }
1056
1057 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001058 * Conversion may be required when the encoding of the file is different
1059 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 */
1061 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001062 converted = need_conversion(fenc);
1063 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 {
1065
1066 /* "ucs-bom" means we need to check the first bytes of the file
1067 * for a BOM. */
1068 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1069 fio_flags = FIO_UCSBOM;
1070
1071 /*
1072 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1073 * done. This is handled below after read(). Prepare the
1074 * fio_flags to avoid having to parse the string each time.
1075 * Also check for Unicode to Latin1 conversion, because iconv()
1076 * appears not to handle this correctly. This works just like
1077 * conversion to UTF-8 except how the resulting character is put in
1078 * the buffer.
1079 */
1080 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1081 fio_flags = get_fio_flags(fenc);
1082
1083# ifdef WIN3264
1084 /*
1085 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1086 * is handled with MultiByteToWideChar().
1087 */
1088 if (fio_flags == 0)
1089 fio_flags = get_win_fio_flags(fenc);
1090# endif
1091
Bram Moolenaard0573012017-10-28 21:11:06 +02001092# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1094 if (fio_flags == 0)
1095 fio_flags = get_mac_fio_flags(fenc);
1096# endif
1097
1098# ifdef USE_ICONV
1099 /*
1100 * Try using iconv() if we can't convert internally.
1101 */
1102 if (fio_flags == 0
1103# ifdef FEAT_EVAL
1104 && !did_iconv
1105# endif
1106 )
1107 iconv_fd = (iconv_t)my_iconv_open(
1108 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1109# endif
1110
1111# ifdef FEAT_EVAL
1112 /*
1113 * Use the 'charconvert' expression when conversion is required
1114 * and we can't do it internally or with iconv().
1115 */
1116 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001117 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118# ifdef USE_ICONV
1119 && iconv_fd == (iconv_t)-1
1120# endif
1121 )
1122 {
1123# ifdef USE_ICONV
1124 did_iconv = FALSE;
1125# endif
1126 /* Skip conversion when it's already done (retry for wrong
1127 * "fileformat"). */
1128 if (tmpname == NULL)
1129 {
1130 tmpname = readfile_charconvert(fname, fenc, &fd);
1131 if (tmpname == NULL)
1132 {
1133 /* Conversion failed. Try another one. */
1134 advance_fenc = TRUE;
1135 if (fd < 0)
1136 {
1137 /* Re-opening the original file failed! */
1138 EMSG(_("E202: Conversion made file unreadable!"));
1139 error = TRUE;
1140 goto failed;
1141 }
1142 goto retry;
1143 }
1144 }
1145 }
1146 else
1147# endif
1148 {
1149 if (fio_flags == 0
1150# ifdef USE_ICONV
1151 && iconv_fd == (iconv_t)-1
1152# endif
1153 )
1154 {
1155 /* Conversion wanted but we can't.
1156 * Try the next conversion in 'fileencodings' */
1157 advance_fenc = TRUE;
1158 goto retry;
1159 }
1160 }
1161 }
1162
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001163 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001165 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001166 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167#endif
1168
1169 if (!skip_read)
1170 {
1171 linerest = 0;
1172 filesize = 0;
1173 skip_count = lines_to_skip;
1174 read_count = lines_to_read;
1175#ifdef FEAT_MBYTE
1176 conv_restlen = 0;
1177#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001178#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001179 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1180 && curbuf->b_ffname != NULL
1181 && curbuf->b_p_udf
1182 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001183 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001184 && !read_stdin
1185 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001186 if (read_undo_file)
1187 sha256_start(&sha_ctx);
1188#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001189#ifdef FEAT_CRYPT
1190 if (curbuf->b_cryptstate != NULL)
1191 {
1192 /* Need to free the state, but keep the key, don't want to ask for
1193 * it again. */
1194 crypt_free_state(curbuf->b_cryptstate);
1195 curbuf->b_cryptstate = NULL;
1196 }
1197#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 }
1199
1200 while (!error && !got_int)
1201 {
1202 /*
1203 * We allocate as much space for the file as we can get, plus
1204 * space for the old line plus room for one terminating NUL.
1205 * The amount is limited by the fact that read() only can read
1206 * upto max_unsigned characters (and other things).
1207 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001208 if (!skip_read)
1209 {
1210#if VIM_SIZEOF_INT > 2
1211# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
1212 size = SSIZE_MAX; /* use max I/O size, 52K */
1213# else
1214 /* Use buffer >= 64K. Add linerest to double the size if the
1215 * line gets very long, to avoid a lot of copying. But don't
1216 * read more than 1 Mbyte at a time, so we can be interrupted.
1217 */
1218 size = 0x10000L + linerest;
1219 if (size > 0x100000L)
1220 size = 0x100000L;
1221# endif
1222#else
1223 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1224#endif
1225 }
1226
1227 /* Protect against the argument of lalloc() going negative. */
1228 if (
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001229#if VIM_SIZEOF_INT <= 2
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001230 linerest >= 0x7ff0
1231#else
1232 size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL
1233#endif
1234 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235 {
1236 ++split;
1237 *ptr = NL; /* split line by inserting a NL */
1238 size = 1;
1239 }
1240 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241 {
1242 if (!skip_read)
1243 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001244 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 {
1246 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1247 FALSE)) != NULL)
1248 break;
1249 }
1250 if (new_buffer == NULL)
1251 {
1252 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1253 error = TRUE;
1254 break;
1255 }
1256 if (linerest) /* copy characters from the previous buffer */
1257 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1258 vim_free(buffer);
1259 buffer = new_buffer;
1260 ptr = buffer + linerest;
1261 line_start = buffer;
1262
1263#ifdef FEAT_MBYTE
1264 /* May need room to translate into.
1265 * For iconv() we don't really know the required space, use a
1266 * factor ICONV_MULT.
1267 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1268 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1269 * become up to 4 bytes, size must be multiple of 2
1270 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1271 * multiple of 2
1272 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1273 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001274 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275# ifdef USE_ICONV
1276 if (iconv_fd != (iconv_t)-1)
1277 size = size / ICONV_MULT;
1278 else
1279# endif
1280 if (fio_flags & FIO_LATIN1)
1281 size = size / 2;
1282 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1283 size = (size * 2 / 3) & ~1;
1284 else if (fio_flags & FIO_UCS4)
1285 size = (size * 2 / 3) & ~3;
1286 else if (fio_flags == FIO_UCSBOM)
1287 size = size / ICONV_MULT; /* worst case */
1288# ifdef WIN3264
1289 else if (fio_flags & FIO_CODEPAGE)
1290 size = size / ICONV_MULT; /* also worst case */
1291# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001292# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293 else if (fio_flags & FIO_MACROMAN)
1294 size = size / ICONV_MULT; /* also worst case */
1295# endif
1296#endif
1297
1298#ifdef FEAT_MBYTE
1299 if (conv_restlen > 0)
1300 {
1301 /* Insert unconverted bytes from previous line. */
1302 mch_memmove(ptr, conv_rest, conv_restlen);
1303 ptr += conv_restlen;
1304 size -= conv_restlen;
1305 }
1306#endif
1307
1308 if (read_buffer)
1309 {
1310 /*
1311 * Read bytes from curbuf. Used for converting text read
1312 * from stdin.
1313 */
1314 if (read_buf_lnum > from)
1315 size = 0;
1316 else
1317 {
1318 int n, ni;
1319 long tlen;
1320
1321 tlen = 0;
1322 for (;;)
1323 {
1324 p = ml_get(read_buf_lnum) + read_buf_col;
1325 n = (int)STRLEN(p);
1326 if ((int)tlen + n + 1 > size)
1327 {
1328 /* Filled up to "size", append partial line.
1329 * Change NL to NUL to reverse the effect done
1330 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001331 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 for (ni = 0; ni < n; ++ni)
1333 {
1334 if (p[ni] == NL)
1335 ptr[tlen++] = NUL;
1336 else
1337 ptr[tlen++] = p[ni];
1338 }
1339 read_buf_col += n;
1340 break;
1341 }
1342 else
1343 {
1344 /* Append whole line and new-line. Change NL
1345 * to NUL to reverse the effect done below. */
1346 for (ni = 0; ni < n; ++ni)
1347 {
1348 if (p[ni] == NL)
1349 ptr[tlen++] = NUL;
1350 else
1351 ptr[tlen++] = p[ni];
1352 }
1353 ptr[tlen++] = NL;
1354 read_buf_col = 0;
1355 if (++read_buf_lnum > from)
1356 {
1357 /* When the last line didn't have an
1358 * end-of-line don't add it now either. */
1359 if (!curbuf->b_p_eol)
1360 --tlen;
1361 size = tlen;
1362 break;
1363 }
1364 }
1365 }
1366 }
1367 }
1368 else
1369 {
1370 /*
1371 * Read bytes from the file.
1372 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001373 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374 }
1375
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001376#ifdef FEAT_CRYPT
1377 /*
1378 * At start of file: Check for magic number of encryption.
1379 */
1380 if (filesize == 0 && size > 0)
1381 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1382 &filesize, newfile, sfname,
1383 &did_ask_for_key);
1384 /*
1385 * Decrypt the read bytes. This is done before checking for
1386 * EOF because the crypt layer may be buffering.
1387 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001388 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1389 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001390 {
1391 if (crypt_works_inplace(curbuf->b_cryptstate))
1392 {
1393 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1394 }
1395 else
1396 {
1397 char_u *newptr = NULL;
1398 int decrypted_size;
1399
1400 decrypted_size = crypt_decode_alloc(
1401 curbuf->b_cryptstate, ptr, size, &newptr);
1402
1403 /* If the crypt layer is buffering, not producing
1404 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001405 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001406 continue;
1407
1408 if (linerest == 0)
1409 {
1410 /* Simple case: reuse returned buffer (may be
1411 * NULL, checked later). */
1412 new_buffer = newptr;
1413 }
1414 else
1415 {
1416 long_u new_size;
1417
1418 /* Need new buffer to add bytes carried over. */
1419 new_size = (long_u)(decrypted_size + linerest + 1);
1420 new_buffer = lalloc(new_size, FALSE);
1421 if (new_buffer == NULL)
1422 {
1423 do_outofmem_msg(new_size);
1424 error = TRUE;
1425 break;
1426 }
1427
1428 mch_memmove(new_buffer, buffer, linerest);
1429 if (newptr != NULL)
1430 mch_memmove(new_buffer + linerest, newptr,
1431 decrypted_size);
1432 }
1433
1434 if (new_buffer != NULL)
1435 {
1436 vim_free(buffer);
1437 buffer = new_buffer;
1438 new_buffer = NULL;
1439 line_start = buffer;
1440 ptr = buffer + linerest;
1441 }
1442 size = decrypted_size;
1443 }
1444 }
1445#endif
1446
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (size <= 0)
1448 {
1449 if (size < 0) /* read error */
1450 error = TRUE;
1451#ifdef FEAT_MBYTE
1452 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001453 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001454 /*
1455 * Reached end-of-file but some trailing bytes could
1456 * not be converted. Truncated file?
1457 */
1458
1459 /* When we did a conversion report an error. */
1460 if (fio_flags != 0
1461# ifdef USE_ICONV
1462 || iconv_fd != (iconv_t)-1
1463# endif
1464 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001465 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001466 if (can_retry)
1467 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001468 if (conv_error == 0)
1469 conv_error = curbuf->b_ml.ml_line_count
1470 - linecnt + 1;
1471 }
1472 /* Remember the first linenr with an illegal byte */
1473 else if (illegal_byte == 0)
1474 illegal_byte = curbuf->b_ml.ml_line_count
1475 - linecnt + 1;
1476 if (bad_char_behavior == BAD_DROP)
1477 {
1478 *(ptr - conv_restlen) = NUL;
1479 conv_restlen = 0;
1480 }
1481 else
1482 {
1483 /* Replace the trailing bytes with the replacement
1484 * character if we were converting; if we weren't,
1485 * leave the UTF8 checking code to do it, as it
1486 * works slightly differently. */
1487 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1488# ifdef USE_ICONV
1489 || iconv_fd != (iconv_t)-1
1490# endif
1491 ))
1492 {
1493 while (conv_restlen > 0)
1494 {
1495 *(--ptr) = bad_char_behavior;
1496 --conv_restlen;
1497 }
1498 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001499 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001500# ifdef USE_ICONV
1501 if (iconv_fd != (iconv_t)-1)
1502 {
1503 iconv_close(iconv_fd);
1504 iconv_fd = (iconv_t)-1;
1505 }
1506# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001507 }
1508 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509#endif
1510 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 }
1512 skip_read = FALSE;
1513
1514#ifdef FEAT_MBYTE
1515 /*
1516 * At start of file (or after crypt magic number): Check for BOM.
1517 * Also check for a BOM for other Unicode encodings, but not after
1518 * converting with 'charconvert' or when a BOM has already been
1519 * found.
1520 */
1521 if ((filesize == 0
1522# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001523 || (cryptkey != NULL
1524 && filesize == crypt_get_header_len(
1525 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526# endif
1527 )
1528 && (fio_flags == FIO_UCSBOM
1529 || (!curbuf->b_p_bomb
1530 && tmpname == NULL
1531 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1532 {
1533 char_u *ccname;
1534 int blen;
1535
1536 /* no BOM detection in a short file or in binary mode */
1537 if (size < 2 || curbuf->b_p_bin)
1538 ccname = NULL;
1539 else
1540 ccname = check_for_bom(ptr, size, &blen,
1541 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1542 if (ccname != NULL)
1543 {
1544 /* Remove BOM from the text */
1545 filesize += blen;
1546 size -= blen;
1547 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001548 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001549 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001551 curbuf->b_start_bomb = TRUE;
1552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 }
1554
1555 if (fio_flags == FIO_UCSBOM)
1556 {
1557 if (ccname == NULL)
1558 {
1559 /* No BOM detected: retry with next encoding. */
1560 advance_fenc = TRUE;
1561 }
1562 else
1563 {
1564 /* BOM detected: set "fenc" and jump back */
1565 if (fenc_alloced)
1566 vim_free(fenc);
1567 fenc = ccname;
1568 fenc_alloced = FALSE;
1569 }
1570 /* retry reading without getting new bytes or rewinding */
1571 skip_read = TRUE;
1572 goto retry;
1573 }
1574 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001575
1576 /* Include not converted bytes. */
1577 ptr -= conv_restlen;
1578 size += conv_restlen;
1579 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580#endif
1581 /*
1582 * Break here for a read error or end-of-file.
1583 */
1584 if (size <= 0)
1585 break;
1586
1587#ifdef FEAT_MBYTE
1588
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589# ifdef USE_ICONV
1590 if (iconv_fd != (iconv_t)-1)
1591 {
1592 /*
1593 * Attempt conversion of the read bytes to 'encoding' using
1594 * iconv().
1595 */
1596 const char *fromp;
1597 char *top;
1598 size_t from_size;
1599 size_t to_size;
1600
1601 fromp = (char *)ptr;
1602 from_size = size;
1603 ptr += size;
1604 top = (char *)ptr;
1605 to_size = real_size - size;
1606
1607 /*
1608 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001609 * another conversion. Except for when there is no
1610 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001612 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1613 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1615 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001616 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001617 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001618 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001619 if (conv_error == 0)
1620 conv_error = readfile_linenr(linecnt,
1621 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001622
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001623 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001624 ++fromp;
1625 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 if (bad_char_behavior == BAD_KEEP)
1627 {
1628 *top++ = *(fromp - 1);
1629 --to_size;
1630 }
1631 else if (bad_char_behavior != BAD_DROP)
1632 {
1633 *top++ = bad_char_behavior;
1634 --to_size;
1635 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001636 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637
1638 if (from_size > 0)
1639 {
1640 /* Some remaining characters, keep them for the next
1641 * round. */
1642 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1643 conv_restlen = (int)from_size;
1644 }
1645
1646 /* move the linerest to before the converted characters */
1647 line_start = ptr - linerest;
1648 mch_memmove(line_start, buffer, (size_t)linerest);
1649 size = (long)((char_u *)top - ptr);
1650 }
1651# endif
1652
1653# ifdef WIN3264
1654 if (fio_flags & FIO_CODEPAGE)
1655 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001656 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001657 WCHAR ucs2buf[3];
1658 int ucs2len;
1659 int codepage = FIO_GET_CP(fio_flags);
1660 int bytelen;
1661 int found_bad;
1662 char replstr[2];
1663
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 /*
1665 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001666 * a codepage, using standard MS-Windows functions. This
1667 * requires two steps:
1668 * 1. convert from 'fileencoding' to ucs-2
1669 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001671 * Because there may be illegal bytes AND an incomplete byte
1672 * sequence at the end, we may have to do the conversion one
1673 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001676 /* Replacement string for WideCharToMultiByte(). */
1677 if (bad_char_behavior > 0)
1678 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001680 replstr[0] = '?';
1681 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682
1683 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001684 * Move the bytes to the end of the buffer, so that we have
1685 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001687 src = ptr + real_size - size;
1688 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001690 /*
1691 * Do the conversion.
1692 */
1693 dst = ptr;
1694 size = size;
1695 while (size > 0)
1696 {
1697 found_bad = FALSE;
1698
1699# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1700 if (codepage == CP_UTF8)
1701 {
1702 /* Handle CP_UTF8 input ourselves to be able to handle
1703 * trailing bytes properly.
1704 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001705 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001706 if (bytelen > size)
1707 {
1708 /* Only got some bytes of a character. Normally
1709 * it's put in "conv_rest", but if it's too long
1710 * deal with it as if they were illegal bytes. */
1711 if (bytelen <= CONV_RESTLEN)
1712 break;
1713
1714 /* weird overlong byte sequence */
1715 bytelen = size;
1716 found_bad = TRUE;
1717 }
1718 else
1719 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001720 int u8c = utf_ptr2char(src);
1721
Bram Moolenaar86e01082005-12-29 22:45:34 +00001722 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001723 found_bad = TRUE;
1724 ucs2buf[0] = u8c;
1725 ucs2len = 1;
1726 }
1727 }
1728 else
1729# endif
1730 {
1731 /* We don't know how long the byte sequence is, try
1732 * from one to three bytes. */
1733 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1734 ++bytelen)
1735 {
1736 ucs2len = MultiByteToWideChar(codepage,
1737 MB_ERR_INVALID_CHARS,
1738 (LPCSTR)src, bytelen,
1739 ucs2buf, 3);
1740 if (ucs2len > 0)
1741 break;
1742 }
1743 if (ucs2len == 0)
1744 {
1745 /* If we have only one byte then it's probably an
1746 * incomplete byte sequence. Otherwise discard
1747 * one byte as a bad character. */
1748 if (size == 1)
1749 break;
1750 found_bad = TRUE;
1751 bytelen = 1;
1752 }
1753 }
1754
1755 if (!found_bad)
1756 {
1757 int i;
1758
1759 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1760 if (enc_utf8)
1761 {
1762 /* From UCS-2 to UTF-8. Cannot fail. */
1763 for (i = 0; i < ucs2len; ++i)
1764 dst += utf_char2bytes(ucs2buf[i], dst);
1765 }
1766 else
1767 {
1768 BOOL bad = FALSE;
1769 int dstlen;
1770
1771 /* From UCS-2 to "enc_codepage". If the
1772 * conversion uses the default character "?",
1773 * the data doesn't fit in this encoding. */
1774 dstlen = WideCharToMultiByte(enc_codepage, 0,
1775 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001776 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001777 replstr, &bad);
1778 if (bad)
1779 found_bad = TRUE;
1780 else
1781 dst += dstlen;
1782 }
1783 }
1784
1785 if (found_bad)
1786 {
1787 /* Deal with bytes we can't convert. */
1788 if (can_retry)
1789 goto rewind_retry;
1790 if (conv_error == 0)
1791 conv_error = readfile_linenr(linecnt, ptr, dst);
1792 if (bad_char_behavior != BAD_DROP)
1793 {
1794 if (bad_char_behavior == BAD_KEEP)
1795 {
1796 mch_memmove(dst, src, bytelen);
1797 dst += bytelen;
1798 }
1799 else
1800 *dst++ = bad_char_behavior;
1801 }
1802 }
1803
1804 src += bytelen;
1805 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001807
1808 if (size > 0)
1809 {
1810 /* An incomplete byte sequence remaining. */
1811 mch_memmove(conv_rest, src, size);
1812 conv_restlen = size;
1813 }
1814
1815 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001816 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 }
1818 else
1819# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001820# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 if (fio_flags & FIO_MACROMAN)
1822 {
1823 /*
1824 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001825 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001827 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 }
1830 else
1831# endif
1832 if (fio_flags != 0)
1833 {
1834 int u8c;
1835 char_u *dest;
1836 char_u *tail = NULL;
1837
1838 /*
1839 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1840 * "enc_utf8" not set: Convert Unicode to Latin1.
1841 * Go from end to start through the buffer, because the number
1842 * of bytes may increase.
1843 * "dest" points to after where the UTF-8 bytes go, "p" points
1844 * to after the next character to convert.
1845 */
1846 dest = ptr + real_size;
1847 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1848 {
1849 p = ptr + size;
1850 if (fio_flags == FIO_UTF8)
1851 {
1852 /* Check for a trailing incomplete UTF-8 sequence */
1853 tail = ptr + size - 1;
1854 while (tail > ptr && (*tail & 0xc0) == 0x80)
1855 --tail;
1856 if (tail + utf_byte2len(*tail) <= ptr + size)
1857 tail = NULL;
1858 else
1859 p = tail;
1860 }
1861 }
1862 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1863 {
1864 /* Check for a trailing byte */
1865 p = ptr + (size & ~1);
1866 if (size & 1)
1867 tail = p;
1868 if ((fio_flags & FIO_UTF16) && p > ptr)
1869 {
1870 /* Check for a trailing leading word */
1871 if (fio_flags & FIO_ENDIAN_L)
1872 {
1873 u8c = (*--p << 8);
1874 u8c += *--p;
1875 }
1876 else
1877 {
1878 u8c = *--p;
1879 u8c += (*--p << 8);
1880 }
1881 if (u8c >= 0xd800 && u8c <= 0xdbff)
1882 tail = p;
1883 else
1884 p += 2;
1885 }
1886 }
1887 else /* FIO_UCS4 */
1888 {
1889 /* Check for trailing 1, 2 or 3 bytes */
1890 p = ptr + (size & ~3);
1891 if (size & 3)
1892 tail = p;
1893 }
1894
1895 /* If there is a trailing incomplete sequence move it to
1896 * conv_rest[]. */
1897 if (tail != NULL)
1898 {
1899 conv_restlen = (int)((ptr + size) - tail);
1900 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1901 size -= conv_restlen;
1902 }
1903
1904
1905 while (p > ptr)
1906 {
1907 if (fio_flags & FIO_LATIN1)
1908 u8c = *--p;
1909 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1910 {
1911 if (fio_flags & FIO_ENDIAN_L)
1912 {
1913 u8c = (*--p << 8);
1914 u8c += *--p;
1915 }
1916 else
1917 {
1918 u8c = *--p;
1919 u8c += (*--p << 8);
1920 }
1921 if ((fio_flags & FIO_UTF16)
1922 && u8c >= 0xdc00 && u8c <= 0xdfff)
1923 {
1924 int u16c;
1925
1926 if (p == ptr)
1927 {
1928 /* Missing leading word. */
1929 if (can_retry)
1930 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001931 if (conv_error == 0)
1932 conv_error = readfile_linenr(linecnt,
1933 ptr, p);
1934 if (bad_char_behavior == BAD_DROP)
1935 continue;
1936 if (bad_char_behavior != BAD_KEEP)
1937 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939
1940 /* found second word of double-word, get the first
1941 * word and compute the resulting character */
1942 if (fio_flags & FIO_ENDIAN_L)
1943 {
1944 u16c = (*--p << 8);
1945 u16c += *--p;
1946 }
1947 else
1948 {
1949 u16c = *--p;
1950 u16c += (*--p << 8);
1951 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001952 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1953 + (u8c & 0x3ff);
1954
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 /* Check if the word is indeed a leading word. */
1956 if (u16c < 0xd800 || u16c > 0xdbff)
1957 {
1958 if (can_retry)
1959 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001960 if (conv_error == 0)
1961 conv_error = readfile_linenr(linecnt,
1962 ptr, p);
1963 if (bad_char_behavior == BAD_DROP)
1964 continue;
1965 if (bad_char_behavior != BAD_KEEP)
1966 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 }
1969 }
1970 else if (fio_flags & FIO_UCS4)
1971 {
1972 if (fio_flags & FIO_ENDIAN_L)
1973 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001974 u8c = (unsigned)*--p << 24;
1975 u8c += (unsigned)*--p << 16;
1976 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 u8c += *--p;
1978 }
1979 else /* big endian */
1980 {
1981 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001982 u8c += (unsigned)*--p << 8;
1983 u8c += (unsigned)*--p << 16;
1984 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
1986 }
1987 else /* UTF-8 */
1988 {
1989 if (*--p < 0x80)
1990 u8c = *p;
1991 else
1992 {
1993 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001994 p -= len;
1995 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 if (len == 0)
1997 {
1998 /* Not a valid UTF-8 character, retry with
1999 * another fenc when possible, otherwise just
2000 * report the error. */
2001 if (can_retry)
2002 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002003 if (conv_error == 0)
2004 conv_error = readfile_linenr(linecnt,
2005 ptr, p);
2006 if (bad_char_behavior == BAD_DROP)
2007 continue;
2008 if (bad_char_behavior != BAD_KEEP)
2009 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011 }
2012 }
2013 if (enc_utf8) /* produce UTF-8 */
2014 {
2015 dest -= utf_char2len(u8c);
2016 (void)utf_char2bytes(u8c, dest);
2017 }
2018 else /* produce Latin1 */
2019 {
2020 --dest;
2021 if (u8c >= 0x100)
2022 {
2023 /* character doesn't fit in latin1, retry with
2024 * another fenc when possible, otherwise just
2025 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002026 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028 if (conv_error == 0)
2029 conv_error = readfile_linenr(linecnt, ptr, p);
2030 if (bad_char_behavior == BAD_DROP)
2031 ++dest;
2032 else if (bad_char_behavior == BAD_KEEP)
2033 *dest = u8c;
2034 else if (eap != NULL && eap->bad_char != 0)
2035 *dest = bad_char_behavior;
2036 else
2037 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038 }
2039 else
2040 *dest = u8c;
2041 }
2042 }
2043
2044 /* move the linerest to before the converted characters */
2045 line_start = dest - linerest;
2046 mch_memmove(line_start, buffer, (size_t)linerest);
2047 size = (long)((ptr + real_size) - dest);
2048 ptr = dest;
2049 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002050 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002052 int incomplete_tail = FALSE;
2053
2054 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2055 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002057 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002058 int l;
2059
2060 if (todo <= 0)
2061 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 if (*p >= 0x80)
2063 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 /* A length of 1 means it's an illegal byte. Accept
2065 * an incomplete character at the end though, the next
2066 * read() will get the next bytes, we'll check it
2067 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002069 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002071 /* Avoid retrying with a different encoding when
2072 * a truncated file is more likely, or attempting
2073 * to read the rest of an incomplete sequence when
2074 * we have already done so. */
2075 if (p > ptr || filesize > 0)
2076 incomplete_tail = TRUE;
2077 /* Incomplete byte sequence, move it to conv_rest[]
2078 * and try to read the rest of it, unless we've
2079 * already done so. */
2080 if (p > ptr)
2081 {
2082 conv_restlen = todo;
2083 mch_memmove(conv_rest, p, conv_restlen);
2084 size -= conv_restlen;
2085 break;
2086 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002088 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002089 {
2090 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002091 * do that, unless at EOF where a truncated
2092 * file is more likely than a conversion error. */
2093 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002094 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002095# ifdef USE_ICONV
2096 /* When we did a conversion report an error. */
2097 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2098 conv_error = readfile_linenr(linecnt, ptr, p);
2099# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002100 /* Remember the first linenr with an illegal byte */
2101 if (conv_error == 0 && illegal_byte == 0)
2102 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002103
2104 /* Drop, keep or replace the bad byte. */
2105 if (bad_char_behavior == BAD_DROP)
2106 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002107 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002108 --p;
2109 --size;
2110 }
2111 else if (bad_char_behavior != BAD_KEEP)
2112 *p = bad_char_behavior;
2113 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002114 else
2115 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116 }
2117 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002118 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 {
2120 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002122 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002124 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2125 /* iconv() failed, try 'charconvert' */
2126 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 else
2128# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002129 /* use next item from 'fileencodings' */
2130 advance_fenc = TRUE;
2131 file_rewind = TRUE;
2132 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 }
2134 }
2135#endif
2136
2137 /* count the number of characters (after conversion!) */
2138 filesize += size;
2139
2140 /*
2141 * when reading the first part of a file: guess EOL type
2142 */
2143 if (fileformat == EOL_UNKNOWN)
2144 {
2145 /* First try finding a NL, for Dos and Unix */
2146 if (try_dos || try_unix)
2147 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002148 /* Reset the carriage return counter. */
2149 if (try_mac)
2150 try_mac = 1;
2151
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 for (p = ptr; p < ptr + size; ++p)
2153 {
2154 if (*p == NL)
2155 {
2156 if (!try_unix
2157 || (try_dos && p > ptr && p[-1] == CAR))
2158 fileformat = EOL_DOS;
2159 else
2160 fileformat = EOL_UNIX;
2161 break;
2162 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002163 else if (*p == CAR && try_mac)
2164 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002165 }
2166
2167 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2168 if (fileformat == EOL_UNIX && try_mac)
2169 {
2170 /* Need to reset the counters when retrying fenc. */
2171 try_mac = 1;
2172 try_unix = 1;
2173 for (; p >= ptr && *p != CAR; p--)
2174 ;
2175 if (p >= ptr)
2176 {
2177 for (p = ptr; p < ptr + size; ++p)
2178 {
2179 if (*p == NL)
2180 try_unix++;
2181 else if (*p == CAR)
2182 try_mac++;
2183 }
2184 if (try_mac > try_unix)
2185 fileformat = EOL_MAC;
2186 }
2187 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002188 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2189 /* Looking for CR but found no end-of-line markers at
2190 * all: use the default format. */
2191 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 }
2193
2194 /* No NL found: may use Mac format */
2195 if (fileformat == EOL_UNKNOWN && try_mac)
2196 fileformat = EOL_MAC;
2197
2198 /* Still nothing found? Use first format in 'ffs' */
2199 if (fileformat == EOL_UNKNOWN)
2200 fileformat = default_fileformat();
2201
2202 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002203 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 set_fileformat(fileformat, OPT_LOCAL);
2205 }
2206 }
2207
2208 /*
2209 * This loop is executed once for every character read.
2210 * Keep it fast!
2211 */
2212 if (fileformat == EOL_MAC)
2213 {
2214 --ptr;
2215 while (++ptr, --size >= 0)
2216 {
2217 /* catch most common case first */
2218 if ((c = *ptr) != NUL && c != CAR && c != NL)
2219 continue;
2220 if (c == NUL)
2221 *ptr = NL; /* NULs are replaced by newlines! */
2222 else if (c == NL)
2223 *ptr = CAR; /* NLs are replaced by CRs! */
2224 else
2225 {
2226 if (skip_count == 0)
2227 {
2228 *ptr = NUL; /* end of line */
2229 len = (colnr_T) (ptr - line_start + 1);
2230 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2231 {
2232 error = TRUE;
2233 break;
2234 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002235#ifdef FEAT_PERSISTENT_UNDO
2236 if (read_undo_file)
2237 sha256_update(&sha_ctx, line_start, len);
2238#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239 ++lnum;
2240 if (--read_count == 0)
2241 {
2242 error = TRUE; /* break loop */
2243 line_start = ptr; /* nothing left to write */
2244 break;
2245 }
2246 }
2247 else
2248 --skip_count;
2249 line_start = ptr + 1;
2250 }
2251 }
2252 }
2253 else
2254 {
2255 --ptr;
2256 while (++ptr, --size >= 0)
2257 {
2258 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2259 continue;
2260 if (c == NUL)
2261 *ptr = NL; /* NULs are replaced by newlines! */
2262 else
2263 {
2264 if (skip_count == 0)
2265 {
2266 *ptr = NUL; /* end of line */
2267 len = (colnr_T)(ptr - line_start + 1);
2268 if (fileformat == EOL_DOS)
2269 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002270 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002272 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 ptr[-1] = NUL;
2274 --len;
2275 }
2276 /*
2277 * Reading in Dos format, but no CR-LF found!
2278 * When 'fileformats' includes "unix", delete all
2279 * the lines read so far and start all over again.
2280 * Otherwise give an error message later.
2281 */
2282 else if (ff_error != EOL_DOS)
2283 {
2284 if ( try_unix
2285 && !read_stdin
2286 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002287 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2288 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 {
2290 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002291 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 set_fileformat(EOL_UNIX, OPT_LOCAL);
2293 file_rewind = TRUE;
2294 keep_fileformat = TRUE;
2295 goto retry;
2296 }
2297 ff_error = EOL_DOS;
2298 }
2299 }
2300 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2301 {
2302 error = TRUE;
2303 break;
2304 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002305#ifdef FEAT_PERSISTENT_UNDO
2306 if (read_undo_file)
2307 sha256_update(&sha_ctx, line_start, len);
2308#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309 ++lnum;
2310 if (--read_count == 0)
2311 {
2312 error = TRUE; /* break loop */
2313 line_start = ptr; /* nothing left to write */
2314 break;
2315 }
2316 }
2317 else
2318 --skip_count;
2319 line_start = ptr + 1;
2320 }
2321 }
2322 }
2323 linerest = (long)(ptr - line_start);
2324 ui_breakcheck();
2325 }
2326
2327failed:
2328 /* not an error, max. number of lines reached */
2329 if (error && read_count == 0)
2330 error = FALSE;
2331
2332 /*
2333 * If we get EOF in the middle of a line, note the fact and
2334 * complete the line ourselves.
2335 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2336 */
2337 if (!error
2338 && !got_int
2339 && linerest != 0
2340 && !(!curbuf->b_p_bin
2341 && fileformat == EOL_DOS
2342 && *line_start == Ctrl_Z
2343 && ptr == line_start + 1))
2344 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002345 /* remember for when writing */
2346 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 curbuf->b_p_eol = FALSE;
2348 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002349 len = (colnr_T)(ptr - line_start + 1);
2350 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 error = TRUE;
2352 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002353 {
2354#ifdef FEAT_PERSISTENT_UNDO
2355 if (read_undo_file)
2356 sha256_update(&sha_ctx, line_start, len);
2357#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 }
2361
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002362 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 save_file_ff(curbuf); /* remember the current file format */
2364
2365#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002366 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002367 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002368 crypt_free_state(curbuf->b_cryptstate);
2369 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002370 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002371 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2372 crypt_free_key(cryptkey);
2373 /* Don't set cryptkey to NULL, it's used below as a flag that
2374 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375#endif
2376
2377#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002378 /* If editing a new file: set 'fenc' for the current buffer.
2379 * Also for ":read ++edit file". */
2380 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002382 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 if (fenc_alloced)
2384 vim_free(fenc);
2385# ifdef USE_ICONV
2386 if (iconv_fd != (iconv_t)-1)
2387 {
2388 iconv_close(iconv_fd);
2389 iconv_fd = (iconv_t)-1;
2390 }
2391# endif
2392#endif
2393
2394 if (!read_buffer && !read_stdin)
2395 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002396#ifdef HAVE_FD_CLOEXEC
2397 else
2398 {
2399 int fdflags = fcntl(fd, F_GETFD);
2400 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002401 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002402 }
2403#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 vim_free(buffer);
2405
2406#ifdef HAVE_DUP
2407 if (read_stdin)
2408 {
2409 /* Use stderr for stdin, makes shell commands work. */
2410 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002411 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412 }
2413#endif
2414
2415#ifdef FEAT_MBYTE
2416 if (tmpname != NULL)
2417 {
2418 mch_remove(tmpname); /* delete converted file */
2419 vim_free(tmpname);
2420 }
2421#endif
2422 --no_wait_return; /* may wait for return now */
2423
2424 /*
2425 * In recovery mode everything but autocommands is skipped.
2426 */
2427 if (!recoverymode)
2428 {
2429 /* need to delete the last line, which comes from the empty buffer */
2430 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2431 {
2432#ifdef FEAT_NETBEANS_INTG
2433 netbeansFireChanges = 0;
2434#endif
2435 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2436#ifdef FEAT_NETBEANS_INTG
2437 netbeansFireChanges = 1;
2438#endif
2439 --linecnt;
2440 }
2441 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2442 if (filesize == 0)
2443 linecnt = 0;
2444 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002445 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002447#ifdef FEAT_DIFF
2448 /* After reading the text into the buffer the diff info needs to
2449 * be updated. */
2450 diff_invalidate(curbuf);
2451#endif
2452#ifdef FEAT_FOLDING
2453 /* All folds in the window are invalid now. Mark them for update
2454 * before triggering autocommands. */
2455 foldUpdateAll(curwin);
2456#endif
2457 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458 else if (linecnt) /* appended at least one line */
2459 appended_lines_mark(from, linecnt);
2460
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461#ifndef ALWAYS_USE_GUI
2462 /*
2463 * If we were reading from the same terminal as where messages go,
2464 * the screen will have been messed up.
2465 * Switch on raw mode now and clear the screen.
2466 */
2467 if (read_stdin)
2468 {
2469 settmode(TMODE_RAW); /* set to raw mode */
2470 starttermcap();
2471 screenclear();
2472 }
2473#endif
2474
2475 if (got_int)
2476 {
2477 if (!(flags & READ_DUMMY))
2478 {
2479 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2480 if (newfile)
2481 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2482 }
2483 msg_scroll = msg_save;
2484#ifdef FEAT_VIMINFO
2485 check_marks_read();
2486#endif
2487 return OK; /* an interrupt isn't really an error */
2488 }
2489
2490 if (!filtering && !(flags & READ_DUMMY))
2491 {
2492 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2493 c = FALSE;
2494
2495#ifdef UNIX
Bram Moolenaard569bb02018-08-11 13:57:20 +02002496 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 {
2498 STRCAT(IObuff, _("[fifo]"));
2499 c = TRUE;
2500 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002501 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 {
2503 STRCAT(IObuff, _("[socket]"));
2504 c = TRUE;
2505 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002506# ifdef OPEN_CHR_FILES
2507 if (S_ISCHR(perm)) /* or character special */
2508 {
2509 STRCAT(IObuff, _("[character special]"));
2510 c = TRUE;
2511 }
2512# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513#endif
2514 if (curbuf->b_p_ro)
2515 {
2516 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2517 c = TRUE;
2518 }
2519 if (read_no_eol_lnum)
2520 {
2521 msg_add_eol();
2522 c = TRUE;
2523 }
2524 if (ff_error == EOL_DOS)
2525 {
2526 STRCAT(IObuff, _("[CR missing]"));
2527 c = TRUE;
2528 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 if (split)
2530 {
2531 STRCAT(IObuff, _("[long lines split]"));
2532 c = TRUE;
2533 }
2534#ifdef FEAT_MBYTE
2535 if (notconverted)
2536 {
2537 STRCAT(IObuff, _("[NOT converted]"));
2538 c = TRUE;
2539 }
2540 else if (converted)
2541 {
2542 STRCAT(IObuff, _("[converted]"));
2543 c = TRUE;
2544 }
2545#endif
2546#ifdef FEAT_CRYPT
2547 if (cryptkey != NULL)
2548 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002549 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 c = TRUE;
2551 }
2552#endif
2553#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002554 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002556 sprintf((char *)IObuff + STRLEN(IObuff),
2557 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 c = TRUE;
2559 }
2560 else if (illegal_byte > 0)
2561 {
2562 sprintf((char *)IObuff + STRLEN(IObuff),
2563 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2564 c = TRUE;
2565 }
2566 else
2567#endif
2568 if (error)
2569 {
2570 STRCAT(IObuff, _("[READ ERRORS]"));
2571 c = TRUE;
2572 }
2573 if (msg_add_fileformat(fileformat))
2574 c = TRUE;
2575#ifdef FEAT_CRYPT
2576 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002577 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002578 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 else
2580#endif
2581 msg_add_lines(c, (long)linecnt, filesize);
2582
Bram Moolenaard23a8232018-02-10 18:45:26 +01002583 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 msg_scrolled_ign = TRUE;
2585#ifdef ALWAYS_USE_GUI
2586 /* Don't show the message when reading stdin, it would end up in a
2587 * message box (which might be shown when exiting!) */
2588 if (read_stdin || read_buffer)
2589 p = msg_may_trunc(FALSE, IObuff);
2590 else
2591#endif
2592 p = msg_trunc_attr(IObuff, FALSE, 0);
2593 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002594 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 /* Need to repeat the message after redrawing when:
2596 * - When reading from stdin (the screen will be cleared next).
2597 * - When restart_edit is set (otherwise there will be a delay
2598 * before redrawing).
2599 * - When the screen was scrolled but there is no wait-return
2600 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002601 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 msg_scrolled_ign = FALSE;
2603 }
2604
2605 /* with errors writing the file requires ":w!" */
2606 if (newfile && (error
2607#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002608 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002609 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610#endif
2611 ))
2612 curbuf->b_p_ro = TRUE;
2613
2614 u_clearline(); /* cannot use "U" command after adding lines */
2615
2616 /*
2617 * In Ex mode: cursor at last new line.
2618 * Otherwise: cursor at first new line.
2619 */
2620 if (exmode_active)
2621 curwin->w_cursor.lnum = from + linecnt;
2622 else
2623 curwin->w_cursor.lnum = from + 1;
2624 check_cursor_lnum();
2625 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2626
2627 /*
2628 * Set '[ and '] marks to the newly read lines.
2629 */
2630 curbuf->b_op_start.lnum = from + 1;
2631 curbuf->b_op_start.col = 0;
2632 curbuf->b_op_end.lnum = from + linecnt;
2633 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002634
2635#ifdef WIN32
2636 /*
2637 * Work around a weird problem: When a file has two links (only
2638 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002639 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002640 * It's correct again after reading the file, thus reset the timestamp
2641 * here.
2642 */
2643 if (newfile && !read_stdin && !read_buffer
2644 && mch_stat((char *)fname, &st) >= 0)
2645 {
2646 buf_store_time(curbuf, &st, fname);
2647 curbuf->b_mtime_read = curbuf->b_mtime;
2648 }
2649#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650 }
2651 msg_scroll = msg_save;
2652
2653#ifdef FEAT_VIMINFO
2654 /*
2655 * Get the marks before executing autocommands, so they can be used there.
2656 */
2657 check_marks_read();
2658#endif
2659
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002661 * We remember if the last line of the read didn't have
2662 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2663 * or writing the read again with 'binary' on. The latter is required
2664 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002666 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002668 /* When reloading a buffer put the cursor at the first line that is
2669 * different. */
2670 if (flags & READ_KEEP_UNDO)
2671 u_find_first_changed();
2672
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002673#ifdef FEAT_PERSISTENT_UNDO
2674 /*
2675 * When opening a new file locate undo info and read it.
2676 */
2677 if (read_undo_file)
2678 {
2679 char_u hash[UNDO_HASH_SIZE];
2680
2681 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002682 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002683 }
2684#endif
2685
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002686 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 {
2688 int m = msg_scroll;
2689 int n = msg_scrolled;
2690
2691 /* Save the fileformat now, otherwise the buffer will be considered
2692 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002693 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 save_file_ff(curbuf);
2695
2696 /*
2697 * The output from the autocommands should not overwrite anything and
2698 * should not be overwritten: Set msg_scroll, restore its value if no
2699 * output was done.
2700 */
2701 msg_scroll = TRUE;
2702 if (filtering)
2703 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2704 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002705 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002706 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2708 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002709 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2710 /*
2711 * EVENT_FILETYPE was not triggered but the buffer already has a
2712 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2713 */
2714 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2715 TRUE, curbuf);
2716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 else
2718 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2719 FALSE, NULL, eap);
2720 if (msg_scrolled == n)
2721 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002722# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 if (aborting()) /* autocmds may abort script processing */
2724 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002725# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727
2728 if (recoverymode && error)
2729 return FAIL;
2730 return OK;
2731}
2732
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002733#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002734/*
2735 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2736 * which is the name of files used for process substitution output by
2737 * some shells on some operating systems, e.g., bash on SunOS.
2738 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2739 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002740 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002741is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002742{
2743 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2744 && VIM_ISDIGIT(fname[8])
2745 && *skipdigits(fname + 9) == NUL
2746 && (fname[9] != NUL
2747 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2748}
2749#endif
2750
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002751#ifdef FEAT_MBYTE
2752
2753/*
2754 * From the current line count and characters read after that, estimate the
2755 * line number where we are now.
2756 * Used for error messages that include a line number.
2757 */
2758 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002759readfile_linenr(
2760 linenr_T linecnt, /* line count before reading more bytes */
2761 char_u *p, /* start of more bytes read */
2762 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002763{
2764 char_u *s;
2765 linenr_T lnum;
2766
2767 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2768 for (s = p; s < endp; ++s)
2769 if (*s == '\n')
2770 ++lnum;
2771 return lnum;
2772}
2773#endif
2774
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002776 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2777 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 * Returns OK or FAIL.
2779 */
2780 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002781prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002783 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002785 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002787 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 if (eap->cmd == NULL)
2789 return FAIL;
2790
2791#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002792 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2793 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002794 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002796 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002798 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002799
2800 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002801 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002802 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 return OK;
2804}
2805
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002806/*
2807 * Set default or forced 'fileformat' and 'binary'.
2808 */
2809 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002810set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002811{
2812 /* set default 'fileformat' */
2813 if (set_options)
2814 {
2815 if (eap != NULL && eap->force_ff != 0)
2816 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2817 else if (*p_ffs != NUL)
2818 set_fileformat(default_fileformat(), OPT_LOCAL);
2819 }
2820
2821 /* set or reset 'binary' */
2822 if (eap != NULL && eap->force_bin != 0)
2823 {
2824 int oldval = curbuf->b_p_bin;
2825
2826 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2827 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2828 }
2829}
2830
2831#if defined(FEAT_MBYTE) || defined(PROTO)
2832/*
2833 * Set forced 'fileencoding'.
2834 */
2835 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002836set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002837{
2838 if (eap->force_enc != 0)
2839 {
2840 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2841
2842 if (fenc != NULL)
2843 set_string_option_direct((char_u *)"fenc", -1,
2844 fenc, OPT_FREE|OPT_LOCAL, 0);
2845 vim_free(fenc);
2846 }
2847}
2848
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849/*
2850 * Find next fileencoding to use from 'fileencodings'.
2851 * "pp" points to fenc_next. It's advanced to the next item.
2852 * When there are no more items, an empty string is returned and *pp is set to
2853 * NULL.
2854 * When *pp is not set to NULL, the result is in allocated memory.
2855 */
2856 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002857next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858{
2859 char_u *p;
2860 char_u *r;
2861
2862 if (**pp == NUL)
2863 {
2864 *pp = NULL;
2865 return (char_u *)"";
2866 }
2867 p = vim_strchr(*pp, ',');
2868 if (p == NULL)
2869 {
2870 r = enc_canonize(*pp);
2871 *pp += STRLEN(*pp);
2872 }
2873 else
2874 {
2875 r = vim_strnsave(*pp, (int)(p - *pp));
2876 *pp = p + 1;
2877 if (r != NULL)
2878 {
2879 p = enc_canonize(r);
2880 vim_free(r);
2881 r = p;
2882 }
2883 }
2884 if (r == NULL) /* out of memory */
2885 {
2886 r = (char_u *)"";
2887 *pp = NULL;
2888 }
2889 return r;
2890}
2891
2892# ifdef FEAT_EVAL
2893/*
2894 * Convert a file with the 'charconvert' expression.
2895 * This closes the file which is to be read, converts it and opens the
2896 * resulting file for reading.
2897 * Returns name of the resulting converted file (the caller should delete it
2898 * after reading it).
2899 * Returns NULL if the conversion failed ("*fdp" is not set) .
2900 */
2901 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002902readfile_charconvert(
2903 char_u *fname, /* name of input file */
2904 char_u *fenc, /* converted from */
2905 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906{
2907 char_u *tmpname;
2908 char_u *errmsg = NULL;
2909
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002910 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 if (tmpname == NULL)
2912 errmsg = (char_u *)_("Can't find temp file for conversion");
2913 else
2914 {
2915 close(*fdp); /* close the input file, ignore errors */
2916 *fdp = -1;
2917 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2918 fname, tmpname) == FAIL)
2919 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2920 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2921 O_RDONLY | O_EXTRA, 0)) < 0)
2922 errmsg = (char_u *)_("can't read output of 'charconvert'");
2923 }
2924
2925 if (errmsg != NULL)
2926 {
2927 /* Don't use emsg(), it breaks mappings, the retry with
2928 * another type of conversion might still work. */
2929 MSG(errmsg);
2930 if (tmpname != NULL)
2931 {
2932 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002933 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 }
2935 }
2936
2937 /* If the input file is closed, open it (caller should check for error). */
2938 if (*fdp < 0)
2939 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2940
2941 return tmpname;
2942}
2943# endif
2944
2945#endif
2946
2947#ifdef FEAT_VIMINFO
2948/*
2949 * Read marks for the current buffer from the viminfo file, when we support
2950 * buffer marks and the buffer has a name.
2951 */
2952 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002953check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954{
2955 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2956 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002957 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958
2959 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2960 * the ' parameter after opening a buffer. */
2961 curbuf->b_marks_read = TRUE;
2962}
2963#endif
2964
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002965#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002967 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2969 * *filesizep are updated.
2970 * Return the (new) encryption key, NULL for no encryption.
2971 */
2972 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002973check_for_cryptkey(
2974 char_u *cryptkey, /* previous encryption key or NULL */
2975 char_u *ptr, /* pointer to read bytes */
2976 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002977 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002978 int newfile, /* editing a new buffer */
2979 char_u *fname, /* file name to display */
2980 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002982 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002983 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002984
2985 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002987 /* Mark the buffer as read-only until the decryption has taken place.
2988 * Avoids accidentally overwriting the file with garbage. */
2989 curbuf->b_p_ro = TRUE;
2990
Bram Moolenaar2be79502014-08-13 21:58:28 +02002991 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002992 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002993 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 {
2995 if (*curbuf->b_p_key)
2996 cryptkey = curbuf->b_p_key;
2997 else
2998 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002999 /* When newfile is TRUE, store the typed key in the 'key'
3000 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003001 * Don't ask for the key again when first time Enter was hit.
3002 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003003 smsg((char_u *)_(need_key_msg), fname);
3004 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003005 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003006 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003007 *did_ask = TRUE;
3008
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 /* check if empty key entered */
3010 if (cryptkey != NULL && *cryptkey == NUL)
3011 {
3012 if (cryptkey != curbuf->b_p_key)
3013 vim_free(cryptkey);
3014 cryptkey = NULL;
3015 }
3016 }
3017 }
3018
3019 if (cryptkey != NULL)
3020 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003021 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003022
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003023 curbuf->b_cryptstate = crypt_create_from_header(
3024 method, cryptkey, ptr);
3025 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003027 /* Remove cryptmethod specific header from the text. */
3028 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003029 if (*sizep <= header_len)
3030 /* invalid header, buffer can't be encrypted */
3031 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003032 *filesizep += header_len;
3033 *sizep -= header_len;
3034 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3035
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003036 /* Restore the read-only flag. */
3037 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 }
3039 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003040 /* When starting to edit a new file which does not have encryption, clear
3041 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003042 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3044
3045 return cryptkey;
3046}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003047#endif /* FEAT_CRYPT */
3048
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049#ifdef UNIX
3050 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003051set_file_time(
3052 char_u *fname,
3053 time_t atime, /* access time */
3054 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055{
3056# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3057 struct utimbuf buf;
3058
3059 buf.actime = atime;
3060 buf.modtime = mtime;
3061 (void)utime((char *)fname, &buf);
3062# else
3063# if defined(HAVE_UTIMES)
3064 struct timeval tvp[2];
3065
3066 tvp[0].tv_sec = atime;
3067 tvp[0].tv_usec = 0;
3068 tvp[1].tv_sec = mtime;
3069 tvp[1].tv_usec = 0;
3070# ifdef NeXT
3071 (void)utimes((char *)fname, tvp);
3072# else
3073 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3074# endif
3075# endif
3076# endif
3077}
3078#endif /* UNIX */
3079
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003080#if defined(VMS) && !defined(MIN)
3081/* Older DECC compiler for VAX doesn't define MIN() */
3082# define MIN(a, b) ((a) < (b) ? (a) : (b))
3083#endif
3084
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003086 * Return TRUE if a file appears to be read-only from the file permissions.
3087 */
3088 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003089check_file_readonly(
3090 char_u *fname, /* full path to file */
3091 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003092{
3093#ifndef USE_MCH_ACCESS
3094 int fd = 0;
3095#endif
3096
3097 return (
3098#ifdef USE_MCH_ACCESS
3099# ifdef UNIX
3100 (perm & 0222) == 0 ||
3101# endif
3102 mch_access((char *)fname, W_OK)
3103#else
3104 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3105 ? TRUE : (close(fd), FALSE)
3106#endif
3107 );
3108}
3109
3110
3111/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003112 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 *
3114 * We do our own buffering here because fwrite() is so slow.
3115 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003116 * If "forceit" is true, we don't care for errors when attempting backups.
3117 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003118 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003119 *
3120 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3121 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122 *
3123 * This function must NOT use NameBuff (because it's called by autowrite()).
3124 *
3125 * return FAIL for failure, OK otherwise
3126 */
3127 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003128buf_write(
3129 buf_T *buf,
3130 char_u *fname,
3131 char_u *sfname,
3132 linenr_T start,
3133 linenr_T end,
3134 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003136 int append, /* append to the file */
3137 int forceit,
3138 int reset_changed,
3139 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140{
3141 int fd;
3142 char_u *backup = NULL;
3143 int backup_copy = FALSE; /* copy the original file? */
3144 int dobackup;
3145 char_u *ffname;
3146 char_u *wfname = NULL; /* name of file to write to */
3147 char_u *s;
3148 char_u *ptr;
3149 char_u c;
3150 int len;
3151 linenr_T lnum;
3152 long nchars;
3153 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003154 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 char_u *errnum = NULL;
3156 char_u *buffer;
3157 char_u smallbuf[SMBUFSIZE];
3158 char_u *backup_ext;
3159 int bufsize;
3160 long perm; /* file permissions */
3161 int retval = OK;
3162 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3163 int msg_save = msg_scroll;
3164 int overwriting; /* TRUE if writing over original */
3165 int no_eol = FALSE; /* no end-of-line written */
3166 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003167 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003169 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 int file_readonly = FALSE; /* overwritten file is read-only */
3171 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003172#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 int made_writable = FALSE; /* 'w' bit has been set */
3174#endif
3175 /* writing everything */
3176 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 int attr;
3179 int fileformat;
3180 int write_bin;
3181 struct bw_info write_info; /* info for buf_write_bytes() */
3182#ifdef FEAT_MBYTE
3183 int converted = FALSE;
3184 int notconverted = FALSE;
3185 char_u *fenc; /* effective 'fileencoding' */
3186 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3187#endif
3188#ifdef HAS_BW_FLAGS
3189 int wb_flags = 0;
3190#endif
3191#ifdef HAVE_ACL
3192 vim_acl_T acl = NULL; /* ACL copied from original file to
3193 backup or new file */
3194#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003195#ifdef FEAT_PERSISTENT_UNDO
3196 int write_undo_file = FALSE;
3197 context_sha256_T sha_ctx;
3198#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003199 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200
3201 if (fname == NULL || *fname == NUL) /* safety check */
3202 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003203 if (buf->b_ml.ml_mfp == NULL)
3204 {
3205 /* This can happen during startup when there is a stray "w" in the
3206 * vimrc file. */
3207 EMSG(_(e_emptybuf));
3208 return FAIL;
3209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
3211 /*
3212 * Disallow writing from .exrc and .vimrc in current directory for
3213 * security reasons.
3214 */
3215 if (check_secure())
3216 return FAIL;
3217
3218 /* Avoid a crash for a long name. */
3219 if (STRLEN(fname) >= MAXPATHL)
3220 {
3221 EMSG(_(e_longname));
3222 return FAIL;
3223 }
3224
3225#ifdef FEAT_MBYTE
3226 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3227 write_info.bw_conv_buf = NULL;
3228 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003229 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 write_info.bw_restlen = 0;
3231# ifdef USE_ICONV
3232 write_info.bw_iconv_fd = (iconv_t)-1;
3233# endif
3234#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003235#ifdef FEAT_CRYPT
3236 write_info.bw_buffer = buf;
3237#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
Bram Moolenaardf177f62005-02-22 08:39:57 +00003239 /* After writing a file changedtick changes but we don't want to display
3240 * the line. */
3241 ex_no_reprint = TRUE;
3242
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 /*
3244 * If there is no file name yet, use the one for the written file.
3245 * BF_NOTEDITED is set to reflect this (in case the write fails).
3246 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003247 * Don't do this when appending.
3248 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003250 if (buf->b_ffname == NULL
3251 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 && whole
3253 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003254#ifdef FEAT_QUICKFIX
3255 && !bt_nofile(buf)
3256#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003258 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3260 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003261 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003263 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 }
3265
3266 if (sfname == NULL)
3267 sfname = fname;
3268 /*
3269 * For Unix: Use the short file name whenever possible.
3270 * Avoids problems with networks and when directory names are changed.
3271 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3272 * another directory, which we don't detect
3273 */
3274 ffname = fname; /* remember full fname */
3275#ifdef UNIX
3276 fname = sfname;
3277#endif
3278
3279 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3280 overwriting = TRUE;
3281 else
3282 overwriting = FALSE;
3283
3284 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003285 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286
3287 ++no_wait_return; /* don't wait for return yet */
3288
3289 /*
3290 * Set '[ and '] marks to the lines to be written.
3291 */
3292 buf->b_op_start.lnum = start;
3293 buf->b_op_start.col = 0;
3294 buf->b_op_end.lnum = end;
3295 buf->b_op_end.col = 0;
3296
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297 {
3298 aco_save_T aco;
3299 int buf_ffname = FALSE;
3300 int buf_sfname = FALSE;
3301 int buf_fname_f = FALSE;
3302 int buf_fname_s = FALSE;
3303 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003304 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003305 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003306 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307
3308 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003309 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310 * Set curbuf to the buffer to be written.
3311 * Careful: The autocommands may call buf_write() recursively!
3312 */
3313 if (ffname == buf->b_ffname)
3314 buf_ffname = TRUE;
3315 if (sfname == buf->b_sfname)
3316 buf_sfname = TRUE;
3317 if (fname == buf->b_ffname)
3318 buf_fname_f = TRUE;
3319 if (fname == buf->b_sfname)
3320 buf_fname_s = TRUE;
3321
3322 /* set curwin/curbuf to buf and save a few things */
3323 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003324 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325
3326 if (append)
3327 {
3328 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3329 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003330 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003331#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003332 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 nofile_err = TRUE;
3334 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003335#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003336 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 }
3340 else if (filtering)
3341 {
3342 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3343 NULL, sfname, FALSE, curbuf, eap);
3344 }
3345 else if (reset_changed && whole)
3346 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003347 int was_changed = curbufIsChanged();
3348
3349 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3350 sfname, sfname, FALSE, curbuf, eap);
3351 if (did_cmd)
3352 {
3353 if (was_changed && !curbufIsChanged())
3354 {
3355 /* Written everything correctly and BufWriteCmd has reset
3356 * 'modified': Correct the undo information so that an
3357 * undo now sets 'modified'. */
3358 u_unchanged(curbuf);
3359 u_update_save_nr(curbuf);
3360 }
3361 }
3362 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003363 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003364#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003365 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003366 nofile_err = TRUE;
3367 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003368#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003369 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003371 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372 }
3373 else
3374 {
3375 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3376 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003377 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003378#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003379 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003380 nofile_err = TRUE;
3381 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003382#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003383 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003384 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003385 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 }
3387
3388 /* restore curwin/curbuf and a few other things */
3389 aucmd_restbuf(&aco);
3390
3391 /*
3392 * In three situations we return here and don't write the file:
3393 * 1. the autocommands deleted or unloaded the buffer.
3394 * 2. The autocommands abort script processing.
3395 * 3. If one of the "Cmd" autocommands was executed.
3396 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003397 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003399 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003400 || did_cmd || nofile_err
3401#ifdef FEAT_EVAL
3402 || aborting()
3403#endif
3404 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405 {
3406 --no_wait_return;
3407 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003408 if (nofile_err)
3409 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3410
Bram Moolenaar1e015462005-09-25 22:16:38 +00003411 if (nofile_err
3412#ifdef FEAT_EVAL
3413 || aborting()
3414#endif
3415 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 /* An aborting error, interrupt or exception in the
3417 * autocommands. */
3418 return FAIL;
3419 if (did_cmd)
3420 {
3421 if (buf == NULL)
3422 /* The buffer was deleted. We assume it was written
3423 * (can't retry anyway). */
3424 return OK;
3425 if (overwriting)
3426 {
3427 /* Assume the buffer was written, update the timestamp. */
3428 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003429 if (append)
3430 buf->b_flags &= ~BF_NEW;
3431 else
3432 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003434 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003435 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 /* Buffer still changed, the autocommands didn't work
3437 * properly. */
3438 return FAIL;
3439 return OK;
3440 }
3441#ifdef FEAT_EVAL
3442 if (!aborting())
3443#endif
3444 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3445 return FAIL;
3446 }
3447
3448 /*
3449 * The autocommands may have changed the number of lines in the file.
3450 * When writing the whole file, adjust the end.
3451 * When writing part of the file, assume that the autocommands only
3452 * changed the number of lines that are to be written (tricky!).
3453 */
3454 if (buf->b_ml.ml_line_count != old_line_count)
3455 {
3456 if (whole) /* write all */
3457 end = buf->b_ml.ml_line_count;
3458 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3459 end += buf->b_ml.ml_line_count - old_line_count;
3460 else /* less lines */
3461 {
3462 end -= old_line_count - buf->b_ml.ml_line_count;
3463 if (end < start)
3464 {
3465 --no_wait_return;
3466 msg_scroll = msg_save;
3467 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3468 return FAIL;
3469 }
3470 }
3471 }
3472
3473 /*
3474 * The autocommands may have changed the name of the buffer, which may
3475 * be kept in fname, ffname and sfname.
3476 */
3477 if (buf_ffname)
3478 ffname = buf->b_ffname;
3479 if (buf_sfname)
3480 sfname = buf->b_sfname;
3481 if (buf_fname_f)
3482 fname = buf->b_ffname;
3483 if (buf_fname_s)
3484 fname = buf->b_sfname;
3485 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486
3487#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003488 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 {
3490 if (whole)
3491 {
3492 /*
3493 * b_changed can be 0 after an undo, but we still need to write
3494 * the buffer to NetBeans.
3495 */
3496 if (buf->b_changed || isNetbeansModified(buf))
3497 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003498 --no_wait_return; /* may wait for return now */
3499 msg_scroll = msg_save;
3500 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501 return retval;
3502 }
3503 else
3504 {
3505 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003506 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507 buffer = NULL;
3508 goto fail;
3509 }
3510 }
3511 else
3512 {
3513 errnum = (char_u *)"E657: ";
3514 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3515 buffer = NULL;
3516 goto fail;
3517 }
3518 }
3519#endif
3520
3521 if (shortmess(SHM_OVER) && !exiting)
3522 msg_scroll = FALSE; /* overwrite previous file message */
3523 else
3524 msg_scroll = TRUE; /* don't overwrite previous file message */
3525 if (!filtering)
3526 filemess(buf,
3527#ifndef UNIX
3528 sfname,
3529#else
3530 fname,
3531#endif
3532 (char_u *)"", 0); /* show that we are busy */
3533 msg_scroll = FALSE; /* always overwrite the file message now */
3534
3535 buffer = alloc(BUFSIZE);
3536 if (buffer == NULL) /* can't allocate big buffer, use small
3537 * one (to be able to write when out of
3538 * memory) */
3539 {
3540 buffer = smallbuf;
3541 bufsize = SMBUFSIZE;
3542 }
3543 else
3544 bufsize = BUFSIZE;
3545
3546 /*
3547 * Get information about original file (if there is one).
3548 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003549#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003550 st_old.st_dev = 0;
3551 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552 perm = -1;
3553 if (mch_stat((char *)fname, &st_old) < 0)
3554 newfile = TRUE;
3555 else
3556 {
3557 perm = st_old.st_mode;
3558 if (!S_ISREG(st_old.st_mode)) /* not a file */
3559 {
3560 if (S_ISDIR(st_old.st_mode))
3561 {
3562 errnum = (char_u *)"E502: ";
3563 errmsg = (char_u *)_("is a directory");
3564 goto fail;
3565 }
3566 if (mch_nodetype(fname) != NODE_WRITABLE)
3567 {
3568 errnum = (char_u *)"E503: ";
3569 errmsg = (char_u *)_("is not a file or writable device");
3570 goto fail;
3571 }
3572 /* It's a device of some kind (or a fifo) which we can write to
3573 * but for which we can't make a backup. */
3574 device = TRUE;
3575 newfile = TRUE;
3576 perm = -1;
3577 }
3578 }
3579#else /* !UNIX */
3580 /*
3581 * Check for a writable device name.
3582 */
3583 c = mch_nodetype(fname);
3584 if (c == NODE_OTHER)
3585 {
3586 errnum = (char_u *)"E503: ";
3587 errmsg = (char_u *)_("is not a file or writable device");
3588 goto fail;
3589 }
3590 if (c == NODE_WRITABLE)
3591 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003592# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003593 /* MS-Windows allows opening a device, but we will probably get stuck
3594 * trying to write to it. */
3595 if (!p_odev)
3596 {
3597 errnum = (char_u *)"E796: ";
3598 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3599 goto fail;
3600 }
3601# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 device = TRUE;
3603 newfile = TRUE;
3604 perm = -1;
3605 }
3606 else
3607 {
3608 perm = mch_getperm(fname);
3609 if (perm < 0)
3610 newfile = TRUE;
3611 else if (mch_isdir(fname))
3612 {
3613 errnum = (char_u *)"E502: ";
3614 errmsg = (char_u *)_("is a directory");
3615 goto fail;
3616 }
3617 if (overwriting)
3618 (void)mch_stat((char *)fname, &st_old);
3619 }
3620#endif /* !UNIX */
3621
3622 if (!device && !newfile)
3623 {
3624 /*
3625 * Check if the file is really writable (when renaming the file to
3626 * make a backup we won't discover it later).
3627 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003628 file_readonly = check_file_readonly(fname, (int)perm);
3629
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 if (!forceit && file_readonly)
3631 {
3632 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3633 {
3634 errnum = (char_u *)"E504: ";
3635 errmsg = (char_u *)_(err_readonly);
3636 }
3637 else
3638 {
3639 errnum = (char_u *)"E505: ";
3640 errmsg = (char_u *)_("is read-only (add ! to override)");
3641 }
3642 goto fail;
3643 }
3644
3645 /*
3646 * Check if the timestamp hasn't changed since reading the file.
3647 */
3648 if (overwriting)
3649 {
3650 retval = check_mtime(buf, &st_old);
3651 if (retval == FAIL)
3652 goto fail;
3653 }
3654 }
3655
3656#ifdef HAVE_ACL
3657 /*
3658 * For systems that support ACL: get the ACL from the original file.
3659 */
3660 if (!newfile)
3661 acl = mch_get_acl(fname);
3662#endif
3663
3664 /*
3665 * If 'backupskip' is not empty, don't make a backup for some files.
3666 */
3667 dobackup = (p_wb || p_bk || *p_pm != NUL);
3668#ifdef FEAT_WILDIGN
3669 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3670 dobackup = FALSE;
3671#endif
3672
3673 /*
3674 * Save the value of got_int and reset it. We don't want a previous
3675 * interruption cancel writing, only hitting CTRL-C while writing should
3676 * abort it.
3677 */
3678 prev_got_int = got_int;
3679 got_int = FALSE;
3680
3681 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3682 buf->b_saving = TRUE;
3683
3684 /*
3685 * If we are not appending or filtering, the file exists, and the
3686 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3687 * When 'patchmode' is set also make a backup when appending.
3688 *
3689 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3690 * off. This helps when editing large files on almost-full disks.
3691 */
3692 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3693 {
3694#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003695 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696#endif
3697
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003698 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 backup_copy = TRUE;
3700#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003701 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702 {
3703 int i;
3704
3705# ifdef UNIX
3706 /*
3707 * Don't rename the file when:
3708 * - it's a hard link
3709 * - it's a symbolic link
3710 * - we don't have write permission in the directory
3711 * - we can't set the owner/group of the new file
3712 */
3713 if (st_old.st_nlink > 1
3714 || mch_lstat((char *)fname, &st) < 0
3715 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003716 || st.st_ino != st_old.st_ino
3717# ifndef HAVE_FCHOWN
3718 || st.st_uid != st_old.st_uid
3719 || st.st_gid != st_old.st_gid
3720# endif
3721 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 backup_copy = TRUE;
3723 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003724# else
3725# ifdef WIN32
3726 /* On NTFS file systems hard links are possible. */
3727 if (mch_is_linked(fname))
3728 backup_copy = TRUE;
3729 else
3730# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731# endif
3732 {
3733 /*
3734 * Check if we can create a file and set the owner/group to
3735 * the ones from the original file.
3736 * First find a file name that doesn't exist yet (use some
3737 * arbitrary numbers).
3738 */
3739 STRCPY(IObuff, fname);
3740 for (i = 4913; ; i += 123)
3741 {
3742 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 break;
3745 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746 fd = mch_open((char *)IObuff,
3747 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 if (fd < 0) /* can't write in directory */
3749 backup_copy = TRUE;
3750 else
3751 {
3752# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003753# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003754 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003755# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 if (mch_stat((char *)IObuff, &st) < 0
3757 || st.st_uid != st_old.st_uid
3758 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003759 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760 backup_copy = TRUE;
3761# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003762 /* Close the file before removing it, on MS-Windows we
3763 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003764 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003765 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003766# ifdef MSWIN
3767 /* MS-Windows may trigger a virus scanner to open the
3768 * file, we can't delete it then. Keep trying for half a
3769 * second. */
3770 {
3771 int try;
3772
3773 for (try = 0; try < 10; ++try)
3774 {
3775 if (mch_lstat((char *)IObuff, &st) < 0)
3776 break;
3777 ui_delay(50L, TRUE); /* wait 50 msec */
3778 mch_remove(IObuff);
3779 }
3780 }
3781# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782 }
3783 }
3784 }
3785
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 /*
3787 * Break symlinks and/or hardlinks if we've been asked to.
3788 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003789 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003791# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 int lstat_res;
3793
3794 lstat_res = mch_lstat((char *)fname, &st);
3795
3796 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003797 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 && lstat_res == 0
3799 && st.st_ino != st_old.st_ino)
3800 backup_copy = FALSE;
3801
3802 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003803 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 && st_old.st_nlink > 1
3805 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3806 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003807# else
3808# if defined(WIN32)
3809 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003810 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003811 backup_copy = FALSE;
3812
3813 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003814 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003815 backup_copy = FALSE;
3816# endif
3817# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819
3820#endif
3821
3822 /* make sure we have a valid backup extension to use */
3823 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 else
3826 backup_ext = p_bex;
3827
3828 if (backup_copy
3829 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3830 {
3831 int bfd;
3832 char_u *copybuf, *wp;
3833 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003834 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835 char_u *dirp;
3836 char_u *rootname;
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003837#if defined(UNIX) || defined(WIN3264)
3838 char_u *p;
3839#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003840#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003842 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843#endif
3844
3845 copybuf = alloc(BUFSIZE + 1);
3846 if (copybuf == NULL)
3847 {
3848 some_error = TRUE; /* out of memory */
3849 goto nobackup;
3850 }
3851
3852 /*
3853 * Try to make the backup in each directory in the 'bdir' option.
3854 *
3855 * Unix semantics has it, that we may have a writable file,
3856 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3857 * - the directory is not writable,
3858 * - the file may be a symbolic link,
3859 * - the file may belong to another user/group, etc.
3860 *
3861 * For these reasons, the existing writable file must be truncated
3862 * and reused. Creation of a backup COPY will be attempted.
3863 */
3864 dirp = p_bdir;
3865 while (*dirp)
3866 {
3867#ifdef UNIX
3868 st_new.st_ino = 0;
3869 st_new.st_dev = 0;
3870 st_new.st_gid = 0;
3871#endif
3872
3873 /*
3874 * Isolate one directory name, using an entry in 'bdir'.
3875 */
3876 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003877
3878#if defined(UNIX) || defined(WIN3264)
3879 p = copybuf + STRLEN(copybuf);
3880 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
3881 // Ends with '//', use full path
3882 if ((p = make_percent_swname(copybuf, fname)) != NULL)
3883 {
3884 backup = modname(p, backup_ext, FALSE);
3885 vim_free(p);
3886 }
3887#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888 rootname = get_file_in_dir(fname, copybuf);
3889 if (rootname == NULL)
3890 {
3891 some_error = TRUE; /* out of memory */
3892 goto nobackup;
3893 }
3894
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003895#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896 did_set_shortname = FALSE;
3897#endif
3898
3899 /*
3900 * May try twice if 'shortname' not set.
3901 */
3902 for (;;)
3903 {
3904 /*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003905 * Make the backup file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003907 if (backup == NULL)
3908 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 rootname, backup_ext, FALSE);
3910 if (backup == NULL)
3911 {
3912 vim_free(rootname);
3913 some_error = TRUE; /* out of memory */
3914 goto nobackup;
3915 }
3916
3917 /*
3918 * Check if backup file already exists.
3919 */
3920 if (mch_stat((char *)backup, &st_new) >= 0)
3921 {
3922#ifdef UNIX
3923 /*
3924 * Check if backup file is same as original file.
3925 * May happen when modname() gave the same file back.
3926 * E.g. silly link, or file name-length reached.
3927 * If we don't check here, we either ruin the file
3928 * when copying or erase it after writing. jw.
3929 */
3930 if (st_new.st_dev == st_old.st_dev
3931 && st_new.st_ino == st_old.st_ino)
3932 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003933 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 /*
3935 * may try again with 'shortname' set
3936 */
3937 if (!(buf->b_shortname || buf->b_p_sn))
3938 {
3939 buf->b_shortname = TRUE;
3940 did_set_shortname = TRUE;
3941 continue;
3942 }
3943 /* setting shortname didn't help */
3944 if (did_set_shortname)
3945 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 break;
3947 }
3948#endif
3949
3950 /*
3951 * If we are not going to keep the backup file, don't
3952 * delete an existing one, try to use another name.
3953 * Change one character, just before the extension.
3954 */
3955 if (!p_bk)
3956 {
3957 wp = backup + STRLEN(backup) - 1
3958 - STRLEN(backup_ext);
3959 if (wp < backup) /* empty file name ??? */
3960 wp = backup;
3961 *wp = 'z';
3962 while (*wp > 'a'
3963 && mch_stat((char *)backup, &st_new) >= 0)
3964 --*wp;
3965 /* They all exist??? Must be something wrong. */
3966 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003967 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 }
3969 }
3970 break;
3971 }
3972 vim_free(rootname);
3973
3974 /*
3975 * Try to create the backup file
3976 */
3977 if (backup != NULL)
3978 {
3979 /* remove old backup, if present */
3980 mch_remove(backup);
3981 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003982 * we were sleeping (symlink hacker attack?). Reset umask
3983 * if possible to avoid mch_setperm() below. */
3984#ifdef UNIX
3985 umask_save = umask(0);
3986#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003988 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3989 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003990#ifdef UNIX
3991 (void)umask(umask_save);
3992#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003994 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995 else
3996 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003997 /* Set file protection same as original file, but
3998 * strip s-bit. Only needed if umask() wasn't used
3999 * above. */
4000#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004002#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003 /*
4004 * Try to set the group of the backup same as the
4005 * original file. If this fails, set the protection
4006 * bits for the group same as the protection bits for
4007 * others.
4008 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004009 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004011 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012# endif
4013 )
4014 mch_setperm(backup,
4015 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004016# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004017 mch_copy_sec(fname, backup);
4018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019#endif
4020
4021 /*
4022 * copy the file.
4023 */
4024 write_info.bw_fd = bfd;
4025 write_info.bw_buf = copybuf;
4026#ifdef HAS_BW_FLAGS
4027 write_info.bw_flags = FIO_NOCONVERT;
4028#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004029 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030 BUFSIZE)) > 0)
4031 {
4032 if (buf_write_bytes(&write_info) == FAIL)
4033 {
4034 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4035 break;
4036 }
4037 ui_breakcheck();
4038 if (got_int)
4039 {
4040 errmsg = (char_u *)_(e_interr);
4041 break;
4042 }
4043 }
4044
4045 if (close(bfd) < 0 && errmsg == NULL)
4046 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4047 if (write_info.bw_len < 0)
4048 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4049#ifdef UNIX
4050 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4051#endif
4052#ifdef HAVE_ACL
4053 mch_set_acl(backup, acl);
4054#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004055#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004056 mch_copy_sec(fname, backup);
4057#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058 break;
4059 }
4060 }
4061 }
4062 nobackup:
4063 close(fd); /* ignore errors for closing read file */
4064 vim_free(copybuf);
4065
4066 if (backup == NULL && errmsg == NULL)
4067 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4068 /* ignore errors when forceit is TRUE */
4069 if ((some_error || errmsg != NULL) && !forceit)
4070 {
4071 retval = FAIL;
4072 goto fail;
4073 }
4074 errmsg = NULL;
4075 }
4076 else
4077 {
4078 char_u *dirp;
4079 char_u *p;
4080 char_u *rootname;
4081
4082 /*
4083 * Make a backup by renaming the original file.
4084 */
4085 /*
4086 * If 'cpoptions' includes the "W" flag, we don't want to
4087 * overwrite a read-only file. But rename may be possible
4088 * anyway, thus we need an extra check here.
4089 */
4090 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4091 {
4092 errnum = (char_u *)"E504: ";
4093 errmsg = (char_u *)_(err_readonly);
4094 goto fail;
4095 }
4096
4097 /*
4098 *
4099 * Form the backup file name - change path/fo.o.h to
4100 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4101 * that works is used.
4102 */
4103 dirp = p_bdir;
4104 while (*dirp)
4105 {
4106 /*
4107 * Isolate one directory name and make the backup file name.
4108 */
4109 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004110
4111#if defined(UNIX) || defined(WIN3264)
4112 p = IObuff + STRLEN(IObuff);
4113 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
4114 // path ends with '//', use full path
4115 if ((p = make_percent_swname(IObuff, fname)) != NULL)
4116 {
4117 backup = modname(p, backup_ext, FALSE);
4118 vim_free(p);
4119 }
4120#endif
4121 if (backup == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 {
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004123 rootname = get_file_in_dir(fname, IObuff);
4124 if (rootname == NULL)
4125 backup = NULL;
4126 else
4127 {
4128 backup = buf_modname(
4129 (buf->b_p_sn || buf->b_shortname),
4130 rootname, backup_ext, FALSE);
4131 vim_free(rootname);
4132 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 }
4134
4135 if (backup != NULL)
4136 {
4137 /*
4138 * If we are not going to keep the backup file, don't
4139 * delete an existing one, try to use another name.
4140 * Change one character, just before the extension.
4141 */
4142 if (!p_bk && mch_getperm(backup) >= 0)
4143 {
4144 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4145 if (p < backup) /* empty file name ??? */
4146 p = backup;
4147 *p = 'z';
4148 while (*p > 'a' && mch_getperm(backup) >= 0)
4149 --*p;
4150 /* They all exist??? Must be something wrong! */
4151 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004152 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 }
4154 }
4155 if (backup != NULL)
4156 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004158 * Delete any existing backup and move the current version
4159 * to the backup. For safety, we don't remove the backup
4160 * until the write has finished successfully. And if the
4161 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162 */
4163 /*
4164 * If the renaming of the original file to the backup file
4165 * works, quit here.
4166 */
4167 if (vim_rename(fname, backup) == 0)
4168 break;
4169
Bram Moolenaard23a8232018-02-10 18:45:26 +01004170 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 }
4172 }
4173 if (backup == NULL && !forceit)
4174 {
4175 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4176 goto fail;
4177 }
4178 }
4179 }
4180
Bram Moolenaar53076832015-12-31 19:53:21 +01004181#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004182 /* When using ":w!" and the file was read-only: make it writable */
4183 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4184 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4185 {
4186 perm |= 0200;
4187 (void)mch_setperm(fname, perm);
4188 made_writable = TRUE;
4189 }
4190#endif
4191
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004192 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004193 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4194 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 {
4196 buf->b_p_ro = FALSE;
4197#ifdef FEAT_TITLE
4198 need_maketitle = TRUE; /* set window title later */
4199#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 }
4202
4203 if (end > buf->b_ml.ml_line_count)
4204 end = buf->b_ml.ml_line_count;
4205 if (buf->b_ml.ml_flags & ML_EMPTY)
4206 start = end + 1;
4207
4208 /*
4209 * If the original file is being overwritten, there is a small chance that
4210 * we crash in the middle of writing. Therefore the file is preserved now.
4211 * This makes all block numbers positive so that recovery does not need
4212 * the original file.
4213 * Don't do this if there is a backup file and we are exiting.
4214 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004215 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004216 && !(exiting && backup != NULL))
4217 {
4218 ml_preserve(buf, FALSE);
4219 if (got_int)
4220 {
4221 errmsg = (char_u *)_(e_interr);
4222 goto restore_backup;
4223 }
4224 }
4225
Bram Moolenaar071d4272004-06-13 20:20:40 +00004226#ifdef VMS
4227 vms_remove_version(fname); /* remove version */
4228#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004229 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 * multi-byte conversion. */
4231 wfname = fname;
4232
4233#ifdef FEAT_MBYTE
4234 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4235 if (eap != NULL && eap->force_enc != 0)
4236 {
4237 fenc = eap->cmd + eap->force_enc;
4238 fenc = enc_canonize(fenc);
4239 fenc_tofree = fenc;
4240 }
4241 else
4242 fenc = buf->b_p_fenc;
4243
4244 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004245 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004247 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004248
4249 /*
4250 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4251 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4252 * Prepare the flags for it and allocate bw_conv_buf when needed.
4253 */
4254 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4255 {
4256 wb_flags = get_fio_flags(fenc);
4257 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4258 {
4259 /* Need to allocate a buffer to translate into. */
4260 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4261 write_info.bw_conv_buflen = bufsize * 2;
4262 else /* FIO_UCS4 */
4263 write_info.bw_conv_buflen = bufsize * 4;
4264 write_info.bw_conv_buf
4265 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4266 if (write_info.bw_conv_buf == NULL)
4267 end = 0;
4268 }
4269 }
4270
4271# ifdef WIN3264
4272 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4273 {
4274 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4275 write_info.bw_conv_buflen = bufsize * 4;
4276 write_info.bw_conv_buf
4277 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4278 if (write_info.bw_conv_buf == NULL)
4279 end = 0;
4280 }
4281# endif
4282
Bram Moolenaard0573012017-10-28 21:11:06 +02004283# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4285 {
4286 write_info.bw_conv_buflen = bufsize * 3;
4287 write_info.bw_conv_buf
4288 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4289 if (write_info.bw_conv_buf == NULL)
4290 end = 0;
4291 }
4292# endif
4293
4294# if defined(FEAT_EVAL) || defined(USE_ICONV)
4295 if (converted && wb_flags == 0)
4296 {
4297# ifdef USE_ICONV
4298 /*
4299 * Use iconv() conversion when conversion is needed and it's not done
4300 * internally.
4301 */
4302 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4303 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4304 if (write_info.bw_iconv_fd != (iconv_t)-1)
4305 {
4306 /* We're going to use iconv(), allocate a buffer to convert in. */
4307 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4308 write_info.bw_conv_buf
4309 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4310 if (write_info.bw_conv_buf == NULL)
4311 end = 0;
4312 write_info.bw_first = TRUE;
4313 }
4314# ifdef FEAT_EVAL
4315 else
4316# endif
4317# endif
4318
4319# ifdef FEAT_EVAL
4320 /*
4321 * When the file needs to be converted with 'charconvert' after
4322 * writing, write to a temp file instead and let the conversion
4323 * overwrite the original file.
4324 */
4325 if (*p_ccv != NUL)
4326 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004327 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328 if (wfname == NULL) /* Can't write without a tempfile! */
4329 {
4330 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4331 goto restore_backup;
4332 }
4333 }
4334# endif
4335 }
4336# endif
4337 if (converted && wb_flags == 0
4338# ifdef USE_ICONV
4339 && write_info.bw_iconv_fd == (iconv_t)-1
4340# endif
4341# ifdef FEAT_EVAL
4342 && wfname == fname
4343# endif
4344 )
4345 {
4346 if (!forceit)
4347 {
4348 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4349 goto restore_backup;
4350 }
4351 notconverted = TRUE;
4352 }
4353#endif
4354
4355 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004356 * If conversion is taking place, we may first pretend to write and check
4357 * for conversion errors. Then loop again to write for real.
4358 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004360 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361 {
4362 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004363 * There is no need to check conversion when:
4364 * - there is no conversion
4365 * - we make a backup file, that can be restored in case of conversion
4366 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004368#ifdef FEAT_MBYTE
4369 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004371 checking_conversion = FALSE;
4372
4373 if (checking_conversion)
4374 {
4375 /* Make sure we don't write anything. */
4376 fd = -1;
4377 write_info.bw_fd = fd;
4378 }
4379 else
4380 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004381#ifdef HAVE_FTRUNCATE
4382# define TRUNC_ON_OPEN 0
4383#else
4384# define TRUNC_ON_OPEN O_TRUNC
4385#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004386 /*
4387 * Open the file "wfname" for writing.
4388 * We may try to open the file twice: If we can't write to the file
4389 * and forceit is TRUE we delete the existing file and try to
4390 * create a new one. If this still fails we may have lost the
4391 * original file! (this may happen when the user reached his
4392 * quotum for number of files).
4393 * Appending will fail if the file does not exist and forceit is
4394 * FALSE.
4395 */
4396 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4397 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004398 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004399 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004401 /*
4402 * A forced write will try to create a new file if the old one
4403 * is still readonly. This may also happen when the directory
4404 * is read-only. In that case the mch_remove() will fail.
4405 */
4406 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 {
4408#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004409 stat_T st;
4410
4411 /* Don't delete the file when it's a hard or symbolic link.
4412 */
4413 if ((!newfile && st_old.st_nlink > 1)
4414 || (mch_lstat((char *)fname, &st) == 0
4415 && (st.st_dev != st_old.st_dev
4416 || st.st_ino != st_old.st_ino)))
4417 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4418 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004419#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004420 {
4421 errmsg = (char_u *)_("E212: Can't open file for writing");
4422 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4423 && perm >= 0)
4424 {
4425#ifdef UNIX
4426 /* we write to the file, thus it should be marked
4427 writable after all */
4428 if (!(perm & 0200))
4429 made_writable = TRUE;
4430 perm |= 0200;
4431 if (st_old.st_uid != getuid()
4432 || st_old.st_gid != getgid())
4433 perm &= 0777;
4434#endif
4435 if (!append) /* don't remove when appending */
4436 mch_remove(wfname);
4437 continue;
4438 }
4439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441
4442restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004444 stat_T st;
4445
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004447 * If we failed to open the file, we don't need a backup.
4448 * Throw it away. If we moved or removed the original file
4449 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004451 if (backup != NULL && wfname == fname)
4452 {
4453 if (backup_copy)
4454 {
4455 /*
4456 * There is a small chance that we removed the
4457 * original, try to move the copy in its place.
4458 * This may not work if the vim_rename() fails.
4459 * In that case we leave the copy around.
4460 */
4461 /* If file does not exist, put the copy in its
4462 * place */
4463 if (mch_stat((char *)fname, &st) < 0)
4464 vim_rename(backup, fname);
4465 /* if original file does exist throw away the copy
4466 */
4467 if (mch_stat((char *)fname, &st) >= 0)
4468 mch_remove(backup);
4469 }
4470 else
4471 {
4472 /* try to put the original file back */
4473 vim_rename(backup, fname);
4474 }
4475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004477 /* if original file no longer exists give an extra warning
4478 */
4479 if (!newfile && mch_stat((char *)fname, &st) < 0)
4480 end = 0;
4481 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482
4483#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004484 if (wfname != fname)
4485 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004487 goto fail;
4488 }
4489 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004491#if defined(UNIX)
4492 {
4493 stat_T st;
4494
4495 /* Double check we are writing the intended file before making
4496 * any changes. */
4497 if (overwriting
4498 && (!dobackup || backup_copy)
4499 && fname == wfname
4500 && perm >= 0
4501 && mch_fstat(fd, &st) == 0
4502 && st.st_ino != st_old.st_ino)
4503 {
4504 close(fd);
4505 errmsg = (char_u *)_("E949: File changed while writing");
4506 goto fail;
4507 }
4508 }
4509#endif
4510#ifdef HAVE_FTRUNCATE
4511 if (!append)
Bram Moolenaarae1e1082017-11-17 21:35:24 +01004512 ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004513#endif
4514
Bram Moolenaard0573012017-10-28 21:11:06 +02004515#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004516 if (backup != NULL && overwriting && !append)
4517 {
4518 if (backup_copy)
4519 (void)mch_copy_file_attribute(wfname, backup);
4520 else
4521 (void)mch_copy_file_attribute(backup, wfname);
4522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004524 if (!overwriting && !append)
4525 {
4526 if (buf->b_ffname != NULL)
4527 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4528 /* Should copy resource fork */
4529 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530#endif
4531
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004533 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004535 char_u *header;
4536 int header_len;
4537
4538 buf->b_cryptstate = crypt_create_for_writing(
4539 crypt_get_method_nr(buf),
4540 buf->b_p_key, &header, &header_len);
4541 if (buf->b_cryptstate == NULL || header == NULL)
4542 end = 0;
4543 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004545 /* Write magic number, so that Vim knows how this file is
4546 * encrypted when reading it back. */
4547 write_info.bw_buf = header;
4548 write_info.bw_len = header_len;
4549 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004551 end = 0;
4552 wb_flags |= FIO_ENCRYPTED;
4553 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004554 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004556#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004558 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004559
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004560 write_info.bw_buf = buffer;
4561 nchars = 0;
4562
4563 /* use "++bin", "++nobin" or 'binary' */
4564 if (eap != NULL && eap->force_bin != 0)
4565 write_bin = (eap->force_bin == FORCE_BIN);
4566 else
4567 write_bin = buf->b_p_bin;
4568
4569#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004571 * The BOM is written just after the encryption magic number.
4572 * Skip it when appending and the file already existed, the BOM only
4573 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004575 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004577 write_info.bw_len = make_bom(buffer, fenc);
4578 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004580 /* don't convert, do encryption */
4581 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4582 if (buf_write_bytes(&write_info) == FAIL)
4583 end = 0;
4584 else
4585 nchars += write_info.bw_len;
4586 }
4587 }
4588 write_info.bw_start_lnum = start;
4589#endif
4590
4591#ifdef FEAT_PERSISTENT_UNDO
4592 write_undo_file = (buf->b_p_udf
4593 && overwriting
4594 && !append
4595 && !filtering
4596 && reset_changed
4597 && !checking_conversion);
4598 if (write_undo_file)
4599 /* Prepare for computing the hash value of the text. */
4600 sha256_start(&sha_ctx);
4601#endif
4602
4603 write_info.bw_len = bufsize;
4604#ifdef HAS_BW_FLAGS
4605 write_info.bw_flags = wb_flags;
4606#endif
4607 fileformat = get_fileformat_force(buf, eap);
4608 s = buffer;
4609 len = 0;
4610 for (lnum = start; lnum <= end; ++lnum)
4611 {
4612 /*
4613 * The next while loop is done once for each character written.
4614 * Keep it fast!
4615 */
4616 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4617#ifdef FEAT_PERSISTENT_UNDO
4618 if (write_undo_file)
4619 sha256_update(&sha_ctx, ptr + 1,
4620 (UINT32_T)(STRLEN(ptr + 1) + 1));
4621#endif
4622 while ((c = *++ptr) != NUL)
4623 {
4624 if (c == NL)
4625 *s = NUL; /* replace newlines with NULs */
4626 else if (c == CAR && fileformat == EOL_MAC)
4627 *s = NL; /* Mac: replace CRs with NLs */
4628 else
4629 *s = c;
4630 ++s;
4631 if (++len != bufsize)
4632 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004633 if (buf_write_bytes(&write_info) == FAIL)
4634 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004635 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004636 break;
4637 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004638 nchars += bufsize;
4639 s = buffer;
4640 len = 0;
4641#ifdef FEAT_MBYTE
4642 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004644 }
4645 /* write failed or last line has no EOL: stop here */
4646 if (end == 0
4647 || (lnum == end
4648 && (write_bin || !buf->b_p_fixeol)
4649 && (lnum == buf->b_no_eol_lnum
4650 || (lnum == buf->b_ml.ml_line_count
4651 && !buf->b_p_eol))))
4652 {
4653 ++lnum; /* written the line, count it */
4654 no_eol = TRUE;
4655 break;
4656 }
4657 if (fileformat == EOL_UNIX)
4658 *s++ = NL;
4659 else
4660 {
4661 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4662 if (fileformat == EOL_DOS) /* write CR-NL */
4663 {
4664 if (++len == bufsize)
4665 {
4666 if (buf_write_bytes(&write_info) == FAIL)
4667 {
4668 end = 0; /* write error: break loop */
4669 break;
4670 }
4671 nchars += bufsize;
4672 s = buffer;
4673 len = 0;
4674 }
4675 *s++ = NL;
4676 }
4677 }
4678 if (++len == bufsize && end)
4679 {
4680 if (buf_write_bytes(&write_info) == FAIL)
4681 {
4682 end = 0; /* write error: break loop */
4683 break;
4684 }
4685 nchars += bufsize;
4686 s = buffer;
4687 len = 0;
4688
4689 ui_breakcheck();
4690 if (got_int)
4691 {
4692 end = 0; /* Interrupted, break loop */
4693 break;
4694 }
4695 }
4696#ifdef VMS
4697 /*
4698 * On VMS there is a problem: newlines get added when writing
4699 * blocks at a time. Fix it by writing a line at a time.
4700 * This is much slower!
4701 * Explanation: VAX/DECC RTL insists that records in some RMS
4702 * structures end with a newline (carriage return) character, and
4703 * if they don't it adds one.
4704 * With other RMS structures it works perfect without this fix.
4705 */
4706 if (buf->b_fab_rfm == FAB$C_VFC
4707 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4708 {
4709 int b2write;
4710
4711 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4712 ? MIN(4096, bufsize)
4713 : MIN(buf->b_fab_mrs, bufsize));
4714
4715 b2write = len;
4716 while (b2write > 0)
4717 {
4718 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4719 if (buf_write_bytes(&write_info) == FAIL)
4720 {
4721 end = 0;
4722 break;
4723 }
4724 b2write -= MIN(b2write, buf->b_fab_mrs);
4725 }
4726 write_info.bw_len = bufsize;
4727 nchars += len;
4728 s = buffer;
4729 len = 0;
4730 }
4731#endif
4732 }
4733 if (len > 0 && end > 0)
4734 {
4735 write_info.bw_len = len;
4736 if (buf_write_bytes(&write_info) == FAIL)
4737 end = 0; /* write error */
4738 nchars += len;
4739 }
4740
4741 /* Stop when writing done or an error was encountered. */
4742 if (!checking_conversion || end == 0)
4743 break;
4744
4745 /* If no error happened until now, writing should be ok, so loop to
4746 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747 }
4748
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004749 /* If we started writing, finish writing. Also when an error was
4750 * encountered. */
4751 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004753#if defined(UNIX) && defined(HAVE_FSYNC)
4754 /*
4755 * On many journalling file systems there is a bug that causes both the
4756 * original and the backup file to be lost when halting the system
4757 * right after writing the file. That's because only the meta-data is
4758 * journalled. Syncing the file slows down the system, but assures it
4759 * has been written to disk and we don't lose it.
4760 * For a device do try the fsync() but don't complain if it does not
4761 * work (could be a pipe).
4762 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4763 */
4764 if (p_fs && fsync(fd) != 0 && !device)
4765 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004766 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004767 end = 0;
4768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769#endif
4770
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004771#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004772 /* Probably need to set the security context. */
4773 if (!backup_copy)
4774 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004775#endif
4776
Bram Moolenaara5792f52005-11-23 21:25:05 +00004777#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004778 /* When creating a new file, set its owner/group to that of the
4779 * original file. Get the new device and inode number. */
4780 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004781 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004782# ifdef HAVE_FCHOWN
4783 stat_T st;
4784
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004785 /* Don't change the owner when it's already OK, some systems remove
4786 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004787 if (mch_stat((char *)wfname, &st) < 0
4788 || st.st_uid != st_old.st_uid
4789 || st.st_gid != st_old.st_gid)
4790 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004791 /* changing owner might not be possible */
4792 ignored = fchown(fd, st_old.st_uid, -1);
4793 /* if changing group fails clear the group permissions */
4794 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4795 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004796 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004797# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004798 buf_setino(buf);
4799 }
4800 else if (!buf->b_dev_valid)
4801 /* Set the inode when creating a new file. */
4802 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004803#endif
4804
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004805#ifdef UNIX
4806 if (made_writable)
4807 perm &= ~0200; /* reset 'w' bit for security reasons */
4808#endif
4809#ifdef HAVE_FCHMOD
4810 /* set permission of new file same as old file */
4811 if (perm >= 0)
4812 (void)mch_fsetperm(fd, perm);
4813#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004814 if (close(fd) != 0)
4815 {
4816 errmsg = (char_u *)_("E512: Close failed");
4817 end = 0;
4818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004820#ifndef HAVE_FCHMOD
4821 /* set permission of new file same as old file */
4822 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004823 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004824#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004826 /*
4827 * Probably need to set the ACL before changing the user (can't set the
4828 * ACL on a file the user doesn't own).
4829 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4830 * default), chmod() discards all part of a file's ACL that don't
4831 * represent the mode of the file. It's non-trivial for us to discover
4832 * whether we're in that situation, so we simply always re-set the ACL.
4833 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004834# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004835 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004836# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004837 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004839#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004840 if (buf->b_cryptstate != NULL)
4841 {
4842 crypt_free_state(buf->b_cryptstate);
4843 buf->b_cryptstate = NULL;
4844 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004845#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004848 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004850 /*
4851 * The file was written to a temp file, now it needs to be
4852 * converted with 'charconvert' to (overwrite) the output file.
4853 */
4854 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004856 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4857 fenc, wfname, fname) == FAIL)
4858 {
4859 write_info.bw_conv_error = TRUE;
4860 end = 0;
4861 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004863 mch_remove(wfname);
4864 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004867 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868
4869 if (end == 0)
4870 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004871 /*
4872 * Error encountered.
4873 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874 if (errmsg == NULL)
4875 {
4876#ifdef FEAT_MBYTE
4877 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004878 {
4879 if (write_info.bw_conv_error_lnum == 0)
4880 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4881 else
4882 {
4883 errmsg_allocated = TRUE;
4884 errmsg = alloc(300);
4885 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4886 (long)write_info.bw_conv_error_lnum);
4887 }
4888 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 else
4890#endif
4891 if (got_int)
4892 errmsg = (char_u *)_(e_interr);
4893 else
4894 errmsg = (char_u *)_("E514: write error (file system full?)");
4895 }
4896
4897 /*
4898 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004899 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 * original file when trying to make a backup when writing the file a
4901 * second time.
4902 * When "backup_copy" is set we need to copy the backup over the new
4903 * file. Otherwise rename the backup file.
4904 * If this is OK, don't give the extra warning message.
4905 */
4906 if (backup != NULL)
4907 {
4908 if (backup_copy)
4909 {
4910 /* This may take a while, if we were interrupted let the user
4911 * know we got the message. */
4912 if (got_int)
4913 {
4914 MSG(_(e_interr));
4915 out_flush();
4916 }
4917 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4918 {
4919 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004920 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4921 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922 {
4923 /* copy the file. */
4924 write_info.bw_buf = smallbuf;
4925#ifdef HAS_BW_FLAGS
4926 write_info.bw_flags = FIO_NOCONVERT;
4927#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004928 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929 SMBUFSIZE)) > 0)
4930 if (buf_write_bytes(&write_info) == FAIL)
4931 break;
4932
4933 if (close(write_info.bw_fd) >= 0
4934 && write_info.bw_len == 0)
4935 end = 1; /* success */
4936 }
4937 close(fd); /* ignore errors for closing read file */
4938 }
4939 }
4940 else
4941 {
4942 if (vim_rename(backup, fname) == 0)
4943 end = 1;
4944 }
4945 }
4946 goto fail;
4947 }
4948
4949 lnum -= start; /* compute number of written lines */
4950 --no_wait_return; /* may wait for return now */
4951
4952#if !(defined(UNIX) || defined(VMS))
4953 fname = sfname; /* use shortname now, for the messages */
4954#endif
4955 if (!filtering)
4956 {
4957 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4958 c = FALSE;
4959#ifdef FEAT_MBYTE
4960 if (write_info.bw_conv_error)
4961 {
4962 STRCAT(IObuff, _(" CONVERSION ERROR"));
4963 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004964 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004965 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004966 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 }
4968 else if (notconverted)
4969 {
4970 STRCAT(IObuff, _("[NOT converted]"));
4971 c = TRUE;
4972 }
4973 else if (converted)
4974 {
4975 STRCAT(IObuff, _("[converted]"));
4976 c = TRUE;
4977 }
4978#endif
4979 if (device)
4980 {
4981 STRCAT(IObuff, _("[Device]"));
4982 c = TRUE;
4983 }
4984 else if (newfile)
4985 {
4986 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4987 c = TRUE;
4988 }
4989 if (no_eol)
4990 {
4991 msg_add_eol();
4992 c = TRUE;
4993 }
4994 /* may add [unix/dos/mac] */
4995 if (msg_add_fileformat(fileformat))
4996 c = TRUE;
4997#ifdef FEAT_CRYPT
4998 if (wb_flags & FIO_ENCRYPTED)
4999 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005000 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001 c = TRUE;
5002 }
5003#endif
5004 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
5005 if (!shortmess(SHM_WRITE))
5006 {
5007 if (append)
5008 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5009 else
5010 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5011 }
5012
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005013 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014 }
5015
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005016 /* When written everything correctly: reset 'modified'. Unless not
5017 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005018 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019#ifdef FEAT_MBYTE
5020 && !write_info.bw_conv_error
5021#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005022 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5023 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024 {
5025 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005026 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005027 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01005028 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
5029 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005031 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032 }
5033
5034 /*
5035 * If written to the current file, update the timestamp of the swap file
5036 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5037 */
5038 if (overwriting)
5039 {
5040 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005041 if (append)
5042 buf->b_flags &= ~BF_NEW;
5043 else
5044 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 }
5046
5047 /*
5048 * If we kept a backup until now, and we are in patch mode, then we make
5049 * the backup file our 'original' file.
5050 */
5051 if (*p_pm && dobackup)
5052 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005053 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054 fname, p_pm, FALSE);
5055
5056 if (backup != NULL)
5057 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005058 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059
5060 /*
5061 * If the original file does not exist yet
5062 * the current backup file becomes the original file
5063 */
5064 if (org == NULL)
5065 EMSG(_("E205: Patchmode: can't save original file"));
5066 else if (mch_stat(org, &st) < 0)
5067 {
5068 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005069 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070#ifdef UNIX
5071 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5072#endif
5073 }
5074 }
5075 /*
5076 * If there is no backup file, remember that a (new) file was
5077 * created.
5078 */
5079 else
5080 {
5081 int empty_fd;
5082
5083 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005084 || (empty_fd = mch_open(org,
5085 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005086 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 EMSG(_("E206: patchmode: can't touch empty original file"));
5088 else
5089 close(empty_fd);
5090 }
5091 if (org != NULL)
5092 {
5093 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5094 vim_free(org);
5095 }
5096 }
5097
5098 /*
5099 * Remove the backup unless 'backup' option is set
5100 */
5101 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5102 EMSG(_("E207: Can't delete backup file"));
5103
5104#ifdef FEAT_SUN_WORKSHOP
5105 if (usingSunWorkShop)
5106 workshop_file_saved((char *) ffname);
5107#endif
5108
5109 goto nofail;
5110
5111 /*
5112 * Finish up. We get here either after failure or success.
5113 */
5114fail:
5115 --no_wait_return; /* may wait for return now */
5116nofail:
5117
5118 /* Done saving, we accept changed buffer warnings again */
5119 buf->b_saving = FALSE;
5120
5121 vim_free(backup);
5122 if (buffer != smallbuf)
5123 vim_free(buffer);
5124#ifdef FEAT_MBYTE
5125 vim_free(fenc_tofree);
5126 vim_free(write_info.bw_conv_buf);
5127# ifdef USE_ICONV
5128 if (write_info.bw_iconv_fd != (iconv_t)-1)
5129 {
5130 iconv_close(write_info.bw_iconv_fd);
5131 write_info.bw_iconv_fd = (iconv_t)-1;
5132 }
5133# endif
5134#endif
5135#ifdef HAVE_ACL
5136 mch_free_acl(acl);
5137#endif
5138
5139 if (errmsg != NULL)
5140 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005141 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005142
Bram Moolenaar8820b482017-03-16 17:23:31 +01005143 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144 msg_add_fname(buf,
5145#ifndef UNIX
5146 sfname
5147#else
5148 fname
5149#endif
5150 ); /* put file name in IObuff with quotes */
5151 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5152 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5153 /* If the error message has the form "is ...", put the error number in
5154 * front of the file name. */
5155 if (errnum != NULL)
5156 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005157 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005158 mch_memmove(IObuff, errnum, (size_t)numlen);
5159 }
5160 STRCAT(IObuff, errmsg);
5161 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005162 if (errmsg_allocated)
5163 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164
5165 retval = FAIL;
5166 if (end == 0)
5167 {
5168 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5169 attr | MSG_HIST);
5170 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5171 attr | MSG_HIST);
5172
5173 /* Update the timestamp to avoid an "overwrite changed file"
5174 * prompt when writing again. */
5175 if (mch_stat((char *)fname, &st_old) >= 0)
5176 {
5177 buf_store_time(buf, &st_old, fname);
5178 buf->b_mtime_read = buf->b_mtime;
5179 }
5180 }
5181 }
5182 msg_scroll = msg_save;
5183
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005184#ifdef FEAT_PERSISTENT_UNDO
5185 /*
5186 * When writing the whole file and 'undofile' is set, also write the undo
5187 * file.
5188 */
5189 if (retval == OK && write_undo_file)
5190 {
5191 char_u hash[UNDO_HASH_SIZE];
5192
5193 sha256_finish(&sha_ctx, hash);
5194 u_write_undo(NULL, FALSE, buf, hash);
5195 }
5196#endif
5197
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198#ifdef FEAT_EVAL
5199 if (!should_abort(retval))
5200#else
5201 if (!got_int)
5202#endif
5203 {
5204 aco_save_T aco;
5205
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005206 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5207
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 /*
5209 * Apply POST autocommands.
5210 * Careful: The autocommands may call buf_write() recursively!
5211 */
5212 aucmd_prepbuf(&aco, buf);
5213
5214 if (append)
5215 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5216 FALSE, curbuf, eap);
5217 else if (filtering)
5218 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5219 FALSE, curbuf, eap);
5220 else if (reset_changed && whole)
5221 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5222 FALSE, curbuf, eap);
5223 else
5224 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5225 FALSE, curbuf, eap);
5226
5227 /* restore curwin/curbuf and a few other things */
5228 aucmd_restbuf(&aco);
5229
5230#ifdef FEAT_EVAL
5231 if (aborting()) /* autocmds may abort script processing */
5232 retval = FALSE;
5233#endif
5234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235
5236 got_int |= prev_got_int;
5237
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 return retval;
5239}
5240
5241/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005242 * Set the name of the current buffer. Use when the buffer doesn't have a
5243 * name and a ":r" or ":w" command with a file name is used.
5244 */
5245 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005246set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005247{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005248 buf_T *buf = curbuf;
5249
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005250 /* It's like the unnamed buffer is deleted.... */
5251 if (curbuf->b_p_bl)
5252 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5253 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005254#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005255 if (aborting()) /* autocmds may abort script processing */
5256 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005257#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005258 if (curbuf != buf)
5259 {
5260 /* We are in another buffer now, don't do the renaming. */
5261 EMSG(_(e_auchangedbuf));
5262 return FAIL;
5263 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005264
5265 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5266 curbuf->b_flags |= BF_NOTEDITED;
5267
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005268 /* ....and a new named one is created */
5269 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5270 if (curbuf->b_p_bl)
5271 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005272#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005273 if (aborting()) /* autocmds may abort script processing */
5274 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005275#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005276
5277 /* Do filetype detection now if 'filetype' is empty. */
5278 if (*curbuf->b_p_ft == NUL)
5279 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005280 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005281 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005282 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005283 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005284
5285 return OK;
5286}
5287
5288/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005289 * Put file name into IObuff with quotes.
5290 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005291 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005292msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005293{
5294 if (fname == NULL)
5295 fname = (char_u *)"-stdin-";
5296 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5297 IObuff[0] = '"';
5298 STRCAT(IObuff, "\" ");
5299}
5300
5301/*
5302 * Append message for text mode to IObuff.
5303 * Return TRUE if something appended.
5304 */
5305 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005306msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005307{
5308#ifndef USE_CRNL
5309 if (eol_type == EOL_DOS)
5310 {
5311 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5312 return TRUE;
5313 }
5314#endif
5315#ifndef USE_CR
5316 if (eol_type == EOL_MAC)
5317 {
5318 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5319 return TRUE;
5320 }
5321#endif
5322#if defined(USE_CRNL) || defined(USE_CR)
5323 if (eol_type == EOL_UNIX)
5324 {
5325 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5326 return TRUE;
5327 }
5328#endif
5329 return FALSE;
5330}
5331
5332/*
5333 * Append line and character count to IObuff.
5334 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005335 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005336msg_add_lines(
5337 int insert_space,
5338 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005339 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340{
5341 char_u *p;
5342
5343 p = IObuff + STRLEN(IObuff);
5344
5345 if (insert_space)
5346 *p++ = ' ';
5347 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005348 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005349 "%ldL, %lldC", lnum, (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350 else
5351 {
5352 if (lnum == 1)
5353 STRCPY(p, _("1 line, "));
5354 else
5355 sprintf((char *)p, _("%ld lines, "), lnum);
5356 p += STRLEN(p);
5357 if (nchars == 1)
5358 STRCPY(p, _("1 character"));
5359 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005360 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005361 _("%lld characters"), (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362 }
5363}
5364
5365/*
5366 * Append message for missing line separator to IObuff.
5367 */
5368 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005369msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370{
5371 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5372}
5373
5374/*
5375 * Check modification time of file, before writing to it.
5376 * The size isn't checked, because using a tool like "gzip" takes care of
5377 * using the same timestamp but can't set the size.
5378 */
5379 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005380check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381{
5382 if (buf->b_mtime_read != 0
5383 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5384 {
5385 msg_scroll = TRUE; /* don't overwrite messages here */
5386 msg_silent = 0; /* must give this prompt */
5387 /* don't use emsg() here, don't want to flush the buffers */
5388 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005389 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5391 TRUE) == 'n')
5392 return FAIL;
5393 msg_scroll = FALSE; /* always overwrite the file message now */
5394 }
5395 return OK;
5396}
5397
5398 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005399time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005401#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5403 * the seconds. Since the roundoff is done when flushing the inode, the
5404 * time may change unexpectedly by one second!!! */
5405 return (t1 - t2 > 1 || t2 - t1 > 1);
5406#else
5407 return (t1 != t2);
5408#endif
5409}
5410
5411/*
5412 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005413 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 *
5415 * Return FAIL for failure, OK otherwise.
5416 */
5417 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005418buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005419{
5420 int wlen;
5421 char_u *buf = ip->bw_buf; /* data to write */
5422 int len = ip->bw_len; /* length of data */
5423#ifdef HAS_BW_FLAGS
5424 int flags = ip->bw_flags; /* extra flags */
5425#endif
5426
5427#ifdef FEAT_MBYTE
5428 /*
5429 * Skip conversion when writing the crypt magic number or the BOM.
5430 */
5431 if (!(flags & FIO_NOCONVERT))
5432 {
5433 char_u *p;
5434 unsigned c;
5435 int n;
5436
5437 if (flags & FIO_UTF8)
5438 {
5439 /*
5440 * Convert latin1 in the buffer to UTF-8 in the file.
5441 */
5442 p = ip->bw_conv_buf; /* translate to buffer */
5443 for (wlen = 0; wlen < len; ++wlen)
5444 p += utf_char2bytes(buf[wlen], p);
5445 buf = ip->bw_conv_buf;
5446 len = (int)(p - ip->bw_conv_buf);
5447 }
5448 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5449 {
5450 /*
5451 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5452 * Latin1 chars in the file.
5453 */
5454 if (flags & FIO_LATIN1)
5455 p = buf; /* translate in-place (can only get shorter) */
5456 else
5457 p = ip->bw_conv_buf; /* translate to buffer */
5458 for (wlen = 0; wlen < len; wlen += n)
5459 {
5460 if (wlen == 0 && ip->bw_restlen != 0)
5461 {
5462 int l;
5463
5464 /* Use remainder of previous call. Append the start of
5465 * buf[] to get a full sequence. Might still be too
5466 * short! */
5467 l = CONV_RESTLEN - ip->bw_restlen;
5468 if (l > len)
5469 l = len;
5470 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005471 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 if (n > ip->bw_restlen + len)
5473 {
5474 /* We have an incomplete byte sequence at the end to
5475 * be written. We can't convert it without the
5476 * remaining bytes. Keep them for the next call. */
5477 if (ip->bw_restlen + len > CONV_RESTLEN)
5478 return FAIL;
5479 ip->bw_restlen += len;
5480 break;
5481 }
5482 if (n > 1)
5483 c = utf_ptr2char(ip->bw_rest);
5484 else
5485 c = ip->bw_rest[0];
5486 if (n >= ip->bw_restlen)
5487 {
5488 n -= ip->bw_restlen;
5489 ip->bw_restlen = 0;
5490 }
5491 else
5492 {
5493 ip->bw_restlen -= n;
5494 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5495 (size_t)ip->bw_restlen);
5496 n = 0;
5497 }
5498 }
5499 else
5500 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005501 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502 if (n > len - wlen)
5503 {
5504 /* We have an incomplete byte sequence at the end to
5505 * be written. We can't convert it without the
5506 * remaining bytes. Keep them for the next call. */
5507 if (len - wlen > CONV_RESTLEN)
5508 return FAIL;
5509 ip->bw_restlen = len - wlen;
5510 mch_memmove(ip->bw_rest, buf + wlen,
5511 (size_t)ip->bw_restlen);
5512 break;
5513 }
5514 if (n > 1)
5515 c = utf_ptr2char(buf + wlen);
5516 else
5517 c = buf[wlen];
5518 }
5519
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005520 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5521 {
5522 ip->bw_conv_error = TRUE;
5523 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5524 }
5525 if (c == NL)
5526 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 }
5528 if (flags & FIO_LATIN1)
5529 len = (int)(p - buf);
5530 else
5531 {
5532 buf = ip->bw_conv_buf;
5533 len = (int)(p - ip->bw_conv_buf);
5534 }
5535 }
5536
5537# ifdef WIN3264
5538 else if (flags & FIO_CODEPAGE)
5539 {
5540 /*
5541 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5542 * codepage.
5543 */
5544 char_u *from;
5545 size_t fromlen;
5546 char_u *to;
5547 int u8c;
5548 BOOL bad = FALSE;
5549 int needed;
5550
5551 if (ip->bw_restlen > 0)
5552 {
5553 /* Need to concatenate the remainder of the previous call and
5554 * the bytes of the current call. Use the end of the
5555 * conversion buffer for this. */
5556 fromlen = len + ip->bw_restlen;
5557 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5558 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5559 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5560 }
5561 else
5562 {
5563 from = buf;
5564 fromlen = len;
5565 }
5566
5567 to = ip->bw_conv_buf;
5568 if (enc_utf8)
5569 {
5570 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5571 * The buffer has been allocated to be big enough. */
5572 while (fromlen > 0)
5573 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005574 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 if (n > (int)fromlen) /* incomplete byte sequence */
5576 break;
5577 u8c = utf_ptr2char(from);
5578 *to++ = (u8c & 0xff);
5579 *to++ = (u8c >> 8);
5580 fromlen -= n;
5581 from += n;
5582 }
5583
5584 /* Copy remainder to ip->bw_rest[] to be used for the next
5585 * call. */
5586 if (fromlen > CONV_RESTLEN)
5587 {
5588 /* weird overlong sequence */
5589 ip->bw_conv_error = TRUE;
5590 return FAIL;
5591 }
5592 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005593 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 }
5595 else
5596 {
5597 /* Convert from enc_codepage to UCS-2, to the start of the
5598 * buffer. The buffer has been allocated to be big enough. */
5599 ip->bw_restlen = 0;
5600 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005601 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 NULL, 0);
5603 if (needed == 0)
5604 {
5605 /* When conversion fails there may be a trailing byte. */
5606 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005607 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 NULL, 0);
5609 if (needed == 0)
5610 {
5611 /* Conversion doesn't work. */
5612 ip->bw_conv_error = TRUE;
5613 return FAIL;
5614 }
5615 /* Save the trailing byte for the next call. */
5616 ip->bw_rest[0] = from[fromlen - 1];
5617 ip->bw_restlen = 1;
5618 }
5619 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005620 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 (LPWSTR)to, needed);
5622 if (needed == 0)
5623 {
5624 /* Safety check: Conversion doesn't work. */
5625 ip->bw_conv_error = TRUE;
5626 return FAIL;
5627 }
5628 to += needed * 2;
5629 }
5630
5631 fromlen = to - ip->bw_conv_buf;
5632 buf = to;
5633# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5634 if (FIO_GET_CP(flags) == CP_UTF8)
5635 {
5636 /* Convert from UCS-2 to UTF-8, using the remainder of the
5637 * conversion buffer. Fails when out of space. */
5638 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5639 {
5640 u8c = *from++;
5641 u8c += (*from++ << 8);
5642 to += utf_char2bytes(u8c, to);
5643 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5644 {
5645 ip->bw_conv_error = TRUE;
5646 return FAIL;
5647 }
5648 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005649 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 }
5651 else
5652#endif
5653 {
5654 /* Convert from UCS-2 to the codepage, using the remainder of
5655 * the conversion buffer. If the conversion uses the default
5656 * character "0", the data doesn't fit in this encoding, so
5657 * fail. */
5658 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5659 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005660 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5661 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 if (bad)
5663 {
5664 ip->bw_conv_error = TRUE;
5665 return FAIL;
5666 }
5667 }
5668 }
5669# endif
5670
Bram Moolenaar56718732006-03-15 22:53:57 +00005671# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 else if (flags & FIO_MACROMAN)
5673 {
5674 /*
5675 * Convert UTF-8 or latin1 to Apple MacRoman.
5676 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677 char_u *from;
5678 size_t fromlen;
5679
5680 if (ip->bw_restlen > 0)
5681 {
5682 /* Need to concatenate the remainder of the previous call and
5683 * the bytes of the current call. Use the end of the
5684 * conversion buffer for this. */
5685 fromlen = len + ip->bw_restlen;
5686 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5687 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5688 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5689 }
5690 else
5691 {
5692 from = buf;
5693 fromlen = len;
5694 }
5695
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005696 if (enc2macroman(from, fromlen,
5697 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5698 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 {
5700 ip->bw_conv_error = TRUE;
5701 return FAIL;
5702 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 }
5705# endif
5706
5707# ifdef USE_ICONV
5708 if (ip->bw_iconv_fd != (iconv_t)-1)
5709 {
5710 const char *from;
5711 size_t fromlen;
5712 char *to;
5713 size_t tolen;
5714
5715 /* Convert with iconv(). */
5716 if (ip->bw_restlen > 0)
5717 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005718 char *fp;
5719
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 /* Need to concatenate the remainder of the previous call and
5721 * the bytes of the current call. Use the end of the
5722 * conversion buffer for this. */
5723 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005724 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5725 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5726 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5727 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728 tolen = ip->bw_conv_buflen - fromlen;
5729 }
5730 else
5731 {
5732 from = (const char *)buf;
5733 fromlen = len;
5734 tolen = ip->bw_conv_buflen;
5735 }
5736 to = (char *)ip->bw_conv_buf;
5737
5738 if (ip->bw_first)
5739 {
5740 size_t save_len = tolen;
5741
5742 /* output the initial shift state sequence */
5743 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5744
5745 /* There is a bug in iconv() on Linux (which appears to be
5746 * wide-spread) which sets "to" to NULL and messes up "tolen".
5747 */
5748 if (to == NULL)
5749 {
5750 to = (char *)ip->bw_conv_buf;
5751 tolen = save_len;
5752 }
5753 ip->bw_first = FALSE;
5754 }
5755
5756 /*
5757 * If iconv() has an error or there is not enough room, fail.
5758 */
5759 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5760 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5761 || fromlen > CONV_RESTLEN)
5762 {
5763 ip->bw_conv_error = TRUE;
5764 return FAIL;
5765 }
5766
5767 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5768 if (fromlen > 0)
5769 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5770 ip->bw_restlen = (int)fromlen;
5771
5772 buf = ip->bw_conv_buf;
5773 len = (int)((char_u *)to - ip->bw_conv_buf);
5774 }
5775# endif
5776 }
5777#endif /* FEAT_MBYTE */
5778
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005779 if (ip->bw_fd < 0)
5780 /* Only checking conversion, which is OK if we get here. */
5781 return OK;
5782
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005784 if (flags & FIO_ENCRYPTED)
5785 {
5786 /* Encrypt the data. Do it in-place if possible, otherwise use an
5787 * allocated buffer. */
5788 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5789 {
5790 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5791 }
5792 else
5793 {
5794 char_u *outbuf;
5795
5796 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5797 if (len == 0)
5798 return OK; /* Crypt layer is buffering, will flush later. */
5799 wlen = write_eintr(ip->bw_fd, outbuf, len);
5800 vim_free(outbuf);
5801 return (wlen < len) ? FAIL : OK;
5802 }
5803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804#endif
5805
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005806 wlen = write_eintr(ip->bw_fd, buf, len);
5807 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808}
5809
5810#ifdef FEAT_MBYTE
5811/*
5812 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005813 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814 */
5815 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005816ucs2bytes(
5817 unsigned c, /* in: character */
5818 char_u **pp, /* in/out: pointer to result */
5819 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820{
5821 char_u *p = *pp;
5822 int error = FALSE;
5823 int cc;
5824
5825
5826 if (flags & FIO_UCS4)
5827 {
5828 if (flags & FIO_ENDIAN_L)
5829 {
5830 *p++ = c;
5831 *p++ = (c >> 8);
5832 *p++ = (c >> 16);
5833 *p++ = (c >> 24);
5834 }
5835 else
5836 {
5837 *p++ = (c >> 24);
5838 *p++ = (c >> 16);
5839 *p++ = (c >> 8);
5840 *p++ = c;
5841 }
5842 }
5843 else if (flags & (FIO_UCS2 | FIO_UTF16))
5844 {
5845 if (c >= 0x10000)
5846 {
5847 if (flags & FIO_UTF16)
5848 {
5849 /* Make two words, ten bits of the character in each. First
5850 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5851 c -= 0x10000;
5852 if (c >= 0x100000)
5853 error = TRUE;
5854 cc = ((c >> 10) & 0x3ff) + 0xd800;
5855 if (flags & FIO_ENDIAN_L)
5856 {
5857 *p++ = cc;
5858 *p++ = ((unsigned)cc >> 8);
5859 }
5860 else
5861 {
5862 *p++ = ((unsigned)cc >> 8);
5863 *p++ = cc;
5864 }
5865 c = (c & 0x3ff) + 0xdc00;
5866 }
5867 else
5868 error = TRUE;
5869 }
5870 if (flags & FIO_ENDIAN_L)
5871 {
5872 *p++ = c;
5873 *p++ = (c >> 8);
5874 }
5875 else
5876 {
5877 *p++ = (c >> 8);
5878 *p++ = c;
5879 }
5880 }
5881 else /* Latin1 */
5882 {
5883 if (c >= 0x100)
5884 {
5885 error = TRUE;
5886 *p++ = 0xBF;
5887 }
5888 else
5889 *p++ = c;
5890 }
5891
5892 *pp = p;
5893 return error;
5894}
5895
5896/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005897 * Return TRUE if file encoding "fenc" requires conversion from or to
5898 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899 */
5900 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005901need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005903 int same_encoding;
5904 int enc_flags;
5905 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005907 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005908 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005909 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005910 fenc_flags = 0;
5911 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005912 else
5913 {
5914 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5915 * "ucs-4be", etc. */
5916 enc_flags = get_fio_flags(p_enc);
5917 fenc_flags = get_fio_flags(fenc);
5918 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5919 }
5920 if (same_encoding)
5921 {
5922 /* Specified encoding matches with 'encoding'. This requires
5923 * conversion when 'encoding' is Unicode but not UTF-8. */
5924 return enc_unicode != 0;
5925 }
5926
5927 /* Encodings differ. However, conversion is not needed when 'enc' is any
5928 * Unicode encoding and the file is UTF-8. */
5929 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930}
5931
5932/*
5933 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5934 * internal conversion.
5935 * if "ptr" is an empty string, use 'encoding'.
5936 */
5937 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005938get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939{
5940 int prop;
5941
5942 if (*ptr == NUL)
5943 ptr = p_enc;
5944
5945 prop = enc_canon_props(ptr);
5946 if (prop & ENC_UNICODE)
5947 {
5948 if (prop & ENC_2BYTE)
5949 {
5950 if (prop & ENC_ENDIAN_L)
5951 return FIO_UCS2 | FIO_ENDIAN_L;
5952 return FIO_UCS2;
5953 }
5954 if (prop & ENC_4BYTE)
5955 {
5956 if (prop & ENC_ENDIAN_L)
5957 return FIO_UCS4 | FIO_ENDIAN_L;
5958 return FIO_UCS4;
5959 }
5960 if (prop & ENC_2WORD)
5961 {
5962 if (prop & ENC_ENDIAN_L)
5963 return FIO_UTF16 | FIO_ENDIAN_L;
5964 return FIO_UTF16;
5965 }
5966 return FIO_UTF8;
5967 }
5968 if (prop & ENC_LATIN1)
5969 return FIO_LATIN1;
5970 /* must be ENC_DBCS, requires iconv() */
5971 return 0;
5972}
5973
5974#ifdef WIN3264
5975/*
5976 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5977 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5978 * Used for conversion between 'encoding' and 'fileencoding'.
5979 */
5980 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005981get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982{
5983 int cp;
5984
5985 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5986 if (!enc_utf8 && enc_codepage <= 0)
5987 return 0;
5988
5989 cp = encname2codepage(ptr);
5990 if (cp == 0)
5991 {
5992# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5993 if (STRCMP(ptr, "utf-8") == 0)
5994 cp = CP_UTF8;
5995 else
5996# endif
5997 return 0;
5998 }
5999 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
6000}
6001#endif
6002
Bram Moolenaard0573012017-10-28 21:11:06 +02006003#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004/*
6005 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
6006 * needed for the internal conversion to/from utf-8 or latin1.
6007 */
6008 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006009get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010{
6011 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
6012 && (enc_canon_props(ptr) & ENC_MACROMAN))
6013 return FIO_MACROMAN;
6014 return 0;
6015}
6016#endif
6017
6018/*
6019 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6020 * "size" must be at least 2.
6021 * Return the name of the encoding and set "*lenp" to the length.
6022 * Returns NULL when no BOM found.
6023 */
6024 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006025check_for_bom(
6026 char_u *p,
6027 long size,
6028 int *lenp,
6029 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030{
6031 char *name = NULL;
6032 int len = 2;
6033
6034 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006035 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006036 {
6037 name = "utf-8"; /* EF BB BF */
6038 len = 3;
6039 }
6040 else if (p[0] == 0xff && p[1] == 0xfe)
6041 {
6042 if (size >= 4 && p[2] == 0 && p[3] == 0
6043 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6044 {
6045 name = "ucs-4le"; /* FF FE 00 00 */
6046 len = 4;
6047 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006048 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006050 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6051 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052 name = "utf-16le"; /* FF FE */
6053 }
6054 else if (p[0] == 0xfe && p[1] == 0xff
6055 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6056 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006057 /* Default to utf-16, it works also for ucs-2 text. */
6058 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006060 else
6061 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 }
6063 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6064 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6065 {
6066 name = "ucs-4"; /* 00 00 FE FF */
6067 len = 4;
6068 }
6069
6070 *lenp = len;
6071 return (char_u *)name;
6072}
6073
6074/*
6075 * Generate a BOM in "buf[4]" for encoding "name".
6076 * Return the length of the BOM (zero when no BOM).
6077 */
6078 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006079make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080{
6081 int flags;
6082 char_u *p;
6083
6084 flags = get_fio_flags(name);
6085
6086 /* Can't put a BOM in a non-Unicode file. */
6087 if (flags == FIO_LATIN1 || flags == 0)
6088 return 0;
6089
6090 if (flags == FIO_UTF8) /* UTF-8 */
6091 {
6092 buf[0] = 0xef;
6093 buf[1] = 0xbb;
6094 buf[2] = 0xbf;
6095 return 3;
6096 }
6097 p = buf;
6098 (void)ucs2bytes(0xfeff, &p, flags);
6099 return (int)(p - buf);
6100}
6101#endif
6102
6103/*
6104 * Try to find a shortname by comparing the fullname with the current
6105 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006106 * Returns "full_path" or pointer into "full_path" if shortened.
6107 */
6108 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006109shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006110{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006111 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006112 char_u *p = full_path;
6113
Bram Moolenaard9462e32011-04-11 21:35:11 +02006114 dirname = alloc(MAXPATHL);
6115 if (dirname == NULL)
6116 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006117 if (mch_dirname(dirname, MAXPATHL) == OK)
6118 {
6119 p = shorten_fname(full_path, dirname);
6120 if (p == NULL || *p == NUL)
6121 p = full_path;
6122 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006123 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006124 return p;
6125}
6126
6127/*
6128 * Try to find a shortname by comparing the fullname with the current
6129 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 * Returns NULL if not shorter name possible, pointer into "full_path"
6131 * otherwise.
6132 */
6133 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006134shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135{
6136 int len;
6137 char_u *p;
6138
6139 if (full_path == NULL)
6140 return NULL;
6141 len = (int)STRLEN(dir_name);
6142 if (fnamencmp(dir_name, full_path, len) == 0)
6143 {
6144 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006145#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006147 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 * slash, since C: by itself does not define a specific dir. In this
6149 * case p may already be correct. <negri>
6150 */
6151 if (!((len > 2) && (*(p - 2) == ':')))
6152#endif
6153 {
6154 if (vim_ispathsep(*p))
6155 ++p;
6156#ifndef VMS /* the path separator is always part of the path */
6157 else
6158 p = NULL;
6159#endif
6160 }
6161 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006162#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163 /*
6164 * When using a file in the current drive, remove the drive name:
6165 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6166 * a floppy from "A:\dir" to "B:\dir".
6167 */
6168 else if (len > 3
6169 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6170 && full_path[1] == ':'
6171 && vim_ispathsep(full_path[2]))
6172 p = full_path + 2;
6173#endif
6174 else
6175 p = NULL;
6176 return p;
6177}
6178
6179/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006180 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181 * When "force" is TRUE: Use full path from now on for files currently being
6182 * edited, both for file name and swap file name. Try to shorten the file
6183 * names a bit, if safe to do so.
6184 * When "force" is FALSE: Only try to shorten absolute file names.
6185 * For buffers that have buftype "nofile" or "scratch": never change the file
6186 * name.
6187 */
6188 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006189shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6190{
6191 char_u *p;
6192
6193 if (buf->b_fname != NULL
6194#ifdef FEAT_QUICKFIX
6195 && !bt_nofile(buf)
6196#endif
6197 && !path_with_url(buf->b_fname)
6198 && (force
6199 || buf->b_sfname == NULL
6200 || mch_isFullName(buf->b_sfname)))
6201 {
6202 VIM_CLEAR(buf->b_sfname);
6203 p = shorten_fname(buf->b_ffname, dirname);
6204 if (p != NULL)
6205 {
6206 buf->b_sfname = vim_strsave(p);
6207 buf->b_fname = buf->b_sfname;
6208 }
6209 if (p == NULL || buf->b_fname == NULL)
6210 buf->b_fname = buf->b_ffname;
6211 }
6212}
6213
6214/*
6215 * Shorten filenames for all buffers.
6216 */
6217 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006218shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219{
6220 char_u dirname[MAXPATHL];
6221 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222
6223 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006224 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006226 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006227
6228 /* Always make the swap file name a full path, a "nofile" buffer may
6229 * also have a swap file. */
6230 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006233 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234}
6235
6236#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6237 || defined(FEAT_GUI_MSWIN) \
6238 || defined(FEAT_GUI_MAC) \
6239 || defined(PROTO)
6240/*
6241 * Shorten all filenames in "fnames[count]" by current directory.
6242 */
6243 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006244shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245{
6246 int i;
6247 char_u dirname[MAXPATHL];
6248 char_u *p;
6249
6250 if (fnames == NULL || count < 1)
6251 return;
6252 mch_dirname(dirname, sizeof(dirname));
6253 for (i = 0; i < count; ++i)
6254 {
6255 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6256 {
6257 /* shorten_fname() returns pointer in given "fnames[i]". If free
6258 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6259 * "p" first then free fnames[i]. */
6260 p = vim_strsave(p);
6261 vim_free(fnames[i]);
6262 fnames[i] = p;
6263 }
6264 }
6265}
6266#endif
6267
6268/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02006269 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 * fo_o_h.ext for MSDOS or when shortname option set.
6271 *
6272 * Assumed that fname is a valid name found in the filesystem we assure that
6273 * the return value is a different name and ends in 'ext'.
6274 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6275 * characters otherwise.
6276 * Space for the returned name is allocated, must be freed later.
6277 * Returns NULL when out of memory.
6278 */
6279 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006280modname(
6281 char_u *fname,
6282 char_u *ext,
6283 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006285 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 fname, ext, prepend_dot);
6287}
6288
6289 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006290buf_modname(
6291 int shortname, /* use 8.3 file name */
6292 char_u *fname,
6293 char_u *ext,
6294 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295{
6296 char_u *retval;
6297 char_u *s;
6298 char_u *e;
6299 char_u *ptr;
6300 int fnamelen, extlen;
6301
6302 extlen = (int)STRLEN(ext);
6303
6304 /*
6305 * If there is no file name we must get the name of the current directory
6306 * (we need the full path in case :cd is used).
6307 */
6308 if (fname == NULL || *fname == NUL)
6309 {
6310 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6311 if (retval == NULL)
6312 return NULL;
6313 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6314 (fnamelen = (int)STRLEN(retval)) == 0)
6315 {
6316 vim_free(retval);
6317 return NULL;
6318 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006319 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 {
6321 retval[fnamelen++] = PATHSEP;
6322 retval[fnamelen] = NUL;
6323 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 }
6326 else
6327 {
6328 fnamelen = (int)STRLEN(fname);
6329 retval = alloc((unsigned)(fnamelen + extlen + 3));
6330 if (retval == NULL)
6331 return NULL;
6332 STRCPY(retval, fname);
6333#ifdef VMS
6334 vms_remove_version(retval); /* we do not need versions here */
6335#endif
6336 }
6337
6338 /*
6339 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6340 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6341 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6342 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6343 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006344 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006347#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006349#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006351#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 )
6353 if (*ptr == '.') /* replace '.' by '_' */
6354 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006356 {
6357 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361
6362 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6364 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365
6366 s = ptr + STRLEN(ptr);
6367
6368 /*
6369 * For 8.3 file names we may have to reduce the length.
6370 */
6371#ifdef USE_LONG_FNAME
6372 if (!USE_LONG_FNAME || shortname)
6373#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375#endif
6376 {
6377 /*
6378 * If there is no file name, or the file name ends in '/', and the
6379 * extension starts with '.', put a '_' before the dot, because just
6380 * ".ext" is invalid.
6381 */
6382 if (fname == NULL || *fname == NUL
6383 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6384 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386 *s++ = '_';
6387 }
6388 /*
6389 * If the extension starts with '.', truncate the base name at 8
6390 * characters
6391 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006394 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 {
6396 s = ptr + 8;
6397 *s = '\0';
6398 }
6399 }
6400 /*
6401 * If the extension doesn't start with '.', and the file name
6402 * doesn't have an extension yet, append a '.'
6403 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 else if ((e = vim_strchr(ptr, '.')) == NULL)
6405 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406 /*
6407 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006408 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 */
6410 else if ((int)STRLEN(e) + extlen > 4)
6411 s = e + 4 - extlen;
6412 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006413#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414 /*
6415 * If there is no file name, and the extension starts with '.', put a
6416 * '_' before the dot, because just ".ext" may be invalid if it's on a
6417 * FAT partition, and on HPFS it doesn't matter.
6418 */
6419 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6420 *s++ = '_';
6421#endif
6422
6423 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006424 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 * ext can start with '.' and cannot exceed 3 more characters.
6426 */
6427 STRCPY(s, ext);
6428
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 /*
6430 * Prepend the dot.
6431 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006432 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433#ifdef USE_LONG_FNAME
6434 && USE_LONG_FNAME
6435#endif
6436 )
6437 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006438 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441
6442 /*
6443 * Check that, after appending the extension, the file name is really
6444 * different.
6445 */
6446 if (fname != NULL && STRCMP(fname, retval) == 0)
6447 {
6448 /* we search for a character that can be replaced by '_' */
6449 while (--s >= ptr)
6450 {
6451 if (*s != '_')
6452 {
6453 *s = '_';
6454 break;
6455 }
6456 }
6457 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6458 *ptr = 'v';
6459 }
6460 return retval;
6461}
6462
6463/*
6464 * Like fgets(), but if the file line is too long, it is truncated and the
6465 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006466 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 */
6468 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006469vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470{
6471 char *eof;
6472#define FGETS_SIZE 200
6473 char tbuf[FGETS_SIZE];
6474
6475 buf[size - 2] = NUL;
6476#ifdef USE_CR
6477 eof = fgets_cr((char *)buf, size, fp);
6478#else
6479 eof = fgets((char *)buf, size, fp);
6480#endif
6481 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6482 {
6483 buf[size - 1] = NUL; /* Truncate the line */
6484
6485 /* Now throw away the rest of the line: */
6486 do
6487 {
6488 tbuf[FGETS_SIZE - 2] = NUL;
6489#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006490 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006492 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493#endif
6494 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6495 }
6496 return (eof == NULL);
6497}
6498
6499#if defined(USE_CR) || defined(PROTO)
6500/*
6501 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6502 * Returns TRUE for end-of-file.
6503 * Only used for the Mac, because it's much slower than vim_fgets().
6504 */
6505 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006506tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507{
6508 int i = 0;
6509 int c;
6510 int eof = FALSE;
6511
6512 for (;;)
6513 {
6514 c = fgetc(fp);
6515 if (c == EOF)
6516 {
6517 eof = TRUE;
6518 break;
6519 }
6520 if (c == '\r')
6521 {
6522 /* Always store a NL for end-of-line. */
6523 if (i < size - 1)
6524 buf[i++] = '\n';
6525 c = fgetc(fp);
6526 if (c != '\n') /* Macintosh format: single CR. */
6527 ungetc(c, fp);
6528 break;
6529 }
6530 if (i < size - 1)
6531 buf[i++] = c;
6532 if (c == '\n')
6533 break;
6534 }
6535 buf[i] = NUL;
6536 return eof;
6537}
6538#endif
6539
6540/*
6541 * rename() only works if both files are on the same file system, this
6542 * function will (attempts to?) copy the file across if rename fails -- webb
6543 * Return -1 for failure, 0 for success.
6544 */
6545 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006546vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547{
6548 int fd_in;
6549 int fd_out;
6550 int n;
6551 char *errmsg = NULL;
6552 char *buffer;
6553#ifdef AMIGA
6554 BPTR flock;
6555#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006556 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006557 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006558#ifdef HAVE_ACL
6559 vim_acl_T acl; /* ACL from original file */
6560#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006561 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562
6563 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006564 * When the names are identical, there is nothing to do. When they refer
6565 * to the same file (ignoring case and slash/backslash differences) but
6566 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 */
6568 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006569 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006570 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006571 use_tmp_file = TRUE;
6572 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006573 return 0;
6574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575
6576 /*
6577 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6578 */
6579 if (mch_stat((char *)from, &st) < 0)
6580 return -1;
6581
Bram Moolenaar3576da72008-12-30 15:15:57 +00006582#ifdef UNIX
6583 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006584 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006585
6586 /* It's possible for the source and destination to be the same file.
6587 * This happens when "from" and "to" differ in case and are on a FAT32
6588 * filesystem. In that case go through a temp file name. */
6589 if (mch_stat((char *)to, &st_to) >= 0
6590 && st.st_dev == st_to.st_dev
6591 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006592 use_tmp_file = TRUE;
6593 }
6594#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006595#ifdef WIN3264
6596 {
6597 BY_HANDLE_FILE_INFORMATION info1, info2;
6598
6599 /* It's possible for the source and destination to be the same file.
6600 * In that case go through a temp file name. This makes rename("foo",
6601 * "./foo") a no-op (in a complicated way). */
6602 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6603 && win32_fileinfo(to, &info2) == FILEINFO_OK
6604 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6605 && info1.nFileIndexHigh == info2.nFileIndexHigh
6606 && info1.nFileIndexLow == info2.nFileIndexLow)
6607 use_tmp_file = TRUE;
6608 }
6609#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006610
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006611 if (use_tmp_file)
6612 {
6613 char tempname[MAXPATHL + 1];
6614
6615 /*
6616 * Find a name that doesn't exist and is in the same directory.
6617 * Rename "from" to "tempname" and then rename "tempname" to "to".
6618 */
6619 if (STRLEN(from) >= MAXPATHL - 5)
6620 return -1;
6621 STRCPY(tempname, from);
6622 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006623 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006624 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6625 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006626 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006627 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006628 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006629 if (mch_rename(tempname, (char *)to) == 0)
6630 return 0;
6631 /* Strange, the second step failed. Try moving the
6632 * file back and return failure. */
6633 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006634 return -1;
6635 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006636 /* If it fails for one temp name it will most likely fail
6637 * for any temp name, give up. */
6638 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006639 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006640 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006641 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006642 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006643
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 /*
6645 * Delete the "to" file, this is required on some systems to make the
6646 * mch_rename() work, on other systems it makes sure that we don't have
6647 * two files when the mch_rename() fails.
6648 */
6649
6650#ifdef AMIGA
6651 /*
6652 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6653 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006654 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 * deleting the "from" file (horror!) we lock it during the remove.
6656 *
6657 * When used for making a backup before writing the file: This should not
6658 * happen with ":w", because startscript() should detect this problem and
6659 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6660 * name. This problem does exist with ":w filename", but then the
6661 * original file will be somewhere else so the backup isn't really
6662 * important. If autoscripting is off the rename may fail.
6663 */
6664 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6665#endif
6666 mch_remove(to);
6667#ifdef AMIGA
6668 if (flock)
6669 UnLock(flock);
6670#endif
6671
6672 /*
6673 * First try a normal rename, return if it works.
6674 */
6675 if (mch_rename((char *)from, (char *)to) == 0)
6676 return 0;
6677
6678 /*
6679 * Rename() failed, try copying the file.
6680 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006681 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006682#ifdef HAVE_ACL
6683 /* For systems that support ACL: get the ACL from the original file. */
6684 acl = mch_get_acl(from);
6685#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6687 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006688 {
6689#ifdef HAVE_ACL
6690 mch_free_acl(acl);
6691#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006693 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006694
6695 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006696 fd_out = mch_open((char *)to,
6697 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 if (fd_out == -1)
6699 {
6700 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006701#ifdef HAVE_ACL
6702 mch_free_acl(acl);
6703#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 return -1;
6705 }
6706
6707 buffer = (char *)alloc(BUFSIZE);
6708 if (buffer == NULL)
6709 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006711 close(fd_in);
6712#ifdef HAVE_ACL
6713 mch_free_acl(acl);
6714#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 return -1;
6716 }
6717
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006718 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6719 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 {
6721 errmsg = _("E208: Error writing to \"%s\"");
6722 break;
6723 }
6724
6725 vim_free(buffer);
6726 close(fd_in);
6727 if (close(fd_out) < 0)
6728 errmsg = _("E209: Error closing \"%s\"");
6729 if (n < 0)
6730 {
6731 errmsg = _("E210: Error reading \"%s\"");
6732 to = from;
6733 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006734#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006735 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006736#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006737#ifdef HAVE_ACL
6738 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006739 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006740#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006741#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006742 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006743#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006744 if (errmsg != NULL)
6745 {
6746 EMSG2(errmsg, to);
6747 return -1;
6748 }
6749 mch_remove(from);
6750 return 0;
6751}
6752
6753static int already_warned = FALSE;
6754
6755/*
6756 * Check if any not hidden buffer has been changed.
6757 * Postpone the check if there are characters in the stuff buffer, a global
6758 * command is being executed, a mapping is being executed or an autocommand is
6759 * busy.
6760 * Returns TRUE if some message was written (screen should be redrawn and
6761 * cursor positioned).
6762 */
6763 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006764check_timestamps(
6765 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766{
6767 buf_T *buf;
6768 int didit = 0;
6769 int n;
6770
6771 /* Don't check timestamps while system() or another low-level function may
6772 * cause us to lose and gain focus. */
6773 if (no_check_timestamps > 0)
6774 return FALSE;
6775
6776 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6777 * event and we would keep on checking if the file is steadily growing.
6778 * Do check again after typing something. */
6779 if (focus && did_check_timestamps)
6780 {
6781 need_check_timestamps = TRUE;
6782 return FALSE;
6783 }
6784
6785 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006786 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787 need_check_timestamps = TRUE; /* check later */
6788 else
6789 {
6790 ++no_wait_return;
6791 did_check_timestamps = TRUE;
6792 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006793 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 {
6795 /* Only check buffers in a window. */
6796 if (buf->b_nwindows > 0)
6797 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006798 bufref_T bufref;
6799
6800 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 n = buf_check_timestamp(buf, focus);
6802 if (didit < n)
6803 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006804 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 {
6806 /* Autocommands have removed the buffer, start at the
6807 * first one again. */
6808 buf = firstbuf;
6809 continue;
6810 }
6811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 }
6813 --no_wait_return;
6814 need_check_timestamps = FALSE;
6815 if (need_wait_return && didit == 2)
6816 {
6817 /* make sure msg isn't overwritten */
6818 msg_puts((char_u *)"\n");
6819 out_flush();
6820 }
6821 }
6822 return didit;
6823}
6824
6825/*
6826 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6827 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6828 * empty.
6829 */
6830 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006831move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832{
6833 buf_T *tbuf = curbuf;
6834 int retval = OK;
6835 linenr_T lnum;
6836 char_u *p;
6837
6838 /* Copy the lines in "frombuf" to "tobuf". */
6839 curbuf = tobuf;
6840 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6841 {
6842 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6843 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6844 {
6845 vim_free(p);
6846 retval = FAIL;
6847 break;
6848 }
6849 vim_free(p);
6850 }
6851
6852 /* Delete all the lines in "frombuf". */
6853 if (retval != FAIL)
6854 {
6855 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006856 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6857 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 {
6859 /* Oops! We could try putting back the saved lines, but that
6860 * might fail again... */
6861 retval = FAIL;
6862 break;
6863 }
6864 }
6865
6866 curbuf = tbuf;
6867 return retval;
6868}
6869
6870/*
6871 * Check if buffer "buf" has been changed.
6872 * Also check if the file for a new buffer unexpectedly appeared.
6873 * return 1 if a changed buffer was found.
6874 * return 2 if a message has been displayed.
6875 * return 0 otherwise.
6876 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006878buf_check_timestamp(
6879 buf_T *buf,
6880 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006882 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 int stat_res;
6884 int retval = 0;
6885 char_u *path;
6886 char_u *tbuf;
6887 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006888 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 int helpmesg = FALSE;
6890 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006891 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6893 int can_reload = FALSE;
6894#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006895 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 int orig_mode = buf->b_orig_mode;
6897#ifdef FEAT_GUI
6898 int save_mouse_correct = need_mouse_correct;
6899#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006901 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006902#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006903 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006904#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006905 bufref_T bufref;
6906
6907 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908
6909 /* If there is no file name, the buffer is not loaded, 'buftype' is
6910 * set, we are in the middle of a save or being called recursively: ignore
6911 * this buffer. */
6912 if (buf->b_ffname == NULL
6913 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02006914 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006917#ifdef FEAT_NETBEANS_INTG
6918 || isNetbeansBuffer(buf)
6919#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006920#ifdef FEAT_TERMINAL
6921 || buf->b_term != NULL
6922#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 )
6924 return 0;
6925
6926 if ( !(buf->b_flags & BF_NOTEDITED)
6927 && buf->b_mtime != 0
6928 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6929 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006930 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931#ifdef HAVE_ST_MODE
6932 || (int)st.st_mode != buf->b_orig_mode
6933#else
6934 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6935#endif
6936 ))
6937 {
6938 retval = 1;
6939
Bram Moolenaar386bc822018-07-07 18:34:12 +02006940 // set b_mtime to stop further warnings (e.g., when executing
6941 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 if (stat_res < 0)
6943 {
Bram Moolenaar386bc822018-07-07 18:34:12 +02006944 // When 'autoread' is set we'll check the file again to see if it
6945 // re-appears.
6946 buf->b_mtime = buf->b_p_ar;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 buf->b_orig_size = 0;
6948 buf->b_orig_mode = 0;
6949 }
6950 else
6951 buf_store_time(buf, &st, buf->b_ffname);
6952
6953 /* Don't do anything for a directory. Might contain the file
6954 * explorer. */
6955 if (mch_isdir(buf->b_fname))
6956 ;
6957
6958 /*
6959 * If 'autoread' is set, the buffer has no changes and the file still
6960 * exists, reload the buffer. Use the buffer-local option value if it
6961 * was set, the global option value otherwise.
6962 */
6963 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6964 && !bufIsChanged(buf) && stat_res >= 0)
6965 reload = TRUE;
6966 else
6967 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006968 if (stat_res < 0)
6969 reason = "deleted";
6970 else if (bufIsChanged(buf))
6971 reason = "conflict";
6972 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6973 reason = "changed";
6974 else if (orig_mode != buf->b_orig_mode)
6975 reason = "mode";
6976 else
6977 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978
6979 /*
6980 * Only give the warning if there are no FileChangedShell
6981 * autocommands.
6982 * Avoid being called recursively by setting "busy".
6983 */
6984 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006985#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006986 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6987 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006988#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006989 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6991 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006992 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 busy = FALSE;
6994 if (n)
6995 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006996 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006998#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006999 s = get_vim_var_str(VV_FCS_CHOICE);
7000 if (STRCMP(s, "reload") == 0 && *reason != 'd')
7001 reload = TRUE;
7002 else if (STRCMP(s, "ask") == 0)
7003 n = FALSE;
7004 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007005#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007006 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007007 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007008 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007010 if (*reason == 'd')
7011 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 else
7013 {
7014 helpmesg = TRUE;
7015#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7016 can_reload = TRUE;
7017#endif
7018 /*
7019 * Check if the file contents really changed to avoid
7020 * giving a warning when only the timestamp was set (e.g.,
7021 * checked out of CVS). Always warn when the buffer was
7022 * changed.
7023 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007024 if (reason[2] == 'n')
7025 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007027 mesg2 = _("See \":help W12\" for more info.");
7028 }
7029 else if (reason[1] == 'h')
7030 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007032 mesg2 = _("See \":help W11\" for more info.");
7033 }
7034 else if (*reason == 'm')
7035 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007037 mesg2 = _("See \":help W16\" for more info.");
7038 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007039 else
7040 /* Only timestamp changed, store it to avoid a warning
7041 * in check_mtime() later. */
7042 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 }
7044 }
7045 }
7046
7047 }
7048 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7049 && vim_fexists(buf->b_ffname))
7050 {
7051 retval = 1;
7052 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7053 buf->b_flags |= BF_NEW_W;
7054#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7055 can_reload = TRUE;
7056#endif
7057 }
7058
7059 if (mesg != NULL)
7060 {
7061 path = home_replace_save(buf, buf->b_fname);
7062 if (path != NULL)
7063 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007064 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065 mesg2 = "";
7066 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7067 + STRLEN(mesg2) + 2));
7068 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007069#ifdef FEAT_EVAL
7070 /* Set warningmsg here, before the unimportant and output-specific
7071 * mesg2 has been appended. */
7072 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7073#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7075 if (can_reload)
7076 {
7077 if (*mesg2 != NUL)
7078 {
7079 STRCAT(tbuf, "\n");
7080 STRCAT(tbuf, mesg2);
7081 }
7082 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007083 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 reload = TRUE;
7085 }
7086 else
7087#endif
7088 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7089 {
7090 if (*mesg2 != NUL)
7091 {
7092 STRCAT(tbuf, "; ");
7093 STRCAT(tbuf, mesg2);
7094 }
7095 EMSG(tbuf);
7096 retval = 2;
7097 }
7098 else
7099 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 {
7102 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007103 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 if (*mesg2 != NUL)
7105 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007106 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 msg_clr_eos();
7108 (void)msg_end();
7109 if (emsg_silent == 0)
7110 {
7111 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007112#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007114#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115 /* give the user some time to think about it */
7116 ui_delay(1000L, TRUE);
7117
7118 /* don't redraw and erase the message */
7119 redraw_cmdline = FALSE;
7120 }
7121 }
7122 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123 }
7124
7125 vim_free(path);
7126 vim_free(tbuf);
7127 }
7128 }
7129
7130 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007131 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007132 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007133 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007134#ifdef FEAT_PERSISTENT_UNDO
7135 if (buf->b_p_udf && buf->b_ffname != NULL)
7136 {
7137 char_u hash[UNDO_HASH_SIZE];
7138 buf_T *save_curbuf = curbuf;
7139
7140 /* Any existing undo file is unusable, write it now. */
7141 curbuf = buf;
7142 u_compute_hash(hash);
7143 u_write_undo(NULL, FALSE, buf, hash);
7144 curbuf = save_curbuf;
7145 }
7146#endif
7147 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007149 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007150 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007151 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7152 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153#ifdef FEAT_GUI
7154 /* restore this in case an autocommand has set it; it would break
7155 * 'mousefocus' */
7156 need_mouse_correct = save_mouse_correct;
7157#endif
7158
7159 return retval;
7160}
7161
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007162/*
7163 * Reload a buffer that is already loaded.
7164 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007165 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7166 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007167 */
7168 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007169buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007170{
7171 exarg_T ea;
7172 pos_T old_cursor;
7173 linenr_T old_topline;
7174 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007175 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007176 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007177 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007178 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007179 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007180
7181 /* set curwin/curbuf for "buf" and save some things */
7182 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007183
7184 /* We only want to read the text from the file, not reset the syntax
7185 * highlighting, clear marks, diff status, etc. Force the fileformat
7186 * and encoding to be the same. */
7187 if (prep_exarg(&ea, buf) == OK)
7188 {
7189 old_cursor = curwin->w_cursor;
7190 old_topline = curwin->w_topline;
7191
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007192 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007193 {
7194 /* Save all the text, so that the reload can be undone.
7195 * Sync first so that this is a separate undo-able action. */
7196 u_sync(FALSE);
7197 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7198 flags |= READ_KEEP_UNDO;
7199 }
7200
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007201 /*
7202 * To behave like when a new file is edited (matters for
7203 * BufReadPost autocommands) we first need to delete the current
7204 * buffer contents. But if reading the file fails we should keep
7205 * the old contents. Can't use memory only, the file might be
7206 * too big. Use a hidden buffer to move the buffer contents to.
7207 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007208 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007209 savebuf = NULL;
7210 else
7211 {
7212 /* Allocate a buffer without putting it in the buffer list. */
7213 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007214 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007215 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216 {
7217 /* Open the memline. */
7218 curbuf = savebuf;
7219 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007220 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007221 curbuf = buf;
7222 curwin->w_buffer = buf;
7223 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007224 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 || move_lines(buf, savebuf) == FAIL)
7226 {
7227 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7228 buf->b_fname);
7229 saved = FAIL;
7230 }
7231 }
7232
7233 if (saved == OK)
7234 {
7235 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007236 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007237 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7238 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007239 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007240 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007241#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007242 if (!aborting())
7243#endif
7244 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007245 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007246 {
7247 /* Put the text back from the save buffer. First
7248 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007249 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007250 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007251 break;
7252 (void)move_lines(savebuf, buf);
7253 }
7254 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007255 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007256 {
7257 /* Mark the buffer as unmodified and free undo info. */
7258 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007259 if ((flags & READ_KEEP_UNDO) == 0)
7260 {
7261 u_blockfree(buf);
7262 u_clearall(buf);
7263 }
7264 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007265 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007266 /* Mark all undo states as changed. */
7267 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007268 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007269 }
7270 }
7271 vim_free(ea.cmd);
7272
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007273 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007274 wipe_buffer(savebuf, FALSE);
7275
7276#ifdef FEAT_DIFF
7277 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007278 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007279#endif
7280
7281 /* Restore the topline and cursor position and check it (lines may
7282 * have been removed). */
7283 if (old_topline > curbuf->b_ml.ml_line_count)
7284 curwin->w_topline = curbuf->b_ml.ml_line_count;
7285 else
7286 curwin->w_topline = old_topline;
7287 curwin->w_cursor = old_cursor;
7288 check_cursor();
7289 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007290 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007291#ifdef FEAT_FOLDING
7292 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007293 win_T *wp;
7294 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007295
7296 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007297 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007298 if (wp->w_buffer == curwin->w_buffer
7299 && !foldmethodIsManual(wp))
7300 foldUpdateAll(wp);
7301 }
7302#endif
7303 /* If the mode didn't change and 'readonly' was set, keep the old
7304 * value; the user probably used the ":view" command. But don't
7305 * reset it, might have had a read error. */
7306 if (orig_mode == curbuf->b_orig_mode)
7307 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007308
7309 /* Modelines must override settings done by autocommands. */
7310 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007311 }
7312
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007313 /* restore curwin/curbuf and a few other things */
7314 aucmd_restbuf(&aco);
7315 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007316}
7317
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007319buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007320{
7321 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007322 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323#ifdef HAVE_ST_MODE
7324 buf->b_orig_mode = (int)st->st_mode;
7325#else
7326 buf->b_orig_mode = mch_getperm(fname);
7327#endif
7328}
7329
7330/*
7331 * Adjust the line with missing eol, used for the next write.
7332 * Used for do_filter(), when the input lines for the filter are deleted.
7333 */
7334 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007335write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007337 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7338 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007339}
7340
Bram Moolenaarda440d22016-01-16 21:27:23 +01007341#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7342/*
7343 * Delete "name" and everything in it, recursively.
7344 * return 0 for succes, -1 if some file was not deleted.
7345 */
7346 int
7347delete_recursive(char_u *name)
7348{
7349 int result = 0;
7350 char_u **files;
7351 int file_count;
7352 int i;
7353 char_u *exp;
7354
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007355 /* A symbolic link to a directory itself is deleted, not the directory it
7356 * points to. */
7357 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007358# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007359 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007360# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007361 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007362# endif
7363 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007364 {
7365 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7366 exp = vim_strsave(NameBuff);
7367 if (exp == NULL)
7368 return -1;
7369 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007370 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007371 {
7372 for (i = 0; i < file_count; ++i)
7373 if (delete_recursive(files[i]) != 0)
7374 result = -1;
7375 FreeWild(file_count, files);
7376 }
7377 else
7378 result = -1;
7379 vim_free(exp);
7380 (void)mch_rmdir(name);
7381 }
7382 else
7383 result = mch_remove(name) == 0 ? 0 : -1;
7384
7385 return result;
7386}
7387#endif
7388
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389#if defined(TEMPDIRNAMES) || defined(PROTO)
7390static long temp_count = 0; /* Temp filename counter. */
7391
7392/*
7393 * Delete the temp directory and all files it contains.
7394 */
7395 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007396vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007398 if (vim_tempdir != NULL)
7399 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007400 /* remove the trailing path separator */
7401 gettail(vim_tempdir)[-1] = NUL;
7402 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007403 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404 }
7405}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406
7407/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007408 * Directory "tempdir" was created. Expand this name to a full path and put
7409 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7410 * "tempdir" must be no longer than MAXPATHL.
7411 */
7412 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007413vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007414{
7415 char_u *buf;
7416
7417 buf = alloc((unsigned)MAXPATHL + 2);
7418 if (buf != NULL)
7419 {
7420 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7421 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007422 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007423 vim_tempdir = vim_strsave(buf);
7424 vim_free(buf);
7425 }
7426}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007427#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428
7429/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 * vim_tempname(): Return a unique name that can be used for a temp file.
7431 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007432 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7433 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434 *
7435 * The returned pointer is to allocated memory.
7436 * The returned pointer is NULL if no valid name was found.
7437 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007439vim_tempname(
7440 int extra_char UNUSED, /* char to use in the name instead of '?' */
7441 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442{
7443#ifdef USE_TMPNAM
7444 char_u itmp[L_tmpnam]; /* use tmpnam() */
7445#else
7446 char_u itmp[TEMPNAMELEN];
7447#endif
7448
7449#ifdef TEMPDIRNAMES
7450 static char *(tempdirs[]) = {TEMPDIRNAMES};
7451 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007453 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454# endif
7455
7456 /*
7457 * This will create a directory for private use by this instance of Vim.
7458 * This is done once, and the same directory is used for all temp files.
7459 * This method avoids security problems because of symlink attacks et al.
7460 * It's also a bit faster, because we only need to check for an existing
7461 * file when creating the directory and not for each temp file.
7462 */
7463 if (vim_tempdir == NULL)
7464 {
7465 /*
7466 * Try the entries in TEMPDIRNAMES to create the temp directory.
7467 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007468 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007470# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007471 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007472 long nr;
7473 long off;
7474# endif
7475
Bram Moolenaare1a61992015-12-03 21:02:27 +01007476 /* Expand $TMP, leave room for "/v1100000/999999999".
7477 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007479 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007481 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007482 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483
Bram Moolenaareaf03392009-11-17 11:08:52 +00007484# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007485 {
7486# if defined(UNIX) || defined(VMS)
7487 /* Make sure the umask doesn't remove the executable bit.
7488 * "repl" has been reported to use "177". */
7489 mode_t umask_save = umask(077);
7490# endif
7491 /* Leave room for filename */
7492 STRCAT(itmp, "vXXXXXX");
7493 if (mkdtemp((char *)itmp) != NULL)
7494 vim_settempdir(itmp);
7495# if defined(UNIX) || defined(VMS)
7496 (void)umask(umask_save);
7497# endif
7498 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007499# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 /* Get an arbitrary number of up to 6 digits. When it's
7501 * unlikely that it already exists it will be faster,
7502 * otherwise it doesn't matter. The use of mkdir() avoids any
7503 * security problems because of the predictable number. */
7504 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007505 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506
7507 /* Try up to 10000 different values until we find a name that
7508 * doesn't exist. */
7509 for (off = 0; off < 10000L; ++off)
7510 {
7511 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007512# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515
Bram Moolenaareaf03392009-11-17 11:08:52 +00007516 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7517# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 /* If mkdir() does not set errno to EEXIST, check for
7519 * existing file here. There is a race condition then,
7520 * although it's fail-safe. */
7521 if (mch_stat((char *)itmp, &st) >= 0)
7522 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007523# endif
7524# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 /* Make sure the umask doesn't remove the executable bit.
7526 * "repl" has been reported to use "177". */
7527 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007530# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007531 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007532# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 if (r == 0)
7534 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007535 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 break;
7537 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007538# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539 /* If the mkdir() didn't fail because the file/dir exists,
7540 * we probably can't create any dir here, try another
7541 * place. */
7542 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007543# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544 break;
7545 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007546# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547 if (vim_tempdir != NULL)
7548 break;
7549 }
7550 }
7551 }
7552
7553 if (vim_tempdir != NULL)
7554 {
7555 /* There is no need to check if the file exists, because we own the
7556 * directory and nobody else creates a file in it. */
7557 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7558 return vim_strsave(itmp);
7559 }
7560
7561 return NULL;
7562
7563#else /* TEMPDIRNAMES */
7564
7565# ifdef WIN3264
7566 char szTempFile[_MAX_PATH + 1];
7567 char buf4[4];
7568 char_u *retval;
7569 char_u *p;
7570
7571 STRCPY(itmp, "");
7572 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007573 {
7574 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7575 szTempFile[1] = NUL;
7576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 strcpy(buf4, "VIM");
7578 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007579 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007580 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007581 if (!keep)
7582 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007583 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007584
7585 /* Backslashes in a temp file name cause problems when filtering with
7586 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7587 * didn't set 'shellslash'. */
7588 retval = vim_strsave(itmp);
7589 if (*p_shcf == '-' || p_ssl)
7590 for (p = retval; *p; ++p)
7591 if (*p == '\\')
7592 *p = '/';
7593 return retval;
7594
7595# else /* WIN3264 */
7596
7597# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007598 char_u *p;
7599
Bram Moolenaar071d4272004-06-13 20:20:40 +00007600 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007601 p = tmpnam((char *)itmp);
7602 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603 return NULL;
7604# else
7605 char_u *p;
7606
7607# ifdef VMS_TEMPNAM
7608 /* mktemp() is not working on VMS. It seems to be
7609 * a do-nothing function. Therefore we use tempnam().
7610 */
7611 sprintf((char *)itmp, "VIM%c", extra_char);
7612 p = (char_u *)tempnam("tmp:", (char *)itmp);
7613 if (p != NULL)
7614 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007615 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 * and VIM will then be unable to find the file later */
7617 STRCPY(itmp, p);
7618 STRCAT(itmp, ".txt");
7619 free(p);
7620 }
7621 else
7622 return NULL;
7623# else
7624 STRCPY(itmp, TEMPNAME);
7625 if ((p = vim_strchr(itmp, '?')) != NULL)
7626 *p = extra_char;
7627 if (mktemp((char *)itmp) == NULL)
7628 return NULL;
7629# endif
7630# endif
7631
7632 return vim_strsave(itmp);
7633# endif /* WIN3264 */
7634#endif /* TEMPDIRNAMES */
7635}
7636
7637#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7638/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007639 * Convert all backslashes in fname to forward slashes in-place, unless when
7640 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641 */
7642 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007643forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644{
7645 char_u *p;
7646
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007647 if (path_with_url(fname))
7648 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 for (p = fname; *p != NUL; ++p)
7650# ifdef FEAT_MBYTE
7651 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007652 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653 ++p;
7654 else
7655# endif
7656 if (*p == '\\')
7657 *p = '/';
7658}
7659#endif
7660
7661
7662/*
7663 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 */
7665
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666/*
7667 * The autocommands are stored in a list for each event.
7668 * Autocommands for the same pattern, that are consecutive, are joined
7669 * together, to avoid having to match the pattern too often.
7670 * The result is an array of Autopat lists, which point to AutoCmd lists:
7671 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007672 * last_autopat[0] -----------------------------+
7673 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7675 * Autopat.cmds Autopat.cmds
7676 * | |
7677 * V V
7678 * AutoCmd.next AutoCmd.next
7679 * | |
7680 * V V
7681 * AutoCmd.next NULL
7682 * |
7683 * V
7684 * NULL
7685 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007686 * last_autopat[1] --------+
7687 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007688 * first_autopat[1] --> Autopat.next --> NULL
7689 * Autopat.cmds
7690 * |
7691 * V
7692 * AutoCmd.next
7693 * |
7694 * V
7695 * NULL
7696 * etc.
7697 *
7698 * The order of AutoCmds is important, this is the order in which they were
7699 * defined and will have to be executed.
7700 */
7701typedef struct AutoCmd
7702{
7703 char_u *cmd; /* The command to be executed (NULL
7704 when command has been removed) */
7705 char nested; /* If autocommands nest here */
7706 char last; /* last command in list */
7707#ifdef FEAT_EVAL
7708 scid_T scriptID; /* script ID where defined */
7709#endif
7710 struct AutoCmd *next; /* Next AutoCmd in list */
7711} AutoCmd;
7712
7713typedef struct AutoPat
7714{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007715 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7716 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 char_u *pat; /* pattern as typed (NULL when pattern
7718 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007719 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007721 int group; /* group ID */
7722 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007723 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007724 char allow_dirs; /* Pattern may match whole path */
7725 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726} AutoPat;
7727
7728static struct event_name
7729{
7730 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007731 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732} event_names[] =
7733{
7734 {"BufAdd", EVENT_BUFADD},
7735 {"BufCreate", EVENT_BUFADD},
7736 {"BufDelete", EVENT_BUFDELETE},
7737 {"BufEnter", EVENT_BUFENTER},
7738 {"BufFilePost", EVENT_BUFFILEPOST},
7739 {"BufFilePre", EVENT_BUFFILEPRE},
7740 {"BufHidden", EVENT_BUFHIDDEN},
7741 {"BufLeave", EVENT_BUFLEAVE},
7742 {"BufNew", EVENT_BUFNEW},
7743 {"BufNewFile", EVENT_BUFNEWFILE},
7744 {"BufRead", EVENT_BUFREADPOST},
7745 {"BufReadCmd", EVENT_BUFREADCMD},
7746 {"BufReadPost", EVENT_BUFREADPOST},
7747 {"BufReadPre", EVENT_BUFREADPRE},
7748 {"BufUnload", EVENT_BUFUNLOAD},
7749 {"BufWinEnter", EVENT_BUFWINENTER},
7750 {"BufWinLeave", EVENT_BUFWINLEAVE},
7751 {"BufWipeout", EVENT_BUFWIPEOUT},
7752 {"BufWrite", EVENT_BUFWRITEPRE},
7753 {"BufWritePost", EVENT_BUFWRITEPOST},
7754 {"BufWritePre", EVENT_BUFWRITEPRE},
7755 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007756 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007757 {"CmdlineEnter", EVENT_CMDLINEENTER},
7758 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759 {"CmdwinEnter", EVENT_CMDWINENTER},
7760 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007761 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007762 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar60a68362018-04-30 15:40:48 +02007763 {"ColorSchemePre", EVENT_COLORSCHEMEPRE},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007764 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007765 {"CursorHold", EVENT_CURSORHOLD},
7766 {"CursorHoldI", EVENT_CURSORHOLDI},
7767 {"CursorMoved", EVENT_CURSORMOVED},
7768 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007769 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007771 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7774 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7775 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7776 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007777 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 {"FileChangedRO", EVENT_FILECHANGEDRO},
7779 {"FileReadPost", EVENT_FILEREADPOST},
7780 {"FileReadPre", EVENT_FILEREADPRE},
7781 {"FileReadCmd", EVENT_FILEREADCMD},
7782 {"FileType", EVENT_FILETYPE},
7783 {"FileWritePost", EVENT_FILEWRITEPOST},
7784 {"FileWritePre", EVENT_FILEWRITEPRE},
7785 {"FileWriteCmd", EVENT_FILEWRITECMD},
7786 {"FilterReadPost", EVENT_FILTERREADPOST},
7787 {"FilterReadPre", EVENT_FILTERREADPRE},
7788 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7789 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7790 {"FocusGained", EVENT_FOCUSGAINED},
7791 {"FocusLost", EVENT_FOCUSLOST},
7792 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7793 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007794 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007795 {"InsertChange", EVENT_INSERTCHANGE},
7796 {"InsertEnter", EVENT_INSERTENTER},
7797 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007798 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007799 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007800 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007801 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7802 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007803 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007805 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007806 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7807 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007808 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007809 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007810 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 {"StdinReadPost", EVENT_STDINREADPOST},
7812 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007813 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007814 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007815 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007816 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007817 {"TabEnter", EVENT_TABENTER},
7818 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007819 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007820 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007822 {"TextChanged", EVENT_TEXTCHANGED},
7823 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007824 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007825 {"User", EVENT_USER},
7826 {"VimEnter", EVENT_VIMENTER},
7827 {"VimLeave", EVENT_VIMLEAVE},
7828 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007829 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830 {"WinEnter", EVENT_WINENTER},
7831 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007832 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007833 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007834 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835};
7836
7837static AutoPat *first_autopat[NUM_EVENTS] =
7838{
7839 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7840 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7841 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7842 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007843 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007844 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007845};
7846
Bram Moolenaar462455e2017-11-10 21:53:11 +01007847static AutoPat *last_autopat[NUM_EVENTS] =
7848{
7849 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7850 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7851 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7852 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7853 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7854 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7855};
7856
Bram Moolenaar071d4272004-06-13 20:20:40 +00007857/*
7858 * struct used to keep status while executing autocommands for an event.
7859 */
7860typedef struct AutoPatCmd
7861{
7862 AutoPat *curpat; /* next AutoPat to examine */
7863 AutoCmd *nextcmd; /* next AutoCmd to execute */
7864 int group; /* group being used */
7865 char_u *fname; /* fname to match with */
7866 char_u *sfname; /* sfname to match with */
7867 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007868 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007869 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7870 buf is deleted */
7871 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872} AutoPatCmd;
7873
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007874static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007875
Bram Moolenaar071d4272004-06-13 20:20:40 +00007876/*
7877 * augroups stores a list of autocmd group names.
7878 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007879static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007880#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007881/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007882static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883
7884/*
7885 * The ID of the current group. Group 0 is the default one.
7886 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887static int current_augroup = AUGROUP_DEFAULT;
7888
7889static int au_need_clean = FALSE; /* need to delete marked patterns */
7890
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007891static void show_autocmd(AutoPat *ap, event_T event);
7892static void au_remove_pat(AutoPat *ap);
7893static void au_remove_cmds(AutoPat *ap);
7894static void au_cleanup(void);
7895static int au_new_group(char_u *name);
7896static void au_del_group(char_u *name);
7897static event_T event_name2nr(char_u *start, char_u **end);
7898static char_u *event_nr2name(event_T event);
7899static char_u *find_end_event(char_u *arg, int have_group);
7900static int event_ignored(event_T event);
7901static int au_get_grouparg(char_u **argp);
7902static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7903static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7904static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007905static 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 +00007906
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007907
Bram Moolenaar754b5602006-02-09 23:53:20 +00007908static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007910static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007912 static char_u *
7913get_deleted_augroup(void)
7914{
7915 if (deleted_augroup == NULL)
7916 deleted_augroup = (char_u *)_("--Deleted--");
7917 return deleted_augroup;
7918}
7919
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920/*
7921 * Show the autocommands for one AutoPat.
7922 */
7923 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007924show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007925{
7926 AutoCmd *ac;
7927
7928 /* Check for "got_int" (here and at various places below), which is set
7929 * when "q" has been hit for the "--more--" prompt */
7930 if (got_int)
7931 return;
7932 if (ap->pat == NULL) /* pattern has been removed */
7933 return;
7934
7935 msg_putchar('\n');
7936 if (got_int)
7937 return;
7938 if (event != last_event || ap->group != last_group)
7939 {
7940 if (ap->group != AUGROUP_DEFAULT)
7941 {
7942 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007943 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007944 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007945 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007946 msg_puts((char_u *)" ");
7947 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007948 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949 last_event = event;
7950 last_group = ap->group;
7951 msg_putchar('\n');
7952 if (got_int)
7953 return;
7954 }
7955 msg_col = 4;
7956 msg_outtrans(ap->pat);
7957
7958 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7959 {
7960 if (ac->cmd != NULL) /* skip removed commands */
7961 {
7962 if (msg_col >= 14)
7963 msg_putchar('\n');
7964 msg_col = 14;
7965 if (got_int)
7966 return;
7967 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007968#ifdef FEAT_EVAL
7969 if (p_verbose > 0)
7970 last_set_msg(ac->scriptID);
7971#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007972 if (got_int)
7973 return;
7974 if (ac->next != NULL)
7975 {
7976 msg_putchar('\n');
7977 if (got_int)
7978 return;
7979 }
7980 }
7981 }
7982}
7983
7984/*
7985 * Mark an autocommand pattern for deletion.
7986 */
7987 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007988au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007989{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007990 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007991 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992 au_need_clean = TRUE;
7993}
7994
7995/*
7996 * Mark all commands for a pattern for deletion.
7997 */
7998 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007999au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008000{
8001 AutoCmd *ac;
8002
8003 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01008004 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008005 au_need_clean = TRUE;
8006}
8007
8008/*
8009 * Cleanup autocommands and patterns that have been deleted.
8010 * This is only done when not executing autocommands.
8011 */
8012 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008013au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008014{
8015 AutoPat *ap, **prev_ap;
8016 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008017 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008018
8019 if (autocmd_busy || !au_need_clean)
8020 return;
8021
8022 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008023 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8024 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008025 {
8026 /* loop over all autocommand patterns */
8027 prev_ap = &(first_autopat[(int)event]);
8028 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8029 {
8030 /* loop over all commands for this pattern */
8031 prev_ac = &(ap->cmds);
8032 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8033 {
8034 /* remove the command if the pattern is to be deleted or when
8035 * the command has been marked for deletion */
8036 if (ap->pat == NULL || ac->cmd == NULL)
8037 {
8038 *prev_ac = ac->next;
8039 vim_free(ac->cmd);
8040 vim_free(ac);
8041 }
8042 else
8043 prev_ac = &(ac->next);
8044 }
8045
8046 /* remove the pattern if it has been marked for deletion */
8047 if (ap->pat == NULL)
8048 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008049 if (ap->next == NULL)
8050 {
8051 if (prev_ap == &(first_autopat[(int)event]))
8052 last_autopat[(int)event] = NULL;
8053 else
8054 /* this depends on the "next" field being the first in
8055 * the struct */
8056 last_autopat[(int)event] = (AutoPat *)prev_ap;
8057 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008058 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008059 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008060 vim_free(ap);
8061 }
8062 else
8063 prev_ap = &(ap->next);
8064 }
8065 }
8066
8067 au_need_clean = FALSE;
8068}
8069
8070/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008071 * Called when buffer is freed, to remove/invalidate related buffer-local
8072 * autocmds.
8073 */
8074 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008075aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008076{
8077 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008078 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008079 AutoPatCmd *apc;
8080
8081 /* invalidate currently executing autocommands */
8082 for (apc = active_apc_list; apc; apc = apc->next)
8083 if (buf->b_fnum == apc->arg_bufnr)
8084 apc->arg_bufnr = 0;
8085
8086 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008087 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8088 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008089 /* loop over all autocommand patterns */
8090 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8091 if (ap->buflocal_nr == buf->b_fnum)
8092 {
8093 au_remove_pat(ap);
8094 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008095 {
8096 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008097 smsg((char_u *)
8098 _("auto-removing autocommand: %s <buffer=%d>"),
8099 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008100 verbose_leave();
8101 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008102 }
8103 au_cleanup();
8104}
8105
8106/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008107 * Add an autocmd group name.
8108 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8109 */
8110 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008111au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008112{
8113 int i;
8114
8115 i = au_find_group(name);
8116 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8117 {
8118 /* First try using a free entry. */
8119 for (i = 0; i < augroups.ga_len; ++i)
8120 if (AUGROUP_NAME(i) == NULL)
8121 break;
8122 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8123 return AUGROUP_ERROR;
8124
8125 AUGROUP_NAME(i) = vim_strsave(name);
8126 if (AUGROUP_NAME(i) == NULL)
8127 return AUGROUP_ERROR;
8128 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008129 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008130 }
8131
8132 return i;
8133}
8134
8135 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008136au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008137{
8138 int i;
8139
8140 i = au_find_group(name);
8141 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8142 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008143 else if (i == current_augroup)
8144 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008145 else
8146 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008147 event_T event;
8148 AutoPat *ap;
8149 int in_use = FALSE;
8150
8151 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8152 event = (event_T)((int)event + 1))
8153 {
8154 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008155 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008156 {
8157 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8158 in_use = TRUE;
8159 event = NUM_EVENTS;
8160 break;
8161 }
8162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008163 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008164 if (in_use)
8165 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008166 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008167 }
8168 else
8169 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008170 }
8171}
8172
8173/*
8174 * Find the ID of an autocmd group name.
8175 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8176 */
8177 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008178au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179{
8180 int i;
8181
8182 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008183 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008184 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008185 return i;
8186 return AUGROUP_ERROR;
8187}
8188
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008189/*
8190 * Return TRUE if augroup "name" exists.
8191 */
8192 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008193au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008194{
8195 return au_find_group(name) != AUGROUP_ERROR;
8196}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008197
Bram Moolenaar071d4272004-06-13 20:20:40 +00008198/*
8199 * ":augroup {name}".
8200 */
8201 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008202do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008203{
8204 int i;
8205
8206 if (del_group)
8207 {
8208 if (*arg == NUL)
8209 EMSG(_(e_argreq));
8210 else
8211 au_del_group(arg);
8212 }
8213 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8214 current_augroup = AUGROUP_DEFAULT;
8215 else if (*arg) /* ":aug xxx": switch to group xxx */
8216 {
8217 i = au_new_group(arg);
8218 if (i != AUGROUP_ERROR)
8219 current_augroup = i;
8220 }
8221 else /* ":aug": list the group names */
8222 {
8223 msg_start();
8224 for (i = 0; i < augroups.ga_len; ++i)
8225 {
8226 if (AUGROUP_NAME(i) != NULL)
8227 {
8228 msg_puts(AUGROUP_NAME(i));
8229 msg_puts((char_u *)" ");
8230 }
8231 }
8232 msg_clr_eos();
8233 msg_end();
8234 }
8235}
8236
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008237#if defined(EXITFREE) || defined(PROTO)
8238 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008239free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008240{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008241 int i;
8242 char_u *s;
8243
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008244 for (current_augroup = -1; current_augroup < augroups.ga_len;
8245 ++current_augroup)
8246 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008247
8248 for (i = 0; i < augroups.ga_len; ++i)
8249 {
8250 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008251 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008252 vim_free(s);
8253 }
8254 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008255}
8256#endif
8257
Bram Moolenaar071d4272004-06-13 20:20:40 +00008258/*
8259 * Return the event number for event name "start".
8260 * Return NUM_EVENTS if the event name was not found.
8261 * Return a pointer to the next event name in "end".
8262 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008263 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008264event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008265{
8266 char_u *p;
8267 int i;
8268 int len;
8269
Bram Moolenaare99e8442016-07-26 20:43:40 +02008270 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008271 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272 ;
8273 for (i = 0; event_names[i].name != NULL; ++i)
8274 {
8275 len = (int)STRLEN(event_names[i].name);
8276 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8277 break;
8278 }
8279 if (*p == ',')
8280 ++p;
8281 *end = p;
8282 if (event_names[i].name == NULL)
8283 return NUM_EVENTS;
8284 return event_names[i].event;
8285}
8286
8287/*
8288 * Return the name for event "event".
8289 */
8290 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008291event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008292{
8293 int i;
8294
8295 for (i = 0; event_names[i].name != NULL; ++i)
8296 if (event_names[i].event == event)
8297 return (char_u *)event_names[i].name;
8298 return (char_u *)"Unknown";
8299}
8300
8301/*
8302 * Scan over the events. "*" stands for all events.
8303 */
8304 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008305find_end_event(
8306 char_u *arg,
8307 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308{
8309 char_u *pat;
8310 char_u *p;
8311
8312 if (*arg == '*')
8313 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008314 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008315 {
8316 EMSG2(_("E215: Illegal character after *: %s"), arg);
8317 return NULL;
8318 }
8319 pat = arg + 1;
8320 }
8321 else
8322 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008323 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324 {
8325 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8326 {
8327 if (have_group)
8328 EMSG2(_("E216: No such event: %s"), pat);
8329 else
8330 EMSG2(_("E216: No such group or event: %s"), pat);
8331 return NULL;
8332 }
8333 }
8334 }
8335 return pat;
8336}
8337
8338/*
8339 * Return TRUE if "event" is included in 'eventignore'.
8340 */
8341 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008342event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008343{
8344 char_u *p = p_ei;
8345
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008346 while (*p != NUL)
8347 {
8348 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8349 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008350 if (event_name2nr(p, &p) == event)
8351 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008353
8354 return FALSE;
8355}
8356
8357/*
8358 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8359 */
8360 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008361check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008362{
8363 char_u *p = p_ei;
8364
Bram Moolenaar071d4272004-06-13 20:20:40 +00008365 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008366 {
8367 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8368 {
8369 p += 3;
8370 if (*p == ',')
8371 ++p;
8372 }
8373 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008374 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008376
8377 return OK;
8378}
8379
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008380# if defined(FEAT_SYN_HL) || defined(PROTO)
8381
8382/*
8383 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8384 * buffer loaded into the window. "what" must start with a comma.
8385 * Returns the old value of 'eventignore' in allocated memory.
8386 */
8387 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008388au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008389{
8390 char_u *new_ei;
8391 char_u *save_ei;
8392
8393 save_ei = vim_strsave(p_ei);
8394 if (save_ei != NULL)
8395 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008396 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008397 if (new_ei != NULL)
8398 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008399 if (*what == ',' && *p_ei == NUL)
8400 STRCPY(new_ei, what + 1);
8401 else
8402 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008403 set_string_option_direct((char_u *)"ei", -1, new_ei,
8404 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008405 vim_free(new_ei);
8406 }
8407 }
8408 return save_ei;
8409}
8410
8411 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008412au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008413{
8414 if (old_ei != NULL)
8415 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008416 set_string_option_direct((char_u *)"ei", -1, old_ei,
8417 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008418 vim_free(old_ei);
8419 }
8420}
8421# endif /* FEAT_SYN_HL */
8422
Bram Moolenaar071d4272004-06-13 20:20:40 +00008423/*
8424 * do_autocmd() -- implements the :autocmd command. Can be used in the
8425 * following ways:
8426 *
8427 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8428 * will be automatically executed for <event>
8429 * when editing a file matching <pat>, in
8430 * the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008431 * :autocmd <event> <pat> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008432 * <event> and <pat>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008433 * :autocmd <event> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008434 * <event>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008435 * :autocmd Show all autocommands.
8436 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437 * <event> and <pat>, and add the command
8438 * <cmd>, for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008439 * :autocmd! <event> <pat> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 * <event> and <pat> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008441 * :autocmd! <event> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008442 * <event> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008443 * :autocmd! Remove ALL autocommands for the current
Bram Moolenaar071d4272004-06-13 20:20:40 +00008444 * group.
8445 *
8446 * Multiple events and patterns may be given separated by commas. Here are
8447 * some examples:
8448 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8449 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8450 *
8451 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008452 *
8453 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008454 */
8455 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008456do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008457{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008458 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008459 char_u *pat;
8460 char_u *envpat = NULL;
8461 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008462 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008463 int need_free = FALSE;
8464 int nested = FALSE;
8465 int group;
8466
Bram Moolenaare99e8442016-07-26 20:43:40 +02008467 if (*arg == '|')
8468 {
8469 arg = (char_u *)"";
8470 group = AUGROUP_ALL; /* no argument, use all groups */
8471 }
8472 else
8473 {
8474 /*
8475 * Check for a legal group name. If not, use AUGROUP_ALL.
8476 */
8477 group = au_get_grouparg(&arg);
8478 if (arg == NULL) /* out of memory */
8479 return;
8480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008481
8482 /*
8483 * Scan over the events.
8484 * If we find an illegal name, return here, don't do anything.
8485 */
8486 pat = find_end_event(arg, group != AUGROUP_ALL);
8487 if (pat == NULL)
8488 return;
8489
Bram Moolenaar071d4272004-06-13 20:20:40 +00008490 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008491 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008492 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008493 pat = (char_u *)"";
8494 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008495 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008496 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008497 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008498 /*
8499 * Scan over the pattern. Put a NUL at the end.
8500 */
8501 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008502 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008503 cmd++;
8504 if (*cmd)
8505 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008506
Bram Moolenaare99e8442016-07-26 20:43:40 +02008507 /* Expand environment variables in the pattern. Set 'shellslash', we want
8508 * forward slashes here. */
8509 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8510 {
8511#ifdef BACKSLASH_IN_FILENAME
8512 int p_ssl_save = p_ssl;
8513
8514 p_ssl = TRUE;
8515#endif
8516 envpat = expand_env_save(pat);
8517#ifdef BACKSLASH_IN_FILENAME
8518 p_ssl = p_ssl_save;
8519#endif
8520 if (envpat != NULL)
8521 pat = envpat;
8522 }
8523
8524 /*
8525 * Check for "nested" flag.
8526 */
8527 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008528 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008529 {
8530 nested = TRUE;
8531 cmd = skipwhite(cmd + 6);
8532 }
8533
8534 /*
8535 * Find the start of the commands.
8536 * Expand <sfile> in it.
8537 */
8538 if (*cmd != NUL)
8539 {
8540 cmd = expand_sfile(cmd);
8541 if (cmd == NULL) /* some error */
8542 return;
8543 need_free = TRUE;
8544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 }
8546
8547 /*
8548 * Print header when showing autocommands.
8549 */
8550 if (!forceit && *cmd == NUL)
8551 {
8552 /* Highlight title */
Bram Moolenaar8c555332018-06-22 21:30:31 +02008553 MSG_PUTS_TITLE(_("\n--- Autocommands ---"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008554 }
8555
8556 /*
8557 * Loop over the events.
8558 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008559 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008560 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008561 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008563 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8564 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008565 if (do_autocmd_event(event, pat,
8566 nested, cmd, forceit, group) == FAIL)
8567 break;
8568 }
8569 else
8570 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008571 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008572 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8573 nested, cmd, forceit, group) == FAIL)
8574 break;
8575 }
8576
8577 if (need_free)
8578 vim_free(cmd);
8579 vim_free(envpat);
8580}
8581
8582/*
8583 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8584 * The "argp" argument is advanced to the following argument.
8585 *
8586 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8587 */
8588 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008589au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590{
8591 char_u *group_name;
8592 char_u *p;
8593 char_u *arg = *argp;
8594 int group = AUGROUP_ALL;
8595
Bram Moolenaar1c465442017-03-12 20:10:05 +01008596 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008597 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008598 if (p > arg)
8599 {
8600 group_name = vim_strnsave(arg, (int)(p - arg));
8601 if (group_name == NULL) /* out of memory */
8602 return AUGROUP_ERROR;
8603 group = au_find_group(group_name);
8604 if (group == AUGROUP_ERROR)
8605 group = AUGROUP_ALL; /* no match, use all groups */
8606 else
8607 *argp = skipwhite(p); /* match, skip over group name */
8608 vim_free(group_name);
8609 }
8610 return group;
8611}
8612
8613/*
8614 * do_autocmd() for one event.
8615 * If *pat == NUL do for all patterns.
8616 * If *cmd == NUL show entries.
8617 * If forceit == TRUE delete entries.
8618 * If group is not AUGROUP_ALL, only use this group.
8619 */
8620 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008621do_autocmd_event(
8622 event_T event,
8623 char_u *pat,
8624 int nested,
8625 char_u *cmd,
8626 int forceit,
8627 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008628{
8629 AutoPat *ap;
8630 AutoPat **prev_ap;
8631 AutoCmd *ac;
8632 AutoCmd **prev_ac;
8633 int brace_level;
8634 char_u *endpat;
8635 int findgroup;
8636 int allgroups;
8637 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008638 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008639 int buflocal_nr;
8640 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008641
8642 if (group == AUGROUP_ALL)
8643 findgroup = current_augroup;
8644 else
8645 findgroup = group;
8646 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8647
8648 /*
8649 * Show or delete all patterns for an event.
8650 */
8651 if (*pat == NUL)
8652 {
8653 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8654 {
8655 if (forceit) /* delete the AutoPat, if it's in the current group */
8656 {
8657 if (ap->group == findgroup)
8658 au_remove_pat(ap);
8659 }
8660 else if (group == AUGROUP_ALL || ap->group == group)
8661 show_autocmd(ap, event);
8662 }
8663 }
8664
8665 /*
8666 * Loop through all the specified patterns.
8667 */
8668 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8669 {
8670 /*
8671 * Find end of the pattern.
8672 * Watch out for a comma in braces, like "*.\{obj,o\}".
8673 */
8674 brace_level = 0;
8675 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008676 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008677 {
8678 if (*endpat == '{')
8679 brace_level++;
8680 else if (*endpat == '}')
8681 brace_level--;
8682 }
8683 if (pat == endpat) /* ignore single comma */
8684 continue;
8685 patlen = (int)(endpat - pat);
8686
8687 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008688 * detect special <buflocal[=X]> buffer-local patterns
8689 */
8690 is_buflocal = FALSE;
8691 buflocal_nr = 0;
8692
Bram Moolenaar1e997822015-02-17 16:04:57 +01008693 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008694 && pat[patlen - 1] == '>')
8695 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008696 /* "<buffer...>": Error will be printed only for addition.
8697 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008698 is_buflocal = TRUE;
8699 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008700 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008701 buflocal_nr = curbuf->b_fnum;
8702 else if (patlen > 9 && pat[7] == '=')
8703 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008704 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8705 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008706 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008707 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008708 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008709 buflocal_nr = atoi((char *)pat + 8);
8710 }
8711 }
8712
8713 if (is_buflocal)
8714 {
8715 /* normalize pat into standard "<buffer>#N" form */
8716 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8717 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008718 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008719 }
8720
8721 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008722 * Find AutoPat entries with this pattern. When adding a command it
8723 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008724 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008725 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8726 prev_ap = &last_autopat[(int)event];
8727 else
8728 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008729 while ((ap = *prev_ap) != NULL)
8730 {
8731 if (ap->pat != NULL)
8732 {
8733 /* Accept a pattern when:
8734 * - a group was specified and it's that group, or a group was
8735 * not specified and it's the current group, or a group was
8736 * not specified and we are listing
8737 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008738 * - the pattern matches.
8739 * For <buffer[=X]>, this condition works because we normalize
8740 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008741 */
8742 if ((allgroups || ap->group == findgroup)
8743 && ap->patlen == patlen
8744 && STRNCMP(pat, ap->pat, patlen) == 0)
8745 {
8746 /*
8747 * Remove existing autocommands.
8748 * If adding any new autocmd's for this AutoPat, don't
8749 * delete the pattern from the autopat list, append to
8750 * this list.
8751 */
8752 if (forceit)
8753 {
8754 if (*cmd != NUL && ap->next == NULL)
8755 {
8756 au_remove_cmds(ap);
8757 break;
8758 }
8759 au_remove_pat(ap);
8760 }
8761
8762 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008763 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764 */
8765 else if (*cmd == NUL)
8766 show_autocmd(ap, event);
8767
8768 /*
8769 * Add autocmd to this autopat, if it's the last one.
8770 */
8771 else if (ap->next == NULL)
8772 break;
8773 }
8774 }
8775 prev_ap = &ap->next;
8776 }
8777
8778 /*
8779 * Add a new command.
8780 */
8781 if (*cmd != NUL)
8782 {
8783 /*
8784 * If the pattern we want to add a command to does appear at the
8785 * end of the list (or not is not in the list at all), add the
8786 * pattern at the end of the list.
8787 */
8788 if (ap == NULL)
8789 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008790 /* refuse to add buffer-local ap if buffer number is invalid */
8791 if (is_buflocal && (buflocal_nr == 0
8792 || buflist_findnr(buflocal_nr) == NULL))
8793 {
8794 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8795 buflocal_nr);
8796 return FAIL;
8797 }
8798
Bram Moolenaar071d4272004-06-13 20:20:40 +00008799 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8800 if (ap == NULL)
8801 return FAIL;
8802 ap->pat = vim_strnsave(pat, patlen);
8803 ap->patlen = patlen;
8804 if (ap->pat == NULL)
8805 {
8806 vim_free(ap);
8807 return FAIL;
8808 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008809
8810 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008811 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008812 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008813 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008814 }
8815 else
8816 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008817 char_u *reg_pat;
8818
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008819 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008820 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008821 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008822 if (reg_pat != NULL)
8823 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008824 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008825 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008826 {
8827 vim_free(ap->pat);
8828 vim_free(ap);
8829 return FAIL;
8830 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008831 }
8832 ap->cmds = NULL;
8833 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008834 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008835 ap->next = NULL;
8836 if (group == AUGROUP_ALL)
8837 ap->group = current_augroup;
8838 else
8839 ap->group = group;
8840 }
8841
8842 /*
8843 * Add the autocmd at the end of the AutoCmd list.
8844 */
8845 prev_ac = &(ap->cmds);
8846 while ((ac = *prev_ac) != NULL)
8847 prev_ac = &ac->next;
8848 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8849 if (ac == NULL)
8850 return FAIL;
8851 ac->cmd = vim_strsave(cmd);
8852#ifdef FEAT_EVAL
8853 ac->scriptID = current_SID;
8854#endif
8855 if (ac->cmd == NULL)
8856 {
8857 vim_free(ac);
8858 return FAIL;
8859 }
8860 ac->next = NULL;
8861 *prev_ac = ac;
8862 ac->nested = nested;
8863 }
8864 }
8865
8866 au_cleanup(); /* may really delete removed patterns/commands now */
8867 return OK;
8868}
8869
8870/*
8871 * Implementation of ":doautocmd [group] event [fname]".
8872 * Return OK for success, FAIL for failure;
8873 */
8874 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008875do_doautocmd(
8876 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008877 int do_msg, /* give message for no matching autocmds? */
8878 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008879{
8880 char_u *fname;
8881 int nothing_done = TRUE;
8882 int group;
8883
Bram Moolenaar1610d052016-06-09 22:53:01 +02008884 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008885 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008886
Bram Moolenaar071d4272004-06-13 20:20:40 +00008887 /*
8888 * Check for a legal group name. If not, use AUGROUP_ALL.
8889 */
8890 group = au_get_grouparg(&arg);
8891 if (arg == NULL) /* out of memory */
8892 return FAIL;
8893
8894 if (*arg == '*')
8895 {
8896 EMSG(_("E217: Can't execute autocommands for ALL events"));
8897 return FAIL;
8898 }
8899
8900 /*
8901 * Scan over the events.
8902 * If we find an illegal name, return here, don't do anything.
8903 */
8904 fname = find_end_event(arg, group != AUGROUP_ALL);
8905 if (fname == NULL)
8906 return FAIL;
8907
8908 fname = skipwhite(fname);
8909
8910 /*
8911 * Loop over the events.
8912 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008913 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914 if (apply_autocmds_group(event_name2nr(arg, &arg),
8915 fname, NULL, TRUE, group, curbuf, NULL))
8916 nothing_done = FALSE;
8917
8918 if (nothing_done && do_msg)
8919 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008920 if (did_something != NULL)
8921 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008922
8923#ifdef FEAT_EVAL
8924 return aborting() ? FAIL : OK;
8925#else
8926 return OK;
8927#endif
8928}
8929
8930/*
8931 * ":doautoall": execute autocommands for each loaded buffer.
8932 */
8933 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008934ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008935{
8936 int retval;
8937 aco_save_T aco;
8938 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008939 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008940 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008941 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008942 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008943
8944 /*
8945 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8946 * equal to curbuf, but for some buffers there may not be a window.
8947 * So we change the buffer for the current window for a moment. This
8948 * gives problems when the autocommands make changes to the list of
8949 * buffers or windows...
8950 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008951 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008952 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008953 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008954 {
8955 /* find a window for this buffer and save some values */
8956 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008957 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008958
8959 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008960 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008961
Bram Moolenaar1610d052016-06-09 22:53:01 +02008962 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008963 {
8964 /* Execute the modeline settings, but don't set window-local
8965 * options if we are using the current window for another
8966 * buffer. */
8967 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8968 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008969
8970 /* restore the current window */
8971 aucmd_restbuf(&aco);
8972
8973 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008974 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975 break;
8976 }
8977 }
8978
8979 check_cursor(); /* just in case lines got deleted */
8980}
8981
8982/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008983 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8984 * return TRUE and advance *argp to after it.
8985 * Thus return TRUE when do_modelines() should be called.
8986 */
8987 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008988check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008989{
8990 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8991 {
8992 *argp = skipwhite(*argp + 12);
8993 return FALSE;
8994 }
8995 return TRUE;
8996}
8997
8998/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008999 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009000 * Search for a visible window containing the current buffer. If there isn't
9001 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00009002 * Set "curbuf" and "curwin" to match "buf".
9003 */
9004 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009005aucmd_prepbuf(
9006 aco_save_T *aco, /* structure to save values in */
9007 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008{
9009 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009010 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009011#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009012 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009013#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009014
9015 /* Find a window that is for the new buffer */
9016 if (buf == curbuf) /* be quick when buf is curbuf */
9017 win = curwin;
9018 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009019 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009020 if (win->w_buffer == buf)
9021 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009022
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009023 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9024 * back to using the current window. */
9025 if (win == NULL && aucmd_win == NULL)
9026 {
9027 win_alloc_aucmd_win();
9028 if (aucmd_win == NULL)
9029 win = curwin;
9030 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009031 if (win == NULL && aucmd_win_used)
9032 /* Strange recursive autocommand, fall back to using the current
9033 * window. Expect a few side effects... */
9034 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009035
9036 aco->save_curwin = curwin;
9037 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009038 if (win != NULL)
9039 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009040 /* There is a window for "buf" in the current tab page, make it the
9041 * curwin. This is preferred, it has the least side effects (esp. if
9042 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009043 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009044 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009045 }
9046 else
9047 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009048 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009049 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009050 * Anything related to a window (e.g., setting folds) may have
9051 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009052 aco->use_aucmd_win = TRUE;
9053 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009054 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009055#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009056 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009057#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009058 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009059 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009060
9061 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9062 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009063 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009064 aco->globaldir = globaldir;
9065 globaldir = NULL;
9066
Bram Moolenaar071d4272004-06-13 20:20:40 +00009067
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009068 /* Split the current window, put the aucmd_win in the upper half.
9069 * We don't want the BufEnter or WinEnter autocommands. */
9070 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009071 make_snapshot(SNAP_AUCMD_IDX);
9072 save_ea = p_ea;
9073 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009074
Bram Moolenaar4033c552017-09-16 20:54:51 +02009075#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009076 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9077 save_acd = p_acd;
9078 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009079#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009080
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009081 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9082 (void)win_comp_pos(); /* recompute window positions */
9083 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009084#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009085 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009086#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009087 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009088 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009089 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009090 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009091 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009092 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009093}
9094
9095/*
9096 * Cleanup after executing autocommands for a (hidden) buffer.
9097 * Restore the window as it was (if possible).
9098 */
9099 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009100aucmd_restbuf(
9101 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009102{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009103 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009104
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009105 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009106 {
9107 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009108 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009109 * page. Do not trigger autocommands here. */
9110 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009111 if (curwin != aucmd_win)
9112 {
9113 tabpage_T *tp;
9114 win_T *wp;
9115
9116 FOR_ALL_TAB_WINDOWS(tp, wp)
9117 {
9118 if (wp == aucmd_win)
9119 {
9120 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009121 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009122 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009123 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009124 }
9125 }
9126 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009127win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009128
9129 /* Remove the window and frame from the tree of frames. */
9130 (void)winframe_remove(curwin, &dummy, NULL);
9131 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009132 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009133 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009134
9135 if (!valid_tabpage_win(curtab))
9136 /* no valid window in current tabpage */
9137 close_tabpage(curtab);
9138
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009139 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9140 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009141 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009142
9143 if (win_valid(aco->save_curwin))
9144 curwin = aco->save_curwin;
9145 else
9146 /* Hmm, original window disappeared. Just use the first one. */
9147 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009148#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009149 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9150 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009151#endif
9152 curbuf = curwin->w_buffer;
9153
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009154 vim_free(globaldir);
9155 globaldir = aco->globaldir;
9156
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009157 /* the buffer contents may have changed */
9158 check_cursor();
9159 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9160 {
9161 curwin->w_topline = curbuf->b_ml.ml_line_count;
9162#ifdef FEAT_DIFF
9163 curwin->w_topfill = 0;
9164#endif
9165 }
9166#if defined(FEAT_GUI)
9167 /* Hide the scrollbars from the aucmd_win and update. */
9168 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9169 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9170 gui_may_update_scrollbars();
9171#endif
9172 }
9173 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009174 {
9175 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009176 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009177 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009178 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009179 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009180 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009181 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009182 && curbuf != aco->new_curbuf.br_buf
9183 && bufref_valid(&aco->new_curbuf)
9184 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009185 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009186# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9187 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009188 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009189# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009190 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009191 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009192 curwin->w_buffer = curbuf;
9193 ++curbuf->b_nwindows;
9194 }
9195
9196 curwin = aco->save_curwin;
9197 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009198 /* In case the autocommand move the cursor to a position that that
9199 * not exist in curbuf. */
9200 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009201 }
9202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009203}
9204
9205static int autocmd_nested = FALSE;
9206
9207/*
9208 * Execute autocommands for "event" and file name "fname".
9209 * Return TRUE if some commands were executed.
9210 */
9211 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009212apply_autocmds(
9213 event_T event,
9214 char_u *fname, /* NULL or empty means use actual file name */
9215 char_u *fname_io, /* fname to use for <afile> on cmdline */
9216 int force, /* when TRUE, ignore autocmd_busy */
9217 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009218{
9219 return apply_autocmds_group(event, fname, fname_io, force,
9220 AUGROUP_ALL, buf, NULL);
9221}
9222
9223/*
9224 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9225 * setting v:filearg.
9226 */
9227 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009228apply_autocmds_exarg(
9229 event_T event,
9230 char_u *fname,
9231 char_u *fname_io,
9232 int force,
9233 buf_T *buf,
9234 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235{
9236 return apply_autocmds_group(event, fname, fname_io, force,
9237 AUGROUP_ALL, buf, eap);
9238}
9239
9240/*
9241 * Like apply_autocmds(), but handles the caller's retval. If the script
9242 * processing is being aborted or if retval is FAIL when inside a try
9243 * conditional, no autocommands are executed. If otherwise the autocommands
9244 * cause the script to be aborted, retval is set to FAIL.
9245 */
9246 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009247apply_autocmds_retval(
9248 event_T event,
9249 char_u *fname, /* NULL or empty means use actual file name */
9250 char_u *fname_io, /* fname to use for <afile> on cmdline */
9251 int force, /* when TRUE, ignore autocmd_busy */
9252 buf_T *buf, /* buffer for <abuf> */
9253 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009254{
9255 int did_cmd;
9256
Bram Moolenaar1e015462005-09-25 22:16:38 +00009257#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009258 if (should_abort(*retval))
9259 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009260#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009261
9262 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9263 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009264 if (did_cmd
9265#ifdef FEAT_EVAL
9266 && aborting()
9267#endif
9268 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269 *retval = FAIL;
9270 return did_cmd;
9271}
9272
Bram Moolenaard35f9712005-12-18 22:02:33 +00009273/*
9274 * Return TRUE when there is a CursorHold autocommand defined.
9275 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009276 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009277has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009278{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009279 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9280 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009281}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009282
9283/*
9284 * Return TRUE if the CursorHold event can be triggered.
9285 */
9286 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009287trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009288{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009289 int state;
9290
Bram Moolenaar05334432011-07-20 18:29:39 +02009291 if (!did_cursorhold
9292 && has_cursorhold()
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02009293 && reg_recording == 0
Bram Moolenaar05334432011-07-20 18:29:39 +02009294 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009295#ifdef FEAT_INS_EXPAND
9296 && !ins_compl_active()
9297#endif
9298 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009299 {
9300 state = get_real_state();
9301 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9302 return TRUE;
9303 }
9304 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009305}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009306
9307/*
9308 * Return TRUE when there is a CursorMoved autocommand defined.
9309 */
9310 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009311has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009312{
9313 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9314}
9315
9316/*
9317 * Return TRUE when there is a CursorMovedI autocommand defined.
9318 */
9319 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009320has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009321{
9322 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9323}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009324
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009325/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009326 * Return TRUE when there is a TextChanged autocommand defined.
9327 */
9328 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009329has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009330{
9331 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9332}
9333
9334/*
9335 * Return TRUE when there is a TextChangedI autocommand defined.
9336 */
9337 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009338has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009339{
9340 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9341}
9342
9343/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009344 * Return TRUE when there is a TextChangedP autocommand defined.
9345 */
9346 int
9347has_textchangedP(void)
9348{
9349 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9350}
9351
9352/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009353 * Return TRUE when there is an InsertCharPre autocommand defined.
9354 */
9355 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009356has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009357{
9358 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9359}
9360
Bram Moolenaard5005162014-08-22 23:05:54 +02009361/*
9362 * Return TRUE when there is an CmdUndefined autocommand defined.
9363 */
9364 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009365has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009366{
9367 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9368}
9369
9370/*
9371 * Return TRUE when there is an FuncUndefined autocommand defined.
9372 */
9373 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009374has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009375{
9376 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9377}
9378
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009379/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009380 * Return TRUE when there is a TextYankPost autocommand defined.
9381 */
9382 int
9383has_textyankpost(void)
9384{
9385 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9386}
9387
9388/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009389 * Execute autocommands for "event" and file name "fname".
9390 * Return TRUE if some commands were executed.
9391 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009392 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009393apply_autocmds_group(
9394 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009395 char_u *fname, /* NULL or empty means use actual file name */
9396 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009397 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009398 int force, /* when TRUE, ignore autocmd_busy */
9399 int group, /* group ID, or AUGROUP_ALL */
9400 buf_T *buf, /* buffer for <abuf> */
9401 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009402{
9403 char_u *sfname = NULL; /* short file name */
9404 char_u *tail;
9405 int save_changed;
9406 buf_T *old_curbuf;
9407 int retval = FALSE;
9408 char_u *save_sourcing_name;
9409 linenr_T save_sourcing_lnum;
9410 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009411 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009412 int save_autocmd_bufnr;
9413 char_u *save_autocmd_match;
9414 int save_autocmd_busy;
9415 int save_autocmd_nested;
9416 static int nesting = 0;
9417 AutoPatCmd patcmd;
9418 AutoPat *ap;
9419#ifdef FEAT_EVAL
9420 scid_T save_current_SID;
9421 void *save_funccalp;
9422 char_u *save_cmdarg;
9423 long save_cmdbang;
9424#endif
9425 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009426#ifdef FEAT_PROFILE
9427 proftime_T wait_time;
9428#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009429 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009430 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009431 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009432
9433 /*
9434 * Quickly return if there are no autocommands for this event or
9435 * autocommands are blocked.
9436 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009437 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9438 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009439 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009440
9441 /*
9442 * When autocommands are busy, new autocommands are only executed when
9443 * explicitly enabled with the "nested" flag.
9444 */
9445 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009446 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009447
9448#ifdef FEAT_EVAL
9449 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009450 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009451 * occurred or an exception was thrown but not caught.
9452 */
9453 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009454 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009455#endif
9456
9457 /*
9458 * FileChangedShell never nests, because it can create an endless loop.
9459 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009460 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9461 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009462 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009463
9464 /*
9465 * Ignore events in 'eventignore'.
9466 */
9467 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009468 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009469
9470 /*
9471 * Allow nesting of autocommands, but restrict the depth, because it's
9472 * possible to create an endless loop.
9473 */
9474 if (nesting == 10)
9475 {
9476 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009477 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478 }
9479
9480 /*
9481 * Check if these autocommands are disabled. Used when doing ":all" or
9482 * ":ball".
9483 */
9484 if ( (autocmd_no_enter
9485 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9486 || (autocmd_no_leave
9487 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009488 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009489
9490 /*
9491 * Save the autocmd_* variables and info about the current buffer.
9492 */
9493 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009494 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 save_autocmd_bufnr = autocmd_bufnr;
9496 save_autocmd_match = autocmd_match;
9497 save_autocmd_busy = autocmd_busy;
9498 save_autocmd_nested = autocmd_nested;
9499 save_changed = curbuf->b_changed;
9500 old_curbuf = curbuf;
9501
9502 /*
9503 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009504 * Make a copy to avoid that changing a buffer name or directory makes it
9505 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009506 */
9507 if (fname_io == NULL)
9508 {
Bram Moolenaar60a68362018-04-30 15:40:48 +02009509 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
9510 || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009511 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009512 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009513 autocmd_fname = fname;
9514 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009515 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009516 else
9517 autocmd_fname = NULL;
9518 }
9519 else
9520 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009521 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009522 autocmd_fname = vim_strsave(autocmd_fname);
9523 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009524
9525 /*
9526 * Set the buffer number to be used for <abuf>.
9527 */
9528 if (buf == NULL)
9529 autocmd_bufnr = 0;
9530 else
9531 autocmd_bufnr = buf->b_fnum;
9532
9533 /*
9534 * When the file name is NULL or empty, use the file name of buffer "buf".
9535 * Always use the full path of the file name to match with, in case
9536 * "allow_dirs" is set.
9537 */
9538 if (fname == NULL || *fname == NUL)
9539 {
9540 if (buf == NULL)
9541 fname = NULL;
9542 else
9543 {
9544#ifdef FEAT_SYN_HL
9545 if (event == EVENT_SYNTAX)
9546 fname = buf->b_p_syn;
9547 else
9548#endif
9549 if (event == EVENT_FILETYPE)
9550 fname = buf->b_p_ft;
9551 else
9552 {
9553 if (buf->b_sfname != NULL)
9554 sfname = vim_strsave(buf->b_sfname);
9555 fname = buf->b_ffname;
9556 }
9557 }
9558 if (fname == NULL)
9559 fname = (char_u *)"";
9560 fname = vim_strsave(fname); /* make a copy, so we can change it */
9561 }
9562 else
9563 {
9564 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009565 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009566 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009567 if (event == EVENT_FILETYPE
9568 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009569 || event == EVENT_CMDLINECHANGED
9570 || event == EVENT_CMDLINEENTER
9571 || event == EVENT_CMDLINELEAVE
9572 || event == EVENT_CMDWINENTER
9573 || event == EVENT_CMDWINLEAVE
9574 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009575 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009576 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009577 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009578 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009579 || event == EVENT_COLORSCHEME
Bram Moolenaar60a68362018-04-30 15:40:48 +02009580 || event == EVENT_COLORSCHEMEPRE
Bram Moolenaar53744302015-07-17 17:38:22 +02009581 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009582 || event == EVENT_QUICKFIXCMDPOST
9583 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009584 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009585 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009586 autocmd_fname_full = TRUE; /* don't expand it later */
9587 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009588 else
9589 fname = FullName_save(fname, FALSE);
9590 }
9591 if (fname == NULL) /* out of memory */
9592 {
9593 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009594 retval = FALSE;
9595 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009596 }
9597
9598#ifdef BACKSLASH_IN_FILENAME
9599 /*
9600 * Replace all backslashes with forward slashes. This makes the
9601 * autocommand patterns portable between Unix and MS-DOS.
9602 */
9603 if (sfname != NULL)
9604 forward_slash(sfname);
9605 forward_slash(fname);
9606#endif
9607
9608#ifdef VMS
9609 /* remove version for correct match */
9610 if (sfname != NULL)
9611 vms_remove_version(sfname);
9612 vms_remove_version(fname);
9613#endif
9614
9615 /*
9616 * Set the name to be used for <amatch>.
9617 */
9618 autocmd_match = fname;
9619
9620
Bram Moolenaar8c555332018-06-22 21:30:31 +02009621 /* Don't redraw while doing autocommands. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009622 ++RedrawingDisabled;
9623 save_sourcing_name = sourcing_name;
9624 sourcing_name = NULL; /* don't free this one */
9625 save_sourcing_lnum = sourcing_lnum;
9626 sourcing_lnum = 0; /* no line number here */
9627
9628#ifdef FEAT_EVAL
9629 save_current_SID = current_SID;
9630
Bram Moolenaar05159a02005-02-26 23:04:13 +00009631# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009632 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009633 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9634# endif
9635
Bram Moolenaar071d4272004-06-13 20:20:40 +00009636 /* Don't use local function variables, if called from a function */
9637 save_funccalp = save_funccal();
9638#endif
9639
9640 /*
9641 * When starting to execute autocommands, save the search patterns.
9642 */
9643 if (!autocmd_busy)
9644 {
9645 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009646#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009647 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009648#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009649 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009650 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009651 did_save_redobuff = TRUE;
9652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009653 did_filetype = keep_filetype;
9654 }
9655
9656 /*
9657 * Note that we are applying autocmds. Some commands need to know.
9658 */
9659 autocmd_busy = TRUE;
9660 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9661 ++nesting; /* see matching decrement below */
9662
9663 /* Remember that FileType was triggered. Used for did_filetype(). */
9664 if (event == EVENT_FILETYPE)
9665 did_filetype = TRUE;
9666
9667 tail = gettail(fname);
9668
9669 /* Find first autocommand that matches */
9670 patcmd.curpat = first_autopat[(int)event];
9671 patcmd.nextcmd = NULL;
9672 patcmd.group = group;
9673 patcmd.fname = fname;
9674 patcmd.sfname = sfname;
9675 patcmd.tail = tail;
9676 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009677 patcmd.arg_bufnr = autocmd_bufnr;
9678 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009679 auto_next_pat(&patcmd, FALSE);
9680
9681 /* found one, start executing the autocommands */
9682 if (patcmd.curpat != NULL)
9683 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009684 /* add to active_apc_list */
9685 patcmd.next = active_apc_list;
9686 active_apc_list = &patcmd;
9687
Bram Moolenaar071d4272004-06-13 20:20:40 +00009688#ifdef FEAT_EVAL
9689 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009690 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009691 if (eap != NULL)
9692 {
9693 save_cmdarg = set_cmdarg(eap, NULL);
9694 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9695 }
9696 else
9697 save_cmdarg = NULL; /* avoid gcc warning */
9698#endif
9699 retval = TRUE;
9700 /* mark the last pattern, to avoid an endless loop when more patterns
9701 * are added when executing autocommands */
9702 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9703 ap->last = FALSE;
9704 ap->last = TRUE;
9705 check_lnums(TRUE); /* make sure cursor and topline are valid */
9706 do_cmdline(NULL, getnextac, (void *)&patcmd,
9707 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9708#ifdef FEAT_EVAL
9709 if (eap != NULL)
9710 {
9711 (void)set_cmdarg(NULL, save_cmdarg);
9712 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9713 }
9714#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009715 /* delete from active_apc_list */
9716 if (active_apc_list == &patcmd) /* just in case */
9717 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009718 }
9719
9720 --RedrawingDisabled;
9721 autocmd_busy = save_autocmd_busy;
9722 filechangeshell_busy = FALSE;
9723 autocmd_nested = save_autocmd_nested;
9724 vim_free(sourcing_name);
9725 sourcing_name = save_sourcing_name;
9726 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009727 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009728 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009729 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009730 autocmd_bufnr = save_autocmd_bufnr;
9731 autocmd_match = save_autocmd_match;
9732#ifdef FEAT_EVAL
9733 current_SID = save_current_SID;
9734 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009735# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009736 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009737 prof_child_exit(&wait_time);
9738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009739#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009740 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009741 vim_free(fname);
9742 vim_free(sfname);
9743 --nesting; /* see matching increment above */
9744
9745 /*
9746 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009747 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9748 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009749 */
9750 if (!autocmd_busy)
9751 {
9752 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009753 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009754 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009755 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009756 while (au_pending_free_buf != NULL)
9757 {
9758 buf_T *b = au_pending_free_buf->b_next;
9759 vim_free(au_pending_free_buf);
9760 au_pending_free_buf = b;
9761 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009762 while (au_pending_free_win != NULL)
9763 {
9764 win_T *w = au_pending_free_win->w_next;
9765 vim_free(au_pending_free_win);
9766 au_pending_free_win = w;
9767 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009768 }
9769
9770 /*
9771 * Some events don't set or reset the Changed flag.
9772 * Check if still in the same buffer!
9773 */
9774 if (curbuf == old_curbuf
9775 && (event == EVENT_BUFREADPOST
9776 || event == EVENT_BUFWRITEPOST
9777 || event == EVENT_FILEAPPENDPOST
9778 || event == EVENT_VIMLEAVE
9779 || event == EVENT_VIMLEAVEPRE))
9780 {
9781#ifdef FEAT_TITLE
9782 if (curbuf->b_changed != save_changed)
9783 need_maketitle = TRUE;
9784#endif
9785 curbuf->b_changed = save_changed;
9786 }
9787
9788 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009789
9790BYPASS_AU:
9791 /* When wiping out a buffer make sure all its buffer-local autocommands
9792 * are deleted. */
9793 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9794 aubuflocal_remove(buf);
9795
Bram Moolenaarc3691332016-04-20 12:49:49 +02009796 if (retval == OK && event == EVENT_FILETYPE)
9797 au_did_filetype = TRUE;
9798
Bram Moolenaar071d4272004-06-13 20:20:40 +00009799 return retval;
9800}
9801
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009802# ifdef FEAT_EVAL
9803static char_u *old_termresponse = NULL;
9804# endif
9805
9806/*
9807 * Block triggering autocommands until unblock_autocmd() is called.
9808 * Can be used recursively, so long as it's symmetric.
9809 */
9810 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009811block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009812{
9813# ifdef FEAT_EVAL
9814 /* Remember the value of v:termresponse. */
9815 if (autocmd_blocked == 0)
9816 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9817# endif
9818 ++autocmd_blocked;
9819}
9820
9821 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009822unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009823{
9824 --autocmd_blocked;
9825
9826# ifdef FEAT_EVAL
9827 /* When v:termresponse was set while autocommands were blocked, trigger
9828 * the autocommands now. Esp. useful when executing a shell command
9829 * during startup (vimdiff). */
9830 if (autocmd_blocked == 0
9831 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9832 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9833# endif
9834}
9835
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009836 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009837is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009838{
9839 return autocmd_blocked != 0;
9840}
9841
Bram Moolenaar071d4272004-06-13 20:20:40 +00009842/*
9843 * Find next autocommand pattern that matches.
9844 */
9845 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009846auto_next_pat(
9847 AutoPatCmd *apc,
9848 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009849{
9850 AutoPat *ap;
9851 AutoCmd *cp;
9852 char_u *name;
9853 char *s;
9854
Bram Moolenaard23a8232018-02-10 18:45:26 +01009855 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009856
9857 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9858 {
9859 apc->curpat = NULL;
9860
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009861 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009862 * the group matches. For buffer-local autocommands only check the
9863 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009864 if (ap->pat != NULL && ap->cmds != NULL
9865 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9866 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009867 /* execution-condition */
9868 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009869 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009870 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009871 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009872 {
9873 name = event_nr2name(apc->event);
Bram Moolenaar8c555332018-06-22 21:30:31 +02009874 s = _("%s Autocommands for \"%s\"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009875 sourcing_name = alloc((unsigned)(STRLEN(s)
9876 + STRLEN(name) + ap->patlen + 1));
9877 if (sourcing_name != NULL)
9878 {
9879 sprintf((char *)sourcing_name, s,
9880 (char *)name, (char *)ap->pat);
9881 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009882 {
9883 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009884 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009885 verbose_leave();
9886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009887 }
9888
9889 apc->curpat = ap;
9890 apc->nextcmd = ap->cmds;
9891 /* mark last command */
9892 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9893 cp->last = FALSE;
9894 cp->last = TRUE;
9895 }
9896 line_breakcheck();
9897 if (apc->curpat != NULL) /* found a match */
9898 break;
9899 }
9900 if (stop_at_last && ap->last)
9901 break;
9902 }
9903}
9904
9905/*
9906 * Get next autocommand command.
9907 * Called by do_cmdline() to get the next line for ":if".
9908 * Returns allocated string, or NULL for end of autocommands.
9909 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009910 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009911getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009912{
9913 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9914 char_u *retval;
9915 AutoCmd *ac;
9916
9917 /* Can be called again after returning the last line. */
9918 if (acp->curpat == NULL)
9919 return NULL;
9920
9921 /* repeat until we find an autocommand to execute */
9922 for (;;)
9923 {
9924 /* skip removed commands */
9925 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9926 if (acp->nextcmd->last)
9927 acp->nextcmd = NULL;
9928 else
9929 acp->nextcmd = acp->nextcmd->next;
9930
9931 if (acp->nextcmd != NULL)
9932 break;
9933
9934 /* at end of commands, find next pattern that matches */
9935 if (acp->curpat->last)
9936 acp->curpat = NULL;
9937 else
9938 acp->curpat = acp->curpat->next;
9939 if (acp->curpat != NULL)
9940 auto_next_pat(acp, TRUE);
9941 if (acp->curpat == NULL)
9942 return NULL;
9943 }
9944
9945 ac = acp->nextcmd;
9946
9947 if (p_verbose >= 9)
9948 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009949 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009950 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009951 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009952 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009953 }
9954 retval = vim_strsave(ac->cmd);
9955 autocmd_nested = ac->nested;
9956#ifdef FEAT_EVAL
9957 current_SID = ac->scriptID;
9958#endif
9959 if (ac->last)
9960 acp->nextcmd = NULL;
9961 else
9962 acp->nextcmd = ac->next;
9963 return retval;
9964}
9965
9966/*
9967 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009968 * To account for buffer-local autocommands, function needs to know
9969 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009970 */
9971 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009972has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973{
9974 AutoPat *ap;
9975 char_u *fname;
9976 char_u *tail = gettail(sfname);
9977 int retval = FALSE;
9978
9979 fname = FullName_save(sfname, FALSE);
9980 if (fname == NULL)
9981 return FALSE;
9982
9983#ifdef BACKSLASH_IN_FILENAME
9984 /*
9985 * Replace all backslashes with forward slashes. This makes the
9986 * autocommand patterns portable between Unix and MS-DOS.
9987 */
9988 sfname = vim_strsave(sfname);
9989 if (sfname != NULL)
9990 forward_slash(sfname);
9991 forward_slash(fname);
9992#endif
9993
9994 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9995 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009996 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009997 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009998 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009999 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010000 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010001 {
10002 retval = TRUE;
10003 break;
10004 }
10005
10006 vim_free(fname);
10007#ifdef BACKSLASH_IN_FILENAME
10008 vim_free(sfname);
10009#endif
10010
10011 return retval;
10012}
10013
10014#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10015/*
10016 * Function given to ExpandGeneric() to obtain the list of autocommand group
10017 * names.
10018 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010019 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010020get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010021{
10022 if (idx == augroups.ga_len) /* add "END" add the end */
10023 return (char_u *)"END";
10024 if (idx >= augroups.ga_len) /* end of list */
10025 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010026 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010027 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010028 return (char_u *)"";
10029 return AUGROUP_NAME(idx); /* return a name */
10030}
10031
10032static int include_groups = FALSE;
10033
10034 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010035set_context_in_autocmd(
10036 expand_T *xp,
10037 char_u *arg,
10038 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039{
10040 char_u *p;
10041 int group;
10042
10043 /* check for a group name, skip it if present */
10044 include_groups = FALSE;
10045 p = arg;
10046 group = au_get_grouparg(&arg);
10047 if (group == AUGROUP_ERROR)
10048 return NULL;
10049 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010050 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010051 {
10052 arg = p;
10053 group = AUGROUP_ALL;
10054 }
10055
10056 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010057 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058 if (*p == ',')
10059 arg = p + 1;
10060 if (*p == NUL)
10061 {
10062 if (group == AUGROUP_ALL)
10063 include_groups = TRUE;
10064 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10065 xp->xp_pattern = arg;
10066 return NULL;
10067 }
10068
10069 /* skip over pattern */
10070 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010071 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072 arg++;
10073 if (*arg)
10074 return arg; /* expand (next) command */
10075
10076 if (doautocmd)
10077 xp->xp_context = EXPAND_FILES; /* expand file names */
10078 else
10079 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10080 return NULL;
10081}
10082
10083/*
10084 * Function given to ExpandGeneric() to obtain the list of event names.
10085 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010086 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010087get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010088{
10089 if (idx < augroups.ga_len) /* First list group names, if wanted */
10090 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010091 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010092 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010093 return (char_u *)""; /* skip deleted entries */
10094 return AUGROUP_NAME(idx); /* return a name */
10095 }
10096 return (char_u *)event_names[idx - augroups.ga_len].name;
10097}
10098
10099#endif /* FEAT_CMDL_COMPL */
10100
10101/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010102 * Return TRUE if autocmd is supported.
10103 */
10104 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010105autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010106{
10107 char_u *p;
10108
10109 return (event_name2nr(name, &p) != NUM_EVENTS);
10110}
10111
10112/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010113 * Return TRUE if an autocommand is defined for a group, event and
10114 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10115 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10116 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10117 * Used for:
10118 * exists("#Group") or
10119 * exists("#Group#Event") or
10120 * exists("#Group#Event#pat") or
10121 * exists("#Event") or
10122 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010123 */
10124 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010125au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010126{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010127 char_u *arg_save;
10128 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129 char_u *event_name;
10130 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010131 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010132 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010133 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010134 int group;
10135 int retval = FALSE;
10136
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010137 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010138 arg_save = vim_strsave(arg);
10139 if (arg_save == NULL)
10140 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010141 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010142 if (p != NULL)
10143 *p++ = NUL;
10144
10145 /* First, look for an autocmd group name */
10146 group = au_find_group(arg_save);
10147 if (group == AUGROUP_ERROR)
10148 {
10149 /* Didn't match a group name, assume the first argument is an event. */
10150 group = AUGROUP_ALL;
10151 event_name = arg_save;
10152 }
10153 else
10154 {
10155 if (p == NULL)
10156 {
10157 /* "Group": group name is present and it's recognized */
10158 retval = TRUE;
10159 goto theend;
10160 }
10161
10162 /* Must be "Group#Event" or "Group#Event#pat". */
10163 event_name = p;
10164 p = vim_strchr(event_name, '#');
10165 if (p != NULL)
10166 *p++ = NUL; /* "Group#Event#pat" */
10167 }
10168
10169 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010170
10171 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010172 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010173
10174 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010175 if (event == NUM_EVENTS)
10176 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010177
10178 /* Find the first autocommand for this event.
10179 * If there isn't any, return FALSE;
10180 * If there is one and no pattern given, return TRUE; */
10181 ap = first_autopat[(int)event];
10182 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010183 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010184
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010185 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10186 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010187 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010188 buflocal_buf = curbuf;
10189
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190 /* Check if there is an autocommand with the given pattern. */
10191 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010192 /* only use a pattern when it has not been removed and has commands. */
10193 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010194 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010195 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010196 && (pattern == NULL
10197 || (buflocal_buf == NULL
10198 ? fnamecmp(ap->pat, pattern) == 0
10199 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010200 {
10201 retval = TRUE;
10202 break;
10203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010204
Bram Moolenaar195d6352005-12-19 22:08:24 +000010205theend:
10206 vim_free(arg_save);
10207 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010208}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010209
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010210
10211/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010212 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10213 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10214 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010215 * Used for autocommands and 'wildignore'.
10216 * Returns TRUE if there is a match, FALSE otherwise.
10217 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010218 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010219match_file_pat(
10220 char_u *pattern, /* pattern to match with */
10221 regprog_T **prog, /* pre-compiled regprog or NULL */
10222 char_u *fname, /* full path of file name */
10223 char_u *sfname, /* short file name or NULL */
10224 char_u *tail, /* tail of path */
10225 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010226{
10227 regmatch_T regmatch;
10228 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010229
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010230 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010231 if (prog != NULL)
10232 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010233 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010234 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010235
10236 /*
10237 * Try for a match with the pattern with:
10238 * 1. the full file name, when the pattern has a '/'.
10239 * 2. the short file name, when the pattern has a '/'.
10240 * 3. the tail of the file name, when the pattern has no '/'.
10241 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010242 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010243 && ((allow_dirs
10244 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10245 || (sfname != NULL
10246 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010247 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010248 result = TRUE;
10249
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010250 if (prog != NULL)
10251 *prog = regmatch.regprog;
10252 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010253 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010254 return result;
10255}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010256
10257#if defined(FEAT_WILDIGN) || defined(PROTO)
10258/*
10259 * Return TRUE if a file matches with a pattern in "list".
10260 * "list" is a comma-separated list of patterns, like 'wildignore'.
10261 * "sfname" is the short file name or NULL, "ffname" the long file name.
10262 */
10263 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010264match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265{
10266 char_u buf[100];
10267 char_u *tail;
10268 char_u *regpat;
10269 char allow_dirs;
10270 int match;
10271 char_u *p;
10272
10273 tail = gettail(sfname);
10274
10275 /* try all patterns in 'wildignore' */
10276 p = list;
10277 while (*p)
10278 {
10279 copy_option_part(&p, buf, 100, ",");
10280 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10281 if (regpat == NULL)
10282 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010283 match = match_file_pat(regpat, NULL, ffname, sfname,
10284 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010285 vim_free(regpat);
10286 if (match)
10287 return TRUE;
10288 }
10289 return FALSE;
10290}
10291#endif
10292
10293/*
10294 * Convert the given pattern "pat" which has shell style wildcards in it, into
10295 * a regular expression, and return the result in allocated memory. If there
10296 * is a directory path separator to be matched, then TRUE is put in
10297 * allow_dirs, otherwise FALSE is put there -- webb.
10298 * Handle backslashes before special characters, like "\*" and "\ ".
10299 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010300 * Returns NULL when out of memory.
10301 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010302 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010303file_pat_to_reg_pat(
10304 char_u *pat,
10305 char_u *pat_end, /* first char after pattern or NULL */
10306 char *allow_dirs, /* Result passed back out in here */
10307 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010308{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010309 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010310 char_u *endp;
10311 char_u *reg_pat;
10312 char_u *p;
10313 int i;
10314 int nested = 0;
10315 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010316
10317 if (allow_dirs != NULL)
10318 *allow_dirs = FALSE;
10319 if (pat_end == NULL)
10320 pat_end = pat + STRLEN(pat);
10321
Bram Moolenaar071d4272004-06-13 20:20:40 +000010322 for (p = pat; p < pat_end; p++)
10323 {
10324 switch (*p)
10325 {
10326 case '*':
10327 case '.':
10328 case ',':
10329 case '{':
10330 case '}':
10331 case '~':
10332 size += 2; /* extra backslash */
10333 break;
10334#ifdef BACKSLASH_IN_FILENAME
10335 case '\\':
10336 case '/':
10337 size += 4; /* could become "[\/]" */
10338 break;
10339#endif
10340 default:
10341 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010342# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010343 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010344 {
10345 ++p;
10346 ++size;
10347 }
10348# endif
10349 break;
10350 }
10351 }
10352 reg_pat = alloc(size + 1);
10353 if (reg_pat == NULL)
10354 return NULL;
10355
Bram Moolenaar071d4272004-06-13 20:20:40 +000010356 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010357
10358 if (pat[0] == '*')
10359 while (pat[0] == '*' && pat < pat_end - 1)
10360 pat++;
10361 else
10362 reg_pat[i++] = '^';
10363 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010364 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010365 {
10366 while (endp - pat > 0 && *endp == '*')
10367 endp--;
10368 add_dollar = FALSE;
10369 }
10370 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10371 {
10372 switch (*p)
10373 {
10374 case '*':
10375 reg_pat[i++] = '.';
10376 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010377 while (p[1] == '*') /* "**" matches like "*" */
10378 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010379 break;
10380 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010381 case '~':
10382 reg_pat[i++] = '\\';
10383 reg_pat[i++] = *p;
10384 break;
10385 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010386 reg_pat[i++] = '.';
10387 break;
10388 case '\\':
10389 if (p[1] == NUL)
10390 break;
10391#ifdef BACKSLASH_IN_FILENAME
10392 if (!no_bslash)
10393 {
10394 /* translate:
10395 * "\x" to "\\x" e.g., "dir\file"
10396 * "\*" to "\\.*" e.g., "dir\*.c"
10397 * "\?" to "\\." e.g., "dir\??.c"
10398 * "\+" to "\+" e.g., "fileX\+.c"
10399 */
10400 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10401 && p[1] != '+')
10402 {
10403 reg_pat[i++] = '[';
10404 reg_pat[i++] = '\\';
10405 reg_pat[i++] = '/';
10406 reg_pat[i++] = ']';
10407 if (allow_dirs != NULL)
10408 *allow_dirs = TRUE;
10409 break;
10410 }
10411 }
10412#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010413 /* Undo escaping from ExpandEscape():
10414 * foo\?bar -> foo?bar
10415 * foo\%bar -> foo%bar
10416 * foo\,bar -> foo,bar
10417 * foo\ bar -> foo bar
10418 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010419 * regexp.
10420 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010421 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010422 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010423 if (*++p == '?'
10424#ifdef BACKSLASH_IN_FILENAME
10425 && no_bslash
10426#endif
10427 )
10428 reg_pat[i++] = '?';
10429 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010430 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010431 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010432 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010433 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10434 {
10435 reg_pat[i++] = '\\';
10436 reg_pat[i++] = '{';
10437 p += 2;
10438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010439 else
10440 {
10441 if (allow_dirs != NULL && vim_ispathsep(*p)
10442#ifdef BACKSLASH_IN_FILENAME
10443 && (!no_bslash || *p != '\\')
10444#endif
10445 )
10446 *allow_dirs = TRUE;
10447 reg_pat[i++] = '\\';
10448 reg_pat[i++] = *p;
10449 }
10450 break;
10451#ifdef BACKSLASH_IN_FILENAME
10452 case '/':
10453 reg_pat[i++] = '[';
10454 reg_pat[i++] = '\\';
10455 reg_pat[i++] = '/';
10456 reg_pat[i++] = ']';
10457 if (allow_dirs != NULL)
10458 *allow_dirs = TRUE;
10459 break;
10460#endif
10461 case '{':
10462 reg_pat[i++] = '\\';
10463 reg_pat[i++] = '(';
10464 nested++;
10465 break;
10466 case '}':
10467 reg_pat[i++] = '\\';
10468 reg_pat[i++] = ')';
10469 --nested;
10470 break;
10471 case ',':
10472 if (nested)
10473 {
10474 reg_pat[i++] = '\\';
10475 reg_pat[i++] = '|';
10476 }
10477 else
10478 reg_pat[i++] = ',';
10479 break;
10480 default:
10481# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010482 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010483 reg_pat[i++] = *p++;
10484 else
10485# endif
10486 if (allow_dirs != NULL && vim_ispathsep(*p))
10487 *allow_dirs = TRUE;
10488 reg_pat[i++] = *p;
10489 break;
10490 }
10491 }
10492 if (add_dollar)
10493 reg_pat[i++] = '$';
10494 reg_pat[i] = NUL;
10495 if (nested != 0)
10496 {
10497 if (nested < 0)
10498 EMSG(_("E219: Missing {."));
10499 else
10500 EMSG(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010501 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010502 }
10503 return reg_pat;
10504}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010505
10506#if defined(EINTR) || defined(PROTO)
10507/*
10508 * Version of read() that retries when interrupted by EINTR (possibly
10509 * by a SIGWINCH).
10510 */
10511 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010512read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010513{
10514 long ret;
10515
10516 for (;;)
10517 {
10518 ret = vim_read(fd, buf, bufsize);
10519 if (ret >= 0 || errno != EINTR)
10520 break;
10521 }
10522 return ret;
10523}
10524
10525/*
10526 * Version of write() that retries when interrupted by EINTR (possibly
10527 * by a SIGWINCH).
10528 */
10529 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010530write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010531{
10532 long ret = 0;
10533 long wlen;
10534
10535 /* Repeat the write() so long it didn't fail, other than being interrupted
10536 * by a signal. */
10537 while (ret < (long)bufsize)
10538 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010539 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010540 if (wlen < 0)
10541 {
10542 if (errno != EINTR)
10543 break;
10544 }
10545 else
10546 ret += wlen;
10547 }
10548 return ret;
10549}
10550#endif