blob: 07b241ece5ee618162c02594ffe250185523ab28 [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 ... */
427# ifdef S_ISFIFO
428 && !S_ISFIFO(perm) /* ... or fifo */
429# endif
430# ifdef S_ISSOCK
431 && !S_ISSOCK(perm) /* ... or socket */
432# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000433# ifdef OPEN_CHR_FILES
434 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
435 /* ... or a character special file named /dev/fd/<n> */
436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 )
438 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100439 int retval = FAIL;
440
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100442 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100444 retval = NOTDONE;
445 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 else
447 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
448 msg_end();
449 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100450 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200452#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100453#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000454 /*
455 * MS-Windows allows opening a device, but we will probably get stuck
456 * trying to read it.
457 */
458 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
459 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000460 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000461 msg_end();
462 msg_scroll = msg_save;
463 return FAIL;
464 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000465#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200466 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000467
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200468 /* Set default or forced 'fileformat' and 'binary'. */
469 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470
471 /*
472 * When opening a new file we take the readonly flag from the file.
473 * Default is r/w, can be set to r/o below.
474 * Don't reset it when in readonly mode
475 * Only set/reset b_p_ro when BF_CHECK_RO is set.
476 */
477 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000478 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 curbuf->b_p_ro = FALSE;
480
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200481 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200483 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 if (mch_stat((char *)fname, &st) >= 0)
485 {
486 buf_store_time(curbuf, &st, fname);
487 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488#ifdef UNIX
489 /*
490 * Use the protection bits of the original file for the swap file.
491 * This makes it possible for others to read the name of the
492 * edited file from the swapfile, but only if they can read the
493 * edited file.
494 * Remove the "write" and "execute" bits for group and others
495 * (they must not write the swapfile).
496 * Add the "read" and "write" bits for the user, otherwise we may
497 * not be able to write to the file ourselves.
498 * Setting the bits is done below, after creating the swap file.
499 */
500 swap_mode = (st.st_mode & 0644) | 0600;
501#endif
502#ifdef FEAT_CW_EDITOR
503 /* Get the FSSpec on MacOS
504 * TODO: Update it properly when the buffer name changes
505 */
506 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
507#endif
508#ifdef VMS
509 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000510 curbuf->b_fab_rat = st.st_fab_rat;
511 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512#endif
513 }
514 else
515 {
516 curbuf->b_mtime = 0;
517 curbuf->b_mtime_read = 0;
518 curbuf->b_orig_size = 0;
519 curbuf->b_orig_mode = 0;
520 }
521
522 /* Reset the "new file" flag. It will be set again below when the
523 * file doesn't exist. */
524 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
525 }
526
527/*
528 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100529 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 */
531 file_readonly = FALSE;
532 if (read_stdin)
533 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100534#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
536 setmode(0, O_BINARY);
537#endif
538 }
539 else if (!read_buffer)
540 {
541#ifdef USE_MCH_ACCESS
542 if (
543# ifdef UNIX
544 !(perm & 0222) ||
545# endif
546 mch_access((char *)fname, W_OK))
547 file_readonly = TRUE;
548 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
549#else
550 if (!newfile
551 || readonlymode
552 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
553 {
554 file_readonly = TRUE;
555 /* try to open ro */
556 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
557 }
558#endif
559 }
560
561 if (fd < 0) /* cannot open at all */
562 {
563#ifndef UNIX
564 int isdir_f;
565#endif
566 msg_scroll = msg_save;
567#ifndef UNIX
568 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100569 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 */
571 isdir_f = (mch_isdir(fname));
572 perm = mch_getperm(fname); /* check if the file exists */
573 if (isdir_f)
574 {
575 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
576 curbuf->b_p_ro = TRUE; /* must use "w!" now */
577 }
578 else
579#endif
580 if (newfile)
581 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200582 if (perm < 0
583#ifdef ENOENT
584 && errno == ENOENT
585#endif
586 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587 {
588 /*
589 * Set the 'new-file' flag, so that when the file has
590 * been created by someone else, a ":w" will complain.
591 */
592 curbuf->b_flags |= BF_NEW;
593
594 /* Create a swap file now, so that other Vims are warned
595 * that we are editing this file. Don't do this for a
596 * "nofile" or "nowrite" buffer type. */
597#ifdef FEAT_QUICKFIX
598 if (!bt_dontwrite(curbuf))
599#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000600 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000602 /* SwapExists autocommand may mess things up */
603 if (curbuf != old_curbuf
604 || (using_b_ffname
605 && (old_b_ffname != curbuf->b_ffname))
606 || (using_b_fname
607 && (old_b_fname != curbuf->b_fname)))
608 {
609 EMSG(_(e_auchangedbuf));
610 return FAIL;
611 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000612 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000613 if (dir_of_file_exists(fname))
614 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
615 else
616 filemess(curbuf, sfname,
617 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618#ifdef FEAT_VIMINFO
619 /* Even though this is a new file, it might have been
620 * edited before and deleted. Get the old marks. */
621 check_marks_read();
622#endif
623#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200624 /* Set forced 'fileencoding'. */
625 if (eap != NULL)
626 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
629 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 /* remember the current fileformat */
631 save_file_ff(curbuf);
632
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100633#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 if (aborting()) /* autocmds may abort script processing */
635 return FAIL;
636#endif
637 return OK; /* a new file is not an error */
638 }
639 else
640 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000641 filemess(curbuf, sfname, (char_u *)(
642# ifdef EFBIG
643 (errno == EFBIG) ? _("[File too big]") :
644# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200645# ifdef EOVERFLOW
646 (errno == EOVERFLOW) ? _("[File too big]") :
647# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000648 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 curbuf->b_p_ro = TRUE; /* must use "w!" now */
650 }
651 }
652
653 return FAIL;
654 }
655
656 /*
657 * Only set the 'ro' flag for readonly files the first time they are
658 * loaded. Help files always get readonly mode
659 */
660 if ((check_readonly && file_readonly) || curbuf->b_help)
661 curbuf->b_p_ro = TRUE;
662
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000663 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000665 /* Don't change 'eol' if reading from buffer as it will already be
666 * correctly set when reading stdin. */
667 if (!read_buffer)
668 {
669 curbuf->b_p_eol = TRUE;
670 curbuf->b_start_eol = TRUE;
671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672#ifdef FEAT_MBYTE
673 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000674 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675#endif
676 }
677
678 /* Create a swap file now, so that other Vims are warned that we are
679 * editing this file.
680 * Don't do this for a "nofile" or "nowrite" buffer type. */
681#ifdef FEAT_QUICKFIX
682 if (!bt_dontwrite(curbuf))
683#endif
684 {
685 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000686 if (!read_stdin && (curbuf != old_curbuf
687 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
688 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
689 {
690 EMSG(_(e_auchangedbuf));
691 if (!read_buffer)
692 close(fd);
693 return FAIL;
694 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695#ifdef UNIX
696 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000697 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
698 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100699 {
700 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
701
702 /*
703 * If the group-read bit is set but not the world-read bit, then
704 * the group must be equal to the group of the original file. If
705 * we can't make that happen then reset the group-read bit. This
706 * avoids making the swap file readable to more users when the
707 * primary group of the user is too permissive.
708 */
709 if ((swap_mode & 044) == 040)
710 {
711 stat_T swap_st;
712
713 if (mch_stat((char *)swap_fname, &swap_st) >= 0
714 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200715# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100716 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200717 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200718# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200719 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100720 swap_mode &= 0600;
721 }
722
723 (void)mch_setperm(swap_fname, (long)swap_mode);
724 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725#endif
726 }
727
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000728#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729 /* If "Quit" selected at ATTENTION dialog, don't load the file */
730 if (swap_exists_action == SEA_QUIT)
731 {
732 if (!read_buffer && !read_stdin)
733 close(fd);
734 return FAIL;
735 }
736#endif
737
738 ++no_wait_return; /* don't wait for return yet */
739
740 /*
741 * Set '[ mark to the line above where the lines go (line 1 if zero).
742 */
743 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
744 curbuf->b_op_start.col = 0;
745
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100746 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
747 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
748 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 if (!read_buffer)
751 {
752 int m = msg_scroll;
753 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
755 /*
756 * The file must be closed again, the autocommands may want to change
757 * the file before reading it.
758 */
759 if (!read_stdin)
760 close(fd); /* ignore errors */
761
762 /*
763 * The output from the autocommands should not overwrite anything and
764 * should not be overwritten: Set msg_scroll, restore its value if no
765 * output was done.
766 */
767 msg_scroll = TRUE;
768 if (filtering)
769 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
770 FALSE, curbuf, eap);
771 else if (read_stdin)
772 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
773 FALSE, curbuf, eap);
774 else if (newfile)
775 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
776 FALSE, curbuf, eap);
777 else
778 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
779 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100780 /* autocommands may have changed it */
781 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
782 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
783 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
784
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785 if (msg_scrolled == n)
786 msg_scroll = m;
787
788#ifdef FEAT_EVAL
789 if (aborting()) /* autocmds may abort script processing */
790 {
791 --no_wait_return;
792 msg_scroll = msg_save;
793 curbuf->b_p_ro = TRUE; /* must use "w!" now */
794 return FAIL;
795 }
796#endif
797 /*
798 * Don't allow the autocommands to change the current buffer.
799 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000800 *
801 * Don't allow the autocommands to change the buffer name either
802 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 */
804 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000805 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
806 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
808 {
809 --no_wait_return;
810 msg_scroll = msg_save;
811 if (fd < 0)
812 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
813 else
814 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
815 curbuf->b_p_ro = TRUE; /* must use "w!" now */
816 return FAIL;
817 }
818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
820 /* Autocommands may add lines to the file, need to check if it is empty */
821 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
822
823 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
824 {
825 /*
826 * Show the user that we are busy reading the input. Sometimes this
827 * may take a while. When reading from stdin another program may
828 * still be running, don't move the cursor to the last line, unless
829 * always using the GUI.
830 */
831 if (read_stdin)
832 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100833 if (!is_not_a_term())
834 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100836 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837#endif
838#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100839 /* Also write a message in the GUI window, if there is one. */
840 if (gui.in_use && !gui.dying && !gui.starting)
841 {
842 p = (char_u *)_("Reading from stdin...");
843 gui_write(p, (int)STRLEN(p));
844 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 }
848 else if (!read_buffer)
849 filemess(curbuf, sfname, (char_u *)"", 0);
850 }
851
852 msg_scroll = FALSE; /* overwrite the file message */
853
854 /*
855 * Set linecnt now, before the "retry" caused by a wrong guess for
856 * fileformat, and after the autocommands, which may change them.
857 */
858 linecnt = curbuf->b_ml.ml_line_count;
859
860#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000861 /* "++bad=" argument. */
862 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000863 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000864 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000865 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000866 curbuf->b_bad_char = eap->bad_char;
867 }
868 else
869 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000870
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 */
874 if (eap != NULL && eap->force_enc != 0)
875 {
876 fenc = enc_canonize(eap->cmd + eap->force_enc);
877 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000878 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 }
880 else if (curbuf->b_p_bin)
881 {
882 fenc = (char_u *)""; /* binary: don't convert */
883 fenc_alloced = FALSE;
884 }
885 else if (curbuf->b_help)
886 {
887 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000888 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889
890 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
891 * fails it must be latin1.
892 * Always do this when 'encoding' is "utf-8". Otherwise only do
893 * this when needed to avoid [converted] remarks all the time.
894 * It is needed when the first line contains non-ASCII characters.
895 * That is only in *.??x files. */
896 fenc = (char_u *)"latin1";
897 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000898 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000900 fc = fname[STRLEN(fname) - 1];
901 if (TOLOWER_ASC(fc) == 'x')
902 {
903 /* Read the first line (and a bit more). Immediately rewind to
904 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100905 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200906 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 for (p = firstline; p < firstline + len; ++p)
908 if (*p >= 0x80)
909 {
910 c = TRUE;
911 break;
912 }
913 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914 }
915
916 if (c)
917 {
918 fenc_next = fenc;
919 fenc = (char_u *)"utf-8";
920
921 /* When the file is utf-8 but a character doesn't fit in
922 * 'encoding' don't retry. In help text editing utf-8 bytes
923 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000924 if (!enc_utf8)
925 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926 }
927 fenc_alloced = FALSE;
928 }
929 else if (*p_fencs == NUL)
930 {
931 fenc = curbuf->b_p_fenc; /* use format from buffer */
932 fenc_alloced = FALSE;
933 }
934 else
935 {
936 fenc_next = p_fencs; /* try items in 'fileencodings' */
937 fenc = next_fenc(&fenc_next);
938 fenc_alloced = TRUE;
939 }
940#endif
941
942 /*
943 * Jump back here to retry reading the file in different ways.
944 * Reasons to retry:
945 * - encoding conversion failed: try another one from "fenc_next"
946 * - BOM detected and fenc was set, need to setup conversion
947 * - "fileformat" check failed: try another
948 *
949 * Variables set for special retry actions:
950 * "file_rewind" Rewind the file to start reading it again.
951 * "advance_fenc" Advance "fenc" using "fenc_next".
952 * "skip_read" Re-use already read bytes (BOM detected).
953 * "did_iconv" iconv() conversion failed, try 'charconvert'.
954 * "keep_fileformat" Don't reset "fileformat".
955 *
956 * Other status indicators:
957 * "tmpname" When != NULL did conversion with 'charconvert'.
958 * Output file has to be deleted afterwards.
959 * "iconv_fd" When != -1 did conversion with iconv().
960 */
961retry:
962
963 if (file_rewind)
964 {
965 if (read_buffer)
966 {
967 read_buf_lnum = 1;
968 read_buf_col = 0;
969 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200970 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971 {
972 /* Can't rewind the file, give up. */
973 error = TRUE;
974 goto failed;
975 }
976 /* Delete the previously read lines. */
977 while (lnum > from)
978 ml_delete(lnum--, FALSE);
979 file_rewind = FALSE;
980#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000981 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000982 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000984 curbuf->b_start_bomb = FALSE;
985 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000986 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987#endif
988 }
989
990 /*
991 * When retrying with another "fenc" and the first time "fileformat"
992 * will be reset.
993 */
994 if (keep_fileformat)
995 keep_fileformat = FALSE;
996 else
997 {
998 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000999 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001001 try_unix = try_dos = try_mac = FALSE;
1002 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003 else if (curbuf->b_p_bin)
1004 fileformat = EOL_UNIX; /* binary: use Unix format */
1005 else if (*p_ffs == NUL)
1006 fileformat = get_fileformat(curbuf);/* use format from buffer */
1007 else
1008 fileformat = EOL_UNKNOWN; /* detect from file */
1009 }
1010
1011#ifdef FEAT_MBYTE
1012# ifdef USE_ICONV
1013 if (iconv_fd != (iconv_t)-1)
1014 {
1015 /* aborted conversion with iconv(), close the descriptor */
1016 iconv_close(iconv_fd);
1017 iconv_fd = (iconv_t)-1;
1018 }
1019# endif
1020
1021 if (advance_fenc)
1022 {
1023 /*
1024 * Try the next entry in 'fileencodings'.
1025 */
1026 advance_fenc = FALSE;
1027
1028 if (eap != NULL && eap->force_enc != 0)
1029 {
1030 /* Conversion given with "++cc=" wasn't possible, read
1031 * without conversion. */
1032 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001033 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 if (fenc_alloced)
1035 vim_free(fenc);
1036 fenc = (char_u *)"";
1037 fenc_alloced = FALSE;
1038 }
1039 else
1040 {
1041 if (fenc_alloced)
1042 vim_free(fenc);
1043 if (fenc_next != NULL)
1044 {
1045 fenc = next_fenc(&fenc_next);
1046 fenc_alloced = (fenc_next != NULL);
1047 }
1048 else
1049 {
1050 fenc = (char_u *)"";
1051 fenc_alloced = FALSE;
1052 }
1053 }
1054 if (tmpname != NULL)
1055 {
1056 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001057 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 }
1059 }
1060
1061 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001062 * Conversion may be required when the encoding of the file is different
1063 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 */
1065 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001066 converted = need_conversion(fenc);
1067 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 {
1069
1070 /* "ucs-bom" means we need to check the first bytes of the file
1071 * for a BOM. */
1072 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1073 fio_flags = FIO_UCSBOM;
1074
1075 /*
1076 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1077 * done. This is handled below after read(). Prepare the
1078 * fio_flags to avoid having to parse the string each time.
1079 * Also check for Unicode to Latin1 conversion, because iconv()
1080 * appears not to handle this correctly. This works just like
1081 * conversion to UTF-8 except how the resulting character is put in
1082 * the buffer.
1083 */
1084 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1085 fio_flags = get_fio_flags(fenc);
1086
1087# ifdef WIN3264
1088 /*
1089 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1090 * is handled with MultiByteToWideChar().
1091 */
1092 if (fio_flags == 0)
1093 fio_flags = get_win_fio_flags(fenc);
1094# endif
1095
Bram Moolenaard0573012017-10-28 21:11:06 +02001096# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1098 if (fio_flags == 0)
1099 fio_flags = get_mac_fio_flags(fenc);
1100# endif
1101
1102# ifdef USE_ICONV
1103 /*
1104 * Try using iconv() if we can't convert internally.
1105 */
1106 if (fio_flags == 0
1107# ifdef FEAT_EVAL
1108 && !did_iconv
1109# endif
1110 )
1111 iconv_fd = (iconv_t)my_iconv_open(
1112 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1113# endif
1114
1115# ifdef FEAT_EVAL
1116 /*
1117 * Use the 'charconvert' expression when conversion is required
1118 * and we can't do it internally or with iconv().
1119 */
1120 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001121 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122# ifdef USE_ICONV
1123 && iconv_fd == (iconv_t)-1
1124# endif
1125 )
1126 {
1127# ifdef USE_ICONV
1128 did_iconv = FALSE;
1129# endif
1130 /* Skip conversion when it's already done (retry for wrong
1131 * "fileformat"). */
1132 if (tmpname == NULL)
1133 {
1134 tmpname = readfile_charconvert(fname, fenc, &fd);
1135 if (tmpname == NULL)
1136 {
1137 /* Conversion failed. Try another one. */
1138 advance_fenc = TRUE;
1139 if (fd < 0)
1140 {
1141 /* Re-opening the original file failed! */
1142 EMSG(_("E202: Conversion made file unreadable!"));
1143 error = TRUE;
1144 goto failed;
1145 }
1146 goto retry;
1147 }
1148 }
1149 }
1150 else
1151# endif
1152 {
1153 if (fio_flags == 0
1154# ifdef USE_ICONV
1155 && iconv_fd == (iconv_t)-1
1156# endif
1157 )
1158 {
1159 /* Conversion wanted but we can't.
1160 * Try the next conversion in 'fileencodings' */
1161 advance_fenc = TRUE;
1162 goto retry;
1163 }
1164 }
1165 }
1166
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001167 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001169 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001170 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171#endif
1172
1173 if (!skip_read)
1174 {
1175 linerest = 0;
1176 filesize = 0;
1177 skip_count = lines_to_skip;
1178 read_count = lines_to_read;
1179#ifdef FEAT_MBYTE
1180 conv_restlen = 0;
1181#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001182#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001183 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1184 && curbuf->b_ffname != NULL
1185 && curbuf->b_p_udf
1186 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001187 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001188 && !read_stdin
1189 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001190 if (read_undo_file)
1191 sha256_start(&sha_ctx);
1192#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001193#ifdef FEAT_CRYPT
1194 if (curbuf->b_cryptstate != NULL)
1195 {
1196 /* Need to free the state, but keep the key, don't want to ask for
1197 * it again. */
1198 crypt_free_state(curbuf->b_cryptstate);
1199 curbuf->b_cryptstate = NULL;
1200 }
1201#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 }
1203
1204 while (!error && !got_int)
1205 {
1206 /*
1207 * We allocate as much space for the file as we can get, plus
1208 * space for the old line plus room for one terminating NUL.
1209 * The amount is limited by the fact that read() only can read
1210 * upto max_unsigned characters (and other things).
1211 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001212 if (!skip_read)
1213 {
1214#if VIM_SIZEOF_INT > 2
1215# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
1216 size = SSIZE_MAX; /* use max I/O size, 52K */
1217# else
1218 /* Use buffer >= 64K. Add linerest to double the size if the
1219 * line gets very long, to avoid a lot of copying. But don't
1220 * read more than 1 Mbyte at a time, so we can be interrupted.
1221 */
1222 size = 0x10000L + linerest;
1223 if (size > 0x100000L)
1224 size = 0x100000L;
1225# endif
1226#else
1227 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1228#endif
1229 }
1230
1231 /* Protect against the argument of lalloc() going negative. */
1232 if (
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001233#if VIM_SIZEOF_INT <= 2
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001234 linerest >= 0x7ff0
1235#else
1236 size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL
1237#endif
1238 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239 {
1240 ++split;
1241 *ptr = NL; /* split line by inserting a NL */
1242 size = 1;
1243 }
1244 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 {
1246 if (!skip_read)
1247 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001248 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249 {
1250 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1251 FALSE)) != NULL)
1252 break;
1253 }
1254 if (new_buffer == NULL)
1255 {
1256 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1257 error = TRUE;
1258 break;
1259 }
1260 if (linerest) /* copy characters from the previous buffer */
1261 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1262 vim_free(buffer);
1263 buffer = new_buffer;
1264 ptr = buffer + linerest;
1265 line_start = buffer;
1266
1267#ifdef FEAT_MBYTE
1268 /* May need room to translate into.
1269 * For iconv() we don't really know the required space, use a
1270 * factor ICONV_MULT.
1271 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1272 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1273 * become up to 4 bytes, size must be multiple of 2
1274 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1275 * multiple of 2
1276 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1277 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001278 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279# ifdef USE_ICONV
1280 if (iconv_fd != (iconv_t)-1)
1281 size = size / ICONV_MULT;
1282 else
1283# endif
1284 if (fio_flags & FIO_LATIN1)
1285 size = size / 2;
1286 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1287 size = (size * 2 / 3) & ~1;
1288 else if (fio_flags & FIO_UCS4)
1289 size = (size * 2 / 3) & ~3;
1290 else if (fio_flags == FIO_UCSBOM)
1291 size = size / ICONV_MULT; /* worst case */
1292# ifdef WIN3264
1293 else if (fio_flags & FIO_CODEPAGE)
1294 size = size / ICONV_MULT; /* also worst case */
1295# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001296# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297 else if (fio_flags & FIO_MACROMAN)
1298 size = size / ICONV_MULT; /* also worst case */
1299# endif
1300#endif
1301
1302#ifdef FEAT_MBYTE
1303 if (conv_restlen > 0)
1304 {
1305 /* Insert unconverted bytes from previous line. */
1306 mch_memmove(ptr, conv_rest, conv_restlen);
1307 ptr += conv_restlen;
1308 size -= conv_restlen;
1309 }
1310#endif
1311
1312 if (read_buffer)
1313 {
1314 /*
1315 * Read bytes from curbuf. Used for converting text read
1316 * from stdin.
1317 */
1318 if (read_buf_lnum > from)
1319 size = 0;
1320 else
1321 {
1322 int n, ni;
1323 long tlen;
1324
1325 tlen = 0;
1326 for (;;)
1327 {
1328 p = ml_get(read_buf_lnum) + read_buf_col;
1329 n = (int)STRLEN(p);
1330 if ((int)tlen + n + 1 > size)
1331 {
1332 /* Filled up to "size", append partial line.
1333 * Change NL to NUL to reverse the effect done
1334 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001335 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 for (ni = 0; ni < n; ++ni)
1337 {
1338 if (p[ni] == NL)
1339 ptr[tlen++] = NUL;
1340 else
1341 ptr[tlen++] = p[ni];
1342 }
1343 read_buf_col += n;
1344 break;
1345 }
1346 else
1347 {
1348 /* Append whole line and new-line. Change NL
1349 * to NUL to reverse the effect done below. */
1350 for (ni = 0; ni < n; ++ni)
1351 {
1352 if (p[ni] == NL)
1353 ptr[tlen++] = NUL;
1354 else
1355 ptr[tlen++] = p[ni];
1356 }
1357 ptr[tlen++] = NL;
1358 read_buf_col = 0;
1359 if (++read_buf_lnum > from)
1360 {
1361 /* When the last line didn't have an
1362 * end-of-line don't add it now either. */
1363 if (!curbuf->b_p_eol)
1364 --tlen;
1365 size = tlen;
1366 break;
1367 }
1368 }
1369 }
1370 }
1371 }
1372 else
1373 {
1374 /*
1375 * Read bytes from the file.
1376 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001377 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001378 }
1379
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001380#ifdef FEAT_CRYPT
1381 /*
1382 * At start of file: Check for magic number of encryption.
1383 */
1384 if (filesize == 0 && size > 0)
1385 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1386 &filesize, newfile, sfname,
1387 &did_ask_for_key);
1388 /*
1389 * Decrypt the read bytes. This is done before checking for
1390 * EOF because the crypt layer may be buffering.
1391 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001392 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1393 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001394 {
1395 if (crypt_works_inplace(curbuf->b_cryptstate))
1396 {
1397 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1398 }
1399 else
1400 {
1401 char_u *newptr = NULL;
1402 int decrypted_size;
1403
1404 decrypted_size = crypt_decode_alloc(
1405 curbuf->b_cryptstate, ptr, size, &newptr);
1406
1407 /* If the crypt layer is buffering, not producing
1408 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001409 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001410 continue;
1411
1412 if (linerest == 0)
1413 {
1414 /* Simple case: reuse returned buffer (may be
1415 * NULL, checked later). */
1416 new_buffer = newptr;
1417 }
1418 else
1419 {
1420 long_u new_size;
1421
1422 /* Need new buffer to add bytes carried over. */
1423 new_size = (long_u)(decrypted_size + linerest + 1);
1424 new_buffer = lalloc(new_size, FALSE);
1425 if (new_buffer == NULL)
1426 {
1427 do_outofmem_msg(new_size);
1428 error = TRUE;
1429 break;
1430 }
1431
1432 mch_memmove(new_buffer, buffer, linerest);
1433 if (newptr != NULL)
1434 mch_memmove(new_buffer + linerest, newptr,
1435 decrypted_size);
1436 }
1437
1438 if (new_buffer != NULL)
1439 {
1440 vim_free(buffer);
1441 buffer = new_buffer;
1442 new_buffer = NULL;
1443 line_start = buffer;
1444 ptr = buffer + linerest;
1445 }
1446 size = decrypted_size;
1447 }
1448 }
1449#endif
1450
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451 if (size <= 0)
1452 {
1453 if (size < 0) /* read error */
1454 error = TRUE;
1455#ifdef FEAT_MBYTE
1456 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001457 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001458 /*
1459 * Reached end-of-file but some trailing bytes could
1460 * not be converted. Truncated file?
1461 */
1462
1463 /* When we did a conversion report an error. */
1464 if (fio_flags != 0
1465# ifdef USE_ICONV
1466 || iconv_fd != (iconv_t)-1
1467# endif
1468 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001469 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001470 if (can_retry)
1471 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001472 if (conv_error == 0)
1473 conv_error = curbuf->b_ml.ml_line_count
1474 - linecnt + 1;
1475 }
1476 /* Remember the first linenr with an illegal byte */
1477 else if (illegal_byte == 0)
1478 illegal_byte = curbuf->b_ml.ml_line_count
1479 - linecnt + 1;
1480 if (bad_char_behavior == BAD_DROP)
1481 {
1482 *(ptr - conv_restlen) = NUL;
1483 conv_restlen = 0;
1484 }
1485 else
1486 {
1487 /* Replace the trailing bytes with the replacement
1488 * character if we were converting; if we weren't,
1489 * leave the UTF8 checking code to do it, as it
1490 * works slightly differently. */
1491 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1492# ifdef USE_ICONV
1493 || iconv_fd != (iconv_t)-1
1494# endif
1495 ))
1496 {
1497 while (conv_restlen > 0)
1498 {
1499 *(--ptr) = bad_char_behavior;
1500 --conv_restlen;
1501 }
1502 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001503 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001504# ifdef USE_ICONV
1505 if (iconv_fd != (iconv_t)-1)
1506 {
1507 iconv_close(iconv_fd);
1508 iconv_fd = (iconv_t)-1;
1509 }
1510# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001511 }
1512 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513#endif
1514 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515 }
1516 skip_read = FALSE;
1517
1518#ifdef FEAT_MBYTE
1519 /*
1520 * At start of file (or after crypt magic number): Check for BOM.
1521 * Also check for a BOM for other Unicode encodings, but not after
1522 * converting with 'charconvert' or when a BOM has already been
1523 * found.
1524 */
1525 if ((filesize == 0
1526# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001527 || (cryptkey != NULL
1528 && filesize == crypt_get_header_len(
1529 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530# endif
1531 )
1532 && (fio_flags == FIO_UCSBOM
1533 || (!curbuf->b_p_bomb
1534 && tmpname == NULL
1535 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1536 {
1537 char_u *ccname;
1538 int blen;
1539
1540 /* no BOM detection in a short file or in binary mode */
1541 if (size < 2 || curbuf->b_p_bin)
1542 ccname = NULL;
1543 else
1544 ccname = check_for_bom(ptr, size, &blen,
1545 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1546 if (ccname != NULL)
1547 {
1548 /* Remove BOM from the text */
1549 filesize += blen;
1550 size -= blen;
1551 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001552 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001553 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001555 curbuf->b_start_bomb = TRUE;
1556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 }
1558
1559 if (fio_flags == FIO_UCSBOM)
1560 {
1561 if (ccname == NULL)
1562 {
1563 /* No BOM detected: retry with next encoding. */
1564 advance_fenc = TRUE;
1565 }
1566 else
1567 {
1568 /* BOM detected: set "fenc" and jump back */
1569 if (fenc_alloced)
1570 vim_free(fenc);
1571 fenc = ccname;
1572 fenc_alloced = FALSE;
1573 }
1574 /* retry reading without getting new bytes or rewinding */
1575 skip_read = TRUE;
1576 goto retry;
1577 }
1578 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001579
1580 /* Include not converted bytes. */
1581 ptr -= conv_restlen;
1582 size += conv_restlen;
1583 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584#endif
1585 /*
1586 * Break here for a read error or end-of-file.
1587 */
1588 if (size <= 0)
1589 break;
1590
1591#ifdef FEAT_MBYTE
1592
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593# ifdef USE_ICONV
1594 if (iconv_fd != (iconv_t)-1)
1595 {
1596 /*
1597 * Attempt conversion of the read bytes to 'encoding' using
1598 * iconv().
1599 */
1600 const char *fromp;
1601 char *top;
1602 size_t from_size;
1603 size_t to_size;
1604
1605 fromp = (char *)ptr;
1606 from_size = size;
1607 ptr += size;
1608 top = (char *)ptr;
1609 to_size = real_size - size;
1610
1611 /*
1612 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001613 * another conversion. Except for when there is no
1614 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001616 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1617 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1619 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001620 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001621 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001622 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001623 if (conv_error == 0)
1624 conv_error = readfile_linenr(linecnt,
1625 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001626
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001627 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001628 ++fromp;
1629 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001630 if (bad_char_behavior == BAD_KEEP)
1631 {
1632 *top++ = *(fromp - 1);
1633 --to_size;
1634 }
1635 else if (bad_char_behavior != BAD_DROP)
1636 {
1637 *top++ = bad_char_behavior;
1638 --to_size;
1639 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001640 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641
1642 if (from_size > 0)
1643 {
1644 /* Some remaining characters, keep them for the next
1645 * round. */
1646 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1647 conv_restlen = (int)from_size;
1648 }
1649
1650 /* move the linerest to before the converted characters */
1651 line_start = ptr - linerest;
1652 mch_memmove(line_start, buffer, (size_t)linerest);
1653 size = (long)((char_u *)top - ptr);
1654 }
1655# endif
1656
1657# ifdef WIN3264
1658 if (fio_flags & FIO_CODEPAGE)
1659 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001660 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001661 WCHAR ucs2buf[3];
1662 int ucs2len;
1663 int codepage = FIO_GET_CP(fio_flags);
1664 int bytelen;
1665 int found_bad;
1666 char replstr[2];
1667
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 /*
1669 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001670 * a codepage, using standard MS-Windows functions. This
1671 * requires two steps:
1672 * 1. convert from 'fileencoding' to ucs-2
1673 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001675 * Because there may be illegal bytes AND an incomplete byte
1676 * sequence at the end, we may have to do the conversion one
1677 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001680 /* Replacement string for WideCharToMultiByte(). */
1681 if (bad_char_behavior > 0)
1682 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001684 replstr[0] = '?';
1685 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686
1687 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001688 * Move the bytes to the end of the buffer, so that we have
1689 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001691 src = ptr + real_size - size;
1692 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001694 /*
1695 * Do the conversion.
1696 */
1697 dst = ptr;
1698 size = size;
1699 while (size > 0)
1700 {
1701 found_bad = FALSE;
1702
1703# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1704 if (codepage == CP_UTF8)
1705 {
1706 /* Handle CP_UTF8 input ourselves to be able to handle
1707 * trailing bytes properly.
1708 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001709 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001710 if (bytelen > size)
1711 {
1712 /* Only got some bytes of a character. Normally
1713 * it's put in "conv_rest", but if it's too long
1714 * deal with it as if they were illegal bytes. */
1715 if (bytelen <= CONV_RESTLEN)
1716 break;
1717
1718 /* weird overlong byte sequence */
1719 bytelen = size;
1720 found_bad = TRUE;
1721 }
1722 else
1723 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001724 int u8c = utf_ptr2char(src);
1725
Bram Moolenaar86e01082005-12-29 22:45:34 +00001726 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001727 found_bad = TRUE;
1728 ucs2buf[0] = u8c;
1729 ucs2len = 1;
1730 }
1731 }
1732 else
1733# endif
1734 {
1735 /* We don't know how long the byte sequence is, try
1736 * from one to three bytes. */
1737 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1738 ++bytelen)
1739 {
1740 ucs2len = MultiByteToWideChar(codepage,
1741 MB_ERR_INVALID_CHARS,
1742 (LPCSTR)src, bytelen,
1743 ucs2buf, 3);
1744 if (ucs2len > 0)
1745 break;
1746 }
1747 if (ucs2len == 0)
1748 {
1749 /* If we have only one byte then it's probably an
1750 * incomplete byte sequence. Otherwise discard
1751 * one byte as a bad character. */
1752 if (size == 1)
1753 break;
1754 found_bad = TRUE;
1755 bytelen = 1;
1756 }
1757 }
1758
1759 if (!found_bad)
1760 {
1761 int i;
1762
1763 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1764 if (enc_utf8)
1765 {
1766 /* From UCS-2 to UTF-8. Cannot fail. */
1767 for (i = 0; i < ucs2len; ++i)
1768 dst += utf_char2bytes(ucs2buf[i], dst);
1769 }
1770 else
1771 {
1772 BOOL bad = FALSE;
1773 int dstlen;
1774
1775 /* From UCS-2 to "enc_codepage". If the
1776 * conversion uses the default character "?",
1777 * the data doesn't fit in this encoding. */
1778 dstlen = WideCharToMultiByte(enc_codepage, 0,
1779 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001780 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001781 replstr, &bad);
1782 if (bad)
1783 found_bad = TRUE;
1784 else
1785 dst += dstlen;
1786 }
1787 }
1788
1789 if (found_bad)
1790 {
1791 /* Deal with bytes we can't convert. */
1792 if (can_retry)
1793 goto rewind_retry;
1794 if (conv_error == 0)
1795 conv_error = readfile_linenr(linecnt, ptr, dst);
1796 if (bad_char_behavior != BAD_DROP)
1797 {
1798 if (bad_char_behavior == BAD_KEEP)
1799 {
1800 mch_memmove(dst, src, bytelen);
1801 dst += bytelen;
1802 }
1803 else
1804 *dst++ = bad_char_behavior;
1805 }
1806 }
1807
1808 src += bytelen;
1809 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001811
1812 if (size > 0)
1813 {
1814 /* An incomplete byte sequence remaining. */
1815 mch_memmove(conv_rest, src, size);
1816 conv_restlen = size;
1817 }
1818
1819 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001820 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 }
1822 else
1823# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001824# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 if (fio_flags & FIO_MACROMAN)
1826 {
1827 /*
1828 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001829 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001831 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 }
1834 else
1835# endif
1836 if (fio_flags != 0)
1837 {
1838 int u8c;
1839 char_u *dest;
1840 char_u *tail = NULL;
1841
1842 /*
1843 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1844 * "enc_utf8" not set: Convert Unicode to Latin1.
1845 * Go from end to start through the buffer, because the number
1846 * of bytes may increase.
1847 * "dest" points to after where the UTF-8 bytes go, "p" points
1848 * to after the next character to convert.
1849 */
1850 dest = ptr + real_size;
1851 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1852 {
1853 p = ptr + size;
1854 if (fio_flags == FIO_UTF8)
1855 {
1856 /* Check for a trailing incomplete UTF-8 sequence */
1857 tail = ptr + size - 1;
1858 while (tail > ptr && (*tail & 0xc0) == 0x80)
1859 --tail;
1860 if (tail + utf_byte2len(*tail) <= ptr + size)
1861 tail = NULL;
1862 else
1863 p = tail;
1864 }
1865 }
1866 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1867 {
1868 /* Check for a trailing byte */
1869 p = ptr + (size & ~1);
1870 if (size & 1)
1871 tail = p;
1872 if ((fio_flags & FIO_UTF16) && p > ptr)
1873 {
1874 /* Check for a trailing leading word */
1875 if (fio_flags & FIO_ENDIAN_L)
1876 {
1877 u8c = (*--p << 8);
1878 u8c += *--p;
1879 }
1880 else
1881 {
1882 u8c = *--p;
1883 u8c += (*--p << 8);
1884 }
1885 if (u8c >= 0xd800 && u8c <= 0xdbff)
1886 tail = p;
1887 else
1888 p += 2;
1889 }
1890 }
1891 else /* FIO_UCS4 */
1892 {
1893 /* Check for trailing 1, 2 or 3 bytes */
1894 p = ptr + (size & ~3);
1895 if (size & 3)
1896 tail = p;
1897 }
1898
1899 /* If there is a trailing incomplete sequence move it to
1900 * conv_rest[]. */
1901 if (tail != NULL)
1902 {
1903 conv_restlen = (int)((ptr + size) - tail);
1904 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1905 size -= conv_restlen;
1906 }
1907
1908
1909 while (p > ptr)
1910 {
1911 if (fio_flags & FIO_LATIN1)
1912 u8c = *--p;
1913 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1914 {
1915 if (fio_flags & FIO_ENDIAN_L)
1916 {
1917 u8c = (*--p << 8);
1918 u8c += *--p;
1919 }
1920 else
1921 {
1922 u8c = *--p;
1923 u8c += (*--p << 8);
1924 }
1925 if ((fio_flags & FIO_UTF16)
1926 && u8c >= 0xdc00 && u8c <= 0xdfff)
1927 {
1928 int u16c;
1929
1930 if (p == ptr)
1931 {
1932 /* Missing leading word. */
1933 if (can_retry)
1934 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001935 if (conv_error == 0)
1936 conv_error = readfile_linenr(linecnt,
1937 ptr, p);
1938 if (bad_char_behavior == BAD_DROP)
1939 continue;
1940 if (bad_char_behavior != BAD_KEEP)
1941 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 }
1943
1944 /* found second word of double-word, get the first
1945 * word and compute the resulting character */
1946 if (fio_flags & FIO_ENDIAN_L)
1947 {
1948 u16c = (*--p << 8);
1949 u16c += *--p;
1950 }
1951 else
1952 {
1953 u16c = *--p;
1954 u16c += (*--p << 8);
1955 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001956 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1957 + (u8c & 0x3ff);
1958
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959 /* Check if the word is indeed a leading word. */
1960 if (u16c < 0xd800 || u16c > 0xdbff)
1961 {
1962 if (can_retry)
1963 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001964 if (conv_error == 0)
1965 conv_error = readfile_linenr(linecnt,
1966 ptr, p);
1967 if (bad_char_behavior == BAD_DROP)
1968 continue;
1969 if (bad_char_behavior != BAD_KEEP)
1970 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 }
1973 }
1974 else if (fio_flags & FIO_UCS4)
1975 {
1976 if (fio_flags & FIO_ENDIAN_L)
1977 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001978 u8c = (unsigned)*--p << 24;
1979 u8c += (unsigned)*--p << 16;
1980 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 u8c += *--p;
1982 }
1983 else /* big endian */
1984 {
1985 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001986 u8c += (unsigned)*--p << 8;
1987 u8c += (unsigned)*--p << 16;
1988 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 }
1990 }
1991 else /* UTF-8 */
1992 {
1993 if (*--p < 0x80)
1994 u8c = *p;
1995 else
1996 {
1997 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001998 p -= len;
1999 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 if (len == 0)
2001 {
2002 /* Not a valid UTF-8 character, retry with
2003 * another fenc when possible, otherwise just
2004 * report the error. */
2005 if (can_retry)
2006 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002007 if (conv_error == 0)
2008 conv_error = readfile_linenr(linecnt,
2009 ptr, p);
2010 if (bad_char_behavior == BAD_DROP)
2011 continue;
2012 if (bad_char_behavior != BAD_KEEP)
2013 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015 }
2016 }
2017 if (enc_utf8) /* produce UTF-8 */
2018 {
2019 dest -= utf_char2len(u8c);
2020 (void)utf_char2bytes(u8c, dest);
2021 }
2022 else /* produce Latin1 */
2023 {
2024 --dest;
2025 if (u8c >= 0x100)
2026 {
2027 /* character doesn't fit in latin1, retry with
2028 * another fenc when possible, otherwise just
2029 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002030 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002032 if (conv_error == 0)
2033 conv_error = readfile_linenr(linecnt, ptr, p);
2034 if (bad_char_behavior == BAD_DROP)
2035 ++dest;
2036 else if (bad_char_behavior == BAD_KEEP)
2037 *dest = u8c;
2038 else if (eap != NULL && eap->bad_char != 0)
2039 *dest = bad_char_behavior;
2040 else
2041 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 }
2043 else
2044 *dest = u8c;
2045 }
2046 }
2047
2048 /* move the linerest to before the converted characters */
2049 line_start = dest - linerest;
2050 mch_memmove(line_start, buffer, (size_t)linerest);
2051 size = (long)((ptr + real_size) - dest);
2052 ptr = dest;
2053 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002054 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002056 int incomplete_tail = FALSE;
2057
2058 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2059 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002061 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002062 int l;
2063
2064 if (todo <= 0)
2065 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 if (*p >= 0x80)
2067 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 /* A length of 1 means it's an illegal byte. Accept
2069 * an incomplete character at the end though, the next
2070 * read() will get the next bytes, we'll check it
2071 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002072 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002073 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002075 /* Avoid retrying with a different encoding when
2076 * a truncated file is more likely, or attempting
2077 * to read the rest of an incomplete sequence when
2078 * we have already done so. */
2079 if (p > ptr || filesize > 0)
2080 incomplete_tail = TRUE;
2081 /* Incomplete byte sequence, move it to conv_rest[]
2082 * and try to read the rest of it, unless we've
2083 * already done so. */
2084 if (p > ptr)
2085 {
2086 conv_restlen = todo;
2087 mch_memmove(conv_rest, p, conv_restlen);
2088 size -= conv_restlen;
2089 break;
2090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002092 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002093 {
2094 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002095 * do that, unless at EOF where a truncated
2096 * file is more likely than a conversion error. */
2097 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002098 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002099# ifdef USE_ICONV
2100 /* When we did a conversion report an error. */
2101 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2102 conv_error = readfile_linenr(linecnt, ptr, p);
2103# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002104 /* Remember the first linenr with an illegal byte */
2105 if (conv_error == 0 && illegal_byte == 0)
2106 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002107
2108 /* Drop, keep or replace the bad byte. */
2109 if (bad_char_behavior == BAD_DROP)
2110 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002111 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002112 --p;
2113 --size;
2114 }
2115 else if (bad_char_behavior != BAD_KEEP)
2116 *p = bad_char_behavior;
2117 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002118 else
2119 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 }
2121 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002122 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123 {
2124 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002126 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002128 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2129 /* iconv() failed, try 'charconvert' */
2130 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131 else
2132# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002133 /* use next item from 'fileencodings' */
2134 advance_fenc = TRUE;
2135 file_rewind = TRUE;
2136 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 }
2138 }
2139#endif
2140
2141 /* count the number of characters (after conversion!) */
2142 filesize += size;
2143
2144 /*
2145 * when reading the first part of a file: guess EOL type
2146 */
2147 if (fileformat == EOL_UNKNOWN)
2148 {
2149 /* First try finding a NL, for Dos and Unix */
2150 if (try_dos || try_unix)
2151 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002152 /* Reset the carriage return counter. */
2153 if (try_mac)
2154 try_mac = 1;
2155
Bram Moolenaar071d4272004-06-13 20:20:40 +00002156 for (p = ptr; p < ptr + size; ++p)
2157 {
2158 if (*p == NL)
2159 {
2160 if (!try_unix
2161 || (try_dos && p > ptr && p[-1] == CAR))
2162 fileformat = EOL_DOS;
2163 else
2164 fileformat = EOL_UNIX;
2165 break;
2166 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002167 else if (*p == CAR && try_mac)
2168 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 }
2170
2171 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2172 if (fileformat == EOL_UNIX && try_mac)
2173 {
2174 /* Need to reset the counters when retrying fenc. */
2175 try_mac = 1;
2176 try_unix = 1;
2177 for (; p >= ptr && *p != CAR; p--)
2178 ;
2179 if (p >= ptr)
2180 {
2181 for (p = ptr; p < ptr + size; ++p)
2182 {
2183 if (*p == NL)
2184 try_unix++;
2185 else if (*p == CAR)
2186 try_mac++;
2187 }
2188 if (try_mac > try_unix)
2189 fileformat = EOL_MAC;
2190 }
2191 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002192 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2193 /* Looking for CR but found no end-of-line markers at
2194 * all: use the default format. */
2195 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196 }
2197
2198 /* No NL found: may use Mac format */
2199 if (fileformat == EOL_UNKNOWN && try_mac)
2200 fileformat = EOL_MAC;
2201
2202 /* Still nothing found? Use first format in 'ffs' */
2203 if (fileformat == EOL_UNKNOWN)
2204 fileformat = default_fileformat();
2205
2206 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002207 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208 set_fileformat(fileformat, OPT_LOCAL);
2209 }
2210 }
2211
2212 /*
2213 * This loop is executed once for every character read.
2214 * Keep it fast!
2215 */
2216 if (fileformat == EOL_MAC)
2217 {
2218 --ptr;
2219 while (++ptr, --size >= 0)
2220 {
2221 /* catch most common case first */
2222 if ((c = *ptr) != NUL && c != CAR && c != NL)
2223 continue;
2224 if (c == NUL)
2225 *ptr = NL; /* NULs are replaced by newlines! */
2226 else if (c == NL)
2227 *ptr = CAR; /* NLs are replaced by CRs! */
2228 else
2229 {
2230 if (skip_count == 0)
2231 {
2232 *ptr = NUL; /* end of line */
2233 len = (colnr_T) (ptr - line_start + 1);
2234 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2235 {
2236 error = TRUE;
2237 break;
2238 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002239#ifdef FEAT_PERSISTENT_UNDO
2240 if (read_undo_file)
2241 sha256_update(&sha_ctx, line_start, len);
2242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 ++lnum;
2244 if (--read_count == 0)
2245 {
2246 error = TRUE; /* break loop */
2247 line_start = ptr; /* nothing left to write */
2248 break;
2249 }
2250 }
2251 else
2252 --skip_count;
2253 line_start = ptr + 1;
2254 }
2255 }
2256 }
2257 else
2258 {
2259 --ptr;
2260 while (++ptr, --size >= 0)
2261 {
2262 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2263 continue;
2264 if (c == NUL)
2265 *ptr = NL; /* NULs are replaced by newlines! */
2266 else
2267 {
2268 if (skip_count == 0)
2269 {
2270 *ptr = NUL; /* end of line */
2271 len = (colnr_T)(ptr - line_start + 1);
2272 if (fileformat == EOL_DOS)
2273 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002274 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002276 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 ptr[-1] = NUL;
2278 --len;
2279 }
2280 /*
2281 * Reading in Dos format, but no CR-LF found!
2282 * When 'fileformats' includes "unix", delete all
2283 * the lines read so far and start all over again.
2284 * Otherwise give an error message later.
2285 */
2286 else if (ff_error != EOL_DOS)
2287 {
2288 if ( try_unix
2289 && !read_stdin
2290 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002291 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2292 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293 {
2294 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002295 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 set_fileformat(EOL_UNIX, OPT_LOCAL);
2297 file_rewind = TRUE;
2298 keep_fileformat = TRUE;
2299 goto retry;
2300 }
2301 ff_error = EOL_DOS;
2302 }
2303 }
2304 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2305 {
2306 error = TRUE;
2307 break;
2308 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002309#ifdef FEAT_PERSISTENT_UNDO
2310 if (read_undo_file)
2311 sha256_update(&sha_ctx, line_start, len);
2312#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 ++lnum;
2314 if (--read_count == 0)
2315 {
2316 error = TRUE; /* break loop */
2317 line_start = ptr; /* nothing left to write */
2318 break;
2319 }
2320 }
2321 else
2322 --skip_count;
2323 line_start = ptr + 1;
2324 }
2325 }
2326 }
2327 linerest = (long)(ptr - line_start);
2328 ui_breakcheck();
2329 }
2330
2331failed:
2332 /* not an error, max. number of lines reached */
2333 if (error && read_count == 0)
2334 error = FALSE;
2335
2336 /*
2337 * If we get EOF in the middle of a line, note the fact and
2338 * complete the line ourselves.
2339 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2340 */
2341 if (!error
2342 && !got_int
2343 && linerest != 0
2344 && !(!curbuf->b_p_bin
2345 && fileformat == EOL_DOS
2346 && *line_start == Ctrl_Z
2347 && ptr == line_start + 1))
2348 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002349 /* remember for when writing */
2350 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 curbuf->b_p_eol = FALSE;
2352 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002353 len = (colnr_T)(ptr - line_start + 1);
2354 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 error = TRUE;
2356 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002357 {
2358#ifdef FEAT_PERSISTENT_UNDO
2359 if (read_undo_file)
2360 sha256_update(&sha_ctx, line_start, len);
2361#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002363 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364 }
2365
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002366 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 save_file_ff(curbuf); /* remember the current file format */
2368
2369#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002370 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002371 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002372 crypt_free_state(curbuf->b_cryptstate);
2373 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002374 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002375 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2376 crypt_free_key(cryptkey);
2377 /* Don't set cryptkey to NULL, it's used below as a flag that
2378 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379#endif
2380
2381#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002382 /* If editing a new file: set 'fenc' for the current buffer.
2383 * Also for ":read ++edit file". */
2384 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002386 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 if (fenc_alloced)
2388 vim_free(fenc);
2389# ifdef USE_ICONV
2390 if (iconv_fd != (iconv_t)-1)
2391 {
2392 iconv_close(iconv_fd);
2393 iconv_fd = (iconv_t)-1;
2394 }
2395# endif
2396#endif
2397
2398 if (!read_buffer && !read_stdin)
2399 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002400#ifdef HAVE_FD_CLOEXEC
2401 else
2402 {
2403 int fdflags = fcntl(fd, F_GETFD);
2404 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002405 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002406 }
2407#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 vim_free(buffer);
2409
2410#ifdef HAVE_DUP
2411 if (read_stdin)
2412 {
2413 /* Use stderr for stdin, makes shell commands work. */
2414 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002415 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 }
2417#endif
2418
2419#ifdef FEAT_MBYTE
2420 if (tmpname != NULL)
2421 {
2422 mch_remove(tmpname); /* delete converted file */
2423 vim_free(tmpname);
2424 }
2425#endif
2426 --no_wait_return; /* may wait for return now */
2427
2428 /*
2429 * In recovery mode everything but autocommands is skipped.
2430 */
2431 if (!recoverymode)
2432 {
2433 /* need to delete the last line, which comes from the empty buffer */
2434 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2435 {
2436#ifdef FEAT_NETBEANS_INTG
2437 netbeansFireChanges = 0;
2438#endif
2439 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2440#ifdef FEAT_NETBEANS_INTG
2441 netbeansFireChanges = 1;
2442#endif
2443 --linecnt;
2444 }
2445 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2446 if (filesize == 0)
2447 linecnt = 0;
2448 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002449 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002451#ifdef FEAT_DIFF
2452 /* After reading the text into the buffer the diff info needs to
2453 * be updated. */
2454 diff_invalidate(curbuf);
2455#endif
2456#ifdef FEAT_FOLDING
2457 /* All folds in the window are invalid now. Mark them for update
2458 * before triggering autocommands. */
2459 foldUpdateAll(curwin);
2460#endif
2461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 else if (linecnt) /* appended at least one line */
2463 appended_lines_mark(from, linecnt);
2464
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465#ifndef ALWAYS_USE_GUI
2466 /*
2467 * If we were reading from the same terminal as where messages go,
2468 * the screen will have been messed up.
2469 * Switch on raw mode now and clear the screen.
2470 */
2471 if (read_stdin)
2472 {
2473 settmode(TMODE_RAW); /* set to raw mode */
2474 starttermcap();
2475 screenclear();
2476 }
2477#endif
2478
2479 if (got_int)
2480 {
2481 if (!(flags & READ_DUMMY))
2482 {
2483 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2484 if (newfile)
2485 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2486 }
2487 msg_scroll = msg_save;
2488#ifdef FEAT_VIMINFO
2489 check_marks_read();
2490#endif
2491 return OK; /* an interrupt isn't really an error */
2492 }
2493
2494 if (!filtering && !(flags & READ_DUMMY))
2495 {
2496 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2497 c = FALSE;
2498
2499#ifdef UNIX
2500# ifdef S_ISFIFO
2501 if (S_ISFIFO(perm)) /* fifo or socket */
2502 {
2503 STRCAT(IObuff, _("[fifo/socket]"));
2504 c = TRUE;
2505 }
2506# else
2507# ifdef S_IFIFO
2508 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2509 {
2510 STRCAT(IObuff, _("[fifo]"));
2511 c = TRUE;
2512 }
2513# endif
2514# ifdef S_IFSOCK
2515 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2516 {
2517 STRCAT(IObuff, _("[socket]"));
2518 c = TRUE;
2519 }
2520# endif
2521# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002522# ifdef OPEN_CHR_FILES
2523 if (S_ISCHR(perm)) /* or character special */
2524 {
2525 STRCAT(IObuff, _("[character special]"));
2526 c = TRUE;
2527 }
2528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529#endif
2530 if (curbuf->b_p_ro)
2531 {
2532 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2533 c = TRUE;
2534 }
2535 if (read_no_eol_lnum)
2536 {
2537 msg_add_eol();
2538 c = TRUE;
2539 }
2540 if (ff_error == EOL_DOS)
2541 {
2542 STRCAT(IObuff, _("[CR missing]"));
2543 c = TRUE;
2544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 if (split)
2546 {
2547 STRCAT(IObuff, _("[long lines split]"));
2548 c = TRUE;
2549 }
2550#ifdef FEAT_MBYTE
2551 if (notconverted)
2552 {
2553 STRCAT(IObuff, _("[NOT converted]"));
2554 c = TRUE;
2555 }
2556 else if (converted)
2557 {
2558 STRCAT(IObuff, _("[converted]"));
2559 c = TRUE;
2560 }
2561#endif
2562#ifdef FEAT_CRYPT
2563 if (cryptkey != NULL)
2564 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002565 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566 c = TRUE;
2567 }
2568#endif
2569#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002570 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002572 sprintf((char *)IObuff + STRLEN(IObuff),
2573 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574 c = TRUE;
2575 }
2576 else if (illegal_byte > 0)
2577 {
2578 sprintf((char *)IObuff + STRLEN(IObuff),
2579 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2580 c = TRUE;
2581 }
2582 else
2583#endif
2584 if (error)
2585 {
2586 STRCAT(IObuff, _("[READ ERRORS]"));
2587 c = TRUE;
2588 }
2589 if (msg_add_fileformat(fileformat))
2590 c = TRUE;
2591#ifdef FEAT_CRYPT
2592 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002593 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002594 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 else
2596#endif
2597 msg_add_lines(c, (long)linecnt, filesize);
2598
Bram Moolenaard23a8232018-02-10 18:45:26 +01002599 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 msg_scrolled_ign = TRUE;
2601#ifdef ALWAYS_USE_GUI
2602 /* Don't show the message when reading stdin, it would end up in a
2603 * message box (which might be shown when exiting!) */
2604 if (read_stdin || read_buffer)
2605 p = msg_may_trunc(FALSE, IObuff);
2606 else
2607#endif
2608 p = msg_trunc_attr(IObuff, FALSE, 0);
2609 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002610 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 /* Need to repeat the message after redrawing when:
2612 * - When reading from stdin (the screen will be cleared next).
2613 * - When restart_edit is set (otherwise there will be a delay
2614 * before redrawing).
2615 * - When the screen was scrolled but there is no wait-return
2616 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002617 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 msg_scrolled_ign = FALSE;
2619 }
2620
2621 /* with errors writing the file requires ":w!" */
2622 if (newfile && (error
2623#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002624 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002625 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626#endif
2627 ))
2628 curbuf->b_p_ro = TRUE;
2629
2630 u_clearline(); /* cannot use "U" command after adding lines */
2631
2632 /*
2633 * In Ex mode: cursor at last new line.
2634 * Otherwise: cursor at first new line.
2635 */
2636 if (exmode_active)
2637 curwin->w_cursor.lnum = from + linecnt;
2638 else
2639 curwin->w_cursor.lnum = from + 1;
2640 check_cursor_lnum();
2641 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2642
2643 /*
2644 * Set '[ and '] marks to the newly read lines.
2645 */
2646 curbuf->b_op_start.lnum = from + 1;
2647 curbuf->b_op_start.col = 0;
2648 curbuf->b_op_end.lnum = from + linecnt;
2649 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002650
2651#ifdef WIN32
2652 /*
2653 * Work around a weird problem: When a file has two links (only
2654 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002655 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002656 * It's correct again after reading the file, thus reset the timestamp
2657 * here.
2658 */
2659 if (newfile && !read_stdin && !read_buffer
2660 && mch_stat((char *)fname, &st) >= 0)
2661 {
2662 buf_store_time(curbuf, &st, fname);
2663 curbuf->b_mtime_read = curbuf->b_mtime;
2664 }
2665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 }
2667 msg_scroll = msg_save;
2668
2669#ifdef FEAT_VIMINFO
2670 /*
2671 * Get the marks before executing autocommands, so they can be used there.
2672 */
2673 check_marks_read();
2674#endif
2675
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002677 * We remember if the last line of the read didn't have
2678 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2679 * or writing the read again with 'binary' on. The latter is required
2680 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002682 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002684 /* When reloading a buffer put the cursor at the first line that is
2685 * different. */
2686 if (flags & READ_KEEP_UNDO)
2687 u_find_first_changed();
2688
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002689#ifdef FEAT_PERSISTENT_UNDO
2690 /*
2691 * When opening a new file locate undo info and read it.
2692 */
2693 if (read_undo_file)
2694 {
2695 char_u hash[UNDO_HASH_SIZE];
2696
2697 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002698 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002699 }
2700#endif
2701
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002702 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 {
2704 int m = msg_scroll;
2705 int n = msg_scrolled;
2706
2707 /* Save the fileformat now, otherwise the buffer will be considered
2708 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002709 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 save_file_ff(curbuf);
2711
2712 /*
2713 * The output from the autocommands should not overwrite anything and
2714 * should not be overwritten: Set msg_scroll, restore its value if no
2715 * output was done.
2716 */
2717 msg_scroll = TRUE;
2718 if (filtering)
2719 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2720 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002721 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002722 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2724 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002725 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2726 /*
2727 * EVENT_FILETYPE was not triggered but the buffer already has a
2728 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2729 */
2730 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2731 TRUE, curbuf);
2732 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733 else
2734 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2735 FALSE, NULL, eap);
2736 if (msg_scrolled == n)
2737 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002738# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 if (aborting()) /* autocmds may abort script processing */
2740 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002741# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743
2744 if (recoverymode && error)
2745 return FAIL;
2746 return OK;
2747}
2748
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002749#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002750/*
2751 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2752 * which is the name of files used for process substitution output by
2753 * some shells on some operating systems, e.g., bash on SunOS.
2754 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2755 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002756 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002757is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002758{
2759 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2760 && VIM_ISDIGIT(fname[8])
2761 && *skipdigits(fname + 9) == NUL
2762 && (fname[9] != NUL
2763 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2764}
2765#endif
2766
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002767#ifdef FEAT_MBYTE
2768
2769/*
2770 * From the current line count and characters read after that, estimate the
2771 * line number where we are now.
2772 * Used for error messages that include a line number.
2773 */
2774 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002775readfile_linenr(
2776 linenr_T linecnt, /* line count before reading more bytes */
2777 char_u *p, /* start of more bytes read */
2778 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002779{
2780 char_u *s;
2781 linenr_T lnum;
2782
2783 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2784 for (s = p; s < endp; ++s)
2785 if (*s == '\n')
2786 ++lnum;
2787 return lnum;
2788}
2789#endif
2790
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002792 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2793 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 * Returns OK or FAIL.
2795 */
2796 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002797prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002799 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002801 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002802#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002803 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804 if (eap->cmd == NULL)
2805 return FAIL;
2806
2807#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002808 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2809 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002810 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002812 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002814 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002815
2816 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002817 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002818 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819 return OK;
2820}
2821
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002822/*
2823 * Set default or forced 'fileformat' and 'binary'.
2824 */
2825 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002826set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002827{
2828 /* set default 'fileformat' */
2829 if (set_options)
2830 {
2831 if (eap != NULL && eap->force_ff != 0)
2832 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2833 else if (*p_ffs != NUL)
2834 set_fileformat(default_fileformat(), OPT_LOCAL);
2835 }
2836
2837 /* set or reset 'binary' */
2838 if (eap != NULL && eap->force_bin != 0)
2839 {
2840 int oldval = curbuf->b_p_bin;
2841
2842 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2843 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2844 }
2845}
2846
2847#if defined(FEAT_MBYTE) || defined(PROTO)
2848/*
2849 * Set forced 'fileencoding'.
2850 */
2851 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002852set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002853{
2854 if (eap->force_enc != 0)
2855 {
2856 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2857
2858 if (fenc != NULL)
2859 set_string_option_direct((char_u *)"fenc", -1,
2860 fenc, OPT_FREE|OPT_LOCAL, 0);
2861 vim_free(fenc);
2862 }
2863}
2864
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865/*
2866 * Find next fileencoding to use from 'fileencodings'.
2867 * "pp" points to fenc_next. It's advanced to the next item.
2868 * When there are no more items, an empty string is returned and *pp is set to
2869 * NULL.
2870 * When *pp is not set to NULL, the result is in allocated memory.
2871 */
2872 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002873next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874{
2875 char_u *p;
2876 char_u *r;
2877
2878 if (**pp == NUL)
2879 {
2880 *pp = NULL;
2881 return (char_u *)"";
2882 }
2883 p = vim_strchr(*pp, ',');
2884 if (p == NULL)
2885 {
2886 r = enc_canonize(*pp);
2887 *pp += STRLEN(*pp);
2888 }
2889 else
2890 {
2891 r = vim_strnsave(*pp, (int)(p - *pp));
2892 *pp = p + 1;
2893 if (r != NULL)
2894 {
2895 p = enc_canonize(r);
2896 vim_free(r);
2897 r = p;
2898 }
2899 }
2900 if (r == NULL) /* out of memory */
2901 {
2902 r = (char_u *)"";
2903 *pp = NULL;
2904 }
2905 return r;
2906}
2907
2908# ifdef FEAT_EVAL
2909/*
2910 * Convert a file with the 'charconvert' expression.
2911 * This closes the file which is to be read, converts it and opens the
2912 * resulting file for reading.
2913 * Returns name of the resulting converted file (the caller should delete it
2914 * after reading it).
2915 * Returns NULL if the conversion failed ("*fdp" is not set) .
2916 */
2917 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002918readfile_charconvert(
2919 char_u *fname, /* name of input file */
2920 char_u *fenc, /* converted from */
2921 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922{
2923 char_u *tmpname;
2924 char_u *errmsg = NULL;
2925
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002926 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 if (tmpname == NULL)
2928 errmsg = (char_u *)_("Can't find temp file for conversion");
2929 else
2930 {
2931 close(*fdp); /* close the input file, ignore errors */
2932 *fdp = -1;
2933 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2934 fname, tmpname) == FAIL)
2935 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2936 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2937 O_RDONLY | O_EXTRA, 0)) < 0)
2938 errmsg = (char_u *)_("can't read output of 'charconvert'");
2939 }
2940
2941 if (errmsg != NULL)
2942 {
2943 /* Don't use emsg(), it breaks mappings, the retry with
2944 * another type of conversion might still work. */
2945 MSG(errmsg);
2946 if (tmpname != NULL)
2947 {
2948 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002949 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 }
2951 }
2952
2953 /* If the input file is closed, open it (caller should check for error). */
2954 if (*fdp < 0)
2955 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2956
2957 return tmpname;
2958}
2959# endif
2960
2961#endif
2962
2963#ifdef FEAT_VIMINFO
2964/*
2965 * Read marks for the current buffer from the viminfo file, when we support
2966 * buffer marks and the buffer has a name.
2967 */
2968 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002969check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970{
2971 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2972 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002973 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974
2975 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2976 * the ' parameter after opening a buffer. */
2977 curbuf->b_marks_read = TRUE;
2978}
2979#endif
2980
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002981#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002983 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2985 * *filesizep are updated.
2986 * Return the (new) encryption key, NULL for no encryption.
2987 */
2988 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002989check_for_cryptkey(
2990 char_u *cryptkey, /* previous encryption key or NULL */
2991 char_u *ptr, /* pointer to read bytes */
2992 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002993 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002994 int newfile, /* editing a new buffer */
2995 char_u *fname, /* file name to display */
2996 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002998 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002999 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003000
3001 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003003 /* Mark the buffer as read-only until the decryption has taken place.
3004 * Avoids accidentally overwriting the file with garbage. */
3005 curbuf->b_p_ro = TRUE;
3006
Bram Moolenaar2be79502014-08-13 21:58:28 +02003007 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003008 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003009 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 {
3011 if (*curbuf->b_p_key)
3012 cryptkey = curbuf->b_p_key;
3013 else
3014 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003015 /* When newfile is TRUE, store the typed key in the 'key'
3016 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003017 * Don't ask for the key again when first time Enter was hit.
3018 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003019 smsg((char_u *)_(need_key_msg), fname);
3020 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003021 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003022 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003023 *did_ask = TRUE;
3024
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 /* check if empty key entered */
3026 if (cryptkey != NULL && *cryptkey == NUL)
3027 {
3028 if (cryptkey != curbuf->b_p_key)
3029 vim_free(cryptkey);
3030 cryptkey = NULL;
3031 }
3032 }
3033 }
3034
3035 if (cryptkey != NULL)
3036 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003037 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003038
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003039 curbuf->b_cryptstate = crypt_create_from_header(
3040 method, cryptkey, ptr);
3041 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003043 /* Remove cryptmethod specific header from the text. */
3044 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003045 if (*sizep <= header_len)
3046 /* invalid header, buffer can't be encrypted */
3047 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003048 *filesizep += header_len;
3049 *sizep -= header_len;
3050 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3051
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003052 /* Restore the read-only flag. */
3053 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054 }
3055 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003056 /* When starting to edit a new file which does not have encryption, clear
3057 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003058 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3060
3061 return cryptkey;
3062}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003063#endif /* FEAT_CRYPT */
3064
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065#ifdef UNIX
3066 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003067set_file_time(
3068 char_u *fname,
3069 time_t atime, /* access time */
3070 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071{
3072# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3073 struct utimbuf buf;
3074
3075 buf.actime = atime;
3076 buf.modtime = mtime;
3077 (void)utime((char *)fname, &buf);
3078# else
3079# if defined(HAVE_UTIMES)
3080 struct timeval tvp[2];
3081
3082 tvp[0].tv_sec = atime;
3083 tvp[0].tv_usec = 0;
3084 tvp[1].tv_sec = mtime;
3085 tvp[1].tv_usec = 0;
3086# ifdef NeXT
3087 (void)utimes((char *)fname, tvp);
3088# else
3089 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3090# endif
3091# endif
3092# endif
3093}
3094#endif /* UNIX */
3095
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003096#if defined(VMS) && !defined(MIN)
3097/* Older DECC compiler for VAX doesn't define MIN() */
3098# define MIN(a, b) ((a) < (b) ? (a) : (b))
3099#endif
3100
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003102 * Return TRUE if a file appears to be read-only from the file permissions.
3103 */
3104 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003105check_file_readonly(
3106 char_u *fname, /* full path to file */
3107 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003108{
3109#ifndef USE_MCH_ACCESS
3110 int fd = 0;
3111#endif
3112
3113 return (
3114#ifdef USE_MCH_ACCESS
3115# ifdef UNIX
3116 (perm & 0222) == 0 ||
3117# endif
3118 mch_access((char *)fname, W_OK)
3119#else
3120 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3121 ? TRUE : (close(fd), FALSE)
3122#endif
3123 );
3124}
3125
3126
3127/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003128 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129 *
3130 * We do our own buffering here because fwrite() is so slow.
3131 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003132 * If "forceit" is true, we don't care for errors when attempting backups.
3133 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003134 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003135 *
3136 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3137 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 *
3139 * This function must NOT use NameBuff (because it's called by autowrite()).
3140 *
3141 * return FAIL for failure, OK otherwise
3142 */
3143 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003144buf_write(
3145 buf_T *buf,
3146 char_u *fname,
3147 char_u *sfname,
3148 linenr_T start,
3149 linenr_T end,
3150 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003152 int append, /* append to the file */
3153 int forceit,
3154 int reset_changed,
3155 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156{
3157 int fd;
3158 char_u *backup = NULL;
3159 int backup_copy = FALSE; /* copy the original file? */
3160 int dobackup;
3161 char_u *ffname;
3162 char_u *wfname = NULL; /* name of file to write to */
3163 char_u *s;
3164 char_u *ptr;
3165 char_u c;
3166 int len;
3167 linenr_T lnum;
3168 long nchars;
3169 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003170 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 char_u *errnum = NULL;
3172 char_u *buffer;
3173 char_u smallbuf[SMBUFSIZE];
3174 char_u *backup_ext;
3175 int bufsize;
3176 long perm; /* file permissions */
3177 int retval = OK;
3178 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3179 int msg_save = msg_scroll;
3180 int overwriting; /* TRUE if writing over original */
3181 int no_eol = FALSE; /* no end-of-line written */
3182 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003183 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003185 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 int file_readonly = FALSE; /* overwritten file is read-only */
3187 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003188#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189 int made_writable = FALSE; /* 'w' bit has been set */
3190#endif
3191 /* writing everything */
3192 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 int attr;
3195 int fileformat;
3196 int write_bin;
3197 struct bw_info write_info; /* info for buf_write_bytes() */
3198#ifdef FEAT_MBYTE
3199 int converted = FALSE;
3200 int notconverted = FALSE;
3201 char_u *fenc; /* effective 'fileencoding' */
3202 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3203#endif
3204#ifdef HAS_BW_FLAGS
3205 int wb_flags = 0;
3206#endif
3207#ifdef HAVE_ACL
3208 vim_acl_T acl = NULL; /* ACL copied from original file to
3209 backup or new file */
3210#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003211#ifdef FEAT_PERSISTENT_UNDO
3212 int write_undo_file = FALSE;
3213 context_sha256_T sha_ctx;
3214#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003215 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216
3217 if (fname == NULL || *fname == NUL) /* safety check */
3218 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003219 if (buf->b_ml.ml_mfp == NULL)
3220 {
3221 /* This can happen during startup when there is a stray "w" in the
3222 * vimrc file. */
3223 EMSG(_(e_emptybuf));
3224 return FAIL;
3225 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226
3227 /*
3228 * Disallow writing from .exrc and .vimrc in current directory for
3229 * security reasons.
3230 */
3231 if (check_secure())
3232 return FAIL;
3233
3234 /* Avoid a crash for a long name. */
3235 if (STRLEN(fname) >= MAXPATHL)
3236 {
3237 EMSG(_(e_longname));
3238 return FAIL;
3239 }
3240
3241#ifdef FEAT_MBYTE
3242 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3243 write_info.bw_conv_buf = NULL;
3244 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003245 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 write_info.bw_restlen = 0;
3247# ifdef USE_ICONV
3248 write_info.bw_iconv_fd = (iconv_t)-1;
3249# endif
3250#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003251#ifdef FEAT_CRYPT
3252 write_info.bw_buffer = buf;
3253#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254
Bram Moolenaardf177f62005-02-22 08:39:57 +00003255 /* After writing a file changedtick changes but we don't want to display
3256 * the line. */
3257 ex_no_reprint = TRUE;
3258
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 /*
3260 * If there is no file name yet, use the one for the written file.
3261 * BF_NOTEDITED is set to reflect this (in case the write fails).
3262 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003263 * Don't do this when appending.
3264 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003266 if (buf->b_ffname == NULL
3267 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268 && whole
3269 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003270#ifdef FEAT_QUICKFIX
3271 && !bt_nofile(buf)
3272#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003274 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3276 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003277 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003279 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 }
3281
3282 if (sfname == NULL)
3283 sfname = fname;
3284 /*
3285 * For Unix: Use the short file name whenever possible.
3286 * Avoids problems with networks and when directory names are changed.
3287 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3288 * another directory, which we don't detect
3289 */
3290 ffname = fname; /* remember full fname */
3291#ifdef UNIX
3292 fname = sfname;
3293#endif
3294
3295 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3296 overwriting = TRUE;
3297 else
3298 overwriting = FALSE;
3299
3300 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003301 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302
3303 ++no_wait_return; /* don't wait for return yet */
3304
3305 /*
3306 * Set '[ and '] marks to the lines to be written.
3307 */
3308 buf->b_op_start.lnum = start;
3309 buf->b_op_start.col = 0;
3310 buf->b_op_end.lnum = end;
3311 buf->b_op_end.col = 0;
3312
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313 {
3314 aco_save_T aco;
3315 int buf_ffname = FALSE;
3316 int buf_sfname = FALSE;
3317 int buf_fname_f = FALSE;
3318 int buf_fname_s = FALSE;
3319 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003320 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003321 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003322 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323
3324 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003325 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326 * Set curbuf to the buffer to be written.
3327 * Careful: The autocommands may call buf_write() recursively!
3328 */
3329 if (ffname == buf->b_ffname)
3330 buf_ffname = TRUE;
3331 if (sfname == buf->b_sfname)
3332 buf_sfname = TRUE;
3333 if (fname == buf->b_ffname)
3334 buf_fname_f = TRUE;
3335 if (fname == buf->b_sfname)
3336 buf_fname_s = TRUE;
3337
3338 /* set curwin/curbuf to buf and save a few things */
3339 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003340 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341
3342 if (append)
3343 {
3344 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3345 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003346 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003347#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003348 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003349 nofile_err = TRUE;
3350 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003351#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003352 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003354 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 }
3356 else if (filtering)
3357 {
3358 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3359 NULL, sfname, FALSE, curbuf, eap);
3360 }
3361 else if (reset_changed && whole)
3362 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003363 int was_changed = curbufIsChanged();
3364
3365 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3366 sfname, sfname, FALSE, curbuf, eap);
3367 if (did_cmd)
3368 {
3369 if (was_changed && !curbufIsChanged())
3370 {
3371 /* Written everything correctly and BufWriteCmd has reset
3372 * 'modified': Correct the undo information so that an
3373 * undo now sets 'modified'. */
3374 u_unchanged(curbuf);
3375 u_update_save_nr(curbuf);
3376 }
3377 }
3378 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003379 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003380#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003381 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003382 nofile_err = TRUE;
3383 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003384#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003385 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 }
3389 else
3390 {
3391 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3392 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003393 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003394#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003395 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003396 nofile_err = TRUE;
3397 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003398#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003399 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003401 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402 }
3403
3404 /* restore curwin/curbuf and a few other things */
3405 aucmd_restbuf(&aco);
3406
3407 /*
3408 * In three situations we return here and don't write the file:
3409 * 1. the autocommands deleted or unloaded the buffer.
3410 * 2. The autocommands abort script processing.
3411 * 3. If one of the "Cmd" autocommands was executed.
3412 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003413 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003414 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003415 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003416 || did_cmd || nofile_err
3417#ifdef FEAT_EVAL
3418 || aborting()
3419#endif
3420 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421 {
3422 --no_wait_return;
3423 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003424 if (nofile_err)
3425 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3426
Bram Moolenaar1e015462005-09-25 22:16:38 +00003427 if (nofile_err
3428#ifdef FEAT_EVAL
3429 || aborting()
3430#endif
3431 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 /* An aborting error, interrupt or exception in the
3433 * autocommands. */
3434 return FAIL;
3435 if (did_cmd)
3436 {
3437 if (buf == NULL)
3438 /* The buffer was deleted. We assume it was written
3439 * (can't retry anyway). */
3440 return OK;
3441 if (overwriting)
3442 {
3443 /* Assume the buffer was written, update the timestamp. */
3444 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003445 if (append)
3446 buf->b_flags &= ~BF_NEW;
3447 else
3448 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003450 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003451 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452 /* Buffer still changed, the autocommands didn't work
3453 * properly. */
3454 return FAIL;
3455 return OK;
3456 }
3457#ifdef FEAT_EVAL
3458 if (!aborting())
3459#endif
3460 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3461 return FAIL;
3462 }
3463
3464 /*
3465 * The autocommands may have changed the number of lines in the file.
3466 * When writing the whole file, adjust the end.
3467 * When writing part of the file, assume that the autocommands only
3468 * changed the number of lines that are to be written (tricky!).
3469 */
3470 if (buf->b_ml.ml_line_count != old_line_count)
3471 {
3472 if (whole) /* write all */
3473 end = buf->b_ml.ml_line_count;
3474 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3475 end += buf->b_ml.ml_line_count - old_line_count;
3476 else /* less lines */
3477 {
3478 end -= old_line_count - buf->b_ml.ml_line_count;
3479 if (end < start)
3480 {
3481 --no_wait_return;
3482 msg_scroll = msg_save;
3483 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3484 return FAIL;
3485 }
3486 }
3487 }
3488
3489 /*
3490 * The autocommands may have changed the name of the buffer, which may
3491 * be kept in fname, ffname and sfname.
3492 */
3493 if (buf_ffname)
3494 ffname = buf->b_ffname;
3495 if (buf_sfname)
3496 sfname = buf->b_sfname;
3497 if (buf_fname_f)
3498 fname = buf->b_ffname;
3499 if (buf_fname_s)
3500 fname = buf->b_sfname;
3501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
3503#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003504 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505 {
3506 if (whole)
3507 {
3508 /*
3509 * b_changed can be 0 after an undo, but we still need to write
3510 * the buffer to NetBeans.
3511 */
3512 if (buf->b_changed || isNetbeansModified(buf))
3513 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003514 --no_wait_return; /* may wait for return now */
3515 msg_scroll = msg_save;
3516 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 return retval;
3518 }
3519 else
3520 {
3521 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003522 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523 buffer = NULL;
3524 goto fail;
3525 }
3526 }
3527 else
3528 {
3529 errnum = (char_u *)"E657: ";
3530 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3531 buffer = NULL;
3532 goto fail;
3533 }
3534 }
3535#endif
3536
3537 if (shortmess(SHM_OVER) && !exiting)
3538 msg_scroll = FALSE; /* overwrite previous file message */
3539 else
3540 msg_scroll = TRUE; /* don't overwrite previous file message */
3541 if (!filtering)
3542 filemess(buf,
3543#ifndef UNIX
3544 sfname,
3545#else
3546 fname,
3547#endif
3548 (char_u *)"", 0); /* show that we are busy */
3549 msg_scroll = FALSE; /* always overwrite the file message now */
3550
3551 buffer = alloc(BUFSIZE);
3552 if (buffer == NULL) /* can't allocate big buffer, use small
3553 * one (to be able to write when out of
3554 * memory) */
3555 {
3556 buffer = smallbuf;
3557 bufsize = SMBUFSIZE;
3558 }
3559 else
3560 bufsize = BUFSIZE;
3561
3562 /*
3563 * Get information about original file (if there is one).
3564 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003565#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003566 st_old.st_dev = 0;
3567 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568 perm = -1;
3569 if (mch_stat((char *)fname, &st_old) < 0)
3570 newfile = TRUE;
3571 else
3572 {
3573 perm = st_old.st_mode;
3574 if (!S_ISREG(st_old.st_mode)) /* not a file */
3575 {
3576 if (S_ISDIR(st_old.st_mode))
3577 {
3578 errnum = (char_u *)"E502: ";
3579 errmsg = (char_u *)_("is a directory");
3580 goto fail;
3581 }
3582 if (mch_nodetype(fname) != NODE_WRITABLE)
3583 {
3584 errnum = (char_u *)"E503: ";
3585 errmsg = (char_u *)_("is not a file or writable device");
3586 goto fail;
3587 }
3588 /* It's a device of some kind (or a fifo) which we can write to
3589 * but for which we can't make a backup. */
3590 device = TRUE;
3591 newfile = TRUE;
3592 perm = -1;
3593 }
3594 }
3595#else /* !UNIX */
3596 /*
3597 * Check for a writable device name.
3598 */
3599 c = mch_nodetype(fname);
3600 if (c == NODE_OTHER)
3601 {
3602 errnum = (char_u *)"E503: ";
3603 errmsg = (char_u *)_("is not a file or writable device");
3604 goto fail;
3605 }
3606 if (c == NODE_WRITABLE)
3607 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003608# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003609 /* MS-Windows allows opening a device, but we will probably get stuck
3610 * trying to write to it. */
3611 if (!p_odev)
3612 {
3613 errnum = (char_u *)"E796: ";
3614 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3615 goto fail;
3616 }
3617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 device = TRUE;
3619 newfile = TRUE;
3620 perm = -1;
3621 }
3622 else
3623 {
3624 perm = mch_getperm(fname);
3625 if (perm < 0)
3626 newfile = TRUE;
3627 else if (mch_isdir(fname))
3628 {
3629 errnum = (char_u *)"E502: ";
3630 errmsg = (char_u *)_("is a directory");
3631 goto fail;
3632 }
3633 if (overwriting)
3634 (void)mch_stat((char *)fname, &st_old);
3635 }
3636#endif /* !UNIX */
3637
3638 if (!device && !newfile)
3639 {
3640 /*
3641 * Check if the file is really writable (when renaming the file to
3642 * make a backup we won't discover it later).
3643 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003644 file_readonly = check_file_readonly(fname, (int)perm);
3645
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646 if (!forceit && file_readonly)
3647 {
3648 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3649 {
3650 errnum = (char_u *)"E504: ";
3651 errmsg = (char_u *)_(err_readonly);
3652 }
3653 else
3654 {
3655 errnum = (char_u *)"E505: ";
3656 errmsg = (char_u *)_("is read-only (add ! to override)");
3657 }
3658 goto fail;
3659 }
3660
3661 /*
3662 * Check if the timestamp hasn't changed since reading the file.
3663 */
3664 if (overwriting)
3665 {
3666 retval = check_mtime(buf, &st_old);
3667 if (retval == FAIL)
3668 goto fail;
3669 }
3670 }
3671
3672#ifdef HAVE_ACL
3673 /*
3674 * For systems that support ACL: get the ACL from the original file.
3675 */
3676 if (!newfile)
3677 acl = mch_get_acl(fname);
3678#endif
3679
3680 /*
3681 * If 'backupskip' is not empty, don't make a backup for some files.
3682 */
3683 dobackup = (p_wb || p_bk || *p_pm != NUL);
3684#ifdef FEAT_WILDIGN
3685 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3686 dobackup = FALSE;
3687#endif
3688
3689 /*
3690 * Save the value of got_int and reset it. We don't want a previous
3691 * interruption cancel writing, only hitting CTRL-C while writing should
3692 * abort it.
3693 */
3694 prev_got_int = got_int;
3695 got_int = FALSE;
3696
3697 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3698 buf->b_saving = TRUE;
3699
3700 /*
3701 * If we are not appending or filtering, the file exists, and the
3702 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3703 * When 'patchmode' is set also make a backup when appending.
3704 *
3705 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3706 * off. This helps when editing large files on almost-full disks.
3707 */
3708 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3709 {
3710#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003711 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712#endif
3713
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003714 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 backup_copy = TRUE;
3716#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003717 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 {
3719 int i;
3720
3721# ifdef UNIX
3722 /*
3723 * Don't rename the file when:
3724 * - it's a hard link
3725 * - it's a symbolic link
3726 * - we don't have write permission in the directory
3727 * - we can't set the owner/group of the new file
3728 */
3729 if (st_old.st_nlink > 1
3730 || mch_lstat((char *)fname, &st) < 0
3731 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003732 || st.st_ino != st_old.st_ino
3733# ifndef HAVE_FCHOWN
3734 || st.st_uid != st_old.st_uid
3735 || st.st_gid != st_old.st_gid
3736# endif
3737 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 backup_copy = TRUE;
3739 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003740# else
3741# ifdef WIN32
3742 /* On NTFS file systems hard links are possible. */
3743 if (mch_is_linked(fname))
3744 backup_copy = TRUE;
3745 else
3746# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747# endif
3748 {
3749 /*
3750 * Check if we can create a file and set the owner/group to
3751 * the ones from the original file.
3752 * First find a file name that doesn't exist yet (use some
3753 * arbitrary numbers).
3754 */
3755 STRCPY(IObuff, fname);
3756 for (i = 4913; ; i += 123)
3757 {
3758 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003759 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760 break;
3761 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003762 fd = mch_open((char *)IObuff,
3763 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764 if (fd < 0) /* can't write in directory */
3765 backup_copy = TRUE;
3766 else
3767 {
3768# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003769# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003770 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003771# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 if (mch_stat((char *)IObuff, &st) < 0
3773 || st.st_uid != st_old.st_uid
3774 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003775 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776 backup_copy = TRUE;
3777# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003778 /* Close the file before removing it, on MS-Windows we
3779 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003780 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003781 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003782# ifdef MSWIN
3783 /* MS-Windows may trigger a virus scanner to open the
3784 * file, we can't delete it then. Keep trying for half a
3785 * second. */
3786 {
3787 int try;
3788
3789 for (try = 0; try < 10; ++try)
3790 {
3791 if (mch_lstat((char *)IObuff, &st) < 0)
3792 break;
3793 ui_delay(50L, TRUE); /* wait 50 msec */
3794 mch_remove(IObuff);
3795 }
3796 }
3797# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 }
3799 }
3800 }
3801
Bram Moolenaar071d4272004-06-13 20:20:40 +00003802 /*
3803 * Break symlinks and/or hardlinks if we've been asked to.
3804 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003805 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003807# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 int lstat_res;
3809
3810 lstat_res = mch_lstat((char *)fname, &st);
3811
3812 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003813 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 && lstat_res == 0
3815 && st.st_ino != st_old.st_ino)
3816 backup_copy = FALSE;
3817
3818 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003819 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 && st_old.st_nlink > 1
3821 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3822 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003823# else
3824# if defined(WIN32)
3825 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003826 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003827 backup_copy = FALSE;
3828
3829 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003830 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003831 backup_copy = FALSE;
3832# endif
3833# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835
3836#endif
3837
3838 /* make sure we have a valid backup extension to use */
3839 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841 else
3842 backup_ext = p_bex;
3843
3844 if (backup_copy
3845 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3846 {
3847 int bfd;
3848 char_u *copybuf, *wp;
3849 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003850 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851 char_u *dirp;
3852 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003853#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003855 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856#endif
3857
3858 copybuf = alloc(BUFSIZE + 1);
3859 if (copybuf == NULL)
3860 {
3861 some_error = TRUE; /* out of memory */
3862 goto nobackup;
3863 }
3864
3865 /*
3866 * Try to make the backup in each directory in the 'bdir' option.
3867 *
3868 * Unix semantics has it, that we may have a writable file,
3869 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3870 * - the directory is not writable,
3871 * - the file may be a symbolic link,
3872 * - the file may belong to another user/group, etc.
3873 *
3874 * For these reasons, the existing writable file must be truncated
3875 * and reused. Creation of a backup COPY will be attempted.
3876 */
3877 dirp = p_bdir;
3878 while (*dirp)
3879 {
3880#ifdef UNIX
3881 st_new.st_ino = 0;
3882 st_new.st_dev = 0;
3883 st_new.st_gid = 0;
3884#endif
3885
3886 /*
3887 * Isolate one directory name, using an entry in 'bdir'.
3888 */
3889 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3890 rootname = get_file_in_dir(fname, copybuf);
3891 if (rootname == NULL)
3892 {
3893 some_error = TRUE; /* out of memory */
3894 goto nobackup;
3895 }
3896
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003897#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898 did_set_shortname = FALSE;
3899#endif
3900
3901 /*
3902 * May try twice if 'shortname' not set.
3903 */
3904 for (;;)
3905 {
3906 /*
3907 * Make backup file name.
3908 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003909 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910 rootname, backup_ext, FALSE);
3911 if (backup == NULL)
3912 {
3913 vim_free(rootname);
3914 some_error = TRUE; /* out of memory */
3915 goto nobackup;
3916 }
3917
3918 /*
3919 * Check if backup file already exists.
3920 */
3921 if (mch_stat((char *)backup, &st_new) >= 0)
3922 {
3923#ifdef UNIX
3924 /*
3925 * Check if backup file is same as original file.
3926 * May happen when modname() gave the same file back.
3927 * E.g. silly link, or file name-length reached.
3928 * If we don't check here, we either ruin the file
3929 * when copying or erase it after writing. jw.
3930 */
3931 if (st_new.st_dev == st_old.st_dev
3932 && st_new.st_ino == st_old.st_ino)
3933 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003934 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 /*
3936 * may try again with 'shortname' set
3937 */
3938 if (!(buf->b_shortname || buf->b_p_sn))
3939 {
3940 buf->b_shortname = TRUE;
3941 did_set_shortname = TRUE;
3942 continue;
3943 }
3944 /* setting shortname didn't help */
3945 if (did_set_shortname)
3946 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 break;
3948 }
3949#endif
3950
3951 /*
3952 * If we are not going to keep the backup file, don't
3953 * delete an existing one, try to use another name.
3954 * Change one character, just before the extension.
3955 */
3956 if (!p_bk)
3957 {
3958 wp = backup + STRLEN(backup) - 1
3959 - STRLEN(backup_ext);
3960 if (wp < backup) /* empty file name ??? */
3961 wp = backup;
3962 *wp = 'z';
3963 while (*wp > 'a'
3964 && mch_stat((char *)backup, &st_new) >= 0)
3965 --*wp;
3966 /* They all exist??? Must be something wrong. */
3967 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003968 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969 }
3970 }
3971 break;
3972 }
3973 vim_free(rootname);
3974
3975 /*
3976 * Try to create the backup file
3977 */
3978 if (backup != NULL)
3979 {
3980 /* remove old backup, if present */
3981 mch_remove(backup);
3982 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003983 * we were sleeping (symlink hacker attack?). Reset umask
3984 * if possible to avoid mch_setperm() below. */
3985#ifdef UNIX
3986 umask_save = umask(0);
3987#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003989 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3990 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003991#ifdef UNIX
3992 (void)umask(umask_save);
3993#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003995 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 else
3997 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003998 /* Set file protection same as original file, but
3999 * strip s-bit. Only needed if umask() wasn't used
4000 * above. */
4001#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004002 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004003#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004 /*
4005 * Try to set the group of the backup same as the
4006 * original file. If this fails, set the protection
4007 * bits for the group same as the protection bits for
4008 * others.
4009 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004010 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004011# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004012 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013# endif
4014 )
4015 mch_setperm(backup,
4016 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004017# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004018 mch_copy_sec(fname, backup);
4019# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020#endif
4021
4022 /*
4023 * copy the file.
4024 */
4025 write_info.bw_fd = bfd;
4026 write_info.bw_buf = copybuf;
4027#ifdef HAS_BW_FLAGS
4028 write_info.bw_flags = FIO_NOCONVERT;
4029#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004030 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031 BUFSIZE)) > 0)
4032 {
4033 if (buf_write_bytes(&write_info) == FAIL)
4034 {
4035 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4036 break;
4037 }
4038 ui_breakcheck();
4039 if (got_int)
4040 {
4041 errmsg = (char_u *)_(e_interr);
4042 break;
4043 }
4044 }
4045
4046 if (close(bfd) < 0 && errmsg == NULL)
4047 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4048 if (write_info.bw_len < 0)
4049 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4050#ifdef UNIX
4051 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4052#endif
4053#ifdef HAVE_ACL
4054 mch_set_acl(backup, acl);
4055#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004056#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004057 mch_copy_sec(fname, backup);
4058#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059 break;
4060 }
4061 }
4062 }
4063 nobackup:
4064 close(fd); /* ignore errors for closing read file */
4065 vim_free(copybuf);
4066
4067 if (backup == NULL && errmsg == NULL)
4068 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4069 /* ignore errors when forceit is TRUE */
4070 if ((some_error || errmsg != NULL) && !forceit)
4071 {
4072 retval = FAIL;
4073 goto fail;
4074 }
4075 errmsg = NULL;
4076 }
4077 else
4078 {
4079 char_u *dirp;
4080 char_u *p;
4081 char_u *rootname;
4082
4083 /*
4084 * Make a backup by renaming the original file.
4085 */
4086 /*
4087 * If 'cpoptions' includes the "W" flag, we don't want to
4088 * overwrite a read-only file. But rename may be possible
4089 * anyway, thus we need an extra check here.
4090 */
4091 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4092 {
4093 errnum = (char_u *)"E504: ";
4094 errmsg = (char_u *)_(err_readonly);
4095 goto fail;
4096 }
4097
4098 /*
4099 *
4100 * Form the backup file name - change path/fo.o.h to
4101 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4102 * that works is used.
4103 */
4104 dirp = p_bdir;
4105 while (*dirp)
4106 {
4107 /*
4108 * Isolate one directory name and make the backup file name.
4109 */
4110 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4111 rootname = get_file_in_dir(fname, IObuff);
4112 if (rootname == NULL)
4113 backup = NULL;
4114 else
4115 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004116 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 rootname, backup_ext, FALSE);
4118 vim_free(rootname);
4119 }
4120
4121 if (backup != NULL)
4122 {
4123 /*
4124 * If we are not going to keep the backup file, don't
4125 * delete an existing one, try to use another name.
4126 * Change one character, just before the extension.
4127 */
4128 if (!p_bk && mch_getperm(backup) >= 0)
4129 {
4130 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4131 if (p < backup) /* empty file name ??? */
4132 p = backup;
4133 *p = 'z';
4134 while (*p > 'a' && mch_getperm(backup) >= 0)
4135 --*p;
4136 /* They all exist??? Must be something wrong! */
4137 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004138 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 }
4140 }
4141 if (backup != NULL)
4142 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004144 * Delete any existing backup and move the current version
4145 * to the backup. For safety, we don't remove the backup
4146 * until the write has finished successfully. And if the
4147 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 */
4149 /*
4150 * If the renaming of the original file to the backup file
4151 * works, quit here.
4152 */
4153 if (vim_rename(fname, backup) == 0)
4154 break;
4155
Bram Moolenaard23a8232018-02-10 18:45:26 +01004156 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 }
4158 }
4159 if (backup == NULL && !forceit)
4160 {
4161 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4162 goto fail;
4163 }
4164 }
4165 }
4166
Bram Moolenaar53076832015-12-31 19:53:21 +01004167#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 /* When using ":w!" and the file was read-only: make it writable */
4169 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4170 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4171 {
4172 perm |= 0200;
4173 (void)mch_setperm(fname, perm);
4174 made_writable = TRUE;
4175 }
4176#endif
4177
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004178 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004179 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4180 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 {
4182 buf->b_p_ro = FALSE;
4183#ifdef FEAT_TITLE
4184 need_maketitle = TRUE; /* set window title later */
4185#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 }
4188
4189 if (end > buf->b_ml.ml_line_count)
4190 end = buf->b_ml.ml_line_count;
4191 if (buf->b_ml.ml_flags & ML_EMPTY)
4192 start = end + 1;
4193
4194 /*
4195 * If the original file is being overwritten, there is a small chance that
4196 * we crash in the middle of writing. Therefore the file is preserved now.
4197 * This makes all block numbers positive so that recovery does not need
4198 * the original file.
4199 * Don't do this if there is a backup file and we are exiting.
4200 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004201 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 && !(exiting && backup != NULL))
4203 {
4204 ml_preserve(buf, FALSE);
4205 if (got_int)
4206 {
4207 errmsg = (char_u *)_(e_interr);
4208 goto restore_backup;
4209 }
4210 }
4211
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212#ifdef VMS
4213 vms_remove_version(fname); /* remove version */
4214#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004215 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004216 * multi-byte conversion. */
4217 wfname = fname;
4218
4219#ifdef FEAT_MBYTE
4220 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4221 if (eap != NULL && eap->force_enc != 0)
4222 {
4223 fenc = eap->cmd + eap->force_enc;
4224 fenc = enc_canonize(fenc);
4225 fenc_tofree = fenc;
4226 }
4227 else
4228 fenc = buf->b_p_fenc;
4229
4230 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004231 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004233 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004234
4235 /*
4236 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4237 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4238 * Prepare the flags for it and allocate bw_conv_buf when needed.
4239 */
4240 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4241 {
4242 wb_flags = get_fio_flags(fenc);
4243 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4244 {
4245 /* Need to allocate a buffer to translate into. */
4246 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4247 write_info.bw_conv_buflen = bufsize * 2;
4248 else /* FIO_UCS4 */
4249 write_info.bw_conv_buflen = bufsize * 4;
4250 write_info.bw_conv_buf
4251 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4252 if (write_info.bw_conv_buf == NULL)
4253 end = 0;
4254 }
4255 }
4256
4257# ifdef WIN3264
4258 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4259 {
4260 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4261 write_info.bw_conv_buflen = bufsize * 4;
4262 write_info.bw_conv_buf
4263 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4264 if (write_info.bw_conv_buf == NULL)
4265 end = 0;
4266 }
4267# endif
4268
Bram Moolenaard0573012017-10-28 21:11:06 +02004269# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4271 {
4272 write_info.bw_conv_buflen = bufsize * 3;
4273 write_info.bw_conv_buf
4274 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4275 if (write_info.bw_conv_buf == NULL)
4276 end = 0;
4277 }
4278# endif
4279
4280# if defined(FEAT_EVAL) || defined(USE_ICONV)
4281 if (converted && wb_flags == 0)
4282 {
4283# ifdef USE_ICONV
4284 /*
4285 * Use iconv() conversion when conversion is needed and it's not done
4286 * internally.
4287 */
4288 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4289 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4290 if (write_info.bw_iconv_fd != (iconv_t)-1)
4291 {
4292 /* We're going to use iconv(), allocate a buffer to convert in. */
4293 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4294 write_info.bw_conv_buf
4295 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4296 if (write_info.bw_conv_buf == NULL)
4297 end = 0;
4298 write_info.bw_first = TRUE;
4299 }
4300# ifdef FEAT_EVAL
4301 else
4302# endif
4303# endif
4304
4305# ifdef FEAT_EVAL
4306 /*
4307 * When the file needs to be converted with 'charconvert' after
4308 * writing, write to a temp file instead and let the conversion
4309 * overwrite the original file.
4310 */
4311 if (*p_ccv != NUL)
4312 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004313 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 if (wfname == NULL) /* Can't write without a tempfile! */
4315 {
4316 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4317 goto restore_backup;
4318 }
4319 }
4320# endif
4321 }
4322# endif
4323 if (converted && wb_flags == 0
4324# ifdef USE_ICONV
4325 && write_info.bw_iconv_fd == (iconv_t)-1
4326# endif
4327# ifdef FEAT_EVAL
4328 && wfname == fname
4329# endif
4330 )
4331 {
4332 if (!forceit)
4333 {
4334 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4335 goto restore_backup;
4336 }
4337 notconverted = TRUE;
4338 }
4339#endif
4340
4341 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004342 * If conversion is taking place, we may first pretend to write and check
4343 * for conversion errors. Then loop again to write for real.
4344 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004345 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004346 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347 {
4348 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004349 * There is no need to check conversion when:
4350 * - there is no conversion
4351 * - we make a backup file, that can be restored in case of conversion
4352 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004354#ifdef FEAT_MBYTE
4355 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004357 checking_conversion = FALSE;
4358
4359 if (checking_conversion)
4360 {
4361 /* Make sure we don't write anything. */
4362 fd = -1;
4363 write_info.bw_fd = fd;
4364 }
4365 else
4366 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004367#ifdef HAVE_FTRUNCATE
4368# define TRUNC_ON_OPEN 0
4369#else
4370# define TRUNC_ON_OPEN O_TRUNC
4371#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004372 /*
4373 * Open the file "wfname" for writing.
4374 * We may try to open the file twice: If we can't write to the file
4375 * and forceit is TRUE we delete the existing file and try to
4376 * create a new one. If this still fails we may have lost the
4377 * original file! (this may happen when the user reached his
4378 * quotum for number of files).
4379 * Appending will fail if the file does not exist and forceit is
4380 * FALSE.
4381 */
4382 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4383 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004384 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004385 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004387 /*
4388 * A forced write will try to create a new file if the old one
4389 * is still readonly. This may also happen when the directory
4390 * is read-only. In that case the mch_remove() will fail.
4391 */
4392 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 {
4394#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004395 stat_T st;
4396
4397 /* Don't delete the file when it's a hard or symbolic link.
4398 */
4399 if ((!newfile && st_old.st_nlink > 1)
4400 || (mch_lstat((char *)fname, &st) == 0
4401 && (st.st_dev != st_old.st_dev
4402 || st.st_ino != st_old.st_ino)))
4403 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4404 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004406 {
4407 errmsg = (char_u *)_("E212: Can't open file for writing");
4408 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4409 && perm >= 0)
4410 {
4411#ifdef UNIX
4412 /* we write to the file, thus it should be marked
4413 writable after all */
4414 if (!(perm & 0200))
4415 made_writable = TRUE;
4416 perm |= 0200;
4417 if (st_old.st_uid != getuid()
4418 || st_old.st_gid != getgid())
4419 perm &= 0777;
4420#endif
4421 if (!append) /* don't remove when appending */
4422 mch_remove(wfname);
4423 continue;
4424 }
4425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427
4428restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004429 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004430 stat_T st;
4431
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004433 * If we failed to open the file, we don't need a backup.
4434 * Throw it away. If we moved or removed the original file
4435 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004437 if (backup != NULL && wfname == fname)
4438 {
4439 if (backup_copy)
4440 {
4441 /*
4442 * There is a small chance that we removed the
4443 * original, try to move the copy in its place.
4444 * This may not work if the vim_rename() fails.
4445 * In that case we leave the copy around.
4446 */
4447 /* If file does not exist, put the copy in its
4448 * place */
4449 if (mch_stat((char *)fname, &st) < 0)
4450 vim_rename(backup, fname);
4451 /* if original file does exist throw away the copy
4452 */
4453 if (mch_stat((char *)fname, &st) >= 0)
4454 mch_remove(backup);
4455 }
4456 else
4457 {
4458 /* try to put the original file back */
4459 vim_rename(backup, fname);
4460 }
4461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004463 /* if original file no longer exists give an extra warning
4464 */
4465 if (!newfile && mch_stat((char *)fname, &st) < 0)
4466 end = 0;
4467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468
4469#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004470 if (wfname != fname)
4471 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004472#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004473 goto fail;
4474 }
4475 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004477#if defined(UNIX)
4478 {
4479 stat_T st;
4480
4481 /* Double check we are writing the intended file before making
4482 * any changes. */
4483 if (overwriting
4484 && (!dobackup || backup_copy)
4485 && fname == wfname
4486 && perm >= 0
4487 && mch_fstat(fd, &st) == 0
4488 && st.st_ino != st_old.st_ino)
4489 {
4490 close(fd);
4491 errmsg = (char_u *)_("E949: File changed while writing");
4492 goto fail;
4493 }
4494 }
4495#endif
4496#ifdef HAVE_FTRUNCATE
4497 if (!append)
Bram Moolenaarae1e1082017-11-17 21:35:24 +01004498 ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004499#endif
4500
Bram Moolenaard0573012017-10-28 21:11:06 +02004501#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004502 if (backup != NULL && overwriting && !append)
4503 {
4504 if (backup_copy)
4505 (void)mch_copy_file_attribute(wfname, backup);
4506 else
4507 (void)mch_copy_file_attribute(backup, wfname);
4508 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004510 if (!overwriting && !append)
4511 {
4512 if (buf->b_ffname != NULL)
4513 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4514 /* Should copy resource fork */
4515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516#endif
4517
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004519 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004521 char_u *header;
4522 int header_len;
4523
4524 buf->b_cryptstate = crypt_create_for_writing(
4525 crypt_get_method_nr(buf),
4526 buf->b_p_key, &header, &header_len);
4527 if (buf->b_cryptstate == NULL || header == NULL)
4528 end = 0;
4529 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004531 /* Write magic number, so that Vim knows how this file is
4532 * encrypted when reading it back. */
4533 write_info.bw_buf = header;
4534 write_info.bw_len = header_len;
4535 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004536 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004537 end = 0;
4538 wb_flags |= FIO_ENCRYPTED;
4539 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004540 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004542#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004546 write_info.bw_buf = buffer;
4547 nchars = 0;
4548
4549 /* use "++bin", "++nobin" or 'binary' */
4550 if (eap != NULL && eap->force_bin != 0)
4551 write_bin = (eap->force_bin == FORCE_BIN);
4552 else
4553 write_bin = buf->b_p_bin;
4554
4555#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004557 * The BOM is written just after the encryption magic number.
4558 * Skip it when appending and the file already existed, the BOM only
4559 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004561 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004563 write_info.bw_len = make_bom(buffer, fenc);
4564 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004566 /* don't convert, do encryption */
4567 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4568 if (buf_write_bytes(&write_info) == FAIL)
4569 end = 0;
4570 else
4571 nchars += write_info.bw_len;
4572 }
4573 }
4574 write_info.bw_start_lnum = start;
4575#endif
4576
4577#ifdef FEAT_PERSISTENT_UNDO
4578 write_undo_file = (buf->b_p_udf
4579 && overwriting
4580 && !append
4581 && !filtering
4582 && reset_changed
4583 && !checking_conversion);
4584 if (write_undo_file)
4585 /* Prepare for computing the hash value of the text. */
4586 sha256_start(&sha_ctx);
4587#endif
4588
4589 write_info.bw_len = bufsize;
4590#ifdef HAS_BW_FLAGS
4591 write_info.bw_flags = wb_flags;
4592#endif
4593 fileformat = get_fileformat_force(buf, eap);
4594 s = buffer;
4595 len = 0;
4596 for (lnum = start; lnum <= end; ++lnum)
4597 {
4598 /*
4599 * The next while loop is done once for each character written.
4600 * Keep it fast!
4601 */
4602 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4603#ifdef FEAT_PERSISTENT_UNDO
4604 if (write_undo_file)
4605 sha256_update(&sha_ctx, ptr + 1,
4606 (UINT32_T)(STRLEN(ptr + 1) + 1));
4607#endif
4608 while ((c = *++ptr) != NUL)
4609 {
4610 if (c == NL)
4611 *s = NUL; /* replace newlines with NULs */
4612 else if (c == CAR && fileformat == EOL_MAC)
4613 *s = NL; /* Mac: replace CRs with NLs */
4614 else
4615 *s = c;
4616 ++s;
4617 if (++len != bufsize)
4618 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004619 if (buf_write_bytes(&write_info) == FAIL)
4620 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004621 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004622 break;
4623 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004624 nchars += bufsize;
4625 s = buffer;
4626 len = 0;
4627#ifdef FEAT_MBYTE
4628 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004630 }
4631 /* write failed or last line has no EOL: stop here */
4632 if (end == 0
4633 || (lnum == end
4634 && (write_bin || !buf->b_p_fixeol)
4635 && (lnum == buf->b_no_eol_lnum
4636 || (lnum == buf->b_ml.ml_line_count
4637 && !buf->b_p_eol))))
4638 {
4639 ++lnum; /* written the line, count it */
4640 no_eol = TRUE;
4641 break;
4642 }
4643 if (fileformat == EOL_UNIX)
4644 *s++ = NL;
4645 else
4646 {
4647 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4648 if (fileformat == EOL_DOS) /* write CR-NL */
4649 {
4650 if (++len == bufsize)
4651 {
4652 if (buf_write_bytes(&write_info) == FAIL)
4653 {
4654 end = 0; /* write error: break loop */
4655 break;
4656 }
4657 nchars += bufsize;
4658 s = buffer;
4659 len = 0;
4660 }
4661 *s++ = NL;
4662 }
4663 }
4664 if (++len == bufsize && end)
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 ui_breakcheck();
4676 if (got_int)
4677 {
4678 end = 0; /* Interrupted, break loop */
4679 break;
4680 }
4681 }
4682#ifdef VMS
4683 /*
4684 * On VMS there is a problem: newlines get added when writing
4685 * blocks at a time. Fix it by writing a line at a time.
4686 * This is much slower!
4687 * Explanation: VAX/DECC RTL insists that records in some RMS
4688 * structures end with a newline (carriage return) character, and
4689 * if they don't it adds one.
4690 * With other RMS structures it works perfect without this fix.
4691 */
4692 if (buf->b_fab_rfm == FAB$C_VFC
4693 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4694 {
4695 int b2write;
4696
4697 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4698 ? MIN(4096, bufsize)
4699 : MIN(buf->b_fab_mrs, bufsize));
4700
4701 b2write = len;
4702 while (b2write > 0)
4703 {
4704 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4705 if (buf_write_bytes(&write_info) == FAIL)
4706 {
4707 end = 0;
4708 break;
4709 }
4710 b2write -= MIN(b2write, buf->b_fab_mrs);
4711 }
4712 write_info.bw_len = bufsize;
4713 nchars += len;
4714 s = buffer;
4715 len = 0;
4716 }
4717#endif
4718 }
4719 if (len > 0 && end > 0)
4720 {
4721 write_info.bw_len = len;
4722 if (buf_write_bytes(&write_info) == FAIL)
4723 end = 0; /* write error */
4724 nchars += len;
4725 }
4726
4727 /* Stop when writing done or an error was encountered. */
4728 if (!checking_conversion || end == 0)
4729 break;
4730
4731 /* If no error happened until now, writing should be ok, so loop to
4732 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733 }
4734
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004735 /* If we started writing, finish writing. Also when an error was
4736 * encountered. */
4737 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004739#if defined(UNIX) && defined(HAVE_FSYNC)
4740 /*
4741 * On many journalling file systems there is a bug that causes both the
4742 * original and the backup file to be lost when halting the system
4743 * right after writing the file. That's because only the meta-data is
4744 * journalled. Syncing the file slows down the system, but assures it
4745 * has been written to disk and we don't lose it.
4746 * For a device do try the fsync() but don't complain if it does not
4747 * work (could be a pipe).
4748 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4749 */
4750 if (p_fs && fsync(fd) != 0 && !device)
4751 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004752 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004753 end = 0;
4754 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755#endif
4756
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004757#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004758 /* Probably need to set the security context. */
4759 if (!backup_copy)
4760 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004761#endif
4762
Bram Moolenaara5792f52005-11-23 21:25:05 +00004763#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764 /* When creating a new file, set its owner/group to that of the
4765 * original file. Get the new device and inode number. */
4766 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004767 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004768# ifdef HAVE_FCHOWN
4769 stat_T st;
4770
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004771 /* Don't change the owner when it's already OK, some systems remove
4772 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004773 if (mch_stat((char *)wfname, &st) < 0
4774 || st.st_uid != st_old.st_uid
4775 || st.st_gid != st_old.st_gid)
4776 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004777 /* changing owner might not be possible */
4778 ignored = fchown(fd, st_old.st_uid, -1);
4779 /* if changing group fails clear the group permissions */
4780 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4781 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004782 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004783# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004784 buf_setino(buf);
4785 }
4786 else if (!buf->b_dev_valid)
4787 /* Set the inode when creating a new file. */
4788 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004789#endif
4790
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004791#ifdef UNIX
4792 if (made_writable)
4793 perm &= ~0200; /* reset 'w' bit for security reasons */
4794#endif
4795#ifdef HAVE_FCHMOD
4796 /* set permission of new file same as old file */
4797 if (perm >= 0)
4798 (void)mch_fsetperm(fd, perm);
4799#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004800 if (close(fd) != 0)
4801 {
4802 errmsg = (char_u *)_("E512: Close failed");
4803 end = 0;
4804 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004806#ifndef HAVE_FCHMOD
4807 /* set permission of new file same as old file */
4808 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004810#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004812 /*
4813 * Probably need to set the ACL before changing the user (can't set the
4814 * ACL on a file the user doesn't own).
4815 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4816 * default), chmod() discards all part of a file's ACL that don't
4817 * represent the mode of the file. It's non-trivial for us to discover
4818 * whether we're in that situation, so we simply always re-set the ACL.
4819 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004820# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004821 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004822# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004823 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004825#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004826 if (buf->b_cryptstate != NULL)
4827 {
4828 crypt_free_state(buf->b_cryptstate);
4829 buf->b_cryptstate = NULL;
4830 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004831#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004834 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004836 /*
4837 * The file was written to a temp file, now it needs to be
4838 * converted with 'charconvert' to (overwrite) the output file.
4839 */
4840 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004842 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4843 fenc, wfname, fname) == FAIL)
4844 {
4845 write_info.bw_conv_error = TRUE;
4846 end = 0;
4847 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004849 mch_remove(wfname);
4850 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004853 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854
4855 if (end == 0)
4856 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004857 /*
4858 * Error encountered.
4859 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 if (errmsg == NULL)
4861 {
4862#ifdef FEAT_MBYTE
4863 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004864 {
4865 if (write_info.bw_conv_error_lnum == 0)
4866 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4867 else
4868 {
4869 errmsg_allocated = TRUE;
4870 errmsg = alloc(300);
4871 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4872 (long)write_info.bw_conv_error_lnum);
4873 }
4874 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 else
4876#endif
4877 if (got_int)
4878 errmsg = (char_u *)_(e_interr);
4879 else
4880 errmsg = (char_u *)_("E514: write error (file system full?)");
4881 }
4882
4883 /*
4884 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004885 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 * original file when trying to make a backup when writing the file a
4887 * second time.
4888 * When "backup_copy" is set we need to copy the backup over the new
4889 * file. Otherwise rename the backup file.
4890 * If this is OK, don't give the extra warning message.
4891 */
4892 if (backup != NULL)
4893 {
4894 if (backup_copy)
4895 {
4896 /* This may take a while, if we were interrupted let the user
4897 * know we got the message. */
4898 if (got_int)
4899 {
4900 MSG(_(e_interr));
4901 out_flush();
4902 }
4903 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4904 {
4905 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004906 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4907 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908 {
4909 /* copy the file. */
4910 write_info.bw_buf = smallbuf;
4911#ifdef HAS_BW_FLAGS
4912 write_info.bw_flags = FIO_NOCONVERT;
4913#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004914 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 SMBUFSIZE)) > 0)
4916 if (buf_write_bytes(&write_info) == FAIL)
4917 break;
4918
4919 if (close(write_info.bw_fd) >= 0
4920 && write_info.bw_len == 0)
4921 end = 1; /* success */
4922 }
4923 close(fd); /* ignore errors for closing read file */
4924 }
4925 }
4926 else
4927 {
4928 if (vim_rename(backup, fname) == 0)
4929 end = 1;
4930 }
4931 }
4932 goto fail;
4933 }
4934
4935 lnum -= start; /* compute number of written lines */
4936 --no_wait_return; /* may wait for return now */
4937
4938#if !(defined(UNIX) || defined(VMS))
4939 fname = sfname; /* use shortname now, for the messages */
4940#endif
4941 if (!filtering)
4942 {
4943 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4944 c = FALSE;
4945#ifdef FEAT_MBYTE
4946 if (write_info.bw_conv_error)
4947 {
4948 STRCAT(IObuff, _(" CONVERSION ERROR"));
4949 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004950 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004951 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004952 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 }
4954 else if (notconverted)
4955 {
4956 STRCAT(IObuff, _("[NOT converted]"));
4957 c = TRUE;
4958 }
4959 else if (converted)
4960 {
4961 STRCAT(IObuff, _("[converted]"));
4962 c = TRUE;
4963 }
4964#endif
4965 if (device)
4966 {
4967 STRCAT(IObuff, _("[Device]"));
4968 c = TRUE;
4969 }
4970 else if (newfile)
4971 {
4972 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4973 c = TRUE;
4974 }
4975 if (no_eol)
4976 {
4977 msg_add_eol();
4978 c = TRUE;
4979 }
4980 /* may add [unix/dos/mac] */
4981 if (msg_add_fileformat(fileformat))
4982 c = TRUE;
4983#ifdef FEAT_CRYPT
4984 if (wb_flags & FIO_ENCRYPTED)
4985 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004986 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987 c = TRUE;
4988 }
4989#endif
4990 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4991 if (!shortmess(SHM_WRITE))
4992 {
4993 if (append)
4994 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4995 else
4996 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4997 }
4998
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004999 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000 }
5001
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005002 /* When written everything correctly: reset 'modified'. Unless not
5003 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005004 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005#ifdef FEAT_MBYTE
5006 && !write_info.bw_conv_error
5007#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005008 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5009 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005010 {
5011 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005012 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005013 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01005014 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
5015 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005017 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018 }
5019
5020 /*
5021 * If written to the current file, update the timestamp of the swap file
5022 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5023 */
5024 if (overwriting)
5025 {
5026 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005027 if (append)
5028 buf->b_flags &= ~BF_NEW;
5029 else
5030 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031 }
5032
5033 /*
5034 * If we kept a backup until now, and we are in patch mode, then we make
5035 * the backup file our 'original' file.
5036 */
5037 if (*p_pm && dobackup)
5038 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005039 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 fname, p_pm, FALSE);
5041
5042 if (backup != NULL)
5043 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005044 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045
5046 /*
5047 * If the original file does not exist yet
5048 * the current backup file becomes the original file
5049 */
5050 if (org == NULL)
5051 EMSG(_("E205: Patchmode: can't save original file"));
5052 else if (mch_stat(org, &st) < 0)
5053 {
5054 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005055 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056#ifdef UNIX
5057 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5058#endif
5059 }
5060 }
5061 /*
5062 * If there is no backup file, remember that a (new) file was
5063 * created.
5064 */
5065 else
5066 {
5067 int empty_fd;
5068
5069 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005070 || (empty_fd = mch_open(org,
5071 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005072 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073 EMSG(_("E206: patchmode: can't touch empty original file"));
5074 else
5075 close(empty_fd);
5076 }
5077 if (org != NULL)
5078 {
5079 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5080 vim_free(org);
5081 }
5082 }
5083
5084 /*
5085 * Remove the backup unless 'backup' option is set
5086 */
5087 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5088 EMSG(_("E207: Can't delete backup file"));
5089
5090#ifdef FEAT_SUN_WORKSHOP
5091 if (usingSunWorkShop)
5092 workshop_file_saved((char *) ffname);
5093#endif
5094
5095 goto nofail;
5096
5097 /*
5098 * Finish up. We get here either after failure or success.
5099 */
5100fail:
5101 --no_wait_return; /* may wait for return now */
5102nofail:
5103
5104 /* Done saving, we accept changed buffer warnings again */
5105 buf->b_saving = FALSE;
5106
5107 vim_free(backup);
5108 if (buffer != smallbuf)
5109 vim_free(buffer);
5110#ifdef FEAT_MBYTE
5111 vim_free(fenc_tofree);
5112 vim_free(write_info.bw_conv_buf);
5113# ifdef USE_ICONV
5114 if (write_info.bw_iconv_fd != (iconv_t)-1)
5115 {
5116 iconv_close(write_info.bw_iconv_fd);
5117 write_info.bw_iconv_fd = (iconv_t)-1;
5118 }
5119# endif
5120#endif
5121#ifdef HAVE_ACL
5122 mch_free_acl(acl);
5123#endif
5124
5125 if (errmsg != NULL)
5126 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005127 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128
Bram Moolenaar8820b482017-03-16 17:23:31 +01005129 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005130 msg_add_fname(buf,
5131#ifndef UNIX
5132 sfname
5133#else
5134 fname
5135#endif
5136 ); /* put file name in IObuff with quotes */
5137 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5138 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5139 /* If the error message has the form "is ...", put the error number in
5140 * front of the file name. */
5141 if (errnum != NULL)
5142 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005143 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144 mch_memmove(IObuff, errnum, (size_t)numlen);
5145 }
5146 STRCAT(IObuff, errmsg);
5147 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005148 if (errmsg_allocated)
5149 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150
5151 retval = FAIL;
5152 if (end == 0)
5153 {
5154 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5155 attr | MSG_HIST);
5156 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5157 attr | MSG_HIST);
5158
5159 /* Update the timestamp to avoid an "overwrite changed file"
5160 * prompt when writing again. */
5161 if (mch_stat((char *)fname, &st_old) >= 0)
5162 {
5163 buf_store_time(buf, &st_old, fname);
5164 buf->b_mtime_read = buf->b_mtime;
5165 }
5166 }
5167 }
5168 msg_scroll = msg_save;
5169
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005170#ifdef FEAT_PERSISTENT_UNDO
5171 /*
5172 * When writing the whole file and 'undofile' is set, also write the undo
5173 * file.
5174 */
5175 if (retval == OK && write_undo_file)
5176 {
5177 char_u hash[UNDO_HASH_SIZE];
5178
5179 sha256_finish(&sha_ctx, hash);
5180 u_write_undo(NULL, FALSE, buf, hash);
5181 }
5182#endif
5183
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184#ifdef FEAT_EVAL
5185 if (!should_abort(retval))
5186#else
5187 if (!got_int)
5188#endif
5189 {
5190 aco_save_T aco;
5191
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005192 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5193
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194 /*
5195 * Apply POST autocommands.
5196 * Careful: The autocommands may call buf_write() recursively!
5197 */
5198 aucmd_prepbuf(&aco, buf);
5199
5200 if (append)
5201 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5202 FALSE, curbuf, eap);
5203 else if (filtering)
5204 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5205 FALSE, curbuf, eap);
5206 else if (reset_changed && whole)
5207 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5208 FALSE, curbuf, eap);
5209 else
5210 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5211 FALSE, curbuf, eap);
5212
5213 /* restore curwin/curbuf and a few other things */
5214 aucmd_restbuf(&aco);
5215
5216#ifdef FEAT_EVAL
5217 if (aborting()) /* autocmds may abort script processing */
5218 retval = FALSE;
5219#endif
5220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221
5222 got_int |= prev_got_int;
5223
Bram Moolenaar071d4272004-06-13 20:20:40 +00005224 return retval;
5225}
5226
5227/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005228 * Set the name of the current buffer. Use when the buffer doesn't have a
5229 * name and a ":r" or ":w" command with a file name is used.
5230 */
5231 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005232set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005233{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005234 buf_T *buf = curbuf;
5235
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005236 /* It's like the unnamed buffer is deleted.... */
5237 if (curbuf->b_p_bl)
5238 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5239 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005240#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005241 if (aborting()) /* autocmds may abort script processing */
5242 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005243#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005244 if (curbuf != buf)
5245 {
5246 /* We are in another buffer now, don't do the renaming. */
5247 EMSG(_(e_auchangedbuf));
5248 return FAIL;
5249 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005250
5251 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5252 curbuf->b_flags |= BF_NOTEDITED;
5253
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005254 /* ....and a new named one is created */
5255 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5256 if (curbuf->b_p_bl)
5257 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005258#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005259 if (aborting()) /* autocmds may abort script processing */
5260 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005261#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005262
5263 /* Do filetype detection now if 'filetype' is empty. */
5264 if (*curbuf->b_p_ft == NUL)
5265 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005266 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005267 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005268 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005269 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005270
5271 return OK;
5272}
5273
5274/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005275 * Put file name into IObuff with quotes.
5276 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005277 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005278msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279{
5280 if (fname == NULL)
5281 fname = (char_u *)"-stdin-";
5282 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5283 IObuff[0] = '"';
5284 STRCAT(IObuff, "\" ");
5285}
5286
5287/*
5288 * Append message for text mode to IObuff.
5289 * Return TRUE if something appended.
5290 */
5291 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005292msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005293{
5294#ifndef USE_CRNL
5295 if (eol_type == EOL_DOS)
5296 {
5297 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5298 return TRUE;
5299 }
5300#endif
5301#ifndef USE_CR
5302 if (eol_type == EOL_MAC)
5303 {
5304 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5305 return TRUE;
5306 }
5307#endif
5308#if defined(USE_CRNL) || defined(USE_CR)
5309 if (eol_type == EOL_UNIX)
5310 {
5311 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5312 return TRUE;
5313 }
5314#endif
5315 return FALSE;
5316}
5317
5318/*
5319 * Append line and character count to IObuff.
5320 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005321 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005322msg_add_lines(
5323 int insert_space,
5324 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005325 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326{
5327 char_u *p;
5328
5329 p = IObuff + STRLEN(IObuff);
5330
5331 if (insert_space)
5332 *p++ = ' ';
5333 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005334 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005335 "%ldL, %lldC", lnum, (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005336 else
5337 {
5338 if (lnum == 1)
5339 STRCPY(p, _("1 line, "));
5340 else
5341 sprintf((char *)p, _("%ld lines, "), lnum);
5342 p += STRLEN(p);
5343 if (nchars == 1)
5344 STRCPY(p, _("1 character"));
5345 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005346 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005347 _("%lld characters"), (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348 }
5349}
5350
5351/*
5352 * Append message for missing line separator to IObuff.
5353 */
5354 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005355msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356{
5357 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5358}
5359
5360/*
5361 * Check modification time of file, before writing to it.
5362 * The size isn't checked, because using a tool like "gzip" takes care of
5363 * using the same timestamp but can't set the size.
5364 */
5365 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005366check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367{
5368 if (buf->b_mtime_read != 0
5369 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5370 {
5371 msg_scroll = TRUE; /* don't overwrite messages here */
5372 msg_silent = 0; /* must give this prompt */
5373 /* don't use emsg() here, don't want to flush the buffers */
5374 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005375 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5377 TRUE) == 'n')
5378 return FAIL;
5379 msg_scroll = FALSE; /* always overwrite the file message now */
5380 }
5381 return OK;
5382}
5383
5384 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005385time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005387#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5389 * the seconds. Since the roundoff is done when flushing the inode, the
5390 * time may change unexpectedly by one second!!! */
5391 return (t1 - t2 > 1 || t2 - t1 > 1);
5392#else
5393 return (t1 != t2);
5394#endif
5395}
5396
5397/*
5398 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005399 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400 *
5401 * Return FAIL for failure, OK otherwise.
5402 */
5403 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005404buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405{
5406 int wlen;
5407 char_u *buf = ip->bw_buf; /* data to write */
5408 int len = ip->bw_len; /* length of data */
5409#ifdef HAS_BW_FLAGS
5410 int flags = ip->bw_flags; /* extra flags */
5411#endif
5412
5413#ifdef FEAT_MBYTE
5414 /*
5415 * Skip conversion when writing the crypt magic number or the BOM.
5416 */
5417 if (!(flags & FIO_NOCONVERT))
5418 {
5419 char_u *p;
5420 unsigned c;
5421 int n;
5422
5423 if (flags & FIO_UTF8)
5424 {
5425 /*
5426 * Convert latin1 in the buffer to UTF-8 in the file.
5427 */
5428 p = ip->bw_conv_buf; /* translate to buffer */
5429 for (wlen = 0; wlen < len; ++wlen)
5430 p += utf_char2bytes(buf[wlen], p);
5431 buf = ip->bw_conv_buf;
5432 len = (int)(p - ip->bw_conv_buf);
5433 }
5434 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5435 {
5436 /*
5437 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5438 * Latin1 chars in the file.
5439 */
5440 if (flags & FIO_LATIN1)
5441 p = buf; /* translate in-place (can only get shorter) */
5442 else
5443 p = ip->bw_conv_buf; /* translate to buffer */
5444 for (wlen = 0; wlen < len; wlen += n)
5445 {
5446 if (wlen == 0 && ip->bw_restlen != 0)
5447 {
5448 int l;
5449
5450 /* Use remainder of previous call. Append the start of
5451 * buf[] to get a full sequence. Might still be too
5452 * short! */
5453 l = CONV_RESTLEN - ip->bw_restlen;
5454 if (l > len)
5455 l = len;
5456 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005457 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458 if (n > ip->bw_restlen + len)
5459 {
5460 /* We have an incomplete byte sequence at the end to
5461 * be written. We can't convert it without the
5462 * remaining bytes. Keep them for the next call. */
5463 if (ip->bw_restlen + len > CONV_RESTLEN)
5464 return FAIL;
5465 ip->bw_restlen += len;
5466 break;
5467 }
5468 if (n > 1)
5469 c = utf_ptr2char(ip->bw_rest);
5470 else
5471 c = ip->bw_rest[0];
5472 if (n >= ip->bw_restlen)
5473 {
5474 n -= ip->bw_restlen;
5475 ip->bw_restlen = 0;
5476 }
5477 else
5478 {
5479 ip->bw_restlen -= n;
5480 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5481 (size_t)ip->bw_restlen);
5482 n = 0;
5483 }
5484 }
5485 else
5486 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005487 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 if (n > len - wlen)
5489 {
5490 /* We have an incomplete byte sequence at the end to
5491 * be written. We can't convert it without the
5492 * remaining bytes. Keep them for the next call. */
5493 if (len - wlen > CONV_RESTLEN)
5494 return FAIL;
5495 ip->bw_restlen = len - wlen;
5496 mch_memmove(ip->bw_rest, buf + wlen,
5497 (size_t)ip->bw_restlen);
5498 break;
5499 }
5500 if (n > 1)
5501 c = utf_ptr2char(buf + wlen);
5502 else
5503 c = buf[wlen];
5504 }
5505
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005506 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5507 {
5508 ip->bw_conv_error = TRUE;
5509 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5510 }
5511 if (c == NL)
5512 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005513 }
5514 if (flags & FIO_LATIN1)
5515 len = (int)(p - buf);
5516 else
5517 {
5518 buf = ip->bw_conv_buf;
5519 len = (int)(p - ip->bw_conv_buf);
5520 }
5521 }
5522
5523# ifdef WIN3264
5524 else if (flags & FIO_CODEPAGE)
5525 {
5526 /*
5527 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5528 * codepage.
5529 */
5530 char_u *from;
5531 size_t fromlen;
5532 char_u *to;
5533 int u8c;
5534 BOOL bad = FALSE;
5535 int needed;
5536
5537 if (ip->bw_restlen > 0)
5538 {
5539 /* Need to concatenate the remainder of the previous call and
5540 * the bytes of the current call. Use the end of the
5541 * conversion buffer for this. */
5542 fromlen = len + ip->bw_restlen;
5543 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5544 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5545 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5546 }
5547 else
5548 {
5549 from = buf;
5550 fromlen = len;
5551 }
5552
5553 to = ip->bw_conv_buf;
5554 if (enc_utf8)
5555 {
5556 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5557 * The buffer has been allocated to be big enough. */
5558 while (fromlen > 0)
5559 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005560 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561 if (n > (int)fromlen) /* incomplete byte sequence */
5562 break;
5563 u8c = utf_ptr2char(from);
5564 *to++ = (u8c & 0xff);
5565 *to++ = (u8c >> 8);
5566 fromlen -= n;
5567 from += n;
5568 }
5569
5570 /* Copy remainder to ip->bw_rest[] to be used for the next
5571 * call. */
5572 if (fromlen > CONV_RESTLEN)
5573 {
5574 /* weird overlong sequence */
5575 ip->bw_conv_error = TRUE;
5576 return FAIL;
5577 }
5578 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005579 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 }
5581 else
5582 {
5583 /* Convert from enc_codepage to UCS-2, to the start of the
5584 * buffer. The buffer has been allocated to be big enough. */
5585 ip->bw_restlen = 0;
5586 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005587 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 NULL, 0);
5589 if (needed == 0)
5590 {
5591 /* When conversion fails there may be a trailing byte. */
5592 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005593 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 NULL, 0);
5595 if (needed == 0)
5596 {
5597 /* Conversion doesn't work. */
5598 ip->bw_conv_error = TRUE;
5599 return FAIL;
5600 }
5601 /* Save the trailing byte for the next call. */
5602 ip->bw_rest[0] = from[fromlen - 1];
5603 ip->bw_restlen = 1;
5604 }
5605 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005606 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 (LPWSTR)to, needed);
5608 if (needed == 0)
5609 {
5610 /* Safety check: Conversion doesn't work. */
5611 ip->bw_conv_error = TRUE;
5612 return FAIL;
5613 }
5614 to += needed * 2;
5615 }
5616
5617 fromlen = to - ip->bw_conv_buf;
5618 buf = to;
5619# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5620 if (FIO_GET_CP(flags) == CP_UTF8)
5621 {
5622 /* Convert from UCS-2 to UTF-8, using the remainder of the
5623 * conversion buffer. Fails when out of space. */
5624 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5625 {
5626 u8c = *from++;
5627 u8c += (*from++ << 8);
5628 to += utf_char2bytes(u8c, to);
5629 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5630 {
5631 ip->bw_conv_error = TRUE;
5632 return FAIL;
5633 }
5634 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005635 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 }
5637 else
5638#endif
5639 {
5640 /* Convert from UCS-2 to the codepage, using the remainder of
5641 * the conversion buffer. If the conversion uses the default
5642 * character "0", the data doesn't fit in this encoding, so
5643 * fail. */
5644 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5645 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005646 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5647 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 if (bad)
5649 {
5650 ip->bw_conv_error = TRUE;
5651 return FAIL;
5652 }
5653 }
5654 }
5655# endif
5656
Bram Moolenaar56718732006-03-15 22:53:57 +00005657# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 else if (flags & FIO_MACROMAN)
5659 {
5660 /*
5661 * Convert UTF-8 or latin1 to Apple MacRoman.
5662 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663 char_u *from;
5664 size_t fromlen;
5665
5666 if (ip->bw_restlen > 0)
5667 {
5668 /* Need to concatenate the remainder of the previous call and
5669 * the bytes of the current call. Use the end of the
5670 * conversion buffer for this. */
5671 fromlen = len + ip->bw_restlen;
5672 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5673 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5674 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5675 }
5676 else
5677 {
5678 from = buf;
5679 fromlen = len;
5680 }
5681
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005682 if (enc2macroman(from, fromlen,
5683 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5684 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 {
5686 ip->bw_conv_error = TRUE;
5687 return FAIL;
5688 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 }
5691# endif
5692
5693# ifdef USE_ICONV
5694 if (ip->bw_iconv_fd != (iconv_t)-1)
5695 {
5696 const char *from;
5697 size_t fromlen;
5698 char *to;
5699 size_t tolen;
5700
5701 /* Convert with iconv(). */
5702 if (ip->bw_restlen > 0)
5703 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005704 char *fp;
5705
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 /* Need to concatenate the remainder of the previous call and
5707 * the bytes of the current call. Use the end of the
5708 * conversion buffer for this. */
5709 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005710 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5711 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5712 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5713 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 tolen = ip->bw_conv_buflen - fromlen;
5715 }
5716 else
5717 {
5718 from = (const char *)buf;
5719 fromlen = len;
5720 tolen = ip->bw_conv_buflen;
5721 }
5722 to = (char *)ip->bw_conv_buf;
5723
5724 if (ip->bw_first)
5725 {
5726 size_t save_len = tolen;
5727
5728 /* output the initial shift state sequence */
5729 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5730
5731 /* There is a bug in iconv() on Linux (which appears to be
5732 * wide-spread) which sets "to" to NULL and messes up "tolen".
5733 */
5734 if (to == NULL)
5735 {
5736 to = (char *)ip->bw_conv_buf;
5737 tolen = save_len;
5738 }
5739 ip->bw_first = FALSE;
5740 }
5741
5742 /*
5743 * If iconv() has an error or there is not enough room, fail.
5744 */
5745 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5746 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5747 || fromlen > CONV_RESTLEN)
5748 {
5749 ip->bw_conv_error = TRUE;
5750 return FAIL;
5751 }
5752
5753 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5754 if (fromlen > 0)
5755 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5756 ip->bw_restlen = (int)fromlen;
5757
5758 buf = ip->bw_conv_buf;
5759 len = (int)((char_u *)to - ip->bw_conv_buf);
5760 }
5761# endif
5762 }
5763#endif /* FEAT_MBYTE */
5764
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005765 if (ip->bw_fd < 0)
5766 /* Only checking conversion, which is OK if we get here. */
5767 return OK;
5768
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005770 if (flags & FIO_ENCRYPTED)
5771 {
5772 /* Encrypt the data. Do it in-place if possible, otherwise use an
5773 * allocated buffer. */
5774 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5775 {
5776 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5777 }
5778 else
5779 {
5780 char_u *outbuf;
5781
5782 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5783 if (len == 0)
5784 return OK; /* Crypt layer is buffering, will flush later. */
5785 wlen = write_eintr(ip->bw_fd, outbuf, len);
5786 vim_free(outbuf);
5787 return (wlen < len) ? FAIL : OK;
5788 }
5789 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790#endif
5791
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005792 wlen = write_eintr(ip->bw_fd, buf, len);
5793 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794}
5795
5796#ifdef FEAT_MBYTE
5797/*
5798 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005799 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 */
5801 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005802ucs2bytes(
5803 unsigned c, /* in: character */
5804 char_u **pp, /* in/out: pointer to result */
5805 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806{
5807 char_u *p = *pp;
5808 int error = FALSE;
5809 int cc;
5810
5811
5812 if (flags & FIO_UCS4)
5813 {
5814 if (flags & FIO_ENDIAN_L)
5815 {
5816 *p++ = c;
5817 *p++ = (c >> 8);
5818 *p++ = (c >> 16);
5819 *p++ = (c >> 24);
5820 }
5821 else
5822 {
5823 *p++ = (c >> 24);
5824 *p++ = (c >> 16);
5825 *p++ = (c >> 8);
5826 *p++ = c;
5827 }
5828 }
5829 else if (flags & (FIO_UCS2 | FIO_UTF16))
5830 {
5831 if (c >= 0x10000)
5832 {
5833 if (flags & FIO_UTF16)
5834 {
5835 /* Make two words, ten bits of the character in each. First
5836 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5837 c -= 0x10000;
5838 if (c >= 0x100000)
5839 error = TRUE;
5840 cc = ((c >> 10) & 0x3ff) + 0xd800;
5841 if (flags & FIO_ENDIAN_L)
5842 {
5843 *p++ = cc;
5844 *p++ = ((unsigned)cc >> 8);
5845 }
5846 else
5847 {
5848 *p++ = ((unsigned)cc >> 8);
5849 *p++ = cc;
5850 }
5851 c = (c & 0x3ff) + 0xdc00;
5852 }
5853 else
5854 error = TRUE;
5855 }
5856 if (flags & FIO_ENDIAN_L)
5857 {
5858 *p++ = c;
5859 *p++ = (c >> 8);
5860 }
5861 else
5862 {
5863 *p++ = (c >> 8);
5864 *p++ = c;
5865 }
5866 }
5867 else /* Latin1 */
5868 {
5869 if (c >= 0x100)
5870 {
5871 error = TRUE;
5872 *p++ = 0xBF;
5873 }
5874 else
5875 *p++ = c;
5876 }
5877
5878 *pp = p;
5879 return error;
5880}
5881
5882/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005883 * Return TRUE if file encoding "fenc" requires conversion from or to
5884 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885 */
5886 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005887need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005889 int same_encoding;
5890 int enc_flags;
5891 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005893 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005894 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005895 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005896 fenc_flags = 0;
5897 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005898 else
5899 {
5900 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5901 * "ucs-4be", etc. */
5902 enc_flags = get_fio_flags(p_enc);
5903 fenc_flags = get_fio_flags(fenc);
5904 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5905 }
5906 if (same_encoding)
5907 {
5908 /* Specified encoding matches with 'encoding'. This requires
5909 * conversion when 'encoding' is Unicode but not UTF-8. */
5910 return enc_unicode != 0;
5911 }
5912
5913 /* Encodings differ. However, conversion is not needed when 'enc' is any
5914 * Unicode encoding and the file is UTF-8. */
5915 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916}
5917
5918/*
5919 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5920 * internal conversion.
5921 * if "ptr" is an empty string, use 'encoding'.
5922 */
5923 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005924get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925{
5926 int prop;
5927
5928 if (*ptr == NUL)
5929 ptr = p_enc;
5930
5931 prop = enc_canon_props(ptr);
5932 if (prop & ENC_UNICODE)
5933 {
5934 if (prop & ENC_2BYTE)
5935 {
5936 if (prop & ENC_ENDIAN_L)
5937 return FIO_UCS2 | FIO_ENDIAN_L;
5938 return FIO_UCS2;
5939 }
5940 if (prop & ENC_4BYTE)
5941 {
5942 if (prop & ENC_ENDIAN_L)
5943 return FIO_UCS4 | FIO_ENDIAN_L;
5944 return FIO_UCS4;
5945 }
5946 if (prop & ENC_2WORD)
5947 {
5948 if (prop & ENC_ENDIAN_L)
5949 return FIO_UTF16 | FIO_ENDIAN_L;
5950 return FIO_UTF16;
5951 }
5952 return FIO_UTF8;
5953 }
5954 if (prop & ENC_LATIN1)
5955 return FIO_LATIN1;
5956 /* must be ENC_DBCS, requires iconv() */
5957 return 0;
5958}
5959
5960#ifdef WIN3264
5961/*
5962 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5963 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5964 * Used for conversion between 'encoding' and 'fileencoding'.
5965 */
5966 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005967get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968{
5969 int cp;
5970
5971 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5972 if (!enc_utf8 && enc_codepage <= 0)
5973 return 0;
5974
5975 cp = encname2codepage(ptr);
5976 if (cp == 0)
5977 {
5978# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5979 if (STRCMP(ptr, "utf-8") == 0)
5980 cp = CP_UTF8;
5981 else
5982# endif
5983 return 0;
5984 }
5985 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5986}
5987#endif
5988
Bram Moolenaard0573012017-10-28 21:11:06 +02005989#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990/*
5991 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5992 * needed for the internal conversion to/from utf-8 or latin1.
5993 */
5994 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005995get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996{
5997 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5998 && (enc_canon_props(ptr) & ENC_MACROMAN))
5999 return FIO_MACROMAN;
6000 return 0;
6001}
6002#endif
6003
6004/*
6005 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6006 * "size" must be at least 2.
6007 * Return the name of the encoding and set "*lenp" to the length.
6008 * Returns NULL when no BOM found.
6009 */
6010 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006011check_for_bom(
6012 char_u *p,
6013 long size,
6014 int *lenp,
6015 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016{
6017 char *name = NULL;
6018 int len = 2;
6019
6020 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006021 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022 {
6023 name = "utf-8"; /* EF BB BF */
6024 len = 3;
6025 }
6026 else if (p[0] == 0xff && p[1] == 0xfe)
6027 {
6028 if (size >= 4 && p[2] == 0 && p[3] == 0
6029 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6030 {
6031 name = "ucs-4le"; /* FF FE 00 00 */
6032 len = 4;
6033 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006034 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006036 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6037 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038 name = "utf-16le"; /* FF FE */
6039 }
6040 else if (p[0] == 0xfe && p[1] == 0xff
6041 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6042 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006043 /* Default to utf-16, it works also for ucs-2 text. */
6044 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006046 else
6047 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 }
6049 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6050 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6051 {
6052 name = "ucs-4"; /* 00 00 FE FF */
6053 len = 4;
6054 }
6055
6056 *lenp = len;
6057 return (char_u *)name;
6058}
6059
6060/*
6061 * Generate a BOM in "buf[4]" for encoding "name".
6062 * Return the length of the BOM (zero when no BOM).
6063 */
6064 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006065make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066{
6067 int flags;
6068 char_u *p;
6069
6070 flags = get_fio_flags(name);
6071
6072 /* Can't put a BOM in a non-Unicode file. */
6073 if (flags == FIO_LATIN1 || flags == 0)
6074 return 0;
6075
6076 if (flags == FIO_UTF8) /* UTF-8 */
6077 {
6078 buf[0] = 0xef;
6079 buf[1] = 0xbb;
6080 buf[2] = 0xbf;
6081 return 3;
6082 }
6083 p = buf;
6084 (void)ucs2bytes(0xfeff, &p, flags);
6085 return (int)(p - buf);
6086}
6087#endif
6088
6089/*
6090 * Try to find a shortname by comparing the fullname with the current
6091 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006092 * Returns "full_path" or pointer into "full_path" if shortened.
6093 */
6094 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006095shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006096{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006097 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006098 char_u *p = full_path;
6099
Bram Moolenaard9462e32011-04-11 21:35:11 +02006100 dirname = alloc(MAXPATHL);
6101 if (dirname == NULL)
6102 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006103 if (mch_dirname(dirname, MAXPATHL) == OK)
6104 {
6105 p = shorten_fname(full_path, dirname);
6106 if (p == NULL || *p == NUL)
6107 p = full_path;
6108 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006109 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006110 return p;
6111}
6112
6113/*
6114 * Try to find a shortname by comparing the fullname with the current
6115 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 * Returns NULL if not shorter name possible, pointer into "full_path"
6117 * otherwise.
6118 */
6119 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006120shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121{
6122 int len;
6123 char_u *p;
6124
6125 if (full_path == NULL)
6126 return NULL;
6127 len = (int)STRLEN(dir_name);
6128 if (fnamencmp(dir_name, full_path, len) == 0)
6129 {
6130 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006131#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006133 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134 * slash, since C: by itself does not define a specific dir. In this
6135 * case p may already be correct. <negri>
6136 */
6137 if (!((len > 2) && (*(p - 2) == ':')))
6138#endif
6139 {
6140 if (vim_ispathsep(*p))
6141 ++p;
6142#ifndef VMS /* the path separator is always part of the path */
6143 else
6144 p = NULL;
6145#endif
6146 }
6147 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006148#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149 /*
6150 * When using a file in the current drive, remove the drive name:
6151 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6152 * a floppy from "A:\dir" to "B:\dir".
6153 */
6154 else if (len > 3
6155 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6156 && full_path[1] == ':'
6157 && vim_ispathsep(full_path[2]))
6158 p = full_path + 2;
6159#endif
6160 else
6161 p = NULL;
6162 return p;
6163}
6164
6165/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006166 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 * When "force" is TRUE: Use full path from now on for files currently being
6168 * edited, both for file name and swap file name. Try to shorten the file
6169 * names a bit, if safe to do so.
6170 * When "force" is FALSE: Only try to shorten absolute file names.
6171 * For buffers that have buftype "nofile" or "scratch": never change the file
6172 * name.
6173 */
6174 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006175shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6176{
6177 char_u *p;
6178
6179 if (buf->b_fname != NULL
6180#ifdef FEAT_QUICKFIX
6181 && !bt_nofile(buf)
6182#endif
6183 && !path_with_url(buf->b_fname)
6184 && (force
6185 || buf->b_sfname == NULL
6186 || mch_isFullName(buf->b_sfname)))
6187 {
6188 VIM_CLEAR(buf->b_sfname);
6189 p = shorten_fname(buf->b_ffname, dirname);
6190 if (p != NULL)
6191 {
6192 buf->b_sfname = vim_strsave(p);
6193 buf->b_fname = buf->b_sfname;
6194 }
6195 if (p == NULL || buf->b_fname == NULL)
6196 buf->b_fname = buf->b_ffname;
6197 }
6198}
6199
6200/*
6201 * Shorten filenames for all buffers.
6202 */
6203 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006204shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205{
6206 char_u dirname[MAXPATHL];
6207 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208
6209 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006210 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006212 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006213
6214 /* Always make the swap file name a full path, a "nofile" buffer may
6215 * also have a swap file. */
6216 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006219 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220}
6221
6222#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6223 || defined(FEAT_GUI_MSWIN) \
6224 || defined(FEAT_GUI_MAC) \
6225 || defined(PROTO)
6226/*
6227 * Shorten all filenames in "fnames[count]" by current directory.
6228 */
6229 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006230shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231{
6232 int i;
6233 char_u dirname[MAXPATHL];
6234 char_u *p;
6235
6236 if (fnames == NULL || count < 1)
6237 return;
6238 mch_dirname(dirname, sizeof(dirname));
6239 for (i = 0; i < count; ++i)
6240 {
6241 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6242 {
6243 /* shorten_fname() returns pointer in given "fnames[i]". If free
6244 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6245 * "p" first then free fnames[i]. */
6246 p = vim_strsave(p);
6247 vim_free(fnames[i]);
6248 fnames[i] = p;
6249 }
6250 }
6251}
6252#endif
6253
6254/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006255 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256 * fo_o_h.ext for MSDOS or when shortname option set.
6257 *
6258 * Assumed that fname is a valid name found in the filesystem we assure that
6259 * the return value is a different name and ends in 'ext'.
6260 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6261 * characters otherwise.
6262 * Space for the returned name is allocated, must be freed later.
6263 * Returns NULL when out of memory.
6264 */
6265 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006266modname(
6267 char_u *fname,
6268 char_u *ext,
6269 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006271 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 fname, ext, prepend_dot);
6273}
6274
6275 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006276buf_modname(
6277 int shortname, /* use 8.3 file name */
6278 char_u *fname,
6279 char_u *ext,
6280 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281{
6282 char_u *retval;
6283 char_u *s;
6284 char_u *e;
6285 char_u *ptr;
6286 int fnamelen, extlen;
6287
6288 extlen = (int)STRLEN(ext);
6289
6290 /*
6291 * If there is no file name we must get the name of the current directory
6292 * (we need the full path in case :cd is used).
6293 */
6294 if (fname == NULL || *fname == NUL)
6295 {
6296 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6297 if (retval == NULL)
6298 return NULL;
6299 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6300 (fnamelen = (int)STRLEN(retval)) == 0)
6301 {
6302 vim_free(retval);
6303 return NULL;
6304 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006305 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 {
6307 retval[fnamelen++] = PATHSEP;
6308 retval[fnamelen] = NUL;
6309 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 }
6312 else
6313 {
6314 fnamelen = (int)STRLEN(fname);
6315 retval = alloc((unsigned)(fnamelen + extlen + 3));
6316 if (retval == NULL)
6317 return NULL;
6318 STRCPY(retval, fname);
6319#ifdef VMS
6320 vms_remove_version(retval); /* we do not need versions here */
6321#endif
6322 }
6323
6324 /*
6325 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6326 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6327 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6328 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6329 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006330 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006333#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006335#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006337#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 )
6339 if (*ptr == '.') /* replace '.' by '_' */
6340 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006342 {
6343 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347
6348 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6350 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351
6352 s = ptr + STRLEN(ptr);
6353
6354 /*
6355 * For 8.3 file names we may have to reduce the length.
6356 */
6357#ifdef USE_LONG_FNAME
6358 if (!USE_LONG_FNAME || shortname)
6359#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361#endif
6362 {
6363 /*
6364 * If there is no file name, or the file name ends in '/', and the
6365 * extension starts with '.', put a '_' before the dot, because just
6366 * ".ext" is invalid.
6367 */
6368 if (fname == NULL || *fname == NUL
6369 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6370 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 *s++ = '_';
6373 }
6374 /*
6375 * If the extension starts with '.', truncate the base name at 8
6376 * characters
6377 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006380 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 {
6382 s = ptr + 8;
6383 *s = '\0';
6384 }
6385 }
6386 /*
6387 * If the extension doesn't start with '.', and the file name
6388 * doesn't have an extension yet, append a '.'
6389 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 else if ((e = vim_strchr(ptr, '.')) == NULL)
6391 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 /*
6393 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006394 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 */
6396 else if ((int)STRLEN(e) + extlen > 4)
6397 s = e + 4 - extlen;
6398 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006399#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400 /*
6401 * If there is no file name, and the extension starts with '.', put a
6402 * '_' before the dot, because just ".ext" may be invalid if it's on a
6403 * FAT partition, and on HPFS it doesn't matter.
6404 */
6405 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6406 *s++ = '_';
6407#endif
6408
6409 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006410 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 * ext can start with '.' and cannot exceed 3 more characters.
6412 */
6413 STRCPY(s, ext);
6414
Bram Moolenaar071d4272004-06-13 20:20:40 +00006415 /*
6416 * Prepend the dot.
6417 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006418 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419#ifdef USE_LONG_FNAME
6420 && USE_LONG_FNAME
6421#endif
6422 )
6423 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006424 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427
6428 /*
6429 * Check that, after appending the extension, the file name is really
6430 * different.
6431 */
6432 if (fname != NULL && STRCMP(fname, retval) == 0)
6433 {
6434 /* we search for a character that can be replaced by '_' */
6435 while (--s >= ptr)
6436 {
6437 if (*s != '_')
6438 {
6439 *s = '_';
6440 break;
6441 }
6442 }
6443 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6444 *ptr = 'v';
6445 }
6446 return retval;
6447}
6448
6449/*
6450 * Like fgets(), but if the file line is too long, it is truncated and the
6451 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006452 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453 */
6454 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006455vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456{
6457 char *eof;
6458#define FGETS_SIZE 200
6459 char tbuf[FGETS_SIZE];
6460
6461 buf[size - 2] = NUL;
6462#ifdef USE_CR
6463 eof = fgets_cr((char *)buf, size, fp);
6464#else
6465 eof = fgets((char *)buf, size, fp);
6466#endif
6467 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6468 {
6469 buf[size - 1] = NUL; /* Truncate the line */
6470
6471 /* Now throw away the rest of the line: */
6472 do
6473 {
6474 tbuf[FGETS_SIZE - 2] = NUL;
6475#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006476 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006478 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479#endif
6480 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6481 }
6482 return (eof == NULL);
6483}
6484
6485#if defined(USE_CR) || defined(PROTO)
6486/*
6487 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6488 * Returns TRUE for end-of-file.
6489 * Only used for the Mac, because it's much slower than vim_fgets().
6490 */
6491 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006492tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493{
6494 int i = 0;
6495 int c;
6496 int eof = FALSE;
6497
6498 for (;;)
6499 {
6500 c = fgetc(fp);
6501 if (c == EOF)
6502 {
6503 eof = TRUE;
6504 break;
6505 }
6506 if (c == '\r')
6507 {
6508 /* Always store a NL for end-of-line. */
6509 if (i < size - 1)
6510 buf[i++] = '\n';
6511 c = fgetc(fp);
6512 if (c != '\n') /* Macintosh format: single CR. */
6513 ungetc(c, fp);
6514 break;
6515 }
6516 if (i < size - 1)
6517 buf[i++] = c;
6518 if (c == '\n')
6519 break;
6520 }
6521 buf[i] = NUL;
6522 return eof;
6523}
6524#endif
6525
6526/*
6527 * rename() only works if both files are on the same file system, this
6528 * function will (attempts to?) copy the file across if rename fails -- webb
6529 * Return -1 for failure, 0 for success.
6530 */
6531 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006532vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533{
6534 int fd_in;
6535 int fd_out;
6536 int n;
6537 char *errmsg = NULL;
6538 char *buffer;
6539#ifdef AMIGA
6540 BPTR flock;
6541#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006542 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006543 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006544#ifdef HAVE_ACL
6545 vim_acl_T acl; /* ACL from original file */
6546#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006547 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548
6549 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006550 * When the names are identical, there is nothing to do. When they refer
6551 * to the same file (ignoring case and slash/backslash differences) but
6552 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 */
6554 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006555 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006556 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006557 use_tmp_file = TRUE;
6558 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006559 return 0;
6560 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561
6562 /*
6563 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6564 */
6565 if (mch_stat((char *)from, &st) < 0)
6566 return -1;
6567
Bram Moolenaar3576da72008-12-30 15:15:57 +00006568#ifdef UNIX
6569 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006570 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006571
6572 /* It's possible for the source and destination to be the same file.
6573 * This happens when "from" and "to" differ in case and are on a FAT32
6574 * filesystem. In that case go through a temp file name. */
6575 if (mch_stat((char *)to, &st_to) >= 0
6576 && st.st_dev == st_to.st_dev
6577 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006578 use_tmp_file = TRUE;
6579 }
6580#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006581#ifdef WIN3264
6582 {
6583 BY_HANDLE_FILE_INFORMATION info1, info2;
6584
6585 /* It's possible for the source and destination to be the same file.
6586 * In that case go through a temp file name. This makes rename("foo",
6587 * "./foo") a no-op (in a complicated way). */
6588 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6589 && win32_fileinfo(to, &info2) == FILEINFO_OK
6590 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6591 && info1.nFileIndexHigh == info2.nFileIndexHigh
6592 && info1.nFileIndexLow == info2.nFileIndexLow)
6593 use_tmp_file = TRUE;
6594 }
6595#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006596
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006597 if (use_tmp_file)
6598 {
6599 char tempname[MAXPATHL + 1];
6600
6601 /*
6602 * Find a name that doesn't exist and is in the same directory.
6603 * Rename "from" to "tempname" and then rename "tempname" to "to".
6604 */
6605 if (STRLEN(from) >= MAXPATHL - 5)
6606 return -1;
6607 STRCPY(tempname, from);
6608 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006609 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006610 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6611 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006612 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006613 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006614 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006615 if (mch_rename(tempname, (char *)to) == 0)
6616 return 0;
6617 /* Strange, the second step failed. Try moving the
6618 * file back and return failure. */
6619 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006620 return -1;
6621 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006622 /* If it fails for one temp name it will most likely fail
6623 * for any temp name, give up. */
6624 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006625 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006626 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006627 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006628 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006629
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 /*
6631 * Delete the "to" file, this is required on some systems to make the
6632 * mch_rename() work, on other systems it makes sure that we don't have
6633 * two files when the mch_rename() fails.
6634 */
6635
6636#ifdef AMIGA
6637 /*
6638 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6639 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006640 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 * deleting the "from" file (horror!) we lock it during the remove.
6642 *
6643 * When used for making a backup before writing the file: This should not
6644 * happen with ":w", because startscript() should detect this problem and
6645 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6646 * name. This problem does exist with ":w filename", but then the
6647 * original file will be somewhere else so the backup isn't really
6648 * important. If autoscripting is off the rename may fail.
6649 */
6650 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6651#endif
6652 mch_remove(to);
6653#ifdef AMIGA
6654 if (flock)
6655 UnLock(flock);
6656#endif
6657
6658 /*
6659 * First try a normal rename, return if it works.
6660 */
6661 if (mch_rename((char *)from, (char *)to) == 0)
6662 return 0;
6663
6664 /*
6665 * Rename() failed, try copying the file.
6666 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006667 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006668#ifdef HAVE_ACL
6669 /* For systems that support ACL: get the ACL from the original file. */
6670 acl = mch_get_acl(from);
6671#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6673 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006674 {
6675#ifdef HAVE_ACL
6676 mch_free_acl(acl);
6677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006679 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006680
6681 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006682 fd_out = mch_open((char *)to,
6683 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 if (fd_out == -1)
6685 {
6686 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006687#ifdef HAVE_ACL
6688 mch_free_acl(acl);
6689#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 return -1;
6691 }
6692
6693 buffer = (char *)alloc(BUFSIZE);
6694 if (buffer == NULL)
6695 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006697 close(fd_in);
6698#ifdef HAVE_ACL
6699 mch_free_acl(acl);
6700#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 return -1;
6702 }
6703
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006704 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6705 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 {
6707 errmsg = _("E208: Error writing to \"%s\"");
6708 break;
6709 }
6710
6711 vim_free(buffer);
6712 close(fd_in);
6713 if (close(fd_out) < 0)
6714 errmsg = _("E209: Error closing \"%s\"");
6715 if (n < 0)
6716 {
6717 errmsg = _("E210: Error reading \"%s\"");
6718 to = from;
6719 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006720#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006721 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006722#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006723#ifdef HAVE_ACL
6724 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006725 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006726#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006727#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006728 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006729#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 if (errmsg != NULL)
6731 {
6732 EMSG2(errmsg, to);
6733 return -1;
6734 }
6735 mch_remove(from);
6736 return 0;
6737}
6738
6739static int already_warned = FALSE;
6740
6741/*
6742 * Check if any not hidden buffer has been changed.
6743 * Postpone the check if there are characters in the stuff buffer, a global
6744 * command is being executed, a mapping is being executed or an autocommand is
6745 * busy.
6746 * Returns TRUE if some message was written (screen should be redrawn and
6747 * cursor positioned).
6748 */
6749 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006750check_timestamps(
6751 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752{
6753 buf_T *buf;
6754 int didit = 0;
6755 int n;
6756
6757 /* Don't check timestamps while system() or another low-level function may
6758 * cause us to lose and gain focus. */
6759 if (no_check_timestamps > 0)
6760 return FALSE;
6761
6762 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6763 * event and we would keep on checking if the file is steadily growing.
6764 * Do check again after typing something. */
6765 if (focus && did_check_timestamps)
6766 {
6767 need_check_timestamps = TRUE;
6768 return FALSE;
6769 }
6770
6771 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006772 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 need_check_timestamps = TRUE; /* check later */
6774 else
6775 {
6776 ++no_wait_return;
6777 did_check_timestamps = TRUE;
6778 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006779 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 {
6781 /* Only check buffers in a window. */
6782 if (buf->b_nwindows > 0)
6783 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006784 bufref_T bufref;
6785
6786 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787 n = buf_check_timestamp(buf, focus);
6788 if (didit < n)
6789 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006790 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 {
6792 /* Autocommands have removed the buffer, start at the
6793 * first one again. */
6794 buf = firstbuf;
6795 continue;
6796 }
6797 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798 }
6799 --no_wait_return;
6800 need_check_timestamps = FALSE;
6801 if (need_wait_return && didit == 2)
6802 {
6803 /* make sure msg isn't overwritten */
6804 msg_puts((char_u *)"\n");
6805 out_flush();
6806 }
6807 }
6808 return didit;
6809}
6810
6811/*
6812 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6813 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6814 * empty.
6815 */
6816 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006817move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818{
6819 buf_T *tbuf = curbuf;
6820 int retval = OK;
6821 linenr_T lnum;
6822 char_u *p;
6823
6824 /* Copy the lines in "frombuf" to "tobuf". */
6825 curbuf = tobuf;
6826 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6827 {
6828 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6829 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6830 {
6831 vim_free(p);
6832 retval = FAIL;
6833 break;
6834 }
6835 vim_free(p);
6836 }
6837
6838 /* Delete all the lines in "frombuf". */
6839 if (retval != FAIL)
6840 {
6841 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006842 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6843 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 {
6845 /* Oops! We could try putting back the saved lines, but that
6846 * might fail again... */
6847 retval = FAIL;
6848 break;
6849 }
6850 }
6851
6852 curbuf = tbuf;
6853 return retval;
6854}
6855
6856/*
6857 * Check if buffer "buf" has been changed.
6858 * Also check if the file for a new buffer unexpectedly appeared.
6859 * return 1 if a changed buffer was found.
6860 * return 2 if a message has been displayed.
6861 * return 0 otherwise.
6862 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006864buf_check_timestamp(
6865 buf_T *buf,
6866 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006868 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 int stat_res;
6870 int retval = 0;
6871 char_u *path;
6872 char_u *tbuf;
6873 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006874 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 int helpmesg = FALSE;
6876 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006877 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6879 int can_reload = FALSE;
6880#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006881 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 int orig_mode = buf->b_orig_mode;
6883#ifdef FEAT_GUI
6884 int save_mouse_correct = need_mouse_correct;
6885#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006887 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006888#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006889 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006890#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006891 bufref_T bufref;
6892
6893 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894
6895 /* If there is no file name, the buffer is not loaded, 'buftype' is
6896 * set, we are in the middle of a save or being called recursively: ignore
6897 * this buffer. */
6898 if (buf->b_ffname == NULL
6899 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006903#ifdef FEAT_NETBEANS_INTG
6904 || isNetbeansBuffer(buf)
6905#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006906#ifdef FEAT_TERMINAL
6907 || buf->b_term != NULL
6908#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 )
6910 return 0;
6911
6912 if ( !(buf->b_flags & BF_NOTEDITED)
6913 && buf->b_mtime != 0
6914 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6915 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006916 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917#ifdef HAVE_ST_MODE
6918 || (int)st.st_mode != buf->b_orig_mode
6919#else
6920 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6921#endif
6922 ))
6923 {
6924 retval = 1;
6925
Bram Moolenaar386bc822018-07-07 18:34:12 +02006926 // set b_mtime to stop further warnings (e.g., when executing
6927 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 if (stat_res < 0)
6929 {
Bram Moolenaar386bc822018-07-07 18:34:12 +02006930 // When 'autoread' is set we'll check the file again to see if it
6931 // re-appears.
6932 buf->b_mtime = buf->b_p_ar;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 buf->b_orig_size = 0;
6934 buf->b_orig_mode = 0;
6935 }
6936 else
6937 buf_store_time(buf, &st, buf->b_ffname);
6938
6939 /* Don't do anything for a directory. Might contain the file
6940 * explorer. */
6941 if (mch_isdir(buf->b_fname))
6942 ;
6943
6944 /*
6945 * If 'autoread' is set, the buffer has no changes and the file still
6946 * exists, reload the buffer. Use the buffer-local option value if it
6947 * was set, the global option value otherwise.
6948 */
6949 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6950 && !bufIsChanged(buf) && stat_res >= 0)
6951 reload = TRUE;
6952 else
6953 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006954 if (stat_res < 0)
6955 reason = "deleted";
6956 else if (bufIsChanged(buf))
6957 reason = "conflict";
6958 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6959 reason = "changed";
6960 else if (orig_mode != buf->b_orig_mode)
6961 reason = "mode";
6962 else
6963 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964
6965 /*
6966 * Only give the warning if there are no FileChangedShell
6967 * autocommands.
6968 * Avoid being called recursively by setting "busy".
6969 */
6970 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006971#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006972 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6973 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006974#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006975 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6977 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006978 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 busy = FALSE;
6980 if (n)
6981 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006982 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006984#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006985 s = get_vim_var_str(VV_FCS_CHOICE);
6986 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6987 reload = TRUE;
6988 else if (STRCMP(s, "ask") == 0)
6989 n = FALSE;
6990 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006991#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006992 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006994 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006996 if (*reason == 'd')
6997 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 else
6999 {
7000 helpmesg = TRUE;
7001#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7002 can_reload = TRUE;
7003#endif
7004 /*
7005 * Check if the file contents really changed to avoid
7006 * giving a warning when only the timestamp was set (e.g.,
7007 * checked out of CVS). Always warn when the buffer was
7008 * changed.
7009 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007010 if (reason[2] == 'n')
7011 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007013 mesg2 = _("See \":help W12\" for more info.");
7014 }
7015 else if (reason[1] == 'h')
7016 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007018 mesg2 = _("See \":help W11\" for more info.");
7019 }
7020 else if (*reason == 'm')
7021 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007023 mesg2 = _("See \":help W16\" for more info.");
7024 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007025 else
7026 /* Only timestamp changed, store it to avoid a warning
7027 * in check_mtime() later. */
7028 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 }
7030 }
7031 }
7032
7033 }
7034 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7035 && vim_fexists(buf->b_ffname))
7036 {
7037 retval = 1;
7038 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7039 buf->b_flags |= BF_NEW_W;
7040#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7041 can_reload = TRUE;
7042#endif
7043 }
7044
7045 if (mesg != NULL)
7046 {
7047 path = home_replace_save(buf, buf->b_fname);
7048 if (path != NULL)
7049 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007050 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 mesg2 = "";
7052 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7053 + STRLEN(mesg2) + 2));
7054 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007055#ifdef FEAT_EVAL
7056 /* Set warningmsg here, before the unimportant and output-specific
7057 * mesg2 has been appended. */
7058 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7059#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7061 if (can_reload)
7062 {
7063 if (*mesg2 != NUL)
7064 {
7065 STRCAT(tbuf, "\n");
7066 STRCAT(tbuf, mesg2);
7067 }
7068 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007069 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 reload = TRUE;
7071 }
7072 else
7073#endif
7074 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7075 {
7076 if (*mesg2 != NUL)
7077 {
7078 STRCAT(tbuf, "; ");
7079 STRCAT(tbuf, mesg2);
7080 }
7081 EMSG(tbuf);
7082 retval = 2;
7083 }
7084 else
7085 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 {
7088 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007089 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 if (*mesg2 != NUL)
7091 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007092 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 msg_clr_eos();
7094 (void)msg_end();
7095 if (emsg_silent == 0)
7096 {
7097 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007098#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007100#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 /* give the user some time to think about it */
7102 ui_delay(1000L, TRUE);
7103
7104 /* don't redraw and erase the message */
7105 redraw_cmdline = FALSE;
7106 }
7107 }
7108 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 }
7110
7111 vim_free(path);
7112 vim_free(tbuf);
7113 }
7114 }
7115
7116 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007117 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007118 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007119 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007120#ifdef FEAT_PERSISTENT_UNDO
7121 if (buf->b_p_udf && buf->b_ffname != NULL)
7122 {
7123 char_u hash[UNDO_HASH_SIZE];
7124 buf_T *save_curbuf = curbuf;
7125
7126 /* Any existing undo file is unusable, write it now. */
7127 curbuf = buf;
7128 u_compute_hash(hash);
7129 u_write_undo(NULL, FALSE, buf, hash);
7130 curbuf = save_curbuf;
7131 }
7132#endif
7133 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007135 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007136 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007137 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7138 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139#ifdef FEAT_GUI
7140 /* restore this in case an autocommand has set it; it would break
7141 * 'mousefocus' */
7142 need_mouse_correct = save_mouse_correct;
7143#endif
7144
7145 return retval;
7146}
7147
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007148/*
7149 * Reload a buffer that is already loaded.
7150 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007151 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7152 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007153 */
7154 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007155buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007156{
7157 exarg_T ea;
7158 pos_T old_cursor;
7159 linenr_T old_topline;
7160 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007161 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007162 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007163 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007164 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007165 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007166
7167 /* set curwin/curbuf for "buf" and save some things */
7168 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007169
7170 /* We only want to read the text from the file, not reset the syntax
7171 * highlighting, clear marks, diff status, etc. Force the fileformat
7172 * and encoding to be the same. */
7173 if (prep_exarg(&ea, buf) == OK)
7174 {
7175 old_cursor = curwin->w_cursor;
7176 old_topline = curwin->w_topline;
7177
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007178 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007179 {
7180 /* Save all the text, so that the reload can be undone.
7181 * Sync first so that this is a separate undo-able action. */
7182 u_sync(FALSE);
7183 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7184 flags |= READ_KEEP_UNDO;
7185 }
7186
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007187 /*
7188 * To behave like when a new file is edited (matters for
7189 * BufReadPost autocommands) we first need to delete the current
7190 * buffer contents. But if reading the file fails we should keep
7191 * the old contents. Can't use memory only, the file might be
7192 * too big. Use a hidden buffer to move the buffer contents to.
7193 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007194 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195 savebuf = NULL;
7196 else
7197 {
7198 /* Allocate a buffer without putting it in the buffer list. */
7199 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007200 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007201 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007202 {
7203 /* Open the memline. */
7204 curbuf = savebuf;
7205 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007206 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007207 curbuf = buf;
7208 curwin->w_buffer = buf;
7209 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007210 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007211 || move_lines(buf, savebuf) == FAIL)
7212 {
7213 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7214 buf->b_fname);
7215 saved = FAIL;
7216 }
7217 }
7218
7219 if (saved == OK)
7220 {
7221 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007222 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007223 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7224 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007225 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007226 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007227#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007228 if (!aborting())
7229#endif
7230 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007231 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007232 {
7233 /* Put the text back from the save buffer. First
7234 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007235 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007236 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007237 break;
7238 (void)move_lines(savebuf, buf);
7239 }
7240 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007241 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007242 {
7243 /* Mark the buffer as unmodified and free undo info. */
7244 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007245 if ((flags & READ_KEEP_UNDO) == 0)
7246 {
7247 u_blockfree(buf);
7248 u_clearall(buf);
7249 }
7250 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007251 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007252 /* Mark all undo states as changed. */
7253 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007254 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007255 }
7256 }
7257 vim_free(ea.cmd);
7258
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007259 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007260 wipe_buffer(savebuf, FALSE);
7261
7262#ifdef FEAT_DIFF
7263 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007264 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007265#endif
7266
7267 /* Restore the topline and cursor position and check it (lines may
7268 * have been removed). */
7269 if (old_topline > curbuf->b_ml.ml_line_count)
7270 curwin->w_topline = curbuf->b_ml.ml_line_count;
7271 else
7272 curwin->w_topline = old_topline;
7273 curwin->w_cursor = old_cursor;
7274 check_cursor();
7275 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007276 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007277#ifdef FEAT_FOLDING
7278 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007279 win_T *wp;
7280 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007281
7282 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007283 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007284 if (wp->w_buffer == curwin->w_buffer
7285 && !foldmethodIsManual(wp))
7286 foldUpdateAll(wp);
7287 }
7288#endif
7289 /* If the mode didn't change and 'readonly' was set, keep the old
7290 * value; the user probably used the ":view" command. But don't
7291 * reset it, might have had a read error. */
7292 if (orig_mode == curbuf->b_orig_mode)
7293 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007294
7295 /* Modelines must override settings done by autocommands. */
7296 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007297 }
7298
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007299 /* restore curwin/curbuf and a few other things */
7300 aucmd_restbuf(&aco);
7301 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007302}
7303
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007305buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306{
7307 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007308 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309#ifdef HAVE_ST_MODE
7310 buf->b_orig_mode = (int)st->st_mode;
7311#else
7312 buf->b_orig_mode = mch_getperm(fname);
7313#endif
7314}
7315
7316/*
7317 * Adjust the line with missing eol, used for the next write.
7318 * Used for do_filter(), when the input lines for the filter are deleted.
7319 */
7320 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007321write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007323 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7324 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325}
7326
Bram Moolenaarda440d22016-01-16 21:27:23 +01007327#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7328/*
7329 * Delete "name" and everything in it, recursively.
7330 * return 0 for succes, -1 if some file was not deleted.
7331 */
7332 int
7333delete_recursive(char_u *name)
7334{
7335 int result = 0;
7336 char_u **files;
7337 int file_count;
7338 int i;
7339 char_u *exp;
7340
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007341 /* A symbolic link to a directory itself is deleted, not the directory it
7342 * points to. */
7343 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007344# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007345 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007346# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007347 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007348# endif
7349 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007350 {
7351 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7352 exp = vim_strsave(NameBuff);
7353 if (exp == NULL)
7354 return -1;
7355 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007356 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007357 {
7358 for (i = 0; i < file_count; ++i)
7359 if (delete_recursive(files[i]) != 0)
7360 result = -1;
7361 FreeWild(file_count, files);
7362 }
7363 else
7364 result = -1;
7365 vim_free(exp);
7366 (void)mch_rmdir(name);
7367 }
7368 else
7369 result = mch_remove(name) == 0 ? 0 : -1;
7370
7371 return result;
7372}
7373#endif
7374
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375#if defined(TEMPDIRNAMES) || defined(PROTO)
7376static long temp_count = 0; /* Temp filename counter. */
7377
7378/*
7379 * Delete the temp directory and all files it contains.
7380 */
7381 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007382vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 if (vim_tempdir != NULL)
7385 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007386 /* remove the trailing path separator */
7387 gettail(vim_tempdir)[-1] = NUL;
7388 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007389 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 }
7391}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392
7393/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007394 * Directory "tempdir" was created. Expand this name to a full path and put
7395 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7396 * "tempdir" must be no longer than MAXPATHL.
7397 */
7398 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007399vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007400{
7401 char_u *buf;
7402
7403 buf = alloc((unsigned)MAXPATHL + 2);
7404 if (buf != NULL)
7405 {
7406 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7407 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007408 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007409 vim_tempdir = vim_strsave(buf);
7410 vim_free(buf);
7411 }
7412}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007413#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007414
7415/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 * vim_tempname(): Return a unique name that can be used for a temp file.
7417 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007418 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7419 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 *
7421 * The returned pointer is to allocated memory.
7422 * The returned pointer is NULL if no valid name was found.
7423 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007425vim_tempname(
7426 int extra_char UNUSED, /* char to use in the name instead of '?' */
7427 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428{
7429#ifdef USE_TMPNAM
7430 char_u itmp[L_tmpnam]; /* use tmpnam() */
7431#else
7432 char_u itmp[TEMPNAMELEN];
7433#endif
7434
7435#ifdef TEMPDIRNAMES
7436 static char *(tempdirs[]) = {TEMPDIRNAMES};
7437 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007439 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440# endif
7441
7442 /*
7443 * This will create a directory for private use by this instance of Vim.
7444 * This is done once, and the same directory is used for all temp files.
7445 * This method avoids security problems because of symlink attacks et al.
7446 * It's also a bit faster, because we only need to check for an existing
7447 * file when creating the directory and not for each temp file.
7448 */
7449 if (vim_tempdir == NULL)
7450 {
7451 /*
7452 * Try the entries in TEMPDIRNAMES to create the temp directory.
7453 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007454 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007456# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007457 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007458 long nr;
7459 long off;
7460# endif
7461
Bram Moolenaare1a61992015-12-03 21:02:27 +01007462 /* Expand $TMP, leave room for "/v1100000/999999999".
7463 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007465 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007467 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007468 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469
Bram Moolenaareaf03392009-11-17 11:08:52 +00007470# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007471 {
7472# if defined(UNIX) || defined(VMS)
7473 /* Make sure the umask doesn't remove the executable bit.
7474 * "repl" has been reported to use "177". */
7475 mode_t umask_save = umask(077);
7476# endif
7477 /* Leave room for filename */
7478 STRCAT(itmp, "vXXXXXX");
7479 if (mkdtemp((char *)itmp) != NULL)
7480 vim_settempdir(itmp);
7481# if defined(UNIX) || defined(VMS)
7482 (void)umask(umask_save);
7483# endif
7484 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007485# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486 /* Get an arbitrary number of up to 6 digits. When it's
7487 * unlikely that it already exists it will be faster,
7488 * otherwise it doesn't matter. The use of mkdir() avoids any
7489 * security problems because of the predictable number. */
7490 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007491 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492
7493 /* Try up to 10000 different values until we find a name that
7494 * doesn't exist. */
7495 for (off = 0; off < 10000L; ++off)
7496 {
7497 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007498# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007500# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007501
Bram Moolenaareaf03392009-11-17 11:08:52 +00007502 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7503# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 /* If mkdir() does not set errno to EEXIST, check for
7505 * existing file here. There is a race condition then,
7506 * although it's fail-safe. */
7507 if (mch_stat((char *)itmp, &st) >= 0)
7508 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007509# endif
7510# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 /* Make sure the umask doesn't remove the executable bit.
7512 * "repl" has been reported to use "177". */
7513 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007516# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007518# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 if (r == 0)
7520 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007521 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522 break;
7523 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007524# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 /* If the mkdir() didn't fail because the file/dir exists,
7526 * we probably can't create any dir here, try another
7527 * place. */
7528 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 break;
7531 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007532# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 if (vim_tempdir != NULL)
7534 break;
7535 }
7536 }
7537 }
7538
7539 if (vim_tempdir != NULL)
7540 {
7541 /* There is no need to check if the file exists, because we own the
7542 * directory and nobody else creates a file in it. */
7543 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7544 return vim_strsave(itmp);
7545 }
7546
7547 return NULL;
7548
7549#else /* TEMPDIRNAMES */
7550
7551# ifdef WIN3264
7552 char szTempFile[_MAX_PATH + 1];
7553 char buf4[4];
7554 char_u *retval;
7555 char_u *p;
7556
7557 STRCPY(itmp, "");
7558 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007559 {
7560 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7561 szTempFile[1] = NUL;
7562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563 strcpy(buf4, "VIM");
7564 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007565 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007567 if (!keep)
7568 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007569 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570
7571 /* Backslashes in a temp file name cause problems when filtering with
7572 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7573 * didn't set 'shellslash'. */
7574 retval = vim_strsave(itmp);
7575 if (*p_shcf == '-' || p_ssl)
7576 for (p = retval; *p; ++p)
7577 if (*p == '\\')
7578 *p = '/';
7579 return retval;
7580
7581# else /* WIN3264 */
7582
7583# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007584 char_u *p;
7585
Bram Moolenaar071d4272004-06-13 20:20:40 +00007586 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007587 p = tmpnam((char *)itmp);
7588 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 return NULL;
7590# else
7591 char_u *p;
7592
7593# ifdef VMS_TEMPNAM
7594 /* mktemp() is not working on VMS. It seems to be
7595 * a do-nothing function. Therefore we use tempnam().
7596 */
7597 sprintf((char *)itmp, "VIM%c", extra_char);
7598 p = (char_u *)tempnam("tmp:", (char *)itmp);
7599 if (p != NULL)
7600 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007601 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602 * and VIM will then be unable to find the file later */
7603 STRCPY(itmp, p);
7604 STRCAT(itmp, ".txt");
7605 free(p);
7606 }
7607 else
7608 return NULL;
7609# else
7610 STRCPY(itmp, TEMPNAME);
7611 if ((p = vim_strchr(itmp, '?')) != NULL)
7612 *p = extra_char;
7613 if (mktemp((char *)itmp) == NULL)
7614 return NULL;
7615# endif
7616# endif
7617
7618 return vim_strsave(itmp);
7619# endif /* WIN3264 */
7620#endif /* TEMPDIRNAMES */
7621}
7622
7623#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7624/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007625 * Convert all backslashes in fname to forward slashes in-place, unless when
7626 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627 */
7628 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007629forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630{
7631 char_u *p;
7632
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007633 if (path_with_url(fname))
7634 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 for (p = fname; *p != NUL; ++p)
7636# ifdef FEAT_MBYTE
7637 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007638 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 ++p;
7640 else
7641# endif
7642 if (*p == '\\')
7643 *p = '/';
7644}
7645#endif
7646
7647
7648/*
7649 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650 */
7651
Bram Moolenaar071d4272004-06-13 20:20:40 +00007652/*
7653 * The autocommands are stored in a list for each event.
7654 * Autocommands for the same pattern, that are consecutive, are joined
7655 * together, to avoid having to match the pattern too often.
7656 * The result is an array of Autopat lists, which point to AutoCmd lists:
7657 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007658 * last_autopat[0] -----------------------------+
7659 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7661 * Autopat.cmds Autopat.cmds
7662 * | |
7663 * V V
7664 * AutoCmd.next AutoCmd.next
7665 * | |
7666 * V V
7667 * AutoCmd.next NULL
7668 * |
7669 * V
7670 * NULL
7671 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007672 * last_autopat[1] --------+
7673 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 * first_autopat[1] --> Autopat.next --> NULL
7675 * Autopat.cmds
7676 * |
7677 * V
7678 * AutoCmd.next
7679 * |
7680 * V
7681 * NULL
7682 * etc.
7683 *
7684 * The order of AutoCmds is important, this is the order in which they were
7685 * defined and will have to be executed.
7686 */
7687typedef struct AutoCmd
7688{
7689 char_u *cmd; /* The command to be executed (NULL
7690 when command has been removed) */
7691 char nested; /* If autocommands nest here */
7692 char last; /* last command in list */
7693#ifdef FEAT_EVAL
7694 scid_T scriptID; /* script ID where defined */
7695#endif
7696 struct AutoCmd *next; /* Next AutoCmd in list */
7697} AutoCmd;
7698
7699typedef struct AutoPat
7700{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007701 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7702 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 char_u *pat; /* pattern as typed (NULL when pattern
7704 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007705 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007707 int group; /* group ID */
7708 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007709 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007710 char allow_dirs; /* Pattern may match whole path */
7711 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712} AutoPat;
7713
7714static struct event_name
7715{
7716 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007717 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007718} event_names[] =
7719{
7720 {"BufAdd", EVENT_BUFADD},
7721 {"BufCreate", EVENT_BUFADD},
7722 {"BufDelete", EVENT_BUFDELETE},
7723 {"BufEnter", EVENT_BUFENTER},
7724 {"BufFilePost", EVENT_BUFFILEPOST},
7725 {"BufFilePre", EVENT_BUFFILEPRE},
7726 {"BufHidden", EVENT_BUFHIDDEN},
7727 {"BufLeave", EVENT_BUFLEAVE},
7728 {"BufNew", EVENT_BUFNEW},
7729 {"BufNewFile", EVENT_BUFNEWFILE},
7730 {"BufRead", EVENT_BUFREADPOST},
7731 {"BufReadCmd", EVENT_BUFREADCMD},
7732 {"BufReadPost", EVENT_BUFREADPOST},
7733 {"BufReadPre", EVENT_BUFREADPRE},
7734 {"BufUnload", EVENT_BUFUNLOAD},
7735 {"BufWinEnter", EVENT_BUFWINENTER},
7736 {"BufWinLeave", EVENT_BUFWINLEAVE},
7737 {"BufWipeout", EVENT_BUFWIPEOUT},
7738 {"BufWrite", EVENT_BUFWRITEPRE},
7739 {"BufWritePost", EVENT_BUFWRITEPOST},
7740 {"BufWritePre", EVENT_BUFWRITEPRE},
7741 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007742 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007743 {"CmdlineEnter", EVENT_CMDLINEENTER},
7744 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007745 {"CmdwinEnter", EVENT_CMDWINENTER},
7746 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007747 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007748 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar60a68362018-04-30 15:40:48 +02007749 {"ColorSchemePre", EVENT_COLORSCHEMEPRE},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007750 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007751 {"CursorHold", EVENT_CURSORHOLD},
7752 {"CursorHoldI", EVENT_CURSORHOLDI},
7753 {"CursorMoved", EVENT_CURSORMOVED},
7754 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007755 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007757 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7760 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7761 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7762 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007763 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 {"FileChangedRO", EVENT_FILECHANGEDRO},
7765 {"FileReadPost", EVENT_FILEREADPOST},
7766 {"FileReadPre", EVENT_FILEREADPRE},
7767 {"FileReadCmd", EVENT_FILEREADCMD},
7768 {"FileType", EVENT_FILETYPE},
7769 {"FileWritePost", EVENT_FILEWRITEPOST},
7770 {"FileWritePre", EVENT_FILEWRITEPRE},
7771 {"FileWriteCmd", EVENT_FILEWRITECMD},
7772 {"FilterReadPost", EVENT_FILTERREADPOST},
7773 {"FilterReadPre", EVENT_FILTERREADPRE},
7774 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7775 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7776 {"FocusGained", EVENT_FOCUSGAINED},
7777 {"FocusLost", EVENT_FOCUSLOST},
7778 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7779 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007780 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007781 {"InsertChange", EVENT_INSERTCHANGE},
7782 {"InsertEnter", EVENT_INSERTENTER},
7783 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007784 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007785 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007786 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007787 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7788 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007789 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007791 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007792 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7793 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007794 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007795 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007796 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007797 {"StdinReadPost", EVENT_STDINREADPOST},
7798 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007799 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007800 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007801 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007802 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007803 {"TabEnter", EVENT_TABENTER},
7804 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007806 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007808 {"TextChanged", EVENT_TEXTCHANGED},
7809 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007810 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 {"User", EVENT_USER},
7812 {"VimEnter", EVENT_VIMENTER},
7813 {"VimLeave", EVENT_VIMLEAVE},
7814 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007815 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816 {"WinEnter", EVENT_WINENTER},
7817 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007818 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007819 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007820 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821};
7822
7823static AutoPat *first_autopat[NUM_EVENTS] =
7824{
7825 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7826 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7827 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7828 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007829 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007830 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007831};
7832
Bram Moolenaar462455e2017-11-10 21:53:11 +01007833static AutoPat *last_autopat[NUM_EVENTS] =
7834{
7835 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7836 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7837 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7838 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7839 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7840 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7841};
7842
Bram Moolenaar071d4272004-06-13 20:20:40 +00007843/*
7844 * struct used to keep status while executing autocommands for an event.
7845 */
7846typedef struct AutoPatCmd
7847{
7848 AutoPat *curpat; /* next AutoPat to examine */
7849 AutoCmd *nextcmd; /* next AutoCmd to execute */
7850 int group; /* group being used */
7851 char_u *fname; /* fname to match with */
7852 char_u *sfname; /* sfname to match with */
7853 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007854 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007855 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7856 buf is deleted */
7857 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007858} AutoPatCmd;
7859
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007860static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007861
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862/*
7863 * augroups stores a list of autocmd group names.
7864 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007865static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007867/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007868static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007869
7870/*
7871 * The ID of the current group. Group 0 is the default one.
7872 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873static int current_augroup = AUGROUP_DEFAULT;
7874
7875static int au_need_clean = FALSE; /* need to delete marked patterns */
7876
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007877static void show_autocmd(AutoPat *ap, event_T event);
7878static void au_remove_pat(AutoPat *ap);
7879static void au_remove_cmds(AutoPat *ap);
7880static void au_cleanup(void);
7881static int au_new_group(char_u *name);
7882static void au_del_group(char_u *name);
7883static event_T event_name2nr(char_u *start, char_u **end);
7884static char_u *event_nr2name(event_T event);
7885static char_u *find_end_event(char_u *arg, int have_group);
7886static int event_ignored(event_T event);
7887static int au_get_grouparg(char_u **argp);
7888static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7889static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7890static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007891static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007893
Bram Moolenaar754b5602006-02-09 23:53:20 +00007894static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007896static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007898 static char_u *
7899get_deleted_augroup(void)
7900{
7901 if (deleted_augroup == NULL)
7902 deleted_augroup = (char_u *)_("--Deleted--");
7903 return deleted_augroup;
7904}
7905
Bram Moolenaar071d4272004-06-13 20:20:40 +00007906/*
7907 * Show the autocommands for one AutoPat.
7908 */
7909 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007910show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911{
7912 AutoCmd *ac;
7913
7914 /* Check for "got_int" (here and at various places below), which is set
7915 * when "q" has been hit for the "--more--" prompt */
7916 if (got_int)
7917 return;
7918 if (ap->pat == NULL) /* pattern has been removed */
7919 return;
7920
7921 msg_putchar('\n');
7922 if (got_int)
7923 return;
7924 if (event != last_event || ap->group != last_group)
7925 {
7926 if (ap->group != AUGROUP_DEFAULT)
7927 {
7928 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007929 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007931 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007932 msg_puts((char_u *)" ");
7933 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007934 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 last_event = event;
7936 last_group = ap->group;
7937 msg_putchar('\n');
7938 if (got_int)
7939 return;
7940 }
7941 msg_col = 4;
7942 msg_outtrans(ap->pat);
7943
7944 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7945 {
7946 if (ac->cmd != NULL) /* skip removed commands */
7947 {
7948 if (msg_col >= 14)
7949 msg_putchar('\n');
7950 msg_col = 14;
7951 if (got_int)
7952 return;
7953 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007954#ifdef FEAT_EVAL
7955 if (p_verbose > 0)
7956 last_set_msg(ac->scriptID);
7957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958 if (got_int)
7959 return;
7960 if (ac->next != NULL)
7961 {
7962 msg_putchar('\n');
7963 if (got_int)
7964 return;
7965 }
7966 }
7967 }
7968}
7969
7970/*
7971 * Mark an autocommand pattern for deletion.
7972 */
7973 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007974au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007976 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007977 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007978 au_need_clean = TRUE;
7979}
7980
7981/*
7982 * Mark all commands for a pattern for deletion.
7983 */
7984 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007985au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007986{
7987 AutoCmd *ac;
7988
7989 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007990 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007991 au_need_clean = TRUE;
7992}
7993
7994/*
7995 * Cleanup autocommands and patterns that have been deleted.
7996 * This is only done when not executing autocommands.
7997 */
7998 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007999au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008000{
8001 AutoPat *ap, **prev_ap;
8002 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008003 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008004
8005 if (autocmd_busy || !au_need_clean)
8006 return;
8007
8008 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008009 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8010 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008011 {
8012 /* loop over all autocommand patterns */
8013 prev_ap = &(first_autopat[(int)event]);
8014 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8015 {
8016 /* loop over all commands for this pattern */
8017 prev_ac = &(ap->cmds);
8018 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8019 {
8020 /* remove the command if the pattern is to be deleted or when
8021 * the command has been marked for deletion */
8022 if (ap->pat == NULL || ac->cmd == NULL)
8023 {
8024 *prev_ac = ac->next;
8025 vim_free(ac->cmd);
8026 vim_free(ac);
8027 }
8028 else
8029 prev_ac = &(ac->next);
8030 }
8031
8032 /* remove the pattern if it has been marked for deletion */
8033 if (ap->pat == NULL)
8034 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008035 if (ap->next == NULL)
8036 {
8037 if (prev_ap == &(first_autopat[(int)event]))
8038 last_autopat[(int)event] = NULL;
8039 else
8040 /* this depends on the "next" field being the first in
8041 * the struct */
8042 last_autopat[(int)event] = (AutoPat *)prev_ap;
8043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008044 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008045 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046 vim_free(ap);
8047 }
8048 else
8049 prev_ap = &(ap->next);
8050 }
8051 }
8052
8053 au_need_clean = FALSE;
8054}
8055
8056/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008057 * Called when buffer is freed, to remove/invalidate related buffer-local
8058 * autocmds.
8059 */
8060 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008061aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008062{
8063 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008064 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008065 AutoPatCmd *apc;
8066
8067 /* invalidate currently executing autocommands */
8068 for (apc = active_apc_list; apc; apc = apc->next)
8069 if (buf->b_fnum == apc->arg_bufnr)
8070 apc->arg_bufnr = 0;
8071
8072 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008073 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8074 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008075 /* loop over all autocommand patterns */
8076 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8077 if (ap->buflocal_nr == buf->b_fnum)
8078 {
8079 au_remove_pat(ap);
8080 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008081 {
8082 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008083 smsg((char_u *)
8084 _("auto-removing autocommand: %s <buffer=%d>"),
8085 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008086 verbose_leave();
8087 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008088 }
8089 au_cleanup();
8090}
8091
8092/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008093 * Add an autocmd group name.
8094 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8095 */
8096 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008097au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008098{
8099 int i;
8100
8101 i = au_find_group(name);
8102 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8103 {
8104 /* First try using a free entry. */
8105 for (i = 0; i < augroups.ga_len; ++i)
8106 if (AUGROUP_NAME(i) == NULL)
8107 break;
8108 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8109 return AUGROUP_ERROR;
8110
8111 AUGROUP_NAME(i) = vim_strsave(name);
8112 if (AUGROUP_NAME(i) == NULL)
8113 return AUGROUP_ERROR;
8114 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008115 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008116 }
8117
8118 return i;
8119}
8120
8121 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008122au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008123{
8124 int i;
8125
8126 i = au_find_group(name);
8127 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8128 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008129 else if (i == current_augroup)
8130 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008131 else
8132 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008133 event_T event;
8134 AutoPat *ap;
8135 int in_use = FALSE;
8136
8137 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8138 event = (event_T)((int)event + 1))
8139 {
8140 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008141 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008142 {
8143 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8144 in_use = TRUE;
8145 event = NUM_EVENTS;
8146 break;
8147 }
8148 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008149 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008150 if (in_use)
8151 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008152 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008153 }
8154 else
8155 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008156 }
8157}
8158
8159/*
8160 * Find the ID of an autocmd group name.
8161 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8162 */
8163 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008164au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008165{
8166 int i;
8167
8168 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008169 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008170 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008171 return i;
8172 return AUGROUP_ERROR;
8173}
8174
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008175/*
8176 * Return TRUE if augroup "name" exists.
8177 */
8178 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008179au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008180{
8181 return au_find_group(name) != AUGROUP_ERROR;
8182}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008183
Bram Moolenaar071d4272004-06-13 20:20:40 +00008184/*
8185 * ":augroup {name}".
8186 */
8187 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008188do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189{
8190 int i;
8191
8192 if (del_group)
8193 {
8194 if (*arg == NUL)
8195 EMSG(_(e_argreq));
8196 else
8197 au_del_group(arg);
8198 }
8199 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8200 current_augroup = AUGROUP_DEFAULT;
8201 else if (*arg) /* ":aug xxx": switch to group xxx */
8202 {
8203 i = au_new_group(arg);
8204 if (i != AUGROUP_ERROR)
8205 current_augroup = i;
8206 }
8207 else /* ":aug": list the group names */
8208 {
8209 msg_start();
8210 for (i = 0; i < augroups.ga_len; ++i)
8211 {
8212 if (AUGROUP_NAME(i) != NULL)
8213 {
8214 msg_puts(AUGROUP_NAME(i));
8215 msg_puts((char_u *)" ");
8216 }
8217 }
8218 msg_clr_eos();
8219 msg_end();
8220 }
8221}
8222
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008223#if defined(EXITFREE) || defined(PROTO)
8224 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008225free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008226{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008227 int i;
8228 char_u *s;
8229
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008230 for (current_augroup = -1; current_augroup < augroups.ga_len;
8231 ++current_augroup)
8232 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008233
8234 for (i = 0; i < augroups.ga_len; ++i)
8235 {
8236 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008237 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008238 vim_free(s);
8239 }
8240 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008241}
8242#endif
8243
Bram Moolenaar071d4272004-06-13 20:20:40 +00008244/*
8245 * Return the event number for event name "start".
8246 * Return NUM_EVENTS if the event name was not found.
8247 * Return a pointer to the next event name in "end".
8248 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008249 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008250event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008251{
8252 char_u *p;
8253 int i;
8254 int len;
8255
Bram Moolenaare99e8442016-07-26 20:43:40 +02008256 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008257 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008258 ;
8259 for (i = 0; event_names[i].name != NULL; ++i)
8260 {
8261 len = (int)STRLEN(event_names[i].name);
8262 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8263 break;
8264 }
8265 if (*p == ',')
8266 ++p;
8267 *end = p;
8268 if (event_names[i].name == NULL)
8269 return NUM_EVENTS;
8270 return event_names[i].event;
8271}
8272
8273/*
8274 * Return the name for event "event".
8275 */
8276 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008277event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008278{
8279 int i;
8280
8281 for (i = 0; event_names[i].name != NULL; ++i)
8282 if (event_names[i].event == event)
8283 return (char_u *)event_names[i].name;
8284 return (char_u *)"Unknown";
8285}
8286
8287/*
8288 * Scan over the events. "*" stands for all events.
8289 */
8290 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008291find_end_event(
8292 char_u *arg,
8293 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008294{
8295 char_u *pat;
8296 char_u *p;
8297
8298 if (*arg == '*')
8299 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008300 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008301 {
8302 EMSG2(_("E215: Illegal character after *: %s"), arg);
8303 return NULL;
8304 }
8305 pat = arg + 1;
8306 }
8307 else
8308 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008309 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008310 {
8311 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8312 {
8313 if (have_group)
8314 EMSG2(_("E216: No such event: %s"), pat);
8315 else
8316 EMSG2(_("E216: No such group or event: %s"), pat);
8317 return NULL;
8318 }
8319 }
8320 }
8321 return pat;
8322}
8323
8324/*
8325 * Return TRUE if "event" is included in 'eventignore'.
8326 */
8327 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008328event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008329{
8330 char_u *p = p_ei;
8331
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008332 while (*p != NUL)
8333 {
8334 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8335 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008336 if (event_name2nr(p, &p) == event)
8337 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339
8340 return FALSE;
8341}
8342
8343/*
8344 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8345 */
8346 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008347check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008348{
8349 char_u *p = p_ei;
8350
Bram Moolenaar071d4272004-06-13 20:20:40 +00008351 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008352 {
8353 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8354 {
8355 p += 3;
8356 if (*p == ',')
8357 ++p;
8358 }
8359 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008360 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008361 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008362
8363 return OK;
8364}
8365
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008366# if defined(FEAT_SYN_HL) || defined(PROTO)
8367
8368/*
8369 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8370 * buffer loaded into the window. "what" must start with a comma.
8371 * Returns the old value of 'eventignore' in allocated memory.
8372 */
8373 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008374au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008375{
8376 char_u *new_ei;
8377 char_u *save_ei;
8378
8379 save_ei = vim_strsave(p_ei);
8380 if (save_ei != NULL)
8381 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008382 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008383 if (new_ei != NULL)
8384 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008385 if (*what == ',' && *p_ei == NUL)
8386 STRCPY(new_ei, what + 1);
8387 else
8388 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008389 set_string_option_direct((char_u *)"ei", -1, new_ei,
8390 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008391 vim_free(new_ei);
8392 }
8393 }
8394 return save_ei;
8395}
8396
8397 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008398au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008399{
8400 if (old_ei != NULL)
8401 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008402 set_string_option_direct((char_u *)"ei", -1, old_ei,
8403 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008404 vim_free(old_ei);
8405 }
8406}
8407# endif /* FEAT_SYN_HL */
8408
Bram Moolenaar071d4272004-06-13 20:20:40 +00008409/*
8410 * do_autocmd() -- implements the :autocmd command. Can be used in the
8411 * following ways:
8412 *
8413 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8414 * will be automatically executed for <event>
8415 * when editing a file matching <pat>, in
8416 * the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008417 * :autocmd <event> <pat> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008418 * <event> and <pat>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008419 * :autocmd <event> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008420 * <event>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008421 * :autocmd Show all autocommands.
8422 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008423 * <event> and <pat>, and add the command
8424 * <cmd>, for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008425 * :autocmd! <event> <pat> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008426 * <event> and <pat> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008427 * :autocmd! <event> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008428 * <event> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008429 * :autocmd! Remove ALL autocommands for the current
Bram Moolenaar071d4272004-06-13 20:20:40 +00008430 * group.
8431 *
8432 * Multiple events and patterns may be given separated by commas. Here are
8433 * some examples:
8434 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8435 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8436 *
8437 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008438 *
8439 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 */
8441 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008442do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008443{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008444 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008445 char_u *pat;
8446 char_u *envpat = NULL;
8447 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008448 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008449 int need_free = FALSE;
8450 int nested = FALSE;
8451 int group;
8452
Bram Moolenaare99e8442016-07-26 20:43:40 +02008453 if (*arg == '|')
8454 {
8455 arg = (char_u *)"";
8456 group = AUGROUP_ALL; /* no argument, use all groups */
8457 }
8458 else
8459 {
8460 /*
8461 * Check for a legal group name. If not, use AUGROUP_ALL.
8462 */
8463 group = au_get_grouparg(&arg);
8464 if (arg == NULL) /* out of memory */
8465 return;
8466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008467
8468 /*
8469 * Scan over the events.
8470 * If we find an illegal name, return here, don't do anything.
8471 */
8472 pat = find_end_event(arg, group != AUGROUP_ALL);
8473 if (pat == NULL)
8474 return;
8475
Bram Moolenaar071d4272004-06-13 20:20:40 +00008476 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008477 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008478 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008479 pat = (char_u *)"";
8480 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008481 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008482 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008483 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008484 /*
8485 * Scan over the pattern. Put a NUL at the end.
8486 */
8487 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008488 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008489 cmd++;
8490 if (*cmd)
8491 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008492
Bram Moolenaare99e8442016-07-26 20:43:40 +02008493 /* Expand environment variables in the pattern. Set 'shellslash', we want
8494 * forward slashes here. */
8495 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8496 {
8497#ifdef BACKSLASH_IN_FILENAME
8498 int p_ssl_save = p_ssl;
8499
8500 p_ssl = TRUE;
8501#endif
8502 envpat = expand_env_save(pat);
8503#ifdef BACKSLASH_IN_FILENAME
8504 p_ssl = p_ssl_save;
8505#endif
8506 if (envpat != NULL)
8507 pat = envpat;
8508 }
8509
8510 /*
8511 * Check for "nested" flag.
8512 */
8513 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008514 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008515 {
8516 nested = TRUE;
8517 cmd = skipwhite(cmd + 6);
8518 }
8519
8520 /*
8521 * Find the start of the commands.
8522 * Expand <sfile> in it.
8523 */
8524 if (*cmd != NUL)
8525 {
8526 cmd = expand_sfile(cmd);
8527 if (cmd == NULL) /* some error */
8528 return;
8529 need_free = TRUE;
8530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531 }
8532
8533 /*
8534 * Print header when showing autocommands.
8535 */
8536 if (!forceit && *cmd == NUL)
8537 {
8538 /* Highlight title */
Bram Moolenaar8c555332018-06-22 21:30:31 +02008539 MSG_PUTS_TITLE(_("\n--- Autocommands ---"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 }
8541
8542 /*
8543 * Loop over the events.
8544 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008545 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008546 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008547 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008548 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008549 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8550 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008551 if (do_autocmd_event(event, pat,
8552 nested, cmd, forceit, group) == FAIL)
8553 break;
8554 }
8555 else
8556 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008557 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008558 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8559 nested, cmd, forceit, group) == FAIL)
8560 break;
8561 }
8562
8563 if (need_free)
8564 vim_free(cmd);
8565 vim_free(envpat);
8566}
8567
8568/*
8569 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8570 * The "argp" argument is advanced to the following argument.
8571 *
8572 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8573 */
8574 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008575au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008576{
8577 char_u *group_name;
8578 char_u *p;
8579 char_u *arg = *argp;
8580 int group = AUGROUP_ALL;
8581
Bram Moolenaar1c465442017-03-12 20:10:05 +01008582 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008583 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008584 if (p > arg)
8585 {
8586 group_name = vim_strnsave(arg, (int)(p - arg));
8587 if (group_name == NULL) /* out of memory */
8588 return AUGROUP_ERROR;
8589 group = au_find_group(group_name);
8590 if (group == AUGROUP_ERROR)
8591 group = AUGROUP_ALL; /* no match, use all groups */
8592 else
8593 *argp = skipwhite(p); /* match, skip over group name */
8594 vim_free(group_name);
8595 }
8596 return group;
8597}
8598
8599/*
8600 * do_autocmd() for one event.
8601 * If *pat == NUL do for all patterns.
8602 * If *cmd == NUL show entries.
8603 * If forceit == TRUE delete entries.
8604 * If group is not AUGROUP_ALL, only use this group.
8605 */
8606 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008607do_autocmd_event(
8608 event_T event,
8609 char_u *pat,
8610 int nested,
8611 char_u *cmd,
8612 int forceit,
8613 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008614{
8615 AutoPat *ap;
8616 AutoPat **prev_ap;
8617 AutoCmd *ac;
8618 AutoCmd **prev_ac;
8619 int brace_level;
8620 char_u *endpat;
8621 int findgroup;
8622 int allgroups;
8623 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008624 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008625 int buflocal_nr;
8626 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008627
8628 if (group == AUGROUP_ALL)
8629 findgroup = current_augroup;
8630 else
8631 findgroup = group;
8632 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8633
8634 /*
8635 * Show or delete all patterns for an event.
8636 */
8637 if (*pat == NUL)
8638 {
8639 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8640 {
8641 if (forceit) /* delete the AutoPat, if it's in the current group */
8642 {
8643 if (ap->group == findgroup)
8644 au_remove_pat(ap);
8645 }
8646 else if (group == AUGROUP_ALL || ap->group == group)
8647 show_autocmd(ap, event);
8648 }
8649 }
8650
8651 /*
8652 * Loop through all the specified patterns.
8653 */
8654 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8655 {
8656 /*
8657 * Find end of the pattern.
8658 * Watch out for a comma in braces, like "*.\{obj,o\}".
8659 */
8660 brace_level = 0;
8661 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008662 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008663 {
8664 if (*endpat == '{')
8665 brace_level++;
8666 else if (*endpat == '}')
8667 brace_level--;
8668 }
8669 if (pat == endpat) /* ignore single comma */
8670 continue;
8671 patlen = (int)(endpat - pat);
8672
8673 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008674 * detect special <buflocal[=X]> buffer-local patterns
8675 */
8676 is_buflocal = FALSE;
8677 buflocal_nr = 0;
8678
Bram Moolenaar1e997822015-02-17 16:04:57 +01008679 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008680 && pat[patlen - 1] == '>')
8681 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008682 /* "<buffer...>": Error will be printed only for addition.
8683 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008684 is_buflocal = TRUE;
8685 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008686 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008687 buflocal_nr = curbuf->b_fnum;
8688 else if (patlen > 9 && pat[7] == '=')
8689 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008690 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8691 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008692 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008693 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008694 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008695 buflocal_nr = atoi((char *)pat + 8);
8696 }
8697 }
8698
8699 if (is_buflocal)
8700 {
8701 /* normalize pat into standard "<buffer>#N" form */
8702 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8703 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008704 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008705 }
8706
8707 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008708 * Find AutoPat entries with this pattern. When adding a command it
8709 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008710 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008711 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8712 prev_ap = &last_autopat[(int)event];
8713 else
8714 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008715 while ((ap = *prev_ap) != NULL)
8716 {
8717 if (ap->pat != NULL)
8718 {
8719 /* Accept a pattern when:
8720 * - a group was specified and it's that group, or a group was
8721 * not specified and it's the current group, or a group was
8722 * not specified and we are listing
8723 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008724 * - the pattern matches.
8725 * For <buffer[=X]>, this condition works because we normalize
8726 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008727 */
8728 if ((allgroups || ap->group == findgroup)
8729 && ap->patlen == patlen
8730 && STRNCMP(pat, ap->pat, patlen) == 0)
8731 {
8732 /*
8733 * Remove existing autocommands.
8734 * If adding any new autocmd's for this AutoPat, don't
8735 * delete the pattern from the autopat list, append to
8736 * this list.
8737 */
8738 if (forceit)
8739 {
8740 if (*cmd != NUL && ap->next == NULL)
8741 {
8742 au_remove_cmds(ap);
8743 break;
8744 }
8745 au_remove_pat(ap);
8746 }
8747
8748 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008749 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008750 */
8751 else if (*cmd == NUL)
8752 show_autocmd(ap, event);
8753
8754 /*
8755 * Add autocmd to this autopat, if it's the last one.
8756 */
8757 else if (ap->next == NULL)
8758 break;
8759 }
8760 }
8761 prev_ap = &ap->next;
8762 }
8763
8764 /*
8765 * Add a new command.
8766 */
8767 if (*cmd != NUL)
8768 {
8769 /*
8770 * If the pattern we want to add a command to does appear at the
8771 * end of the list (or not is not in the list at all), add the
8772 * pattern at the end of the list.
8773 */
8774 if (ap == NULL)
8775 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008776 /* refuse to add buffer-local ap if buffer number is invalid */
8777 if (is_buflocal && (buflocal_nr == 0
8778 || buflist_findnr(buflocal_nr) == NULL))
8779 {
8780 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8781 buflocal_nr);
8782 return FAIL;
8783 }
8784
Bram Moolenaar071d4272004-06-13 20:20:40 +00008785 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8786 if (ap == NULL)
8787 return FAIL;
8788 ap->pat = vim_strnsave(pat, patlen);
8789 ap->patlen = patlen;
8790 if (ap->pat == NULL)
8791 {
8792 vim_free(ap);
8793 return FAIL;
8794 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008795
8796 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008797 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008798 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008799 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008800 }
8801 else
8802 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008803 char_u *reg_pat;
8804
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008805 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008806 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008807 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008808 if (reg_pat != NULL)
8809 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008810 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008811 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008812 {
8813 vim_free(ap->pat);
8814 vim_free(ap);
8815 return FAIL;
8816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008817 }
8818 ap->cmds = NULL;
8819 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008820 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008821 ap->next = NULL;
8822 if (group == AUGROUP_ALL)
8823 ap->group = current_augroup;
8824 else
8825 ap->group = group;
8826 }
8827
8828 /*
8829 * Add the autocmd at the end of the AutoCmd list.
8830 */
8831 prev_ac = &(ap->cmds);
8832 while ((ac = *prev_ac) != NULL)
8833 prev_ac = &ac->next;
8834 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8835 if (ac == NULL)
8836 return FAIL;
8837 ac->cmd = vim_strsave(cmd);
8838#ifdef FEAT_EVAL
8839 ac->scriptID = current_SID;
8840#endif
8841 if (ac->cmd == NULL)
8842 {
8843 vim_free(ac);
8844 return FAIL;
8845 }
8846 ac->next = NULL;
8847 *prev_ac = ac;
8848 ac->nested = nested;
8849 }
8850 }
8851
8852 au_cleanup(); /* may really delete removed patterns/commands now */
8853 return OK;
8854}
8855
8856/*
8857 * Implementation of ":doautocmd [group] event [fname]".
8858 * Return OK for success, FAIL for failure;
8859 */
8860 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008861do_doautocmd(
8862 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008863 int do_msg, /* give message for no matching autocmds? */
8864 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865{
8866 char_u *fname;
8867 int nothing_done = TRUE;
8868 int group;
8869
Bram Moolenaar1610d052016-06-09 22:53:01 +02008870 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008871 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008872
Bram Moolenaar071d4272004-06-13 20:20:40 +00008873 /*
8874 * Check for a legal group name. If not, use AUGROUP_ALL.
8875 */
8876 group = au_get_grouparg(&arg);
8877 if (arg == NULL) /* out of memory */
8878 return FAIL;
8879
8880 if (*arg == '*')
8881 {
8882 EMSG(_("E217: Can't execute autocommands for ALL events"));
8883 return FAIL;
8884 }
8885
8886 /*
8887 * Scan over the events.
8888 * If we find an illegal name, return here, don't do anything.
8889 */
8890 fname = find_end_event(arg, group != AUGROUP_ALL);
8891 if (fname == NULL)
8892 return FAIL;
8893
8894 fname = skipwhite(fname);
8895
8896 /*
8897 * Loop over the events.
8898 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008899 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008900 if (apply_autocmds_group(event_name2nr(arg, &arg),
8901 fname, NULL, TRUE, group, curbuf, NULL))
8902 nothing_done = FALSE;
8903
8904 if (nothing_done && do_msg)
8905 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008906 if (did_something != NULL)
8907 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908
8909#ifdef FEAT_EVAL
8910 return aborting() ? FAIL : OK;
8911#else
8912 return OK;
8913#endif
8914}
8915
8916/*
8917 * ":doautoall": execute autocommands for each loaded buffer.
8918 */
8919 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008920ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008921{
8922 int retval;
8923 aco_save_T aco;
8924 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008925 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008926 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008927 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008928 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929
8930 /*
8931 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8932 * equal to curbuf, but for some buffers there may not be a window.
8933 * So we change the buffer for the current window for a moment. This
8934 * gives problems when the autocommands make changes to the list of
8935 * buffers or windows...
8936 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008937 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008939 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008940 {
8941 /* find a window for this buffer and save some values */
8942 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008943 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944
8945 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008946 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008947
Bram Moolenaar1610d052016-06-09 22:53:01 +02008948 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008949 {
8950 /* Execute the modeline settings, but don't set window-local
8951 * options if we are using the current window for another
8952 * buffer. */
8953 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955
8956 /* restore the current window */
8957 aucmd_restbuf(&aco);
8958
8959 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008960 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008961 break;
8962 }
8963 }
8964
8965 check_cursor(); /* just in case lines got deleted */
8966}
8967
8968/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008969 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8970 * return TRUE and advance *argp to after it.
8971 * Thus return TRUE when do_modelines() should be called.
8972 */
8973 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008974check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008975{
8976 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8977 {
8978 *argp = skipwhite(*argp + 12);
8979 return FALSE;
8980 }
8981 return TRUE;
8982}
8983
8984/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008985 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008986 * Search for a visible window containing the current buffer. If there isn't
8987 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008988 * Set "curbuf" and "curwin" to match "buf".
8989 */
8990 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008991aucmd_prepbuf(
8992 aco_save_T *aco, /* structure to save values in */
8993 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994{
8995 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008996 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008997#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008998 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008999#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009000
9001 /* Find a window that is for the new buffer */
9002 if (buf == curbuf) /* be quick when buf is curbuf */
9003 win = curwin;
9004 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009005 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 if (win->w_buffer == buf)
9007 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009009 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9010 * back to using the current window. */
9011 if (win == NULL && aucmd_win == NULL)
9012 {
9013 win_alloc_aucmd_win();
9014 if (aucmd_win == NULL)
9015 win = curwin;
9016 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009017 if (win == NULL && aucmd_win_used)
9018 /* Strange recursive autocommand, fall back to using the current
9019 * window. Expect a few side effects... */
9020 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009021
9022 aco->save_curwin = curwin;
9023 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009024 if (win != NULL)
9025 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009026 /* There is a window for "buf" in the current tab page, make it the
9027 * curwin. This is preferred, it has the least side effects (esp. if
9028 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009029 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009030 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031 }
9032 else
9033 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009034 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009035 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009036 * Anything related to a window (e.g., setting folds) may have
9037 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009038 aco->use_aucmd_win = TRUE;
9039 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009040 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009041#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009042 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009044 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009045 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009046
9047 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9048 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009049 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009050 aco->globaldir = globaldir;
9051 globaldir = NULL;
9052
Bram Moolenaar071d4272004-06-13 20:20:40 +00009053
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009054 /* Split the current window, put the aucmd_win in the upper half.
9055 * We don't want the BufEnter or WinEnter autocommands. */
9056 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009057 make_snapshot(SNAP_AUCMD_IDX);
9058 save_ea = p_ea;
9059 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009060
Bram Moolenaar4033c552017-09-16 20:54:51 +02009061#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009062 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9063 save_acd = p_acd;
9064 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009065#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009066
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009067 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9068 (void)win_comp_pos(); /* recompute window positions */
9069 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009070#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009071 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009072#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009073 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009074 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009075 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009077 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009078 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009079}
9080
9081/*
9082 * Cleanup after executing autocommands for a (hidden) buffer.
9083 * Restore the window as it was (if possible).
9084 */
9085 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009086aucmd_restbuf(
9087 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009089 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009090
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009091 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009092 {
9093 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009094 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009095 * page. Do not trigger autocommands here. */
9096 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009097 if (curwin != aucmd_win)
9098 {
9099 tabpage_T *tp;
9100 win_T *wp;
9101
9102 FOR_ALL_TAB_WINDOWS(tp, wp)
9103 {
9104 if (wp == aucmd_win)
9105 {
9106 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009107 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009108 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009109 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009110 }
9111 }
9112 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009113win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009114
9115 /* Remove the window and frame from the tree of frames. */
9116 (void)winframe_remove(curwin, &dummy, NULL);
9117 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009118 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009119 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009120
9121 if (!valid_tabpage_win(curtab))
9122 /* no valid window in current tabpage */
9123 close_tabpage(curtab);
9124
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009125 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9126 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009127 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009128
9129 if (win_valid(aco->save_curwin))
9130 curwin = aco->save_curwin;
9131 else
9132 /* Hmm, original window disappeared. Just use the first one. */
9133 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009134#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009135 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9136 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009137#endif
9138 curbuf = curwin->w_buffer;
9139
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009140 vim_free(globaldir);
9141 globaldir = aco->globaldir;
9142
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009143 /* the buffer contents may have changed */
9144 check_cursor();
9145 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9146 {
9147 curwin->w_topline = curbuf->b_ml.ml_line_count;
9148#ifdef FEAT_DIFF
9149 curwin->w_topfill = 0;
9150#endif
9151 }
9152#if defined(FEAT_GUI)
9153 /* Hide the scrollbars from the aucmd_win and update. */
9154 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9155 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9156 gui_may_update_scrollbars();
9157#endif
9158 }
9159 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009160 {
9161 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009163 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009164 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009165 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009166 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009167 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009168 && curbuf != aco->new_curbuf.br_buf
9169 && bufref_valid(&aco->new_curbuf)
9170 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009171 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009172# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9173 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009174 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009175# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009176 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009177 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009178 curwin->w_buffer = curbuf;
9179 ++curbuf->b_nwindows;
9180 }
9181
9182 curwin = aco->save_curwin;
9183 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009184 /* In case the autocommand move the cursor to a position that that
9185 * not exist in curbuf. */
9186 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009187 }
9188 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009189}
9190
9191static int autocmd_nested = FALSE;
9192
9193/*
9194 * Execute autocommands for "event" and file name "fname".
9195 * Return TRUE if some commands were executed.
9196 */
9197 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009198apply_autocmds(
9199 event_T event,
9200 char_u *fname, /* NULL or empty means use actual file name */
9201 char_u *fname_io, /* fname to use for <afile> on cmdline */
9202 int force, /* when TRUE, ignore autocmd_busy */
9203 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009204{
9205 return apply_autocmds_group(event, fname, fname_io, force,
9206 AUGROUP_ALL, buf, NULL);
9207}
9208
9209/*
9210 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9211 * setting v:filearg.
9212 */
9213 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009214apply_autocmds_exarg(
9215 event_T event,
9216 char_u *fname,
9217 char_u *fname_io,
9218 int force,
9219 buf_T *buf,
9220 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009221{
9222 return apply_autocmds_group(event, fname, fname_io, force,
9223 AUGROUP_ALL, buf, eap);
9224}
9225
9226/*
9227 * Like apply_autocmds(), but handles the caller's retval. If the script
9228 * processing is being aborted or if retval is FAIL when inside a try
9229 * conditional, no autocommands are executed. If otherwise the autocommands
9230 * cause the script to be aborted, retval is set to FAIL.
9231 */
9232 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009233apply_autocmds_retval(
9234 event_T event,
9235 char_u *fname, /* NULL or empty means use actual file name */
9236 char_u *fname_io, /* fname to use for <afile> on cmdline */
9237 int force, /* when TRUE, ignore autocmd_busy */
9238 buf_T *buf, /* buffer for <abuf> */
9239 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009240{
9241 int did_cmd;
9242
Bram Moolenaar1e015462005-09-25 22:16:38 +00009243#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009244 if (should_abort(*retval))
9245 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009246#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009247
9248 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9249 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009250 if (did_cmd
9251#ifdef FEAT_EVAL
9252 && aborting()
9253#endif
9254 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009255 *retval = FAIL;
9256 return did_cmd;
9257}
9258
Bram Moolenaard35f9712005-12-18 22:02:33 +00009259/*
9260 * Return TRUE when there is a CursorHold autocommand defined.
9261 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009262 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009263has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009264{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009265 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9266 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009267}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009268
9269/*
9270 * Return TRUE if the CursorHold event can be triggered.
9271 */
9272 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009273trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009274{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009275 int state;
9276
Bram Moolenaar05334432011-07-20 18:29:39 +02009277 if (!did_cursorhold
9278 && has_cursorhold()
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02009279 && reg_recording == 0
Bram Moolenaar05334432011-07-20 18:29:39 +02009280 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009281#ifdef FEAT_INS_EXPAND
9282 && !ins_compl_active()
9283#endif
9284 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009285 {
9286 state = get_real_state();
9287 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9288 return TRUE;
9289 }
9290 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009291}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009292
9293/*
9294 * Return TRUE when there is a CursorMoved autocommand defined.
9295 */
9296 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009297has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009298{
9299 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9300}
9301
9302/*
9303 * Return TRUE when there is a CursorMovedI autocommand defined.
9304 */
9305 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009306has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009307{
9308 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9309}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009310
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009311/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009312 * Return TRUE when there is a TextChanged autocommand defined.
9313 */
9314 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009315has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009316{
9317 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9318}
9319
9320/*
9321 * Return TRUE when there is a TextChangedI autocommand defined.
9322 */
9323 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009324has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009325{
9326 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9327}
9328
9329/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009330 * Return TRUE when there is a TextChangedP autocommand defined.
9331 */
9332 int
9333has_textchangedP(void)
9334{
9335 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9336}
9337
9338/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009339 * Return TRUE when there is an InsertCharPre autocommand defined.
9340 */
9341 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009342has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009343{
9344 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9345}
9346
Bram Moolenaard5005162014-08-22 23:05:54 +02009347/*
9348 * Return TRUE when there is an CmdUndefined autocommand defined.
9349 */
9350 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009351has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009352{
9353 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9354}
9355
9356/*
9357 * Return TRUE when there is an FuncUndefined autocommand defined.
9358 */
9359 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009360has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009361{
9362 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9363}
9364
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009365/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009366 * Return TRUE when there is a TextYankPost autocommand defined.
9367 */
9368 int
9369has_textyankpost(void)
9370{
9371 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9372}
9373
9374/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009375 * Execute autocommands for "event" and file name "fname".
9376 * Return TRUE if some commands were executed.
9377 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009378 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009379apply_autocmds_group(
9380 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009381 char_u *fname, /* NULL or empty means use actual file name */
9382 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009383 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009384 int force, /* when TRUE, ignore autocmd_busy */
9385 int group, /* group ID, or AUGROUP_ALL */
9386 buf_T *buf, /* buffer for <abuf> */
9387 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009388{
9389 char_u *sfname = NULL; /* short file name */
9390 char_u *tail;
9391 int save_changed;
9392 buf_T *old_curbuf;
9393 int retval = FALSE;
9394 char_u *save_sourcing_name;
9395 linenr_T save_sourcing_lnum;
9396 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009397 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009398 int save_autocmd_bufnr;
9399 char_u *save_autocmd_match;
9400 int save_autocmd_busy;
9401 int save_autocmd_nested;
9402 static int nesting = 0;
9403 AutoPatCmd patcmd;
9404 AutoPat *ap;
9405#ifdef FEAT_EVAL
9406 scid_T save_current_SID;
9407 void *save_funccalp;
9408 char_u *save_cmdarg;
9409 long save_cmdbang;
9410#endif
9411 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009412#ifdef FEAT_PROFILE
9413 proftime_T wait_time;
9414#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009415 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009416 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009417 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009418
9419 /*
9420 * Quickly return if there are no autocommands for this event or
9421 * autocommands are blocked.
9422 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009423 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9424 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009425 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009426
9427 /*
9428 * When autocommands are busy, new autocommands are only executed when
9429 * explicitly enabled with the "nested" flag.
9430 */
9431 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009432 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009433
9434#ifdef FEAT_EVAL
9435 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009436 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009437 * occurred or an exception was thrown but not caught.
9438 */
9439 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009440 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441#endif
9442
9443 /*
9444 * FileChangedShell never nests, because it can create an endless loop.
9445 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009446 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9447 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009448 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009449
9450 /*
9451 * Ignore events in 'eventignore'.
9452 */
9453 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009454 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009455
9456 /*
9457 * Allow nesting of autocommands, but restrict the depth, because it's
9458 * possible to create an endless loop.
9459 */
9460 if (nesting == 10)
9461 {
9462 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009463 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009464 }
9465
9466 /*
9467 * Check if these autocommands are disabled. Used when doing ":all" or
9468 * ":ball".
9469 */
9470 if ( (autocmd_no_enter
9471 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9472 || (autocmd_no_leave
9473 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009474 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009475
9476 /*
9477 * Save the autocmd_* variables and info about the current buffer.
9478 */
9479 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009480 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009481 save_autocmd_bufnr = autocmd_bufnr;
9482 save_autocmd_match = autocmd_match;
9483 save_autocmd_busy = autocmd_busy;
9484 save_autocmd_nested = autocmd_nested;
9485 save_changed = curbuf->b_changed;
9486 old_curbuf = curbuf;
9487
9488 /*
9489 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009490 * Make a copy to avoid that changing a buffer name or directory makes it
9491 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009492 */
9493 if (fname_io == NULL)
9494 {
Bram Moolenaar60a68362018-04-30 15:40:48 +02009495 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
9496 || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009497 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009498 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009499 autocmd_fname = fname;
9500 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009501 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009502 else
9503 autocmd_fname = NULL;
9504 }
9505 else
9506 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009507 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009508 autocmd_fname = vim_strsave(autocmd_fname);
9509 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009510
9511 /*
9512 * Set the buffer number to be used for <abuf>.
9513 */
9514 if (buf == NULL)
9515 autocmd_bufnr = 0;
9516 else
9517 autocmd_bufnr = buf->b_fnum;
9518
9519 /*
9520 * When the file name is NULL or empty, use the file name of buffer "buf".
9521 * Always use the full path of the file name to match with, in case
9522 * "allow_dirs" is set.
9523 */
9524 if (fname == NULL || *fname == NUL)
9525 {
9526 if (buf == NULL)
9527 fname = NULL;
9528 else
9529 {
9530#ifdef FEAT_SYN_HL
9531 if (event == EVENT_SYNTAX)
9532 fname = buf->b_p_syn;
9533 else
9534#endif
9535 if (event == EVENT_FILETYPE)
9536 fname = buf->b_p_ft;
9537 else
9538 {
9539 if (buf->b_sfname != NULL)
9540 sfname = vim_strsave(buf->b_sfname);
9541 fname = buf->b_ffname;
9542 }
9543 }
9544 if (fname == NULL)
9545 fname = (char_u *)"";
9546 fname = vim_strsave(fname); /* make a copy, so we can change it */
9547 }
9548 else
9549 {
9550 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009551 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009552 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009553 if (event == EVENT_FILETYPE
9554 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009555 || event == EVENT_CMDLINECHANGED
9556 || event == EVENT_CMDLINEENTER
9557 || event == EVENT_CMDLINELEAVE
9558 || event == EVENT_CMDWINENTER
9559 || event == EVENT_CMDWINLEAVE
9560 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009561 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009562 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009563 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009564 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009565 || event == EVENT_COLORSCHEME
Bram Moolenaar60a68362018-04-30 15:40:48 +02009566 || event == EVENT_COLORSCHEMEPRE
Bram Moolenaar53744302015-07-17 17:38:22 +02009567 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009568 || event == EVENT_QUICKFIXCMDPOST
9569 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009570 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009571 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009572 autocmd_fname_full = TRUE; /* don't expand it later */
9573 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009574 else
9575 fname = FullName_save(fname, FALSE);
9576 }
9577 if (fname == NULL) /* out of memory */
9578 {
9579 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009580 retval = FALSE;
9581 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009582 }
9583
9584#ifdef BACKSLASH_IN_FILENAME
9585 /*
9586 * Replace all backslashes with forward slashes. This makes the
9587 * autocommand patterns portable between Unix and MS-DOS.
9588 */
9589 if (sfname != NULL)
9590 forward_slash(sfname);
9591 forward_slash(fname);
9592#endif
9593
9594#ifdef VMS
9595 /* remove version for correct match */
9596 if (sfname != NULL)
9597 vms_remove_version(sfname);
9598 vms_remove_version(fname);
9599#endif
9600
9601 /*
9602 * Set the name to be used for <amatch>.
9603 */
9604 autocmd_match = fname;
9605
9606
Bram Moolenaar8c555332018-06-22 21:30:31 +02009607 /* Don't redraw while doing autocommands. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009608 ++RedrawingDisabled;
9609 save_sourcing_name = sourcing_name;
9610 sourcing_name = NULL; /* don't free this one */
9611 save_sourcing_lnum = sourcing_lnum;
9612 sourcing_lnum = 0; /* no line number here */
9613
9614#ifdef FEAT_EVAL
9615 save_current_SID = current_SID;
9616
Bram Moolenaar05159a02005-02-26 23:04:13 +00009617# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009618 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009619 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9620# endif
9621
Bram Moolenaar071d4272004-06-13 20:20:40 +00009622 /* Don't use local function variables, if called from a function */
9623 save_funccalp = save_funccal();
9624#endif
9625
9626 /*
9627 * When starting to execute autocommands, save the search patterns.
9628 */
9629 if (!autocmd_busy)
9630 {
9631 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009632#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009633 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009634#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009635 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009636 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009637 did_save_redobuff = TRUE;
9638 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009639 did_filetype = keep_filetype;
9640 }
9641
9642 /*
9643 * Note that we are applying autocmds. Some commands need to know.
9644 */
9645 autocmd_busy = TRUE;
9646 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9647 ++nesting; /* see matching decrement below */
9648
9649 /* Remember that FileType was triggered. Used for did_filetype(). */
9650 if (event == EVENT_FILETYPE)
9651 did_filetype = TRUE;
9652
9653 tail = gettail(fname);
9654
9655 /* Find first autocommand that matches */
9656 patcmd.curpat = first_autopat[(int)event];
9657 patcmd.nextcmd = NULL;
9658 patcmd.group = group;
9659 patcmd.fname = fname;
9660 patcmd.sfname = sfname;
9661 patcmd.tail = tail;
9662 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009663 patcmd.arg_bufnr = autocmd_bufnr;
9664 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009665 auto_next_pat(&patcmd, FALSE);
9666
9667 /* found one, start executing the autocommands */
9668 if (patcmd.curpat != NULL)
9669 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009670 /* add to active_apc_list */
9671 patcmd.next = active_apc_list;
9672 active_apc_list = &patcmd;
9673
Bram Moolenaar071d4272004-06-13 20:20:40 +00009674#ifdef FEAT_EVAL
9675 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009676 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009677 if (eap != NULL)
9678 {
9679 save_cmdarg = set_cmdarg(eap, NULL);
9680 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9681 }
9682 else
9683 save_cmdarg = NULL; /* avoid gcc warning */
9684#endif
9685 retval = TRUE;
9686 /* mark the last pattern, to avoid an endless loop when more patterns
9687 * are added when executing autocommands */
9688 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9689 ap->last = FALSE;
9690 ap->last = TRUE;
9691 check_lnums(TRUE); /* make sure cursor and topline are valid */
9692 do_cmdline(NULL, getnextac, (void *)&patcmd,
9693 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9694#ifdef FEAT_EVAL
9695 if (eap != NULL)
9696 {
9697 (void)set_cmdarg(NULL, save_cmdarg);
9698 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9699 }
9700#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009701 /* delete from active_apc_list */
9702 if (active_apc_list == &patcmd) /* just in case */
9703 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009704 }
9705
9706 --RedrawingDisabled;
9707 autocmd_busy = save_autocmd_busy;
9708 filechangeshell_busy = FALSE;
9709 autocmd_nested = save_autocmd_nested;
9710 vim_free(sourcing_name);
9711 sourcing_name = save_sourcing_name;
9712 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009713 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009714 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009715 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009716 autocmd_bufnr = save_autocmd_bufnr;
9717 autocmd_match = save_autocmd_match;
9718#ifdef FEAT_EVAL
9719 current_SID = save_current_SID;
9720 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009721# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009722 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009723 prof_child_exit(&wait_time);
9724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009725#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009726 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009727 vim_free(fname);
9728 vim_free(sfname);
9729 --nesting; /* see matching increment above */
9730
9731 /*
9732 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009733 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9734 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009735 */
9736 if (!autocmd_busy)
9737 {
9738 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009739 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009740 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009741 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009742 while (au_pending_free_buf != NULL)
9743 {
9744 buf_T *b = au_pending_free_buf->b_next;
9745 vim_free(au_pending_free_buf);
9746 au_pending_free_buf = b;
9747 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009748 while (au_pending_free_win != NULL)
9749 {
9750 win_T *w = au_pending_free_win->w_next;
9751 vim_free(au_pending_free_win);
9752 au_pending_free_win = w;
9753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009754 }
9755
9756 /*
9757 * Some events don't set or reset the Changed flag.
9758 * Check if still in the same buffer!
9759 */
9760 if (curbuf == old_curbuf
9761 && (event == EVENT_BUFREADPOST
9762 || event == EVENT_BUFWRITEPOST
9763 || event == EVENT_FILEAPPENDPOST
9764 || event == EVENT_VIMLEAVE
9765 || event == EVENT_VIMLEAVEPRE))
9766 {
9767#ifdef FEAT_TITLE
9768 if (curbuf->b_changed != save_changed)
9769 need_maketitle = TRUE;
9770#endif
9771 curbuf->b_changed = save_changed;
9772 }
9773
9774 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009775
9776BYPASS_AU:
9777 /* When wiping out a buffer make sure all its buffer-local autocommands
9778 * are deleted. */
9779 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9780 aubuflocal_remove(buf);
9781
Bram Moolenaarc3691332016-04-20 12:49:49 +02009782 if (retval == OK && event == EVENT_FILETYPE)
9783 au_did_filetype = TRUE;
9784
Bram Moolenaar071d4272004-06-13 20:20:40 +00009785 return retval;
9786}
9787
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009788# ifdef FEAT_EVAL
9789static char_u *old_termresponse = NULL;
9790# endif
9791
9792/*
9793 * Block triggering autocommands until unblock_autocmd() is called.
9794 * Can be used recursively, so long as it's symmetric.
9795 */
9796 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009797block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009798{
9799# ifdef FEAT_EVAL
9800 /* Remember the value of v:termresponse. */
9801 if (autocmd_blocked == 0)
9802 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9803# endif
9804 ++autocmd_blocked;
9805}
9806
9807 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009808unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009809{
9810 --autocmd_blocked;
9811
9812# ifdef FEAT_EVAL
9813 /* When v:termresponse was set while autocommands were blocked, trigger
9814 * the autocommands now. Esp. useful when executing a shell command
9815 * during startup (vimdiff). */
9816 if (autocmd_blocked == 0
9817 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9818 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9819# endif
9820}
9821
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009822 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009823is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009824{
9825 return autocmd_blocked != 0;
9826}
9827
Bram Moolenaar071d4272004-06-13 20:20:40 +00009828/*
9829 * Find next autocommand pattern that matches.
9830 */
9831 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009832auto_next_pat(
9833 AutoPatCmd *apc,
9834 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009835{
9836 AutoPat *ap;
9837 AutoCmd *cp;
9838 char_u *name;
9839 char *s;
9840
Bram Moolenaard23a8232018-02-10 18:45:26 +01009841 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009842
9843 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9844 {
9845 apc->curpat = NULL;
9846
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009847 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009848 * the group matches. For buffer-local autocommands only check the
9849 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009850 if (ap->pat != NULL && ap->cmds != NULL
9851 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9852 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009853 /* execution-condition */
9854 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009855 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009856 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009857 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009858 {
9859 name = event_nr2name(apc->event);
Bram Moolenaar8c555332018-06-22 21:30:31 +02009860 s = _("%s Autocommands for \"%s\"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009861 sourcing_name = alloc((unsigned)(STRLEN(s)
9862 + STRLEN(name) + ap->patlen + 1));
9863 if (sourcing_name != NULL)
9864 {
9865 sprintf((char *)sourcing_name, s,
9866 (char *)name, (char *)ap->pat);
9867 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009868 {
9869 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009870 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009871 verbose_leave();
9872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009873 }
9874
9875 apc->curpat = ap;
9876 apc->nextcmd = ap->cmds;
9877 /* mark last command */
9878 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9879 cp->last = FALSE;
9880 cp->last = TRUE;
9881 }
9882 line_breakcheck();
9883 if (apc->curpat != NULL) /* found a match */
9884 break;
9885 }
9886 if (stop_at_last && ap->last)
9887 break;
9888 }
9889}
9890
9891/*
9892 * Get next autocommand command.
9893 * Called by do_cmdline() to get the next line for ":if".
9894 * Returns allocated string, or NULL for end of autocommands.
9895 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009896 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009897getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009898{
9899 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9900 char_u *retval;
9901 AutoCmd *ac;
9902
9903 /* Can be called again after returning the last line. */
9904 if (acp->curpat == NULL)
9905 return NULL;
9906
9907 /* repeat until we find an autocommand to execute */
9908 for (;;)
9909 {
9910 /* skip removed commands */
9911 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9912 if (acp->nextcmd->last)
9913 acp->nextcmd = NULL;
9914 else
9915 acp->nextcmd = acp->nextcmd->next;
9916
9917 if (acp->nextcmd != NULL)
9918 break;
9919
9920 /* at end of commands, find next pattern that matches */
9921 if (acp->curpat->last)
9922 acp->curpat = NULL;
9923 else
9924 acp->curpat = acp->curpat->next;
9925 if (acp->curpat != NULL)
9926 auto_next_pat(acp, TRUE);
9927 if (acp->curpat == NULL)
9928 return NULL;
9929 }
9930
9931 ac = acp->nextcmd;
9932
9933 if (p_verbose >= 9)
9934 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009935 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009936 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009937 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009938 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009939 }
9940 retval = vim_strsave(ac->cmd);
9941 autocmd_nested = ac->nested;
9942#ifdef FEAT_EVAL
9943 current_SID = ac->scriptID;
9944#endif
9945 if (ac->last)
9946 acp->nextcmd = NULL;
9947 else
9948 acp->nextcmd = ac->next;
9949 return retval;
9950}
9951
9952/*
9953 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009954 * To account for buffer-local autocommands, function needs to know
9955 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956 */
9957 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009958has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009959{
9960 AutoPat *ap;
9961 char_u *fname;
9962 char_u *tail = gettail(sfname);
9963 int retval = FALSE;
9964
9965 fname = FullName_save(sfname, FALSE);
9966 if (fname == NULL)
9967 return FALSE;
9968
9969#ifdef BACKSLASH_IN_FILENAME
9970 /*
9971 * Replace all backslashes with forward slashes. This makes the
9972 * autocommand patterns portable between Unix and MS-DOS.
9973 */
9974 sfname = vim_strsave(sfname);
9975 if (sfname != NULL)
9976 forward_slash(sfname);
9977 forward_slash(fname);
9978#endif
9979
9980 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9981 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009982 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009983 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009984 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009985 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009986 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987 {
9988 retval = TRUE;
9989 break;
9990 }
9991
9992 vim_free(fname);
9993#ifdef BACKSLASH_IN_FILENAME
9994 vim_free(sfname);
9995#endif
9996
9997 return retval;
9998}
9999
10000#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10001/*
10002 * Function given to ExpandGeneric() to obtain the list of autocommand group
10003 * names.
10004 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010005 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010006get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010007{
10008 if (idx == augroups.ga_len) /* add "END" add the end */
10009 return (char_u *)"END";
10010 if (idx >= augroups.ga_len) /* end of list */
10011 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010012 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010013 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010014 return (char_u *)"";
10015 return AUGROUP_NAME(idx); /* return a name */
10016}
10017
10018static int include_groups = FALSE;
10019
10020 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010021set_context_in_autocmd(
10022 expand_T *xp,
10023 char_u *arg,
10024 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010025{
10026 char_u *p;
10027 int group;
10028
10029 /* check for a group name, skip it if present */
10030 include_groups = FALSE;
10031 p = arg;
10032 group = au_get_grouparg(&arg);
10033 if (group == AUGROUP_ERROR)
10034 return NULL;
10035 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010036 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010037 {
10038 arg = p;
10039 group = AUGROUP_ALL;
10040 }
10041
10042 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010043 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010044 if (*p == ',')
10045 arg = p + 1;
10046 if (*p == NUL)
10047 {
10048 if (group == AUGROUP_ALL)
10049 include_groups = TRUE;
10050 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10051 xp->xp_pattern = arg;
10052 return NULL;
10053 }
10054
10055 /* skip over pattern */
10056 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010057 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058 arg++;
10059 if (*arg)
10060 return arg; /* expand (next) command */
10061
10062 if (doautocmd)
10063 xp->xp_context = EXPAND_FILES; /* expand file names */
10064 else
10065 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10066 return NULL;
10067}
10068
10069/*
10070 * Function given to ExpandGeneric() to obtain the list of event names.
10071 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010073get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010074{
10075 if (idx < augroups.ga_len) /* First list group names, if wanted */
10076 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010077 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010078 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010079 return (char_u *)""; /* skip deleted entries */
10080 return AUGROUP_NAME(idx); /* return a name */
10081 }
10082 return (char_u *)event_names[idx - augroups.ga_len].name;
10083}
10084
10085#endif /* FEAT_CMDL_COMPL */
10086
10087/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010088 * Return TRUE if autocmd is supported.
10089 */
10090 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010091autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010092{
10093 char_u *p;
10094
10095 return (event_name2nr(name, &p) != NUM_EVENTS);
10096}
10097
10098/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010099 * Return TRUE if an autocommand is defined for a group, event and
10100 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10101 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10102 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10103 * Used for:
10104 * exists("#Group") or
10105 * exists("#Group#Event") or
10106 * exists("#Group#Event#pat") or
10107 * exists("#Event") or
10108 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010109 */
10110 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010111au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010112{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010113 char_u *arg_save;
10114 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010115 char_u *event_name;
10116 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010117 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010118 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010119 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010120 int group;
10121 int retval = FALSE;
10122
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010123 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010124 arg_save = vim_strsave(arg);
10125 if (arg_save == NULL)
10126 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010127 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010128 if (p != NULL)
10129 *p++ = NUL;
10130
10131 /* First, look for an autocmd group name */
10132 group = au_find_group(arg_save);
10133 if (group == AUGROUP_ERROR)
10134 {
10135 /* Didn't match a group name, assume the first argument is an event. */
10136 group = AUGROUP_ALL;
10137 event_name = arg_save;
10138 }
10139 else
10140 {
10141 if (p == NULL)
10142 {
10143 /* "Group": group name is present and it's recognized */
10144 retval = TRUE;
10145 goto theend;
10146 }
10147
10148 /* Must be "Group#Event" or "Group#Event#pat". */
10149 event_name = p;
10150 p = vim_strchr(event_name, '#');
10151 if (p != NULL)
10152 *p++ = NUL; /* "Group#Event#pat" */
10153 }
10154
10155 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010156
10157 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010158 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010159
10160 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010161 if (event == NUM_EVENTS)
10162 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010163
10164 /* Find the first autocommand for this event.
10165 * If there isn't any, return FALSE;
10166 * If there is one and no pattern given, return TRUE; */
10167 ap = first_autopat[(int)event];
10168 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010169 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010170
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010171 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10172 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010173 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010174 buflocal_buf = curbuf;
10175
Bram Moolenaar071d4272004-06-13 20:20:40 +000010176 /* Check if there is an autocommand with the given pattern. */
10177 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010178 /* only use a pattern when it has not been removed and has commands. */
10179 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010180 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010181 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010182 && (pattern == NULL
10183 || (buflocal_buf == NULL
10184 ? fnamecmp(ap->pat, pattern) == 0
10185 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010186 {
10187 retval = TRUE;
10188 break;
10189 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190
Bram Moolenaar195d6352005-12-19 22:08:24 +000010191theend:
10192 vim_free(arg_save);
10193 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010194}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010195
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010196
10197/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010198 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10199 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10200 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201 * Used for autocommands and 'wildignore'.
10202 * Returns TRUE if there is a match, FALSE otherwise.
10203 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010204 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010205match_file_pat(
10206 char_u *pattern, /* pattern to match with */
10207 regprog_T **prog, /* pre-compiled regprog or NULL */
10208 char_u *fname, /* full path of file name */
10209 char_u *sfname, /* short file name or NULL */
10210 char_u *tail, /* tail of path */
10211 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010212{
10213 regmatch_T regmatch;
10214 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010215
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010216 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010217 if (prog != NULL)
10218 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010219 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010220 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221
10222 /*
10223 * Try for a match with the pattern with:
10224 * 1. the full file name, when the pattern has a '/'.
10225 * 2. the short file name, when the pattern has a '/'.
10226 * 3. the tail of the file name, when the pattern has no '/'.
10227 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010228 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010229 && ((allow_dirs
10230 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10231 || (sfname != NULL
10232 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010233 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010234 result = TRUE;
10235
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010236 if (prog != NULL)
10237 *prog = regmatch.regprog;
10238 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010239 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010240 return result;
10241}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010242
10243#if defined(FEAT_WILDIGN) || defined(PROTO)
10244/*
10245 * Return TRUE if a file matches with a pattern in "list".
10246 * "list" is a comma-separated list of patterns, like 'wildignore'.
10247 * "sfname" is the short file name or NULL, "ffname" the long file name.
10248 */
10249 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010250match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010251{
10252 char_u buf[100];
10253 char_u *tail;
10254 char_u *regpat;
10255 char allow_dirs;
10256 int match;
10257 char_u *p;
10258
10259 tail = gettail(sfname);
10260
10261 /* try all patterns in 'wildignore' */
10262 p = list;
10263 while (*p)
10264 {
10265 copy_option_part(&p, buf, 100, ",");
10266 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10267 if (regpat == NULL)
10268 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010269 match = match_file_pat(regpat, NULL, ffname, sfname,
10270 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010271 vim_free(regpat);
10272 if (match)
10273 return TRUE;
10274 }
10275 return FALSE;
10276}
10277#endif
10278
10279/*
10280 * Convert the given pattern "pat" which has shell style wildcards in it, into
10281 * a regular expression, and return the result in allocated memory. If there
10282 * is a directory path separator to be matched, then TRUE is put in
10283 * allow_dirs, otherwise FALSE is put there -- webb.
10284 * Handle backslashes before special characters, like "\*" and "\ ".
10285 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010286 * Returns NULL when out of memory.
10287 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010288 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010289file_pat_to_reg_pat(
10290 char_u *pat,
10291 char_u *pat_end, /* first char after pattern or NULL */
10292 char *allow_dirs, /* Result passed back out in here */
10293 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010294{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010295 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010296 char_u *endp;
10297 char_u *reg_pat;
10298 char_u *p;
10299 int i;
10300 int nested = 0;
10301 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010302
10303 if (allow_dirs != NULL)
10304 *allow_dirs = FALSE;
10305 if (pat_end == NULL)
10306 pat_end = pat + STRLEN(pat);
10307
Bram Moolenaar071d4272004-06-13 20:20:40 +000010308 for (p = pat; p < pat_end; p++)
10309 {
10310 switch (*p)
10311 {
10312 case '*':
10313 case '.':
10314 case ',':
10315 case '{':
10316 case '}':
10317 case '~':
10318 size += 2; /* extra backslash */
10319 break;
10320#ifdef BACKSLASH_IN_FILENAME
10321 case '\\':
10322 case '/':
10323 size += 4; /* could become "[\/]" */
10324 break;
10325#endif
10326 default:
10327 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010328# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010329 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010330 {
10331 ++p;
10332 ++size;
10333 }
10334# endif
10335 break;
10336 }
10337 }
10338 reg_pat = alloc(size + 1);
10339 if (reg_pat == NULL)
10340 return NULL;
10341
Bram Moolenaar071d4272004-06-13 20:20:40 +000010342 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010343
10344 if (pat[0] == '*')
10345 while (pat[0] == '*' && pat < pat_end - 1)
10346 pat++;
10347 else
10348 reg_pat[i++] = '^';
10349 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010350 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010351 {
10352 while (endp - pat > 0 && *endp == '*')
10353 endp--;
10354 add_dollar = FALSE;
10355 }
10356 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10357 {
10358 switch (*p)
10359 {
10360 case '*':
10361 reg_pat[i++] = '.';
10362 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010363 while (p[1] == '*') /* "**" matches like "*" */
10364 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010365 break;
10366 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010367 case '~':
10368 reg_pat[i++] = '\\';
10369 reg_pat[i++] = *p;
10370 break;
10371 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010372 reg_pat[i++] = '.';
10373 break;
10374 case '\\':
10375 if (p[1] == NUL)
10376 break;
10377#ifdef BACKSLASH_IN_FILENAME
10378 if (!no_bslash)
10379 {
10380 /* translate:
10381 * "\x" to "\\x" e.g., "dir\file"
10382 * "\*" to "\\.*" e.g., "dir\*.c"
10383 * "\?" to "\\." e.g., "dir\??.c"
10384 * "\+" to "\+" e.g., "fileX\+.c"
10385 */
10386 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10387 && p[1] != '+')
10388 {
10389 reg_pat[i++] = '[';
10390 reg_pat[i++] = '\\';
10391 reg_pat[i++] = '/';
10392 reg_pat[i++] = ']';
10393 if (allow_dirs != NULL)
10394 *allow_dirs = TRUE;
10395 break;
10396 }
10397 }
10398#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010399 /* Undo escaping from ExpandEscape():
10400 * foo\?bar -> foo?bar
10401 * foo\%bar -> foo%bar
10402 * foo\,bar -> foo,bar
10403 * foo\ bar -> foo bar
10404 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010405 * regexp.
10406 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010407 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010408 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010409 if (*++p == '?'
10410#ifdef BACKSLASH_IN_FILENAME
10411 && no_bslash
10412#endif
10413 )
10414 reg_pat[i++] = '?';
10415 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010416 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010417 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010418 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010419 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10420 {
10421 reg_pat[i++] = '\\';
10422 reg_pat[i++] = '{';
10423 p += 2;
10424 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010425 else
10426 {
10427 if (allow_dirs != NULL && vim_ispathsep(*p)
10428#ifdef BACKSLASH_IN_FILENAME
10429 && (!no_bslash || *p != '\\')
10430#endif
10431 )
10432 *allow_dirs = TRUE;
10433 reg_pat[i++] = '\\';
10434 reg_pat[i++] = *p;
10435 }
10436 break;
10437#ifdef BACKSLASH_IN_FILENAME
10438 case '/':
10439 reg_pat[i++] = '[';
10440 reg_pat[i++] = '\\';
10441 reg_pat[i++] = '/';
10442 reg_pat[i++] = ']';
10443 if (allow_dirs != NULL)
10444 *allow_dirs = TRUE;
10445 break;
10446#endif
10447 case '{':
10448 reg_pat[i++] = '\\';
10449 reg_pat[i++] = '(';
10450 nested++;
10451 break;
10452 case '}':
10453 reg_pat[i++] = '\\';
10454 reg_pat[i++] = ')';
10455 --nested;
10456 break;
10457 case ',':
10458 if (nested)
10459 {
10460 reg_pat[i++] = '\\';
10461 reg_pat[i++] = '|';
10462 }
10463 else
10464 reg_pat[i++] = ',';
10465 break;
10466 default:
10467# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010468 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010469 reg_pat[i++] = *p++;
10470 else
10471# endif
10472 if (allow_dirs != NULL && vim_ispathsep(*p))
10473 *allow_dirs = TRUE;
10474 reg_pat[i++] = *p;
10475 break;
10476 }
10477 }
10478 if (add_dollar)
10479 reg_pat[i++] = '$';
10480 reg_pat[i] = NUL;
10481 if (nested != 0)
10482 {
10483 if (nested < 0)
10484 EMSG(_("E219: Missing {."));
10485 else
10486 EMSG(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010487 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010488 }
10489 return reg_pat;
10490}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010491
10492#if defined(EINTR) || defined(PROTO)
10493/*
10494 * Version of read() that retries when interrupted by EINTR (possibly
10495 * by a SIGWINCH).
10496 */
10497 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010498read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010499{
10500 long ret;
10501
10502 for (;;)
10503 {
10504 ret = vim_read(fd, buf, bufsize);
10505 if (ret >= 0 || errno != EINTR)
10506 break;
10507 }
10508 return ret;
10509}
10510
10511/*
10512 * Version of write() that retries when interrupted by EINTR (possibly
10513 * by a SIGWINCH).
10514 */
10515 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010516write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010517{
10518 long ret = 0;
10519 long wlen;
10520
10521 /* Repeat the write() so long it didn't fail, other than being interrupted
10522 * by a signal. */
10523 while (ret < (long)bufsize)
10524 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010525 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010526 if (wlen < 0)
10527 {
10528 if (errno != EINTR)
10529 break;
10530 }
10531 else
10532 ret += wlen;
10533 }
10534 return ret;
10535}
10536#endif